Object(Object & obj) 

Are there any reasons to use this constructor?

Only auto_ptr comes to mind, although this is a rather bad example.

  • four
    Well, you never know - you suddenly need to put a flag in the object, whether this object was copied ... - Harry
  • When using the prototype approach, you may need to pass a reference to the object to be modified in order to get a reference to the prototype to be modified to initialize the prototype of this object. - VTT

1 answer 1

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 хранит указатель и сам удаляет память } 
  • But this is exactly what the displacement constructor is intended for ! The essence of the question is precisely in this: why in modern C ++, supporting the concept of displacement, you may need a copy constructor with a non-constant argument. - AnT pm
  • @AnT, for example, we can assume that all copies of an object should be in a linked list. That is, it is possible to invent some kind of application, but how much it will relate to real tasks is a big question. We can say that with the advent of the displacement constructor, the non-constant copying itself became obsolete. - freim