function header temporary variable
-
Hello! Is it part of the C++ standard that a temporary variable instantiated in the function header is destroyed after a possible assignment operation, so that the following code can be used safely:
class Obj
{
//...
};Obj& function(Obj& temp = Obj())
{
return temp;
}int main()
{
Obj myObj;
myObj = function();//... return 0;
}
In VC++ 2008, this works as expected. In contrast, when the object is instantiated in the function body, it is destroyed before the assignment operator - so this code is not valid:
Obj& function()
{
Obj temp = Obj();
return temp;
}Thank you in advance. Alex
-
Hello! Is it part of the C++ standard that a temporary variable instantiated in the function header is destroyed after a possible assignment operation, so that the following code can be used safely:
class Obj
{
//...
};Obj& function(Obj& temp = Obj())
{
return temp;
}int main()
{
Obj myObj;
myObj = function();//... return 0;
}
In VC++ 2008, this works as expected. In contrast, when the object is instantiated in the function body, it is destroyed before the assignment operator - so this code is not valid:
Obj& function()
{
Obj temp = Obj();
return temp;
}Thank you in advance. Alex
-
In the first example you're returning a reference to an object that exists *outside* the function (it was created by the caller, *before* it called the function) In the second you're returning a reference to something that no longer exists