Why is unique_ptrlt;Tgt;(T*) explicit?(为什么 unique_ptrlt;Tgt;(T*) 是显式的?)
问题描述
以下函数无法编译:
std::unique_ptr<int> foo()
{
int* answer = new int(42);
return answer;
}
std::unique_ptr<int> bar()
{
return new int(42);
}
我觉得这有点不方便.使 std::unique_ptr<T>(T*)
显式的基本原理是什么?
I find this a bit inconvenient. What was the rationale for making std::unique_ptr<T>(T*)
explicit?
推荐答案
您不希望托管指针隐式地获取原始指针的所有权,因为这可能会导致未定义的行为.考虑一个函数 void f( int * );
和一个调用 int * p = new int(5);f(p);删除 p;
.现在假设有人重构 f
以获取托管指针(任何类型)并且允许隐式转换: void f( std::unique_ptr<int> p );
如果允许隐式转换,您的代码将编译但会导致未定义的行为.
You don't want a managed pointer to grab ownership of a raw pointer implicitly, as that could end up in undefined behavior. Consider a function void f( int * );
and a call int * p = new int(5); f(p); delete p;
. Now imagine that someone refactors f
to take a managed pointer (of any type) and that implicit conversions were allowed: void f( std::unique_ptr<int> p );
if the implicit conversion is allowed, your code will compile but cause undefined behavior.
以同样的方式考虑指针可能甚至不是动态分配的:int x = 5;f( &x );
...
In the same way consider that the pointer might not be even dynamically allocated: int x = 5; f( &x );
...
获取所有权是一项非常重要的操作,最好明确说明:程序员(而不是编译器)知道是否应该通过智能指针管理资源.
Acquisition of ownership is a important enough operation that it is better having it explicit: the programmer (and not the compiler) knows whether the resource should be managed through a smart pointer or not.
这篇关于为什么 unique_ptr<T>(T*) 是显式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 unique_ptr<T>(T*) 是显式的?


- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- C++ 协变模板 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16