c++ - const_cast 'this' in const method to assign 'this' to outer variable? -




have @ following code:

struct foo;  foo* bar;  struct foo {     void func() const {         bar = this;     } }  int main() {     foo().func(); }         

this not work bar won't accept const foo*. around this, const_cast used:

struct foo {     void func() const {         bar = const_cast<foo*>(this);     } } 

is safe? i'm cautious when comes using const_cast, in case seems legit me.

no, potentially dangerous.

func() marked const means can called const object:

const foo foo; foo.func(); 

because this const foo*.

if const_cast away const end foo* const object. means modification object through non-const pointer (or through copy of pointer, bar in case) undefined behavior since not allowed modify const object (duh).

plus obvious problem you're lying consumer of class foo saying func() won't modify while you're doing opposite.

const_cast never correct , seems xy-problem me.





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -