【发布时间】:2018-08-14 04:04:42
【问题描述】:
这是一段导致 C2664 错误的 sn-p 代码:
无法将参数 1 从 'std::unique_ptr
>' 转换为 'ComPtr &'
那么为什么非 const 引用必须用左值初始化呢?除了声明一个新变量,如何避免这种情况?
#include <memory>
#include <list>
class Component {
};
using ComPtr = unique_ptr<Component>;
using ComList = list<ComPtr>;
ComList coms;
void addComponent(ComPtr&c) {
coms.push_back(c);
}
int main() {
addComponent(make_unique<Component>()); //Error here.
return 0;
}
【问题讨论】:
-
@PaulRooney “编译器允许我们对临时文件进行更改不是一个好主意吗?”这正是 r-value 引用可以让你做的事情。
标签: c++ c++11 smart-pointers lvalue-to-rvalue