簡體   English   中英

在 GCC 5.4 中使用初始化列表和 make_unique 創建 unique_ptr 列表失敗

[英]Creating list of unique_ptr using initialization list and make_unique fails in GCC 5.4

我正在使用 GCC 5.4 在 C++ 14 中編譯測試程序。

#include <type_traits>
#include <list>
#include <iostream>
#include <memory>

int main()
{
    int VALUE = 42;
    const auto list_ = {
        std::make_unique<int>(VALUE),
        std::make_unique<int>(0),
        std::make_unique<int>(0)
    };
}

GCC 5.4 失敗並顯示以下錯誤消息:

<source>: In function 'int main()':
<source>:13:5: error: use of deleted function 'std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = int; _Dp = std::default_delete<int>]'
     };
     ^
In file included from /opt/compiler-explorer/gcc-5.4.0/include/c++/5.4.0/memory:81:0,
                 from <source>:4:
/opt/compiler-explorer/gcc-5.4.0/include/c++/5.4.0/bits/unique_ptr.h:356:7: note: declared here
       unique_ptr(const unique_ptr&) = delete;
       ^

相同的代碼可以使用 Clang 3.5 正確編譯。 https://godbolt.org/z/PM776xGP4

這個問題似乎一直存在,直到它正確編譯的 GCC 9.2。

這是 GCC 9.1 及更低版本中的已知錯誤嗎? 如果是,有沒有辦法使用初始化列表來解決這個問題?

您可以使用:

const std::initializer_list<std::unique_ptr<int>> list{
    std::make_unique< int >( 42 ),
    std::make_unique< int >( 0 ),
    std::make_unique< int >( 0 )
};

演示(舊的 gcc-5.4 測試)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM