在C ++ 14中new和delete仍然有用吗? [英] Are new and delete still useful in C++14?
问题描述
考虑到 make_unique
和 make_shared
的可用性,以及 unique_ptr
和 shared_ptr
析构函数的自动删除功能,在C ++ 14中使用 new
和 delete
的情况(除了支持旧版代码的情况)是什么?
Given availability of make_unique
and make_shared
, as well as automatic deletion by unique_ptr
and shared_ptr
destructors, what are the situations (apart from supporting legacy code) for using new
and delete
in C++14?
推荐答案
尽管在许多情况下,智能指针优于原始指针,但 new
/仍然有很多用例在C ++ 14中删除
.
While smart pointers are preferable to raw pointers in many cases, there are still lots of use-cases for new
/delete
in C++14.
如果您需要编写任何需要就地构建的内容,例如:
If you need to write anything that requires in-place construction, for example:
- 内存池
- 分配器
- 带标签的变体
- 二进制消息到缓冲区
您将需要使用展示位置 new
,并且可能需要使用 delete
.没办法.
you will need to use placement new
and, possibly, delete
. No way around that.
对于某些要编写的容器,您可能需要使用原始指针进行存储.
For some containers that you want to write, you may want to use raw pointers for storage.
甚至对于标准智能指针,如果要使用自定义删除器,则仍然需要 new
,因为 make_unique
和 make_shared
不允许这样做.
Even for the standard smart pointers, you will still need new
if you want to use custom deleters since make_unique
and make_shared
don't allow for that.
这篇关于在C ++ 14中new和delete仍然有用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!