![](/img/trans.png)
[英]Convert vector of shared_ptr into the vector of raw pointers in C++
[英]c++: Initialize vector of shared_ptr in constructor as different pointers
這是我所擁有的:
class A
{
A(int i):_i(i){}
private:
int _i;
};
class B
{
B();
private:
std::vector< boost::shared_ptr<A> > _v;
}
我需要用兩個boost::shared_ptr<A>
初始化_v
。
我嘗試了這個:
B::B():_v(2, boost::make_shared<A>(0)){}
但是似乎兩個指針都指向唯一創建的對象-不是我所需要的。
我沒有c++11
所以無法使用:
B::B():_v{boost::make_shared<A>(0), boost::make_shared<A>(0)}{}
對於這種情況最好的解決方案是什么?
將vector
的創建移動到返回vector
的函數中。
復制包含2個元素的shared_ptr
vector
的成本將足夠低,您將不必在意,並且使用NRVO和RVO,即使在C ++ 03中也可以完全優化它。 (在C ++ 11中,如果NRVO和RVO由於某種原因被阻止,它將僅執行移動操作)。
// if you make it a member, make it `static`:
std::vector<boost::shared_ptr<A> > make_vector() {
std::vector<boost::shared_ptr<A> > retval;
retval.push_back( boost::make_shared<A>(0) );
retval.push_back( boost::make_shared<A>(0) );
return retval;
}
B::B():_v( make_vector() ) {}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.