What constructor is called when initialising with temporary object?
#include<iostream>
class Test{
public:
int a;
Test(){
std::cout<<"default"<<std::endl;
}
Test(Test& t):a(t.a){
std::cout<<"copy constructor called"<<std::endl;
}
Test(int x):a(x){
std::cout<<"int construct"<<std::endl;
}
Test(Test&& t):a(t.a){
std::cout<<"rvalue reference"<<std::endl;
}
Test operator+(const Test& t1){
Test out;
out.a = a + t1.a;
std::cout<<"a"<<a<<std::endl;
return out;
}
};
int main(){
Test t(10), t1(20), t2(30);
Test out(t+t1+t2);
Test o(std::move(t));
}
Output:
int construct //from t(10)
int construct // from t1(20)
int construct // from t2(30)
default // from inside operator+ 1st time
a10 // value of a from t
default // from inside operator+ 2nd time
a30 // value of a from temporary object
rvalue // from Test(Test&& t)
How is out
intialized here in Test out(t+t1+t2);
? What constructor is called when initialising with temporary object.
But when I comment out Test(Test&& t)
and removed this line Test o(std::move(t));
it gives me error:
Compiled with g++ -std=c++11 -o new new.cpp
, g++ -std=c++14 -o new new.cpp
new.cpp: In function ‘int main()’:
new.cpp:28:18: error: cannot bind non-const lvalue reference of type ‘Test&’ to an rvalue of type ‘Test’
new.cpp:9:16: note: initializing argument 1 of ‘Test::Test(Test&)’
But when compiled with -std=c++17
no error is raised
int construct
int construct
int construct
default
a10
default
a30