unique_ptr not unique_ptr , it is only movable.
This will directly affect Test, which in the second example can also be movable and not copyable.
In fact, it’s good that you use unique_ptr which protects you from a big mistake.
For example, the main problem with your first code is that the pointer is never deleted, which is very, very bad. Say you would fix it:
class Test { int* ptr; // writing this in one line is meh, not sure if even standard C++ Test() : ptr(new int(10)) {} ~Test() {delete ptr;} }; int main() { Test o; Test t = o; }
This is also bad. What happens if you copy Test ? There will be two classes that have a pointer pointing to the same address.
When one Test destroyed, it will also destroy the pointer. When your second Test is destroyed, it will also try to delete the memory behind the pointer. But it has already been deleted, and we will get some error during memory access execution (or undefined behavior if we are out of luck).
Thus, the right way is to implement the copy constructor and copy assignment operator so that the behavior is clear and we can create a copy.
unique_ptr far ahead of us here. It makes sense: " I am unique , so you cannot just copy me." Thus, this prevents us from making mistakes when implementing operators at hand.
You can define a copy constructor and copy assignment operator for specific behavior, and your code will work. But you are rightfully (!) Forced to do so.
The moral of this story is: always use unique_ptr in situations like this.
IceFire Jan 22 '19 at 16:04 2019-01-22 16:04
source share