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

前端 未结 3 1101
别跟我提以往
别跟我提以往 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:28

    The reason it's illegal to return the address to a local variable is once the function returns, the local variable ceases to exist, thus you're returning an address which is known to be no longer valid. (The object may still live there but its destructor will have already been called, and the memory it occupied will be used for something else at some point -- perhaps with the very next subroutine call.)

    The reason it's ok to return the address returned by new is that address is not pointing to an object that lives in a temporary location (your program stack is where locals are normally placed); rather it comes from heap memory which will persist until you dispose of it. This object doesn't rely on the scope of code it was allocated in since it's not local to that scope.

提交回复
热议问题