I would like to be able to call a non-trivial constructor on an object when I use the push_back()
method. Instead, all I have been able to do is pass a shallow copy of an object to the vector. When using regular c-style arrays, the constructor is automatically called when the array is created, but since vectors are dynamic, the object don't exist yet.
How would I go about adding a new, empty object to a vector without having two pointers point to the same memory address? Do I need a copy constructor or an overloaded assignment operator?
Here is some example code that demonstrates my problem:
struct Object
{
int *Pointer;
Object()
{
Pointer = new int;
*Pointer = 42;
}
~Object()
{
delete Pointer;
}
};
int main()
{
std::vector <Object> *Array;
Array = new std::vector <Object>;
// Attempt 1
Array->push_back(Object());
// Attempt 2
{
Object LocalInstance;
Array->push_back(LocalInstance);
}
// Error here because the destructor has already been called for
// LocalInstance and for Object()
delete Array;
return 0;
}