"MyClass mc = MyClass ()" or "MyClass mc"?

What's the difference between

MyClass mc = MyClass(); 

and

 MyClass mc; 

in c ++?

+4
source share
5 answers

The first calls the copy constructor, with a temporary object as a parameter - MyClass() creates a temporary one.

The second calls the default constructor.

In fact, they are in most cases optimized for the same code, but what is the semantic difference.


As Negal noted, the case is slightly different from POD types; when "MyClass" is POD, the second fragment will not initialize the mc value, while the first will.

+8
source

The first is copy initialization, and the second is the default initialization.

For example, the following code will not compile:

 class MyC { public: MyC(){} private: MyC(const MyC&) {} }; int main() { MyC myc = MyC(); return 0; } 
+2
source

Custom copy constructor and default constructor.

+1
source

First create a temp-object via c-tor without arguments , and then call copy-ctor on the object (do not consider any optimizations). The second call to c-tor without arguments , without copying. When optimizing compilers, both cases are equal.

Differences in fundamental types, therefore

 // initialized to something int c; // initialized to int() that is 0 by standard. int c = int(); 
0
source

no difference. default call ctor. sugar syntax) no copy ctor !!!!

 class PPP{ public: PPP(PPP&){ std::cout<<"PPP1"<<std::endl; } PPP(const PPP&){ std::cout<<"PPP2"<<std::endl; } PPP(){ std::cout<<"PPP3"<<std::endl; } }; PPP ppp = PPP(); 

and you will only find PPP in the console.

-3
source

All Articles