[英]C++ object construction in a multidimensional dynamic array
我正在尝试创建一个nxn对象数组,但我不知道在哪里调用它们的构造函数。 这是我的代码:
class obj {
private: int x;
public: obj( int _x ) { x = _x; }
};
int main( int argc, const char* argv[] ) {
int n = 3; //matrix size
obj** matrix = new obj*[n];
for( int i = 0; i < n; i++ )
matrix[i] = new obj[n];
return 0;
}
如果只需要默认构造函数调用,则代码已经调用它。
对于非默认构造函数,添加嵌套循环,如下所示:
for( int i = 0; i < n; i++ ) {
matrix[i] = new obj[n];
for (int j = 0 ; j != n ; j++) {
matrix[i][j] = obj(arg1, arg2, arg3); // Non-default constructor
}
}
更好的方法是使用obj
std::vector
of obj
如果不需要多态行为,或者如果需要多态行为则使用obj
的智能指针。
如果你真的想要使用低级内存管理,那么你不能 - new
的数组形式不允许你将参数传递给对象的构造函数。 你可以做的最好的事情是让它们默认构造(如果需要的话,在你的类中添加一个构造函数),然后循环并重新分配它们。 这很乏味且容易出错。
我建议使用更高级别的课程; 对于动态数组,使用向量:
std::vector<std::vector<obj>> matrix(n);
for (auto & row : matrix) {
row.reserve(n);
for (size_t i = 0; i < n; ++n) {
row.emplace_back(/* constructor argument(s) here */);
}
}
作为奖励, RAII意味着您不需要自己删除所有分配,并且如果其中任何一个失败,它将不会泄漏内存。
dasblinkenlight已经给出了相当不错的答案,但是,还有第二种方法可以做到更有效率。 因为,如果你这样做(代码取自他的回答)
matrix[i] = new obj[n];
for (int j = 0 ; j != n ; j++) {
matrix[i][j] = obj(arg1, arg2, arg3); // Non-default constructor
}
以下将发生:
分配n
对象的内存。
所有n
对象都是默认构造的。
对于每个对象,在堆栈上自定义构造新对象。
堆栈上的此对象将复制到已分配的对象中。
堆栈上的对象被破坏。
显然远远超过必要的(虽然完全正确)。
您可以使用展示位置新语法来解决此问题:
matrix[i] = (obj*)new char[n*sizeof obj]; //Allocate only memory, do not construct!
for (int j = 0 ; j != n ; j++) {
new (&matrix[i][j]) obj(arg1, arg2, arg3); // Non-default constructor called directly on the object in the matrix.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.