I have a class that has a const member, const pointer and enum class member,
My Questions for the sample code bellow:
- How to nuliffy a enum class member of “other”` in move constructor
properly (what value to assign to it?) - How to nullify a const pointer of “other”` in move constructor so
that destructor of other does not delete a memory of object that is
being constructed, and so that a pointer reamins valid? - How to nullify a constant member of “other” in move constructor so
that destructor of other does not get called?
enum class EnumClass
{
VALUE0, // this is zero
VALUE1
};
class MyClass
{
public:
MyClass() :
member(EnumClass::VALUE1),
x(10.f),
y(new int(4)) { }
MyClass(MyClass&& other) :
member(other.member),
x(other.x),
y(other.y)
{
// Can I be sure that this approach will nullify a "member" and avoid
// destructor call of other
other.member = EnumClass::VALUE0;
// Or shall I use this method?
other.member = static_cast<EnumClass>(0);
// ERROR how do I nullify "x" to avoid destructor call of other?
other.x = 0.f;
// ERROR the same here, delete is going to be called twice!
other.y = nullptr;
}
~MyClass()
{
delete y;
}
private:
EnumClass member;
const float x;
int* const y;
};
You don’t need to worry about nullifying non-pointer types. They cannot be “freed” more than once, because their data is located inside of the class, not on the heap. Your const int pointer does need to be nullified, and it looks like you are doing that right.
Take a look at this MDSN article for more info: http://msdn.microsoft.com/en-us/library/dd293665.aspx
EDIT:
If you declare an int* const y, you are declaring the pointer to be const. If you simply want the int to be const, declare it as const int* y. You cannot change the address of a pointer declared as int* const y.