我正在尝试通过执行以下操作来利用 C++x0 中的 unique_ptr
#include <memory>
并与 -std=c++0x 兼容,但是它会抛出许多错误,这就是一个例子。
/usr/lib/gcc/x86_64-redhat-linux/4.4.4/../../../../include/c++/4.4.4/bits/unique_ptr.h:214: error: deleted function ‘std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = Descriptor, _Tp_Deleter = std::default_delete<Descriptor>]’
更新**** 这就是我想要做的,我已经删除了 typedef,所以你可以清楚地看到类型
static std::unique_ptr<SomeType> GetSomeType()
{
std::unique_ptr<SomeType> st("Data","Data2",false);
std::unique_ptr<OtherType> ot("uniportantconstructor data");
st->Add(ot);
return st;
}
//Public method of SomeType
void Add(std::unique_ptr<OtherType> ot)
{
//otmap is std::map<std::string,std::unique_ptr<OtherType> >
//mappair is std::Pair<std::string,std::unique_ptr<OtherType> >
otMap.Insert(mappair(ot->name(),ot));
}
更新:
如果我的类 SomeType 有一个从 map 返回元素的方法(使用键)说
std::unique_ptr<OtherType> get_othertype(std::string name)
{
return otMap.find(name);
}
这将确保调用者会收到指向映射中的指针而不是拷贝?
最佳答案
std::unique_ptr<OtherType> ot("unimportant constructor data");
st->Add(ot);
您不能将左值传递给接受unique_pointer
的函数,因为unique_pointer
没有复制构造函数。您必须移动左值(将其转换为亡值)或传递纯右值:
// pass an xvalue:
std::unique_ptr<OtherType> ot("unimportant constructor data");
st->Add(std::move(ot));
// note: ot is now empty
// pass a prvalue:
st->Add(std::unique_ptr<OtherType>("unimportant constructor data"));
在 Add
方法中,事情稍微复杂一些。首先,您必须从 ot
移动,因为形式参数始终是左值(因为它们有名称)。其次,您不能从 ot
移动并获取 ot->name()
作为 mappair
函数的参数,因为参数评估的顺序是在 C++ 中未指定。所以我们必须在从 ot
移动之前在单独的语句中获取 ot->name()
:
void Add(std::unique_ptr<OtherType> ot)
{
auto name = ot->name();
otMap.Insert(mappair(name, std::move(ot)));
}
希望这对您有所帮助。请注意,在任何(理智的)情况下,两个 unique_ptr
对象都不能指向同一事物。如果您需要该功能,unique_ptr
不是您想要的。
关于C++x0 unique_ptr GCC 4.4.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3763621/