Why is the constructor not called?

I wrote a test class, but I do not understand what is happening!

Is moving / copying sent? if so, how can it be updated with a new value. I'm definitely missing something.

here is a test case (please do not consider utility)

#include<iostream> struct Test { int a; Test(){a = 10;std::cout<<"def\n";} Test(int a){this->a = a;std::cout<<"unary\n";} Test(const Test& a){this->a = aa; std::cout<<"copy\n";} Test(Test&& a){this->a = aa; std::cout<<"Move\n";} Test& operator=(const Test& a){this->a = aa;std::cout<<"op=\n";} Test& operator=(Test&& a){this->a = aa;std::cout<<"Move=\n";} void display(){std::cout << "Display ";} }; Test gi(Test a) { std::cout<<aa<<"&\n"; return a; } int main() { //Test a = 99; //Test(); /*Line MST*/ Test b = Test(102);//gi(a); std::cout<<ba<<'\n'; return 0; } 

here the MST line is what I do not understand. if I initialize it with a temporary Test object, if it does not call the Move constructor (or at least a copy)?

output:

 unary 102 

similar output with this line

  Test b = gi(Test(103)); 

here moving / copying doesn't happen during gi () call?

but it is as i expect

 Test a = 99; Test b = gi(a); 

What am I missing here?

+4
source share
1 answer

Is moving / copying sent? if so, how can it be updated with a new value

Yes, the copy is copied in accordance with Β§ 12.8 / 31 of the C ++ Standard 11. It depends entirely on the compiler, when and whether to perform this optimization, and you should not have expectations that it will be executed or not (even if copy constructor or move constructor have side effects).

+3
source

Source: https://habr.com/ru/post/1480474/


All Articles