我在下面有這個示例代碼。我對RVO(返回值優化)知之甚少,在優化期間如何跳過複製構造函數和賦值運算符,並將值直接放回到左側的內存中。因此,如果共享指針執行RVO,共享指針如何知道何時增加其計數器?由於某種原因,我認爲共享指針類會根據所創建的副本或賦值數量知道何時增加計數器。按值傳遞時,shared_ptr如何增加計數器?
#include <iostream>
#include <memory>
using namespace std;
class A{
public:
A(){}
A(const A& other){ std::cout << " Copy Constructor " << std::endl; }
A& operator=(const A&other){
std::cout << "Assingment operator " << std::endl;
return *this;
}
~A(){
std::cout << "~A" << std::endl;
}
};
std::shared_ptr<A> give_me_A(){
std::shared_ptr<A> sp(new A);
return sp;
}
void pass_shared_ptr_by_val(std::shared_ptr<A> sp){
std::cout << __func__ << ": count sp = " << sp.use_count() << std::endl;
std::shared_ptr<A> sp1 = sp;
std::cout << __func__ << ": count sp = " << sp.use_count() << std::endl;
std::cout << __func__ << ": count sp1 = " << sp1.use_count() << std::endl;
}
void pass_shared_ptr_by_ref(std::shared_ptr<A>& sp){
std::cout << __func__ << ": count sp = " << sp.use_count() << std::endl;
std::shared_ptr<A> sp1 = sp;
std::cout << __func__ << ": count sp = " << sp.use_count() << std::endl;
std::cout << __func__ << ": count sp1 = " << sp1.use_count() << std::endl;
}
int main(){
{
shared_ptr<A> sp3 = give_me_A();
std::cout << "sp3 count = " << sp3.use_count() << std::endl;
pass_shared_ptr_by_val(sp3);
pass_shared_ptr_by_ref(sp3);
}
return 0;
}
輸出:
SP3計數= 1
pass_shared_ptr_by_val:計數SP = 2
pass_shared_ptr_by_val:計數SP = 3
pass_shared_ptr_by_val:計數SP1 = 3
pass_shared_ptr_by_ref:計數SP = 1
pass_shared_ptr_by_ref:計數SP = 2
pass_shared_ptr_by_ref:計數SP1 = 2
〜甲
如果執行RVO,則共享指針不需要增加引用計數,因爲不會執行副本。我不確定你的問題是什麼。你會期望什麼輸出? – TartanLlama
@TartanLlama我認爲RVO發生在傳遞值以及..因此複製構造函數不會被調用..但我錯了......當通過值複製構造函數確實被調用,因此計數器增加。我認爲我的疑問現在很清楚 – solti