Vector of Vector
-
Suppose i have got a struct with vectors inside
struct A { int a; vector b; }; vector b;
Is this safe or do i have to write a copy contructor ?
"Just looking for loopholes." W. C. Fields
American actor, 1880-1946, explaining why he was reading the Bible on his deathbed. -
Suppose i have got a struct with vectors inside
struct A { int a; vector b; }; vector b;
Is this safe or do i have to write a copy contructor ?
"Just looking for loopholes." W. C. Fields
American actor, 1880-1946, explaining why he was reading the Bible on his deathbed.Perfectly safe. The compiler will automatically generate a copy constructor using what's defined by the aggregated objects. Generally, a copy constructor is only needed if the structure contains pointers, and aliasing them would be a bad ideatm. Imagine this scenario:
struct S {
int* p;
S() { p = new int[10]; }
~S() { delete [] p; }
};{
S a;
S b(a);
} // <- when a and b falls out of scope, the ~S() will crash trying
// to delete the same array twice.In cases like this it's necessary to write your own copy constructor which either a) makes a complete copy of the array inside the object being copied from, or b) you implement some reference counting mechanism. There are gigantic semantic differences between the two cases, as you may understand. It's basically a question of "by value" or "by reference". If I chose b), any modification to let's say
a.p[0]
would be visible inb.p[0]
. In your example,std::vector
has a well defined copy constructor. By the way,std::vector
implements "by value" semantics. Anyway, the C++ compiler will always automatically generate a copy constructor if, and only if, you omit one. The generated code would look something like this:A::A(const A& other) : a(other.a), b(other.b) { /* empty */ }
. And how
a
andb
are copied is defined by their copy constructors. -- Gott weiß ich will kein Engel sein.