1

Assume that I have a function foo() that returns object of class A by value

A foo() {
    A a(...);
    return A;
}

Now in function bar() I store a pointer to the return value of A

void bar() {
    A* pA = &foo();
}

Will the return value go out of scope at the end of bar(), or is there any need to call a delete on pA ?

Dooggy
  • 330
  • 2
  • 11
  • ***or is there any need to call a delete on pA*** You don't delete it. ***Will the return value go out of scope at the end of bar()*** Before that. You can't do this. – drescherjm Jun 21 '17 at 15:53

1 Answers1

4

It's much worse than that!

The behaviour on dereferencing pA in bar will be undefined. That's because foo() returns an anonymous temporary whose lifetime is limited to the statement at the call site.

You only ever call delete on a pointer that's attained by the result of an allocation using new.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483