Why is the copy initialization the same as it is? Why do I need a copy constructor?

Possible duplicate:
What is the motivation for having a copy and direct initialization, behave differently?

And when I initialize the copy, I mean like this:

struct MyStruct { MyStruct(int) {} MyStruct(const MyStruct&) {} }; MyStruct s = 5; // needs *both* the int and copy constructor 

Despite programming in C ++ for many years, I never realized that the above code requires a copy constructor (thanks to jogojapan). The temporary was always deleted, and therefore I did not even know that it even exists (at least on a superficial level, despite the fact that it is optimized) until he pointed me out.

After a decent amount of googling, I get an idea of ​​how this works. My question is: why is this the case?

Why didn’t the standard make the copy constructor necessary in the above example? Is there any specific example / example that shows that the need for a copy constructor in this type of initialization is important?

Without a worthy explanation of why this is the case, I just see it as an annoying artifact, but I would rather not be ignorant if there is something important that I am missing.

+8
c ++ copy-constructor
source share
1 answer

Copying an object's initialization is ambiguous for direct initialization, both can be used the same way to set values ​​equal to each other.

 int a = 4; int a = int(4); int a(4); 

all these calls are ambiguous, they are all set to 4. The reason for the copy constructor in the case of an integer is convenience, imagine C ++ data types without it

 int a(foo(b,r)); //a little messy for a variable declaration int a = foo(b,r) //ok, cleaner 

you could also use an implicit and explicit copy constructor, here is an example program that explicitly uses the copy constructor to process imaginary numbers:

 #include <iostream> using std::cout; using std::endl; class complexNumbers { double real, img; public: complexNumbers() : real(0), img(0) { } complexNumbers(const complexNumbers& c) { real = c.real; img = c.img; } explicit complexNumbers( double r, double i = 0.0) { real = r; img = i; } friend void display(complexNumbers cx); }; void display(complexNumbers cx){ cout<<&quot;Real Part: &quot;<<cx.real<<&quot; Imag Part: &quot;<<cx.img<<endl; } int main() { complexNumbers one(1); display(one); complexNumbers two =2; display(200); return 0; } 
0
source share

All Articles