-1

这是导致 C2664 错误的代码片段:

无法将参数 1 从 'std::unique_ptr<Component,std::default_delete<_Ty>>' 转换为 '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;
}
4

1 回答 1

4

编写此内容的方法是: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;
}

in addComponent将c通过移动构造函数创建,因为 make_unique 的结果是一个右值。

最好以这种方式按值传递大型(移动友好)数据结构。

于 2018-08-14T04:14:38.570 回答