繁体   English   中英

为什么 shared_ptr 在 function 中返回时没有隐式转换为 boolean?

[英]Why isn't shared_ptr implicitly converted to boolean when returning it in a function?

以下不会编译:

#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;

标准(我认为)不允许隐式转换的原因可能是什么?

因为用于将std::shared_ptr转换为bool用户定义运算符显式的:

explicit operator bool() const noexcept;

请注意,即使使用明确的用户定义转换运算符到bool ,在if语句的条件下隐式转换为bool除其他外)仍会发生:

std::shared_ptr<int> ptr;

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

}

也就是说,您不需要在if语句的条件下编写static_cast<bool>(ptr)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM