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:
struct Foo {
typedef std::vector<int> MyVec;
Foo ()
: m_vec(12)
{
}
MyVec m_vec;
};
It's called a c++ member initialization list.
I can't use initializer lists because I need to do stuff in the constructor before the assignment.
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:
struct Foo {
typedef std::vector<int> MyVec;
Foo ()
: m_vec(calculateVectorSize())
{
}
static int calculateVectorSize()
{
// determine how big the vector needs to be.
// .....
}
MyVec m_vec;
};
If those are impossible too, then a cheaper solution than your original post is:
struct Foo {
typedef std::vector<int> MyVec;
Foo () {
// determine how big the vector needs to be.
// .....
m_vec.resize(12);
}
MyVec m_vec;
};
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