【问题标题】:Why must a non-const reference be initialized with an lvalue?为什么非 const 引用必须用左值初始化?
【发布时间】: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;
}

【问题讨论】:

标签: c++ c++11 smart-pointers lvalue-to-rvalue


【解决方案1】:

这样你就不必做你正在与之抗争的事情的写法是: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 的结果是一个右值。

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

【讨论】:

    猜你喜欢
    • 2013-07-20
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-11-30
    • 1970-01-01
    • 2019-06-14
    • 1970-01-01
    • 2020-05-31
    相关资源
    最近更新 更多