最近我正在研究一个项目,该项目涉及在C ++中按值传递参数,并且在尝试访问参数字段时发生了一些奇怪的事情。代码看起来像这样:
int main (){
int sizes[] = {2, 3};
Topology top;
top.set_dim(2); // 2D topology
top.set_sizes(sizes); // 2 rows and 3 columns
Architecture arch;
arch.set_topology(top);
}
拓扑类看起来像这样(它没有复制构造函数,所以我假设它将由编译器自动生成,并且将是浅层的,只复制指针地址,而不是内部数据):
class Topology {
public:
Topology();
~Topology();
void set_dim(int);
void set_sizes(int*);
int get_dim();
int* get_sizes();
private:
int dim;
int *sizes;
};
Topology::Topology(){
}
Topology::~Topology(){
if (sizes != NULL)
delete sizes;
}
void Topology::set_dim(int dim_){
dim = dim_;
}
void Topology::set_sizes(int *sizes_){
sizes = new int[dim];
for (int i = 0; i < dim; i++){
sizes[i] = sizes_[i];
}
}
int Topology::get_dim(){
return dim;
}
int* Topology::get_sizes(){
return sizes;
}
Architecture类如下:
class Architecture {
public:
Architecture();
~Architecture();
void set_topology(Topology top);
private:
Parallelization p;
};
Architecture::Architecture(){
}
Architecture::~Architecture(){
}
Architecture::set_topology(Topology top){
p.set_topology(top);
}
最后,Parallelization类:
class Parallelization{
public:
Parallelization();
~Parallelization();
void set_topology(Topology top);
private:
};
Parallelization::Parallelization(){
}
Parallelization::~Parallelization(){
}
void Parallelization::set_topology(Topology top){
int *s = top.get_sizes();
for (int i = 0; i < top.get_dim(); i++){
std::cout << s[i] << " "; // here it prints different numbers, like the vector was never initialized [23144, 352452]
}
}
很快,我有一个拓扑对象被传递给架构,然后传递给Parallelization类,我希望看到拓扑sizes
向量的内部值。每次按值传递对象时,都会调用隐式复制构造函数,并仅复制dim
字段和sizes
字段的地址,而不是整个向量。我想知道为什么我会收到不同的值,因为向量仍然在内存中,所以它应该打印相同的值。
我提到如果我在拓扑类中实现了深层复制构造函数,它可以正常工作,或者我通过引用发送top
对象。
我错过了什么吗?这种行为可能是什么原因?