編集:賛成ですが、これは正解ではないようです。申し訳ありません:
http://en.cppreference.com/w/cpp/memory/shared_ptr/operator_cmp
template< class T >
bool operator==( const shared_ptr<T>& lhs, std::nullptr_t rhs );
(7) (since C++11)
template< class T >
bool operator!=( const shared_ptr<T>& lhs, std::nullptr_t rhs );
(9) (since C++11)
7) !lhs
9) (ブール)lhs
....壊れた実装?? 本当にわからない。
gcc -std=c++11 でテスト: ( http://en.cppreference.com/w/cpp/memory/weak_ptrから取得し、適応)
#include <iostream>
#include <memory>
std::weak_ptr<int> gw;
void f()
{
auto spt = gw.lock();
if (spt != nullptr) {
std::cout << *spt << "\n";
}
else {
std::cout << "gw is expired\n";
}
}
int main()
{
{
auto sp = std::make_shared<int>(42);
gw = sp;
f();
}
f();
}
期待どおりの出力:
42
gwは期限切れです
他の場所にある必要があります
オリジナル:
つまり、bool としてチェックし、nullptr と比較しないでください (nullptrlhs.get() == rhs.get()
で rhs = shared_ptr で失敗するものを試します):
auto foo_sharedptr = foo_weakptr.lock();
if (foo_sharedptr)
{
// do stuff with foo
}
ドキュメントを参照してください。
#include <iostream>
#include <memory>
#include <thread>
void observe(std::weak_ptr<int> weak)
{
std::shared_ptr<int> observe(weak.lock());
if (observe) {
std::cout << "\tobserve() able to lock weak_ptr<>, value=" << *observe << "\n";
} else {
std::cout << "\tobserve() unable to lock weak_ptr<>\n";
}
}
int main()
{
std::weak_ptr<int> weak;
std::cout << "weak_ptr<> not yet initialized\n";
observe(weak);
{
std::shared_ptr<int> shared(new int(42));
weak = shared;
std::cout << "weak_ptr<> initialized with shared_ptr.\n";
observe(weak);
}
std::cout << "shared_ptr<> has been destructed due to scope exit.\n";
observe(weak);
}