Copy and Assign

Can someone explain to me the difference between copying and assignment?

SomeClass a;
SomeClass b = a; // assignment
SomeClass c(a); // assignment
b = c; // copying

but what is the difference, why are there two different constructions in the language?

+5
source share
4 answers

Copying is designed to initialize new objects by copying the contents of existing ones, the purpose is to rewrite existing objects with the contents of other objects - these two things are very different. In particular, this

SomeClass a;
SomeClass b = a;

- copy initialization - you copy ato create a new SomeClass called busing form syntax

T x = y;

SomeClass copy ( , , ). a; , .

SomeClass(const SomeClass& rhs)
: x(rhs.x)
{}

( , , , , .)

,

SomeClass c(a);

- . , , , , :

http://www.gotw.ca/gotw/036.htm

. :

http://www.gotw.ca/gotw/001.htm

,

b = c;

- . , b c ( , std::auto_ptr, , ). , - ( , , , ):

SomeClass& operator=(const SomeClass& rhs)
{
    x = rhs.x;
    return *this;
}

, , , , . . :

http://en.wikibooks.org/wiki/More_C++_Idioms/Copy-and-swap

+1

, . , . .

, , :

SomeClass a();

a, SomeClass.

SomeClass b = a; // actually copy constructor & initialization of b
SomeClass c(a); // same

a SomeClass, - SomeClass::SomeClass(const SomeClass&). .

b = c; // assignment

c SomeClass, . SomeClass::operator =(const SomeClass&).

+3

( ):

SomeClass b = a;

:

SomeClass c(a);

:

b = c;

Oh, and this one is not initialization :

SomeClass a();
+2
source

Initialization initializes a previously uninitialized object. Assignments, on the other hand, overwrite an already initialized object and can destroy an existing state. These are different operations; while they usually have the same result for an object on LHS, they are not semantically equivalent.

+1
source

All Articles