My code resembles something along these lines.
class A
{
public:
A(int i) { printf("hello %d\n", i); }
~A() { printf("Goodbye\n"); }
}
std::vector(10, A(10));
I notice that hello prints out once. It seems to imply that the vector only allocates space for the element but doesn't construct it. How do I make it construct 10 A objects?
The object is constructed only once, as you pass it to std::vector. Then this object is copied 10 times. You have to do a printf in the copy constructor to see it.
You forgot the copy constructor:
#include <iostream>
#include <vector>
using namespace std;
class A
{
int i;
public:
A(int d) : i(d) { cout << "create i=" << i << endl; }
~A() { cout << "destroy" << endl; }
A(const A& d) : i(d.i) { cout << "copy i=" << d.i << endl; }
};
int main()
{
vector<A> d(10,A(10));
}
Output:
create i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
copy i=10
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With