Posts

Showing posts with the label destructor

Avoid infinite recursion in destructor

7 1 As part of an exercise my university has tasked me with, I have written a small Graph implementation, following this header. class Node { private: std::string name; std::vector<Node*> children; public: Node(const std::string& name=""); virtual ~Node(); } When writing code for the destructor ~Node() , I noticed that my implementation fails when the graph contains a cycle. This is my implementation so far, which obviously doesn't work if the graph contains a cycle. Node::~Node() { for (Node* n : children) { delete n; n = NULL; } children.clear(); } I am uncertain as to how I would most elegantly write a destructor that can handle cycles in the graph? Please note that I was specifically tasked ...

Destructor of typedef alias

#include <iostream> struct A { ~A(); }; A::~A() { std::cout << "Destructor was called!" << std::endl; } typedef A AB; int main() { AB x; x.AB::~AB(); // Why does this work? x.AB::~A(); } The output of the above program is: Destructor was called! Destructor was called! Destructor was called! I assume the first two lines belonging to user destructor calls, while the third line is due to the destructor being called when exiting the scope of main function. From my understanding a typedef is an alias for a type. In this case AB is an alias for A. Why does this apply for the name of the destructor too? A reference to the language specification is very much appreciated. Edit: This was compiled using Apple LLVM version 9.1.0 (clang-902.0.39.1) on macOS High Sierra Version 10.13.3. Why does this apply for the name of the destructor too? Because standard says: [class.dtor] In an explicit destructor call, the destructor is specified by a ~ ...