为什么unique_ptr< T>(T *)是显式的? [英] Why is unique_ptr<T>(T*) explicit?

查看:121
本文介绍了为什么unique_ptr< T>(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); delete 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&lt; T&gt;(T *)是显式的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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