开发者

GCC error: cannot convert 'const shared_ptr<...>' to 'bool' in return

I'm switching to GCC 4.6.1, and it starts to complain about code which works fine with GCC 4.4 and MSVC10. It seems that it doesn't want to convert between shared_ptr 开发者_运维知识库and bool when returning from a function like this:

class Class { shared_ptr<Somewhere> pointer_; };

bool Class::Function () const
{
    return pointer_;
}

using

return static_cast<bool> (pointer_);

everything works. What the heck is going on? This is with --std=cpp0x.


In C++11, shared_ptr has an explicit operator bool which means that a shared_ptr can't be implicitly converted to a bool.

This is to prevent some potentially pitfalls where a shared_ptr might accidentally be converted in arithmetic expressions and the similar situations.

Adding an explicit cast is a valid fix to your code.

You could also do return pointer_.get() != 0;, return pointer_.get(); or even return pointer_ != nullptr;.


shared_ptr has an explicit bool conversion. It can be used in a conditional expression or can be explicitly converted to bool as you did with static_cast.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜