c++pointers

Pointers reassignment with value from stack


Is this undefined behavior

#include <iostream>
#include <string>
using namespace std;

class A {
public: 
    ~A() { cout << "~A\n"; }
};

void f(A*& d) 
{
    A e;
    *d = e;
}

int main()
{   
    A *u = new A;
    f(u);
    delete u;
 
    return 0;
} 

when u pointer will be deleted since e from f function is local variable?


Solution

  • Is this undefined behavior

    No, it's not.

    when u pointer will be deleted since e from f function is local variable?

    e is a local variable and will be destroyed when it goes out of scope (that is, when the function returns).

    The assignment *d = e; only assigns the value of e to the instance of A that d points at. u will be deleted when you do delete u; in main. No problem there.

    One warning flag is that you take the raw owning pointer by reference though. That means that the function can actually assign d to point at a different A (d = new A; for example), and then the original pointer will be lost and it will leak memory. d = &e; would be even worse since you'd both have a leak and when f returns, u would be a dangling pointer and delete u; would have undefined behavior.