C++ cannot bind temporary objects to non-const references (clc++)
This property is one of the C++ gotchas where a temporary object when passed as a reference argument, must bind to a const reference. Its physical state cannot change within the function. There is no logical reason why it has to be this way but it's mandated by C++ spec.
#include
class Test{
public:
Test(int i ) { std::cout << "Test Constructor!" << std::endl ; }
Test( Test & test ) { std::cout << "Copy" << std::endl; }
~Test() { std::cout << "Destroy!" << std::endl ; };
};
int main( int argc , char ** argv ){
Test array[10] = { Test(1) } ;
return 0 ;
}
g++ say: no matching call to : Test::Test(Test)
In order to copy-construct from a temporary, the copy constructor should be 'Test(Test const&)'
#include
class Test{
public:
Test(int i ) { std::cout << "Test Constructor!" << std::endl ; }
Test( Test & test ) { std::cout << "Copy" << std::endl; }
~Test() { std::cout << "Destroy!" << std::endl ; };
};
int main( int argc , char ** argv ){
Test array[10] = { Test(1) } ;
return 0 ;
}
g++ say: no matching call to : Test::Test(Test)
In order to copy-construct from a temporary, the copy constructor should be 'Test(Test const&)'
<< Home