C++x0 unique_ptr GCC 4.4.4

标签 c++ gcc c++11

我正在尝试通过执行以下操作来利用 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/

相关文章:

c++ - 无法理解零规则中的 C++11 语法

c++ - 在函数内释放动态内存

c++ - 使用结构体从 .txt 文件读取着色器

c - 为什么 "+="在 SSE 内在函数中给了我意想不到的结果

c - 与 C 的接口(interface)程序集

c - 如何在 Mac OS X Sierra 中安装 C 头文件?

c++ - 移动构造函数中的深拷贝

c++ - 自动与字符串文字

c++ - 如果 C++ 枚举的 switch 语句中的枚举值 > const N,如何获取?

c++ - 按值返回时不调用应对构造函数