Object(Object & obj)
Are there any reasons to use this constructor?
Only auto_ptr
comes to mind, although this is a rather bad example.
Object(Object & obj)
Are there any reasons to use this constructor?
Only auto_ptr
comes to mind, although this is a rather bad example.
There are cases when an object must store memory exclusively. Without external intervention. In this case, the constructor removes the given memory from the argument, keeps it.
// g++ -Wall -Wpedantic -std=c++98 secr.cpp class Secret { int * pointer ; public: Secret (Secret & o) : pointer ( o.pointer ) { o.pointer = 0 ; } Secret (Secret const & ) ; // без определения explicit Secret(int * * x) : pointer(*x) { (*x) = 0 ; } ~Secret(){delete pointer;} } ; void f(){ int * pi = new int(1); Secret s(&pi) ; delete pi ; // здесь pi указывает на NULL - ничего не удалится Secret s2(s); // здесь s с указателем NULL - пустой // а s2 хранит указатель и сам удаляет память }