为什么非常量引用必须用左值初始化?
Why must a non-const reference be initialized with an lvalue?
这是导致 C2664 错误的代码片段:
cannot convert argument 1 from 'std::unique_ptr<Component,std::default_delete<_Ty>>' to 'ComPtr &'
那么为什么非常量引用必须用左值初始化?除了声明一个新变量之外,如何避免这种情况?
#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;
}
写这篇文章的方法是:https://godbolt.org/g/vceL4q
#include <memory>
#include <list>
using namespace std;
class Component {
};
using ComPtr = unique_ptr<Component>;
using ComList = list<ComPtr>;
ComList coms;
void addComponent(ComPtr c) { // <== change here
coms.push_back(std::move(c)); // and here
}
int main() {
addComponent(make_unique<Component>());
return 0;
}
addComponent 中的 c
将通过移动构造函数创建,因为 make_unique 的结果是右值。
最好以这种方式按值传递大型(移动友好)数据结构。
这是导致 C2664 错误的代码片段:
cannot convert argument 1 from 'std::unique_ptr<Component,std::default_delete<_Ty>>' to 'ComPtr &'
那么为什么非常量引用必须用左值初始化?除了声明一个新变量之外,如何避免这种情况?
#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;
}
写这篇文章的方法是:https://godbolt.org/g/vceL4q
#include <memory>
#include <list>
using namespace std;
class Component {
};
using ComPtr = unique_ptr<Component>;
using ComList = list<ComPtr>;
ComList coms;
void addComponent(ComPtr c) { // <== change here
coms.push_back(std::move(c)); // and here
}
int main() {
addComponent(make_unique<Component>());
return 0;
}
addComponent 中的 c
将通过移动构造函数创建,因为 make_unique 的结果是右值。
最好以这种方式按值传递大型(移动友好)数据结构。