空的和空的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
共享相同的控制塊,所以使用count不爲0. 可以說shared_ptr
的所有副本共享相同的nullptr
。非空空shared_ptr
可以與對象的類型(未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
值得注意的是: ** C++ 11§20.7.2.2.1(p16)**「注意:這個構造函數允許創建一個帶有非NULL存儲指針的空'shared_ptr'實例。」另外值得一提的是前面的註釋(p15),「爲了避免懸掛指針的可能性,這個構造函數的用戶必須確保'p'至少在'r'所有權組被破壞之前保持有效。確實很少使用的結構。 – WhozCraig 2014-09-18 19:31:16
@Cubbi'get()'返回'nullptr' *的'shared_ptr' *不管它是否擁有任何東西,都會與nullptr相比。 – 2014-09-18 20:55:27
一個空但非空的''shared_ptr's *可以很有用,以確保一旦所有擁有的指針超出了作用域(即使在例外的情況下!),一些函數就會被執行。不確定,現在是否有專門的課程。 – coldfix 2014-09-18 20:58:39