Recently I was working on a project that involved passing arguments by value in C++ and something strange was happening when trying to access the argument fields. The code looked like this:
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);
}
The Topology class looks like this (it does not have a copy constructor, so I assume it will be generated automatically by the compiler and will be a shallow one, only copying the pointer address, not the data inside):
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;
}
The Architecture class is the following:
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);
}
Finally, the Parallelization class:
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]
}
}
Shortly, I have a Topology object that gets passed to the Architecture and then to the Parallelization class and there I want to see the internal values from the topology sizes
vector. Every time the object is passed by value the implicit copy constructor is called and copies only the dim
field and the address of the sizes
field, not the whole vector. I wonder why I receive different values, because the vector is still in memory, so it should print the same values.
I mention that if I implement a deep copy-constructor inside the Topology class it works just fine, or if I send the top
object by reference.
Am I missing something? What could be the cause of this behavior?