Possible Duplicate:
Does a const reference prolong the life of a temporary?
prolonging the lifetime of temporaries
C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference.
For example:
String& a = String("test"); // Error
const String& a = String("test"); // Ok
Everywhere I google for this result, i only see the following answers
- Modifying temporary objects would cause unidentifiable problems
- Modifying temporary objects is dangerous
- At some point of time, you will forget it is a temporary variable
It's been said, temporary objects vanishes after the statement. So you should not modify it.
If C++, is so keen in blocking modifying the temporary objects, it should have blocked reading the temporary objects right? If the temporary object is vanished, then there is no point in reading contents from there right? The possible cases, where a right can occur, could also involve the read too.
Then why its been blocking write alone and allowing read?
Please give me a solid c++ code explanation.
Please dont deviate the question by pointing some alternatives. Please give me solid answer with code why const int & is allowed and int & is not allowed for temporary objects.
One says && is there.. My question different.. ANother say,changing will not reflect.. Changing will not reflect even when it is const int & too. Eg: double a; Const int & i = a; a++; will not affect i..