[英]C++: dynamically allocating a member array of structs using non-default constructor
如果我有:
struct a_struct
{
int an_int;
a_struct(int f) : an_int(f) {}
a_struct() : an_int(0) {}
};
class a_class
{
a_struct * my_structs;
a_class() {...}
};
我可以:
a_class() {my_structs = new a_struct(1)}
//or
a_class() {my_structs = new a_struct [10]}
但我不能這樣做:
a_class() {my_structs = new a_struct(1) [10]}
//or
a_class() {my_structs = new a_struct() [10]}
有什么正確的語法可以讓它工作嗎? 還是一個簡單的解決方法?
如果使用 STL 是一個選項,您可以使用 std::vector 代替動態數組。
我認為這會起作用:
std::vector<a_struct> my_structs;
my_structs.assign(10, 1);
如果沒有,這應該:
my_structs.assign(10, a_struct(1));
您可以分配 memory 的原始塊並使用placement new來初始化每個struct
:
int number_of_structs = 10;
my_structs = (a_struct*)new unsigned char[sizeof(a_struct) * number_of_structs];
// allocate a raw chunk of memory
a_struct* p = m_structs;
for (int i=0; i<number_of_structs; i++)
{
new (p) a_struct(i);
p++;
}
另請參閱: “放置新”有什么用途?
您可以使用指向指針的指針數組。 然后你可以創建一個數組來保存指向 a_struct() 的指針,這樣你就可以稍后決定使用哪個構造函數:
class a_class {
a_struct ** my_structs;
a_class() { my_structs = new a_struct* [10]}
void foo () {
my_structs[0] = new a_struct(1);
my_structs[5] = new a_struct("some string and float constructor", 3.14);
}
};
您不能直接在任何特定的參數化構造函數上執行此操作。 不管你怎么做,
a_struct *my_struct[10] = {}; // create an array of pointers
for (int i = 0; i < 10; i++)
my_struct[i] = new a_struct(i); // allocate using non-default constructor
當您要取消分配 memory 時,
for (int i = 0; i < 10; i++)
delete my_struct[i] // de-allocate memory
我建議使用std::vector
容器而不是通過這個過程。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.