【发布时间】:2015-02-02 22:35:06
【问题描述】:
我正在为一个结构创建一个 unique_ptr(效果很好):
std::unique_ptr<w9::Product> product (new w9::Product(desc[i].desc, price[j].price));
之后,我将该 unique_ptr 附加到向量成员函数中。
object += product;
重载 += 如下:
void operator+=(std::unique_ptr<Product> const &p) {
object.push_back(&p);
}
问题是最后一点。将唯一 ptr 推回向量上的正确方法是什么?
编辑:
Object 是包含向量作为数据成员的模板类对象。 std::vector 列表
template <typename T>
class List {
std::vector<T> list;
}
在这种情况下,T 将是一个 'unqiue_ptr'。
实际代码:
w9::List<w9::Product> merge(const w9::List<w9::Description> &desc, const w9::List<w9::Price>& price) {
w9::List<w9::Product> priceList;
for(int i = 0; i < desc.size(); i++){
for(int j = 0; j < price.size(); j++){
if(price[j].code == desc[i].code){
std::unique_ptr<w9::Product> product (new w9::Product(desc[i].desc, price[j].price));
product->validate();
priceList += std::move(product);
}
}
}
return priceList;
}
void operator+=(std::unique_ptr<w9::Product> &&p) {
list.push_back(std::move(p));
}
错误:
./List.h:41:12: error: no matching member function for call to 'push_back'
list.push_back(std::move(p));
~~~~~^~~~~~~~~
w10.cpp:18:15: note: in instantiation of member function 'w9::List<w9::Product>::operator+=' requested here
priceList += std::move(product);
^
/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/../include/c++/v1/vector:700:36: note: candidate function not viable: no
known conversion from 'typename remove_reference<unique_ptr<Product, default_delete<Product> > &>::type' (aka 'std::__1::unique_ptr<w9::Product,
std::__1::default_delete<w9::Product> >') to 'const value_type' (aka 'const w9::Product') for 1st argument
_LIBCPP_INLINE_VISIBILITY void push_back(const_reference __x);
【问题讨论】:
-
object的类型是什么?不要让我们猜测。 -
它是一个模板类对象,包含一个向量作为数据成员。 std::vector
列表; -
T是什么?unique_ptr<Product>?或者是其他东西?您的问题需要包含所有相关信息 -
结构的 unique_ptr。我很抱歉。*** 是的,你是对的。
-
当您将
unique_ptr推入向量时,您希望发生什么?请记住,它被称为独特是有原因的。
标签: c++