#cpp
Имеем класс D унаследованного от класса B , а в классе D есть данные класса M. Вопрос
при вызове деструктора класса D порядок будет M D B ?
Ответы
Ответ 1
это легко проверить: #includeusing namespace std; class M{ public: ~M(){ cout << "M" << endl; } }; class B{ public: ~B(){ cout << "B" << endl; } }; class D : public B{ public: ~D(){ cout << "D" << endl; } M m; }; int main(){ D * d = new D; delete(d); return 0; } Ответ 2
Гарантирован следующий порядок: Сначала отрабатывает код деструктора самого класса (D). Затем вызываются деструкторы подобъектов самого класса (M). При этом M должен быть именно подобъектом, указатель не катит. Порядок уничтожения подобъектов противоположен порядку их объявления в классе. Затем вызываются деструкторы невиртуальных базовых классов (B). Для них продолжается эта же история, рекурсивно вниз. Порядок уничтожения базовых объектов противоположен порядку их объявления в списке наследования. Затем вызываются деструкторы всех виртуальных базовых классов. Порядок вызова противоположен порядку виртуальных конструкторов: обходится дерево базовых классов, составляется список виртуальных базовых классов (игнорируя дубликаты), и в обратном порядке вызываются деструкторы. Ссылки на официальный C++ FAQ: When I write a destructor, do I need to explicitly call the destructors for my member objects? When I write a derived class’s destructor, do I need to explicitly call the destructor for my base class? What is the exact order of destructors in a multiple and/or virtual inheritance situation?Ответ 3
Деструкторы вызываются в обратном порядке относительно конструкторов. Деструкторы членов класса будут вызваны в обратном порядке относительно их инициализации после выполнения тела деструктора класса. Таким образом, порядок будет: D M B. Немного из стандарта: After executing the body of the destructor and destroying any automatic objects allocated within the body, a destructor for class X calls the destructors for X’s direct non-variant non-static data members, the destructors for X’s direct base classes and, if X is the type of the most derived class (12.6.2), its destructor calls the destructors for X’s virtual base classes. All destructors are called as if they were referenced with a qualified name, that is, ignoring any possible virtual overriding destructors in more derived classes. Bases and members are destroyed in the reverse order of the completion of their constructor (see 12.6.2). A return statement (6.6.3) in a destructor might not directly return to the caller; before transferring control to the caller, the destructors for the members and bases are called. Destructors for elements of an array are called in reverse order of their construction (see 12.6).
Комментариев нет:
Отправить комментарий