在复制构造函数中分配和初始化
Both allocate and initialize in copy constructor
在下面的代码中,我如何同时分配和初始化pt
。我所知道的是new
分配,但也初始化。
Grid.h
class Grid
{
int nPt;
double* pt;
};
Grid.cpp
Grid::Grid (const Grid& g)
{
pt = new double [nPt];
for (int i=0; i<nPt; ++i)
{
pt[i] = g.pt[i];
}
}
Mat的注释可能暗示:
Grid.h
class Grid
{
public:
Grid (const Grid& g);
std::vector<double> pt;
// ... some more members of your grid?
};
Grid.cpp
Grid::Grid (const Grid& g): pt(g.pt)
{
// ... manage other members if any
}
但是,如果我们考虑到三个规则(如所提到的)π α ντα ρ ε ε)更可能是:
Grid.h
class Grid
{
public:
std::vector<double> pt;
// ... some more members of your grid?
};
Grid.cpp
// (nothing to do)
…如果到目前为止没有其他你想做的Grid
类,那么最好使用一个普通的向量。
BTW:如果您正在搜索nPt
, pt.size()
是您的新朋友:-)
是的,你可以在数组中这样做,但只有在必须的情况下。否则就像其他人建议的那样使用矢量。下面是我的答案:
#include <iostream>
using namespace std;
int main() {
//unitialise == garbage
cout << "*** Unitialised ***n";
int* p1 = new int[3];
for(int i = 0; i < 3; i++)
cout << i << "t" << p1[i] << endl;
// initialise individual elements
cout << "*** Initialise individual elements ***n";
int* p2 = new int[3] { 1, 2, 3 };
for(int i = 0; i < 3; i++)
cout << i << "t" << p2[i] << endl;
// initialise all elements
cout << "*** Initialise all elements ***n";
int* p3 = new int[3] {0};
for(int i = 0; i < 3; i++)
cout << i << "t" << p3[i] << endl;
//initialise all elements stack array
cout << "*** Initialise stack array ***n";
int p4[3] = {0};
for(int i = 0; i < 3; i++)
cout << i << "t" << p4[i] << endl;
delete[] p1;
delete[] p2;
delete[] p3;
return 0;
}
输出如下:
*** Unitialised ***
0 6449456
1 0
2 3277144
*** Initialise individual elements ***
0 1
1 2
2 3
*** Initialise all elements ***
0 0
1 0
2 3277144
*** Initialise stack array ***
0 0
1 0
2 0
如果在堆上分配数组,则不可能初始化所有元素,但如果在堆栈上分配数组,则可以初始化所有元素。我的建议是,如果你坚持使用数组,那么使用你现有的代码,因为它是缓存友好的,几乎不需要任何时间来执行。你可以在这里和这里找到一些有趣的答案。
相关文章:
- 初始化或分配空字符串文字到指向 C 中的 char 的指针或指向 C++ 中 const char 的指针的原因是什么
- 为什么通过指针编译时不能分配 const 初始化
- C++ 手动分配和初始化对象
- 静态分配对象的值初始化
- (为什么)我们可以在初始化中将非静态类成员分配给静态变量吗?
- 分配给已删除/未初始化的对象
- C++初始化列表与分配值
- 动态分配的对象未初始化
- 可视化C++将分配移动到未初始化的对象?
- 如何修复初始化后'stack around variable was corrupted.'变量未更改为分配的值
- 在不放置新运算符的情况下,在预分配的内存上使用虚函数初始化对象 - 这可能吗?如果没有,为什么
- 在 C++ 中初始化后的数组分配
- 将已初始化的基类分配给派生类
- 初始化原子指针是原子的吗?如果初始化或内存分配引发,会发生什么情况?
- 当您通过分配初始化C 对象时会发生什么
- 指向未由对象地址初始化的对象的指针如何将值分配给类的数据成员
- 将空初始化器列表分配给现有向量或地图的效果
- 为什么支撑初始化分配分配填充垃圾变量
- 课堂初始化(分配样式)与构造函数性能
- 如何在构造函数中初始化分配的堆可变量