Why is taking the address of a temporary illegal?

&std::string(“Hello World”) The problem with this isn’t that std::string(“Hello World”) yields a temporary object. The problem is that the expression std::string(“Hello World”) is an rvalue expression that refers to a temporary object. You cannot take the address of an rvalue because not all rvalues have addresses (and not all rvalues are objects). Consider the following: … Read more

Disallowing creation of the temporary objects

Edit: As j_random_hacker notes, it is possible to force the user to declare a named object in order to take out a lock. However, even if creation of temporaries was somehow banned for your class, then the user could make a similar mistake: // take out a lock: if (m_multiThreaded) { CSingleLock c(&m_criticalSection, TRUE); } … Read more