我应该使用智能指针吗? [英] Should I use a smart pointer?

查看:239
本文介绍了我应该使用智能指针吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类如下:

class node
{
public:

     node* parent;
     std::list<node*> children;
};

我应该使用智能指针而不是原始指针吗?为什么?

Should I use a smart pointer instead of raw pointers? Why? If yes, what kind of smart pointer?

推荐答案

始终在拥有资源(内存,文件等)的任何地方使用智能指针。手动拥有这些内容会非常出错,违反了许多良好做法,例如 DRY

Always use a smart pointer wherever you own resources (memory, files etc). Owning them manually is extremely error prone and violates many good practices, like DRY.

使用哪一个取决于您需要什么所有权语义。 unique_ptr 最适合单一所有权, shared_ptr 共享所有权。

Which one to use depends on what ownership semantics you need. unique_ptr is best for single ownership, and shared_ptr shared ownership.

由于孩子不拥有他们的父母,一个原始的父指针是好的。但是,如果父母拥​​有他们的孩子, unique_ptr 在这里工作最好。

As children do not own their parents, a raw parent pointer is fine. However, if the parents own their children, unique_ptr works best here.

在地球,一个链接的指针列表?这是没有意义的。为什么不是一个值链接的列表?

It's also notable that what on earth, a linked list of pointers? That makes no sense. Why not a linked list of values?

这篇关于我应该使用智能指针吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆