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

Posted

技术标签:

【中文标题】在复制构造函数中分配和初始化【英文标题】:Both allocate and initialize in copy constructor 【发布时间】:2014-05-26 14:33:42 【问题描述】:

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

【问题讨论】:

使用std::vector&lt;double&gt;,别再担心这种细节了。 你也忘记初始化 nPt 的值...并在头文件中声明构造函数... 当然相关:***.com/questions/4172722/what-is-the-rule-of-three 【参考方案1】:

comment by 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

但如果我们考虑三的规则(如mentioned by πάντα ῥεῖ)更有可能是这样的:

Grid.h

class Grid

public:
    std::vector<double> pt;
    // ... some more members of your grid?
;

Grid.cpp

// (nothing to do)

...如果到目前为止您对 Grid 类没有其他想要做的事情,那么最好使用普通向量。

顺便说一句:如果您正在搜索 nPtpt.size() 是您的新朋友 :-)

【讨论】:

【参考方案2】:

是的,您可以在数组中这样做,但前提是必须这样做。 否则,请按照其他人的建议选择向量。 这是我在代码中的答案:

#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

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

【讨论】:

以上是关于在复制构造函数中分配和初始化的主要内容,如果未能解决你的问题,请参考以下文章

关于在函数中分配和释放对象的问题

复制构造函数的运用

如何从派生类复制构造函数调用基类复制构造函数? [复制]

c++的复制构造函数

什么时候构造函数称为默认构造函数? [复制]

C++中的复制构造函数