1

I have a somewhat specific question regarding destructors in C++. It's far easier to explain what I'm asking through code. Basically I want to do something similar (but not exactly) to this:

foo( bar().ptr );

In this example the pointer points to dynamic memory within the object returned from 'bar()'. We can assume the pointer is a char* from simplicity. I want to be sure that the data that 'ptr' points to lives during 'foo()'s execution. Now to flesh out what I mean in code:

foo( char* ptr )
{
    // do stuff with *ptr
}

obj bar()
{
    obj thing;

    return thing;
}

struct obj
{
    char* ptr;

    obj()
    {
        ptr = new char[1];
    }

    ~obj()
    {
        delete[] ptr;
    }
};

Now this works in Visual Studio without full optimizations. I'm paranoid and want to have 100% confidence in this though. This code also needs to run on Linux (compiled with gcc). Strictly x86.

This is somewhat subtle so I figured I'd ask to see if this behavior is standard. It would seem like a compiler would want to ensure that this works.

Thanks!

rici
  • 234,347
  • 28
  • 237
  • 341
Tom
  • 11
  • 2

1 Answers1

4

Yes, you have the guarantee. Temporaries live until the end of the expression, which is until a function foo() returns in your case.

Conceptually, your case is no different from

void x(const char* );

x(std::string("String").c_str());

And this is time-honored practice!

As a side note, your smart-pointer class is extremely badly written, but I take it is just for illustration and not the real code.

SergeyA
  • 61,605
  • 5
  • 78
  • 137
  • Haha, good point with c_ptr()! Yes, all of that code above is just distilled down to only the most relevant parts. Thanks! – Tom May 06 '16 at 14:55
  • A side note to your side note: The example smart pointer class is so badly written, it breaks this usage. The temporary is (without RVO) incorrectly copy constructed from a function local that is destructed before the temporary is used. – Avi Berger May 06 '16 at 16:02