I'm wondering what the standard says about the following piece of code. Can string
destructor of temporary object be executed before calling printPointer
?
p.s. VS2010 compiler doesn't complain about this code and works correctly.
void printPointer(const string* pointer)
{
cout << *pointer << endl;
}
const string* func(const string& s1)
{
return &s1;
}
int main()
{
printPointer(func("Hello, World!!!"));
}
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor is a member function with the same name as its class prefixed by a ~ (tilde).
No. You never need to explicitly call a destructor (except with placement new ). A derived class's destructor (whether or not you explicitly define one) automagically invokes the destructors for base class subobjects. Base classes are destructed after member objects.
A trivial destructor is a destructor that performs no action. Objects with trivial destructors don't require a delete-expression and may be disposed of by simply deallocating their storage. All data types compatible with the C language (POD types) are trivially destructible.
Can
string
destructor of temporary object be executed before callingprintPointer
?
No, because temporary objects will be destroyed as the last step in evaluating the full-expression which contains the point where they were created, which means it will persist until the invoking of printPointer()
ends.
From the standard #12.2/4 Temporary objects [class.temporary]:
Temporary objects are destroyed as the last step in evaluating the full-expression ([intro.execution]) that (lexically) contains the point where they were created.
And #12.2/6 Temporary objects [class.temporary]:
A temporary object bound to a reference parameter in a function call ([expr.call]) persists until the completion of the full-expression containing the call.
explanatory demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With