Returning an address to a local variable vs returning a pointer to a local variable

前端 未结 3 1148
别跟我提以往
别跟我提以往 2021-01-24 19:58

I have this in my testing.cpp:

class Supp{
public:
virtual Supp* add(Supp& val) = 0;
};

class SubA : public Supp{
public:
int val;

SubA(int a){
    val = a         


        
3条回答
  •  野性不改
    2021-01-24 20:32

    In the first example, your local variable is allocated on the stack (where all local variables for the duration of their scope) and will be immediately deallocated on returning to the calling function. As such, the pointer returned will be invalid the moment you leave the function.

    In the second, you are creating a new object on the heap where it will be retained until you manually deallocate the pointer somewhere else down the line.

提交回复
热议问题