gpt4 book ai didi

c++ - shared_ptr 在 if 条件下如何工作

转载 作者:可可西里 更新时间:2023-11-01 15:50:23 25 4
gpt4 key购买 nike

在 C++ 中,我可以这样写:

shared_ptr<A> a_sp = someFunctionReturningSharedPtr();
if (a_sp) {
cout << a_sp->someData << endl;
} else {
cout << "Shared Pointer is NULL << endl;
}

为什么 if (a_sp) 检查工作正常? a_sp 不是 bool 值,但如何检查它是真还是假? if 条件如何知道检查 a_sp.get() 函数的结果?或者,如果没有,如何检查 a_spNULL 性? shared_ptr 中是否定义了一些将其转换为 bool 值的函数?

最佳答案

shared_ptr 有一个 operator unspecified-bool-type() const 允许它在 bool 上下文中使用。 unspecified-bool-type 通常定义为指向函数的指针或指向成员函数的指针,以防止意外匹配 bool 函数重载。

C++0x 中,习惯用法是使用 explicit operator bool() const;,它不允许隐式转换(例如函数调用,转换为 int 用于算术等),但仍然允许 shared_ptr 在 bool 上下文中转换为 bool。

关于c++ - shared_ptr 在 if 条件下如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7226801/

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