0
What is wromg in this code
Hi Came across below code : What could have been done better ? Can any one suggest ? I tried to add cout statements and found that only a destructor is called where as constructor and move constructor is called once each.. so one destructor call is missed https://code.sololearn.com/c4eR7JMYnzyb/?ref=app
1 ответ
+ 4
There are 2 things wrong.
First of all, the pointer p inside main is never deleted so the object is never destructed and no destructor is called.
Even if you fix that the program will crash due to a double delete in the destructor.
The move constructor is not moving anything, it's just copying.
If you want to actually move the data you should replace 'ptr = temp.ptr' with `ptr = std::exchange( temp.ptr, nullptr )`
This assigns temp.ptr to ptr and then nullptr is assigned to temp.ptr.
For the move assignment operator ( if it existed ) you want to be careful because you still have to delete the ptr that's being moved into, so you may want to opt for a swap instead so that the destructor can take care of the old pointer.
Also some general tips:
Always mark the move constructor and move operator as noexcept if it cannot throw like in your example.
It allows for some major optimizations, especially for a vector.
deleting a nullptr is fine 'if( ptr )' is not needed.