Setup std::vector in class constructor

fenkerbb picture fenkerbb · Jul 10, 2012 · Viewed 87.5k times · Source

I'm designing a class that has a std::vector<int> as an instance variable. I'm using a std::vector because I need to set its size at runtime. Here are the relevant portions of my code:

my_class.h:

#include <vector>
using std::vector;
class MyClass {
    int size;
    vector<int> vec;
}

my_class.cc:

#include "my_class.h"
using std::vector
MyClass::MyClass(int m_size) : size(m_size) {
     vec = new vector<int>(size,0);
}

When I attempt to compile I get these error messages:

g++ -c -Wall my_class.cc -o my_class.o

my_class.cc: In constructor ‘MyClass::MyClass(int):

  my_class.cc:4 error: no match for ‘operator=’ in ‘((MyClass*)this)->My_Class::vec = ((*(const allocator_type*)(& std::allocator<int>())), (operator new(24u), (<statement>, ((std::vector<int>*)<anonymous>))))’

make: *** [my_class.o] Error 1

However, when I change the offending line to:

vector<int> temp(size,0);
vec = temp;

It now compiles without a hitch and I get the desired behavior and can access my vector as

vec[i]  // i having been defined as an int yada yada yada

This workaround is okay, but I would like to understand why it works and the first method fails. Thanks in advance.

Answer

Luchian Grigore picture Luchian Grigore · Jul 10, 2012

Just do:

MyClass::MyClass(int m_size) : size(m_size), vec(m_size, 0)

You already seem to know about initializer lists, why not initialize vector there directly?

vec = new vector<int>(size,0);

is illegal because new returns a pointer and in your case vec is an object.

Your second option:

vector<int> temp(size,0);
vec = temp;

although it compiles, does extra work for no gain. By the time you reach the assignment, two vectors would already have been constructed and discarded afterwards.