Quando copia gli oggetti, il problema con l'array dichiarato staticamente, che è un membro di un oggetto membro dell'oggetto che viene copiato
Domanda
Ho un vettore di oggetti.Classe A contiene un oggetto membro di tipo B. La classe B contiene una matrice dichiarata staticamente di BOOL.Quando copia un oggetto nel vettore, i valori nell'array BOOL sono persi.Anche se questo non dovrebbe essere un problema perché la gamma di bool è dichiarata staticamente.Devo gestire questo usando un costruttore di copia?
class B
{
public:
bool theArray[5] ;
B(bool x) {theArray[1] = x;};
B(){};
};
class A
{
public:
B obj_B;
A() : obj_B(1) {};
A(A const &origin) : obj_B(origin.obj_B){};
};
int main ()
{
std::vector <A> someAs;
for(int q=0;q<10;q++)
someAs.push_back(A());
for(int q=0;q<10;q++)
std::cout << someAs[q].obj_B.theArray[1] << std::endl;
}
. Soluzione
You shouldn't need to define a copy constructor to do this. I'm not sure what you mean by "static arrays," since there are two meanings, but neither require a copy constructor.
If you mean "array that's statically sized," like this:
class MyClass {
private:
bool myArray[137];
};
Then the default copy constructor will do a memberwise copy of the elements from the object being copied.
If you mean "a static array of bools," like this:
class MyClass {
private:
static bool myArray[137];
};
Then the copy constructor won't touch this array because it's shared across all instances of the class.
If your array of bool
s is getting corrupted, you might have a memory corruption bug on your hands, perhaps by reading off the end of an array or dereferencing a bad pointer. I'd look into this, since the default copy behavior will indeed give you what you want.