This operator does not use an assignment operator (two lines are equivalent, as far as I know). = used in the syntax, but operator= is not actually used:
myClass myVariable = myClass(123); //or myClass myVariable(123);
In this case, the assignment operator is used:
myClass myVariable; myVariable = myClass(123);
If the assignment operator is poor or not implemented, the first operator works, the second may (and most likely) fail.
#include <iostream> #include <string.h> using namespace std; class Dvector { public: Dvector( int thesize = 0 ) { std::cout << "Constructing object of size " << thesize << std::endl; size = thesize; data = new double[size]; } Dvector( const Dvector& v ) { std::cout << "Constructing object of size " << v.size << " by copy" << std::endl; size = v.size; data = new double[size]; memcpy( data, v.data, sizeof(double)*size ); } Dvector& operator=( const Dvector& v ) { std::cout << "Assigning object of size " << v.size << std::endl; if ( &v != this ) { size = v.size; data = new double[size]; memcpy( data, v.data, sizeof(double)*size ); } return *this; } ~Dvector() { std::cout << "Destroying object" << std::endl; delete [] data; } private: double* data; int size; }; int main() { Dvector v = Dvector(3); return 0; }
Output:
Constructing object of size 3 Destroying object
When:
int main() { Dvector v; v = Dvector(3); return 0; }
Output:
Constructing object of size 0 Constructing object of size 3 Assigning object of size 3 Destroying object Destroying object
And it would crash if the copy constructor were not defined ... because then v.data ends up pointing to data allocated by temporary variables ( Dvector(3) ) and then is deleted. Possible failure when trying to access v.data or when v destroyed (deletion of already freed memory).
jpo38 source share