[英]C++ Class destructor
How do I delete map<char, map<char, char>> board_game
, map<int, char> X_index
and list<Node*>
?如何删除map<char, map<char, char>> board_game
、 map<int, char> X_index
和list<Node*>
?
How would I write a proper destructor for the classes Tree
, Node
and Boardgame
?我将如何为类Tree
、 Node
和Boardgame
编写适当的析构函数?
class Search_tree {
Node* root = nullptr;
char playerColor;
list<Node*> leaveNodes;
// Constructor, functions ...
~ Search_tree(); <--?
}
class Node {
Board_game* currentBoard = nullptr;
Node* parent = nullptr;
list<Node*> childs;
// Constructor, functions ...
~Node(); <--?
}
class Board_game {
public:
// Boardgame
map<char, map<char, char>> board_game;
map<int, char> X_index;
map<int, char> Y_index;
// Figures
Position figures[8];
// Constructor, functions ...
~Board_game(); <--?
}
struct Position {
char x;
char y;
};
You need to decide who owns what.你需要决定谁拥有什么。 Then you should turn those "owning" raw pointers into std::unique_ptr
and then you won't need hand-written destructors.然后你应该把那些“拥有”的原始指针变成std::unique_ptr
然后你就不需要手写的析构函数了。 A possible ownership structure might be:可能的所有权结构可能是:
class Search_tree {
std::unique_ptr<Node> root;
char playerColor;
list<Node*> leaveNodes;
}
class Node {
Board_game* currentBoard = nullptr;
Node* parent = nullptr;
list<std::unique_ptr<Node>> childs;
}
Since Board_game
does not contain any raw pointers, it already doesn't need a hand-written destructor.由于Board_game
不包含任何原始指针,它已经不需要手写的析构函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.