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*) 是显式的?
基础教程推荐
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 这个宏可以转换成函数吗? 2022-01-01
