【发布时间】:2016-07-06 17:55:55
【问题描述】:
我在地图值中使用了 unique_ptr。我需要将这些值作为原始指针的列表/向量。到目前为止,我已经完成了以下工作。
#include <iostream>
#include <string>
#include <vector>
#include <memory>
#include <map>
class Foo {
public:
std::string val;
Foo(std::string v) : val(v) {
}
};
class Unique {
public:
std::map<int, std::unique_ptr<Foo>> unique_map;
std::vector<Foo*> getFoos() {
std::vector<Foo*> foos;
for (auto& it : unique_map) {
foos.push_back(it.second.get());
}
return foos;
}
};
int main() {
Unique unique;
Foo* f1 = new Foo("1");
Foo* f2 = new Foo("2");
unique.unique_map.emplace(1, f1);
unique.unique_map.emplace(2, f2);
std::vector<Foo*> foos = unique.getFoos();
for (Foo* foo : foos) {
std::cout << foo->val;
}
std::cout<<"\n";
return 0;
}
但这无法编译。最相关的错误信息似乎是
"/usr/include/c++/4.8/bits/stl_tree.h:140:49: 注意:无法转换 'std::forward((* & __args#1))'(输入'Foo*')来输入'const std::unique_ptr&'"
但我不确定我是否理解它的含义,因为我的理解是 it.second 返回一个对 unique_ptr 的引用,而不是它自己假设问题所在的 Foo 实例。需要做什么来修复这个例子?
编辑 我使用的是较旧的 g++ 版本。
g++ (Ubuntu 4.8.4-2ubuntu1~14.04.3) 4.8.4
使用命令行。
g++ -std=c++11 -o unique unique.cpp
【问题讨论】:
-
为我编译。
g++ (GCC) 6.1.1 20160602,没有额外的标志。 -
有趣。所以它可能是一个编译器错误?刚刚添加了我的编译器详细信息。
-
Clang++ 也接受它(当给定
-std=c++11时)。clang version 3.8.0 (tags/RELEASE_380/final. -
@chamibuddhika 它不是编译器错误。如果它编译,那么这是一个错误。
-
@Thomas 在您测试代码的版本中,
unique_ptr构造函数不是显式的。将原始指针隐式转换为 smart_pointer 是一项危险的业务
标签: c++ c++11 smart-pointers