无法按值从数组中返回unique_ptr元素

时间:2015-07-14 06:09:12

标签: c++ c++11 move-semantics unique-ptr nrvo

以下编译并按预期工作:

std::unique_ptr<char> input_to_char_array()
{
    std::unique_ptr<char> c;
    c.reset(new char('b'));
    // c[1].reset(new char[20]());

    return c;
}

但这并不是:

std::unique_ptr<char> input_to_char_array()
{
    std::unique_ptr<char> c[2];
    c[0].reset(new char('b'));
    c[1].reset(new char('a'));

    return c[0]; // is this considered "return statement's expression is the name of a non-volatile object with automatic storage duration"
}

g ++输出:error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = char; _Dp = std::default_delete<char>]

从某些SO研究Returning unique_ptr from functionsWhy can't I return a unique_ptr from a pair?来看,这似乎与复制省略命名的返回值优化有关。

有人可以确认我的猜测是否正确。如果是这样,复制elison 的标准究竟是什么,以便可以应用 NRVO

0 个答案:

没有答案