خرید بک لینک

Vote count: 0

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 retued 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;

    retu 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!

asked 2 mins ago

1 Answer

Vote count: 0

Yes, you have the guarantee. Temporaries live until the end of the expression, which is until a function foo() retus 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!

answered 57 secs ago

برچسب: نویسنده: استخدام کار تاريخ: جمعه 17 ارديبهشت 1395 ساعت: 21:58

صفحه بندی