Are there two MyVec‘s being created? Does a temporarty, default constructed, MyVec exist before the assinment in Foo‘s constructor?
struct Foo {
typedef std::vector<int> MyVec;
Foo () {
// determine how big the vector needs to be.
// .....
m_vec = MyVec(12);
}
MyVec m_vec;
};
I know I can do it using pointers.
struct Foo {
typedef std::vector<int> MyVec;
Foo () {
m_vec = new MyVec();
}
~Foo () {
delete m_vec;
}
MyVec * m_vec;
};
But I’d like to avoid that if possible.
Edit:
I forgot to mention. I can’t use initializer lists because I need to do stuff in the constructor before the assignment.
Try this syntax instead:
It’s called a c++ member initialization list.
If you need to calculate how big the vector is, perhaps you can do that either before you call the constructor, or in a static method which you call from the constructor:
If those are impossible too, then a cheaper solution than your original post is: