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

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

    Initially misread the question, sorry.

    The second works because you're not returning by reference, but by value. If the signature was

    Supp*& add(Supp& value)
    

    then the second would be illegal as well.

    Keep in mind that objects with automatic storage duration get destroyed at the closing }. So after the functions return, the object b is no longer accessible. Copies of it are. If you return by value, the original goes away, but you're left with the copy.

提交回复
热议问题