【问题标题】:Why isn't shared_ptr implicitly converted to boolean when returning it in a function?为什么 shared_ptr 在函数中返回时没有隐式转换为布尔值?
【发布时间】:2021-04-22 13:35:07
【问题描述】:

以下内容无法编译:

#include <memory>
class A;
bool f() {
    std::shared_ptr<A> a;
    return a;
}

int main()
{
    f();
    return 0;
}

失败:

Compilation failed due to following error(s).main.cpp: In function ‘bool f()’:
main.cpp:13:12: error: cannot convert ‘std::shared_ptr’ to ‘bool’ in return
     return a;

标准(我推测)不允许在这里进行隐式转换的原因是什么?

【问题讨论】:

标签: c++ boolean shared-ptr implicit-conversion return-type


【解决方案1】:

因为将std::shared_ptr 转换为booluser-defined operator显式

explicit operator bool() const noexcept;

请注意,在if 语句的条件下隐式转换为bool - among others - 即使使用显式 用户定义的转换运算符到bool 时仍然会发生:

std::shared_ptr<int> ptr;

if (ptr) { // <-- implicit conversion to bool

}

也就是说,你不需要在if语句的条件下写static_cast&lt;bool&gt;(ptr)

【讨论】:

    猜你喜欢
    • 2018-02-11
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2018-01-24
    • 2021-02-04
    • 2015-02-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多