在下面的小程式中,我有兩個使用movewith的例子shared_ptr。
第一個示例的行為與我預期的一樣,并將 的所有權shared_ptr p分配給 new 指標p2。賦值后p是一個無效的指標。
我希望在第二個示例中也會發生同樣的情況,但事實并非如此。精確的問題作為注釋嵌入到源代碼中。我的推理有什么問題?
#include <memory>
#include <iostream>
using namespace std;
void foo(shared_ptr<int>&& p)
{
std::cout << "zoo: " << p.use_count() << "\n";
// when this function terminates, should the destructor of p
// decrement the ref counter and destroy the pointed object?
}
void example1()
{
auto p = make_shared<int>(0);
std::cout << "count before move: " << p.use_count() << "\n";
shared_ptr<int> p2(move(p));
std::cout << "count after move: " << p.use_count() << "\n"; // output 0: ownership transferred to p2
}
void example2()
{
auto p = make_shared<int>(0);
std::cout << "count before move: " << p.use_count() << "\n";
foo(move(p));
std::cout << "count after move: " << p.use_count() << "\n";
// output 1: Why is this not zero?
//Why has ownership not transferred to the argument of the function foo?
}
int main()
{
example1();
example2();
return 0;
}
uj5u.com熱心網友回復:
為什么所有權沒有轉移到函式 foo 的引數上?
因為引數型別foo是 的右值參考,shared_ptr所以不會創建新shared_ptr物件,pinfoo只是對原始物件的參考p,不會移動到任何物件。
如果foo改為按值傳遞,會創建一個新的shared_ptr物件,然后你會發現它p已經被移動了:
void foo(shared_ptr<int> p)
{
//...
}
foo(move(p)); // ownership transferred
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/421518.html
標籤:
