Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector as a class member

Hello I have this question: I would like to have a vector as class member. This is perhaps my question easier for you and I apologize for that.

  • how should I declare the vector? And is this correct? std::vector<int> *myVector; or std::vector<int> myVector ?
  • how should I handle this vector in dealloc?
  • How can I initialize the array into a if?

Is this correct?

if(myCondition)
{
   if(!myVector) //is this correct?
       myVector = new std::vector<int>(); //is this correct? on this i have a error
}
like image 245
Safari Avatar asked Dec 18 '11 17:12

Safari


2 Answers

You most certainly want to use std::vector<int> myVector. No need to initialize it, as it gets automatically initialized in the constructor of your class and deallocated when your class is destroyed.

like image 125
fschoenm Avatar answered Sep 18 '22 14:09

fschoenm


Just use automatic allocation: declare it as a member like this:

class YourClass
{
    std::vector<int> myVector;
    // ...
};

The array gets constructed automatically before any of your constructor is run and is destroyed automatically when your object is deallocated, you don't need to care about it (also, the default copy constructor and assignment operator will handle copying gracefully automatically).

If, instead, you want to create the array only after a particular condition, you have to resort to a (smart) pointer and dynamic allocation, but IMHO it's quite cumbersome (especially because you then have to get right the "big three" - copy constructor, assignment operator, destructor); you could instead simply allocate the vector with automatic allocation and use a separate flag to mark your array as not initialized, or just check if its size is 0.

like image 34
Matteo Italia Avatar answered Sep 20 '22 14:09

Matteo Italia