Meditation, The Art of Exploitation

Thinking? At last I have discovered it--thought; this alone is inseparable from me. I am, I exist--that is certain. But for how long? For as long as I am thinking. For it could be, that were I totally to cease from thinking, I should totally cease to exist....I am, then, in the strict sense only a thing that thinks.

Wednesday, November 29, 2006

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.

class Test{
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&)'