动态分配数组时设置Ctor参数
Setting Ctor params when dynamically allocating an array
我正在尝试动态分配对象数组。我的每个对象在构造函数中有一个必须初始化的参数。我更喜欢在构造时初始化它们,因为我认为这样可以节省时间。如何在分配时使用需要参数的构造函数初始化动态分配对象的数组?
class Thingy{
private:
int* a;
public:
Thingy(int size);
};
class ThingyLayer{
private:
Thingy* m_things;
public:
ThingyLayer(int n){
m_things = new Thingy[n]; //!< How do I pass a param here to the ctor of Thingy
}
};
在这种情况下我宁愿不使用std::vector
,因为有一天我可能想在不支持STL的嵌入式系统上运行它,比如Atmel AVR芯片。所以我正在寻找如何做到这一点与指针。
我已经尝试过了,m_things = new Thingy[n](val)
,但这不起作用,因为它会引发编译器警告。我还查看了动态分配对象数组,但这并没有回答我的问题。
c++的方法是std::vector
(和我不相信你,你真的有一个很好的理由使用指针代替好吧,你命名了一个原因,我不能真正判断如果它是一个很好的,因为我没有嵌入式系统的知识):
class ThingyLayer{
private:
std::vector<Thingy> m_things;
public:
ThingyLayer(int n) : m_things(n,val){}
};
这也使您避免了手动new
和delete
的痛苦,这不是一件有趣的事情。
std::vector
还附带了一大堆其他整洁的功能,如果您不熟悉它,请查看我链接的手册页。
您可以使用:
ThingyLayer(int n){
char* temp = new char[sizeof(Thingy)*n];
for (int i = 0; i < n; ++i )
{
// Use placement new to construct Thingy objects.
new (temp+i*sizeof(Thingy)) Thingy(10); // Assuming 10 here.
}
m_things = reinterpret_cast<Thingy*>(temp);
}
我有点犹豫,因为Thingy
的对齐要求是char
不同的。我不确定这会如何影响代码的行为。
如果你遵循这条路径,ThingyLayer
的析构函数也必须精心制作。
class ThingyLayer
{
private:
int m_n;
Thingy* m_things;
public:
ThingyLayer(int n) : m_n(n) {
char* temp = new char[sizeof(Thingy)*n];
for (int i = 0; i < n; ++i )
{
// Use placement new to construct Thingy objects.
new (temp+i*sizeof(Thingy)) Thingy(10); // Assuming 10 here.
}
m_things = reinterpret_cast<Thingy*>(temp);
}
~ThingyLayer()
{
for (int i = 0; i < m_n; ++i )
{
// Call the destructor of Thingy explicitly.
m_things[i].~Thingy();
}
// Now deallocate the memory using a char*.
char* temp = reinterpret_cast<char*>(m_things);
delete [] temp;
}
// Make sure to implement copy constructor and copy assignment
// operator properly. If you use the default copy constructor and
// copy assignment operator, the program will exhibit undefined
// behavior.
ThingyLayer(ThingyLayer const& copy) { ... }
ThingyLayer& operator=(ThingyLayer const& rhs) { ... }
};
深入阅读:什么是三法则?
相关文章:
- 如何反转整数参数包
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 为什么在 ctor 的参数列表中将成员"x"的类型替换为"decltype(x)"会破坏类模板参数推导?
- 模板 ctor 类型推导不起作用(没有匹配的构造函数用于初始化 ...)与函数<>参数
- 委派的 ctor 是否受参数计算顺序的影响?
- 如果每个参数都可以转换为特定类型,则启用 ctor
- C++内部类 ctor 和参数
- 通过ctor-rvale参数进行Lambda赋值
- 当使用类型为"类&&"的变量作为参数时,为什么调用复制 ctor 而不是移动 ctor
- c++友元类作为ctor的参数
- 插入>>运算符重载:从 CIN 检索对象的 CTOR 参数时的异常处理
- 根据模板参数启用模板 Ctor
- C++使用 ctor 参数在类中实例化类
- 在Ctor调用中,将std::initializer_list与括号内的参数分离
- std::array 作为字段的语法是什么,里面的对象必须使用接受参数的 ctor 构造
- 同时在另一个类中创建类的对象,该类仅具有参数化的 Ctor "error: x is not a type"
- c++ 11: bind std::sort用于用户定义的类型,然后使用该绑定作为ctor的参数
- 为什么"std::p air"将"std::tuple"作为ctor参数类型而不是"const std::tuple&"?
- 为什么分配器类型作为模板参数而不是 ctor 的参数?
- 动态分配数组时设置Ctor参数