相关疑难解决方法(0)

为什么我不能将unique_ptr push_back到向量中?

这个程序有什么问题?

#include <memory>
#include <vector>

int main()
{
    std::vector<std::unique_ptr<int>> vec;

    int x(1);
    std::unique_ptr<int> ptr2x(&x);
    vec.push_back(ptr2x); //This tiny command has a vicious error.

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误:

In file included from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/mingw32/bits/c++allocator.h:34:0,
                 from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/allocator.h:48,
                 from c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/memory:64,
                 from main.cpp:6:
c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h: In member function 'void __gnu_cxx::new_allocator<_Tp>::construct(_Tp*, const _Tp&) [with _Tp = std::unique_ptr<int>, _Tp* = std::unique_ptr<int>*]':
c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/stl_vector.h:745:6:   instantiated from 'void std::vector<_Tp, _Alloc>::push_back(const value_type&) [with _Tp = std::unique_ptr<int>, _Alloc = std::allocator<std::unique_ptr<int> >, value_type = std::unique_ptr<int>]'
main.cpp:16:21:   instantiated from here
c:\mingw\bin\../lib/gcc/mingw32/4.5.0/include/c++/bits/unique_ptr.h:207:7: error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::unique_ptr(const …
Run Code Online (Sandbox Code Playgroud)

c++ stl smart-pointers unique-ptr c++11

192
推荐指数
2
解决办法
13万
查看次数

使用std :: make_unique的push_back或emplace_back

基于在回答这些 问题 在这里,我知道这肯定是最好使用C++ 14的std::make_unique,而不是emplace_back(new X)直接.

那就是说,打电话是首选

my_vector.push_back(std::make_unique<Foo>("constructor", "args"));
Run Code Online (Sandbox Code Playgroud)

要么

my_vector.emplace_back(std::make_unique<Foo>("constructor", "args"));
Run Code Online (Sandbox Code Playgroud)

也就是说,我应该使用push_backemplace_back何时添加std::unique_ptr构造的std::make_unique

====编辑====

为什么?c:< - (微笑)

c++ stdvector unique-ptr c++11 c++14

17
推荐指数
1
解决办法
6435
查看次数

用什么代替std :: map :: emplace?

对于std::map< std::string, std::unique_ptr< Foo >>像这样的容器emplace(),从gcc 4.7.2开始,它似乎还没有在stdc ++中实现.

不幸的是,我无法直接按值存储Foo,因为它是一个抽象的超类.

作为一个简单但效率低下的占位符,我刚刚std::map< std::string, Foo* >std::vector< std::unique_ptr< Foo >>垃圾收集一起使用.

你有一个临时解决方案,一旦emplace()可用,效率更高,更容易更换吗?

c++ std c++11

4
推荐指数
1
解决办法
5665
查看次数

标签 统计

c++ ×3

c++11 ×3

unique-ptr ×2

c++14 ×1

smart-pointers ×1

std ×1

stdvector ×1

stl ×1