在复制构造函数中分配和初始化

Both allocate and initialize in copy constructor

本文关键字:初始化 分配 复制 构造函数      更新时间:2023-10-16

在下面的代码中,我如何同时分配和初始化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

如果在堆上分配数组,则不可能初始化所有元素,但如果在堆栈上分配数组,则可以初始化所有元素。我的建议是,如果你坚持使用数组,那么使用你现有的代码,因为它是缓存友好的,几乎不需要任何时间来执行。你可以在这里和这里找到一些有趣的答案。