Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implicit destructor execution in function calling

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!!!"));
}
like image 882
skap Avatar asked Jul 13 '16 07:07

skap


People also ask

How to invoke destructor?

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() .

When destructor will be called?

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).

Do c++ classes need a destructor?

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.

What is a trivial destructor?

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.


1 Answers

Can string destructor of temporary object be executed before calling printPointer?

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

like image 94
songyuanyao Avatar answered Nov 01 '22 01:11

songyuanyao