0

this is sample code

class a

class a {
public:
    int *i;
    a() {
        i = new int;
    }
    ~a(){
        delete i;
    }
};

method returnA()

a returnA() {
    a A;
    A.i = new int;
    return A;
}

and then I called returnA in main()

int main() {
    returnA();
}

this throws a exception when the code run to the 'delete i' inside ~a(), when I change returnA() to allacote A on heap, the problem goes away, what's the difference for i, didn't it allocated on heap all the time, cause I use new in constructor, please show me some light

Z.better
  • 348
  • 1
  • 5
  • 15
  • 2
    You need a proper copy constructor (and assignment operator) that handles the dynamic memory allocation. See http://en.cppreference.com/w/cpp/language/rule_of_three – Michael Burr Mar 25 '17 at 06:27
  • Returning local variable. Might be overwritten in the stack by some other function/method call. – vivekn Mar 25 '17 at 07:50

0 Answers0