Деструкторы не называются? - PullRequest
0 голосов
/ 19 мая 2019

Я пытаюсь отследить эту программу, однако по какой-то причине она отображает Процесс завершен с кодом выхода 4. и конец без вызова деструкторов? в чем может быть причина?

#include <iostream>
using namespace std;

class A {
public:
    A() { cout << "A ctor" << endl; }
    A(const A& a) { cout << "A copy ctor" << endl; }
    virtual ~A() { cout << "A dtor" << endl; }
    virtual void foo() { cout << "A foo()" << endl; }
    virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }
};

class B : public A {
public:
    B() { cout << "B ctor" << endl; }
    virtual ~B() { cout << "B dtor" << endl; }
    virtual void foo() { cout << "B foo()" << endl; }
protected:
    A mInstanceOfA; // don't forget about me!
};
A foo(A& input)
{
    input.foo();
    return input;
}
int main()
{
    B myB;

    B myOtherB;
    A myA;
    myOtherB = myB;
    myA = foo(myOtherB);
}

Ответы [ 2 ]

4 голосов
/ 19 мая 2019

Ваша программа демонстрирует неопределенное поведение, достигая закрывающей скобки не пустой функции (здесь operator=), не встречая оператор return.

3 голосов
/ 19 мая 2019

Для меня (с gcc 8.3.0) это работает хорошо. Но я получаю предупреждение:

test.cpp: In member function ‘virtual A& A::operator=(const A&)’:
test.cpp:10:63: warning: no return statement in function returning non-void [-Wreturn-type]
 virtual A& operator=(const A& rhs) { cout << "A op=" << endl; }

И это распечатывает:

A ctor
A ctor
B ctor
A ctor
A ctor
B ctor
A ctor
A op=
A op=
B foo()
A copy ctor
A op=
A dtor
A dtor
B dtor
A dtor
A dtor
B dtor
A dtor
A dtor

Возможно, вам следует попытаться устранить предупреждение.

...