C++ allows assignment of temporary objects only to const reference. It wont allow assignement of temporary objects to reference.
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..
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?
No, reading the object is perfectly sensible. Just because it's going to vanish in the future doesn't mean reading the data now is pointless.
std::string("foo.txt") is a temporary which will stop existing after the call to open_file() but the data it contains while it does exist matters very much.
It's just that the designers felt that it would cause a sufficient number of problems (probably due to the common idiom of 'out parameters') without enabling anything of similar value, so they simply made a design decision to prohibit temporaries binding to non-const references.
This works fine, it's just not very useful.
If you have a temporary object that's very expensive to copy, you may prefer to take a const& to that object (say a function return) rather than copying it into another variable to use later. Taking a constant reference to a temporary extends the life of that temporary to as long as the reference lives, allowing you to access any readable state.
Writing is disallowed because as soon as you want to mutate a variable you may as well have a real instance rather than a temporary that's aliased only as a non-const reference.
See, the temporary object String("hello ") survives the entire line of code, which means it is intact when sent to DoubleString and after it. It is destroyed only when the entire line has finished.
Not the answer you're looking for? Browse other questions tagged c++ temporary-objects or ask your own question.
Why can you initialize a const reference but not a non-const reference from an rvalue?
How are references encoded in C++?
Why can a non-const reference parameter be bound to a temporary object?
Will const-casting a const reference of a temporary cause undefined behavior?