gpt4 book ai didi

c++ - 为什么 shared_ptr 在函数中返回时没有隐式转换为 boolean 值?

转载 作者:行者123 更新时间:2023-12-03 11:15:03 44 4
gpt4 key购买 nike

以下内容无法编译:

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

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

最佳答案

因为 user-defined operator用于转换 std::shared_ptrbool显式:

explicit operator bool() const noexcept;

请注意,隐式转换为 boolif 的条件下声明 – among others – 即使使用 explicit 用户定义的转换运算符到 bool,仍然会发生:

std::shared_ptr<int> ptr;

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

}

也就是说,你不需要写static_cast<bool>(ptr)if 的条件下声明。

关于c++ - 为什么 shared_ptr 在函数中返回时没有隐式转换为 boolean 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65771392/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com