Suppose I have a class Foo that has a private pointer to a Bar:
class Foo
{
private:
Bar * bar;
public:
Foo () : bar (new Bar ())
{}
~Foo ()
{
delete bar;
}
};
If the pointer bar
should never be reassigned to a different instance, then it makes sense to make the pointer itself const
in order to stop me (or a maintainer) from doing so in the future:
private:
Bar * const bar;
I like doing this wherever the opportunity arises.
If I then wanted to write a move constructor, it would look something like this:
Foo (Foo && f) :
bar (f.bar)
{
f.bar = NULL; // uh oh; f.bar is const.
}
I can "make the error go away" either by casting away the constness of f.bar
or by not making it const in the first place. Neither of which are things I want to do. I'd rather not remove the const completely because it's there for a reason. On the other hand, casting away constness rings alarm bells for me and is something I never usually do. My question is: is it considered acceptable practice to cast away constness within a move constructor like this? Is there a better way that I haven't considered?
I don't think my question is the same as this one: Use const_cast to implement the move constructor