【发布时间】:2017-07-23 13:44:26
【问题描述】:
当我寻找内存泄漏时,我发现了这个有趣的特性。 我有
class Perseptron :
public Neiron
{
private:
Neiron** neirons;
}
在类的头文件中。
当neirons[i][0] 初始化时,我在调试器中看到neirons[i][1,2...n] 字段在构造函数neirons[i][1,2...n] 初始化之前已经初始化了neirons[i][0] 字段值等值。
neirons = new Neiron*[layerCount];
for (int i=0;i<layerCount;++i)
{
neirons[i] = new Neiron[this->eachLayerCount[i]];
for (int j=0;j<this->eachLayerCount[i];++j)
{
if (i == 0) {
neirons[i][j] = Neiron(2, this->inCount, this->eachLayerCount[i + 1], i, j);
neirons[i][j].inX = this->inX;
}
else if(i!=layerCount-1)
neirons[i][j] = Neiron(2, this->eachLayerCount[i - 1], this->eachLayerCount[i + 1],i,j);
else
neirons[i][j] = Neiron(2, this->eachLayerCount[i - 1], 1,i,j);
}
}
我的Neiron 构造函数:
Neiron::Neiron(int limit,int inCount,int outCount,int layerN,int neironN)
Neiron::Neiron(){}
这是为什么呢?
编辑
MCVE
class Test{
public:
int fieldA;
Test(int a)
{
fieldA = a;//when a=3, why already fieldA=2 ?
}
Test()
{
}
};
int main()
{
int layers[] = { 3,4,2 };
int counter = 0;
Test** test=new Test*[3];
for (int i = 0;i < 3;++i)
{
test[i] = new Test[layers[i]];
for (int j = 0;j < layers[i];++j)
{
test[i][j] = Test(counter);
counter++;
}
}
for (int i = 0;i < 3;++i) delete[] test[i];
delete[] test;
return 0;
}
【问题讨论】:
-
为什么不使用
std::vector? -
@NathanOliver,对我来说,动态内存的工作非常有趣......
-
您是否还在此
for循环之前创建了指针数组?如果不是,那么您可能正在访问触发未定义行为的未分配内存。在创建neirons之前,您不能分配给neirons[i]。 -
@Kos,我刚刚编辑了问题
标签: c++ arrays pointers object dynamic