【发布时间】:2019-02-03 19:16:50
【问题描述】:
我知道,除非真的需要,否则必须避免使用现代 C++ 中的原始指针(或更准确地说是 new 和 delete)。我相信在图形实现方面,指针非常有用。不过,我很高兴听到 cmets 对此的看法。
我在玩二叉搜索树并编写insert 函数。我使用两种不同但相似的方法来实现,一种使用指针,另一种使用指针引用。显然我想更改指针本身(参考 ptr)。想知道它们中的任何一个是否有优点或者不应该使用并且必须使用 const 引用或智能指针(现代方式)编写。
Node *insert_ptr(Node *root, int data)
{
if (root == NULL)
return create(data);
else if (data < root->data)
root->left = insert(root->left, data);
else
root->right = insert(root->right, data);
return root;
}
void insert_ref_to_ptr(Node *&root, int data)
{
if (root == NULL)
root = create(data);
else if (data < root->data)
insert(root->left, data);
else
insert(root->right, data);
}
如果您想试一试,我将在下面提供其余代码。您可能想使用1 3 6 8 10 14 13 4 7 作为输入
struct Node
{
int data;
Node *left;
Node *right;
};
void display(Node *root)
{
if (root != NULL)
{
display(root->left);
cout << root->data << " ";
display(root->right);
}
}
Node *create(int data)
{
Node *node = new Node();
node->data = data;
node->left = node->right = NULL;
return node;
}
int main()
{
Node *root = NULL;
vector<int> nodes;
string line;
int value;
getline(cin, line);
stringstream split(line);
while (split >> value)
nodes.push_back(value);
/*
root = insert_ptr(root, nodes[0]);
for (int i = 1; i < nodes.size(); i++)
insert_ptr(root, nodes[i]);
*/
for (int i = 0; i < nodes.size(); i++)
insert_ref_to_ptr(root, nodes[i]);
display(root);
return 0;
}
【问题讨论】:
-
绝对不是一个好的设计。所有这些函数都应该在类中,左右应该是唯一的指针。
-
你绝对应该避免使用原始指针,除非你 100% 确定你会需要它们。
-
@MatthieuBrucher 绝对正确。但我不关心这里的设计。
-
那么这个问题有什么意义呢?
-
您问的是二叉树、封装还是良好的 C++ 实践?如果你想new/delete,你必须完全封装它。不过,您没有理由在这里进行新建/删除。
标签: c++ pointers reference c++17