开发者

How does shared_ptr work in if condition

开发者 https://www.devze.com 2023-03-31 04:45 出处:网络
In C++, I can write something like: shared_ptr<A> a_sp = someFunctionReturningSharedPtr(); if (a_sp) {

In C++, I can write something like:

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

Why does if (a_sp) check work correctly? a_sp is not a boolean, but how is开发者_如何学Python it checked for true or false? How does the if condition know to check the result of a_sp.get() function? Or if it does not, how is the NULLity of the a_sp checked? Is there some function in shared_ptr defined that converts it to boolean value?


shared_ptr has an operator unspecified-bool-type() const that allows it to be used in boolean contexts. The unspecified-bool-type is typically defined as a pointer to function, or pointer to member-function, to disallow accidental matching to bool function overloads.

In C++0x the idiom is to use explicit operator bool() const;, which disallows implicit conversions (such as function calls, conversions to int for arithmetic, and so on), but still allows the shared_ptr to be converted to bool in boolean contexts.


shared_ptr has operator bool(), which returns true if it is not empty.

For example, this is Microsoft implementation of shared_ptr::operator bool(): http://msdn.microsoft.com/en-us/library/bb982901.aspx

shared_ptr::operator boolean-type - Tests if an owned resource exists.

0

精彩评论

暂无评论...
验证码 换一张
取 消