1

One day, I'm wondering whether there is memory copy when returning a string object. But, I find a weird thing. When I return an object in my function, I expect there is a copy construction to create a temporary object as the return value. So, I try the following code.

class Substring: public string
{
public:
    Substring(const char* s)
    :string(s)
    {
    }

    ~Substring()
    {
        cout << "Deconstruct" << endl;
    }
};

Substring foo()
{
    Substring ret("test");
    printf("Inner address: %p\n", ret.c_str());
    return ret;
}

int main()
{
    Substring test = foo();
    printf("Return address: %p\n", test.c_str());
    return 0;
}

As I said, I'm expecting the Return address is different from Inner address. And Deconstruct should be print out after Inner address

Here is what I got. It seems like ret is deconstructed when the outside variable test died, not the time when out of its scope! Why?

Inner address: 0x7ffed3a4cb40
Return address: 0x7ffed3a4cb40
Deconstruct
Neal Yi
  • 13
  • 2

1 Answers1

1

C++ has this thing called elision.

Multiple objects can have their lifetimes elided together. This means that while at first glance there are 3 substring objects (ret, test and the anonymous return value), after elision they are all the same object with one construction and destruction.

There are various limits (both standard mandated and practical) to elision, and in certain forms became mandated.

In particular, eliding a prvalue is almost always permitted, and if permitted almost always required in C++17.

Named variables can be elided with prvalues, and return values elided with named locals if the return statement is return var_name; and the types match.

People have made up names for particular kinds of elision -- RVO and NRVO -- but I find them more confusing than enlightening.

Disabling elision is a bad idea, and having to do so is a sign that your object model is alien to C++'s assumptions.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • It's a good answer. Since I'm new to here, my vote doesn't show up. I'm sorry for that. Anyway, thanks a lot! – Neal Yi Dec 11 '17 at 03:15