有沒有辦法創建一個包含N個std::unique_ptr<T>s的向量?GCC v11.2顯示巨大而神秘的錯誤訊息,因此我無法檢測到該問題。
這是我正在嘗試做的 MRE:
#include <iostream>
#include <vector>
#include <memory>
// a dummy struct
struct Foo
{
int m_value;
};
int main( )
{
constexpr auto rowCount { 10uz };
constexpr auto colCount { 20uz };
// a 1D vector of pointers, does not compile
std::vector< std::unique_ptr<Foo> > vec_1D( colCount, std::make_unique<Foo>( ) );
for ( const auto& ptr : vec_1D )
{
std::cout << "Address: " << ptr << " --- value: " << ptr->m_value << '\n';
}
// a 2D vector of pointers, does not compile
std::vector< std::vector< std::unique_ptr<Foo> > >
matrix( rowCount, std::vector< std::unique_ptr<Foo> >( colCount, std::make_unique<Foo>( ) ) );
}
我想我在std::unique_ptr這里遺漏了一些重要的東西。這個錯誤是因為unique_ptr不可復制嗎?
如果上述方法不可行,那還有什么替代方法?
uj5u.com熱心網友回復:
該行:
std::vector< std::unique_ptr<Foo> > vec_1D( colCount, std::make_unique<Foo>( ) );
使用以下向量建構式:
vector( size_type count, const T& value, const Allocator& alloc = Allocator());
它接收給定的值并將其復制到向量的每個元素。從cppreference:
- 用value元素的 count 個副本構造容器 。
因此,您正在呼叫std::make_unique<Foo>(),從該呼叫中獲得std::unique_ptr<Foo>&&回傳,并將其傳遞給std::vector的建構式,以便將其復制。問題是該唯一指標不可復制。
你可以:
- 創建一個給定大小的向量,并且
- 對于向量中的每個元素,
- 創建一個唯一的指標(一次一個),并且
- move 將該唯一指標分配給向量的元素。
下面的示例std::generate用于填充向量。請注意,生成器函式回傳一個std::unique_ptr<Foo>&&可移動分配給每個向量元素的 a。
[演示]
#include <algorithm> // generate
#include <iostream> // cout
#include <memory>
#include <vector>
// a dummy struct
struct Foo
{
Foo() : m_value{value } {}
static inline int value{};
int m_value{};
};
int main( )
{
const size_t count{ 20 };
std::vector<std::unique_ptr<Foo>> v(count);
std::generate(v.begin(), v.end(), []() { return std::make_unique<Foo>(); });
for (auto&& up : v) { std::cout << up->m_value << " "; }
}
// Outputs
//
// 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/419332.html
標籤:
上一篇:將成員函式作為模板引數傳遞
下一篇:如何顯示地圖的地圖(C )?
