关于新和删除的使用,和Stroustrup的建议 [英] About the usage of new and delete, and Stroustrup's advice

查看:105
本文介绍了关于新和删除的使用,和Stroustrup的建议的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于新的和删除的使用,和Stroustrup的建议...

About the usage of new and delete, and Stroustrup's advice...

他说的东西像(但不完全是,这是从他的书的笔记) :

He says something like (but not exactly, this is from my notes of his book):


一个经验法则是, new 属于构造函数和类似操作, delete 属于析构函数。另外, new 通常用于资源句柄的参数。否则避免使用 new delete ,而是使用资源句柄(智能指针)。

A rule of thumb is that, new belongs in constructors and similar operations, delete belongs in destructors. In addition, new is often used in arguments to resource handles. Otherwise avoid using new and delete, use resource handles (smart pointers) instead.

我想知道更多经验丰富的C ++ 11人是否真的应用了这个。

I was wondering if the more experienced folks with C++11 have really applied this or not.

我的印象是,这似乎是一个很酷的规则。
但是我有可疑,一般规则。在结束
,你将最终使用新的和删除,如有必要。但也许这个规则
是一个很好的指南,我不知道。

My impression of this was, wow this seems like a really cool rule to follow. But then I got suspicious, as for any general rule. At the end of the day you will end up using new and delete wherever necessary. But maybe this rule is a good guideline I don't know.

推荐答案

这是一个伟大的规则。事实上,通过使用适当的 make _ 函数,可以避免在智能指针的参数中使用 new 。例如,而不是:

It's a great rule. In fact, you can avoid using new in arguments to smart pointers by using the appropriate make_ functions. For example, instead of:

std::shared_ptr<int> p(new int(5));

您可以经常:

auto p = std::make_shared<int>(5);

这也有更多的异常安全的好处。虽然 std :: make_unique 目前还不存在,但计划使用C ++ 14(它已经在工作草案中)。如果您现在想要,现在有一些现有实现

This also has the benefit of being more exception safe. While a std::make_unique doesn't yet exist, it is planned to make its way into C++14 (it is already in the working draft). If you want it now, there are some existing implementations.

你可以进一步,甚至避免在构造函数和析构函数中使用 new delete 。如果你总是在智能指针中包装动态分配的对象,即使它们是类成员,你也不需要管理自己的内存。请参阅零规则。这个想法是,实现任何形式的所有权语义不是你的类的责任( SRP ) - 这就是智能指针为。然后,你理论上从来不必写复制/移动构造函数,复制/移动赋值运算符或析构函数,因为隐式定义的函数通常会做适当的事情。

You can go a step further and even avoid using new and delete in constructors and destructors. If you always wrap dynamically allocated objects in smart pointers, even when they're class members, you won't need to manage your own memory at all. See the Rule of Zero. The idea is that it's not the responsibility of your class to implement any form of ownership semantics (SRP) - that's what the smart pointers are for. Then you theoretically never have to write copy/move constructors, copy/move assignment operators or destructors, because the implicitly defined functions will generally do the appropriate thing.

这篇关于关于新和删除的使用,和Stroustrup的建议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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