Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ class member initialized twice

Tags:

c++

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.

like image 693
Ilia Choly Avatar asked Feb 18 '23 06:02

Ilia Choly


1 Answers

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; 
};
like image 150
ChrisW Avatar answered Feb 26 '23 17:02

ChrisW