空のshared_ptrとnullのshared_ptrに違いはありますか?
空にshared_ptrは制御ブロックがなく、その使用カウントは0と見なされます。空のコピーshared_ptrは別の空shared_ptrです。それらは両方とも別個shared_ptrのものであり、共通の制御ブロックを持っていないため、それを共有しません。空shared_ptrは、デフォルトのコンストラクターまたはnullptr。
空でないnullにshared_ptrは、他shared_ptrのsと共有できる制御ブロックがあります。空でないヌルのコピーがshared_ptrあるshared_ptrオリジナルと同じ制御ブロックその共有shared_ptrの使用回数は0ではないので、それはのすべてのコピーと言うことができるshared_ptrシェアは同じnullptr。空でないnullshared_ptrは、オブジェクトのタイプのnullポインタを使用して構築できます(nullptr)
次に例を示します。
#include <iostream>
#include <memory>
int main()
{
std::cout << "std::shared_ptr<int> ptr1:" << std::endl;
{
std::shared_ptr<int> ptr1;
std::cout << "\tuse count before copying ptr: " << ptr1.use_count() << std::endl;
std::shared_ptr<int> ptr2 = ptr1;
std::cout << "\tuse count after copying ptr: " << ptr1.use_count() << std::endl;
std::cout << "\tptr1 is " << (ptr1 ? "not null" : "null") << std::endl;
}
std::cout << std::endl;
std::cout << "std::shared_ptr<int> ptr1(nullptr):" << std::endl;
{
std::shared_ptr<int> ptr1(nullptr);
std::cout << "\tuse count before copying ptr: " << ptr1.use_count() << std::endl;
std::shared_ptr<int> ptr2 = ptr1;
std::cout << "\tuse count after copying ptr: " << ptr1.use_count() << std::endl;
std::cout << "\tptr1 is " << (ptr1 ? "not null" : "null") << std::endl;
}
std::cout << std::endl;
std::cout << "std::shared_ptr<int> ptr1(static_cast<int*>(nullptr))" << std::endl;
{
std::shared_ptr<int> ptr1(static_cast<int*>(nullptr));
std::cout << "\tuse count before copying ptr: " << ptr1.use_count() << std::endl;
std::shared_ptr<int> ptr2 = ptr1;
std::cout << "\tuse count after copying ptr: " << ptr1.use_count() << std::endl;
std::cout << "\tptr1 is " << (ptr1 ? "not null" : "null") << std::endl;
}
std::cout << std::endl;
return 0;
}
出力:
std::shared_ptr<int> ptr1:
use count before copying ptr: 0
use count after copying ptr: 0
ptr1 is null
std::shared_ptr<int> ptr1(nullptr):
use count before copying ptr: 0
use count after copying ptr: 0
ptr1 is null
std::shared_ptr<int> ptr1(static_cast<int*>(nullptr))
use count before copying ptr: 1
use count after copying ptr: 2
ptr1 is null
http://coliru.stacked-crooked.com/a/54f59730905ed2ff
shared_ptrと、NULL以外の格納ポインターを使用して空のインスタンスを作成できます。」また、前述の注記(p15)に言及する価値があります。「ダングリングポインタの可能性を回避するために、このコンストラクタのユーザーはp、少なくともの所有権グループrが破棄されるまで、それが有効なままであることを確認する必要があります。」確かにめったに使用されない構造。