Initialization of vector in a constructor - C++

烂漫一生 提交于 2019-12-13 07:40:20

问题


I'm struggling with the constructor of one of my classes do to a member that is not initialized properly.

I have a class "Settings" that handles the setting I use for my simulations and a class Simulations that performs the simulation steps.

What I can't understand is why this code doesn't work as expected:

      class Settings{ 
         public: 
           int n ; // a number I need to create properly a vector in my class simulation
           // ... rest of the code constructors etc to read values from files.
           // everything works fine and the values are assigned properly
       }

       class Simulation{
          public:
          std::vector<int> v ;
          Settings *SP;

          Simulation(Settings *);
        }

        Simulation::Simulation(Settings *pS) 
           :SP(pS), v(std::vector<int>(SP->n,0)) {}    // the constructor doesn't work,
    // v is initialized but it is not created as a vector of size n, but 0.

I think there is a problem in the way I use the constructor but I can't understand why.

By the way defining v inside the curly brackets works fine, I'm just curious to know why defining it the proper way doesn't work as expected!

Thanks a lot for the help!


回答1:


You don't need the extra vector:

Simulation::Simulation(Settings *pS) 
       :SP(pS), v(SP->n,0) {}

If this doesn't work, this isn't your code. Are you sure SP is declared before v in the class definition? If this also doesn't work, try with pS instead of SP.




回答2:


You've verified that pS->n != 0 prior to instantiating the Simulation, right?

Anyway, I think the line you're looking for in your constructor is:

:SP(pS), v(pS->n, 0) {}

The way you're doing it now is creating a whole std::vector and then copying it to v.




回答3:


Also please make sure you check SP is not null pointer. This will otherwise have a crash.

Simulation::Simulation(Settings *pS) 
   :SP(pS), v(pS != NULL ? pS->n : 0 , 0) {}

This will check for SP not being NULL. this is the case when Simulation(NULL) is used as constructor.




回答4:


You don't need to create an extra vector and use the copy constructor. Just pass the arguments straight to your vector in the member initializer. As another poster mentioned, did you verify that the return of SP->n is actually not 0? If you hardcode some values in, you'll see that it works fine, as below:

#include <iostream>
#include <vector>
using namespace std;

class foo
{
public:
    foo();
    vector<int> vec;
};

int main()
{
    foo obj;
    for(int i=0;i<obj.vec.size();++i) {
        cout << obj.vec[i] << ' ';
    }
    system("pause");
    return 0;
}


foo::foo()
    :vec(vector<int>(10,2))
{

}


来源:https://stackoverflow.com/questions/11821998/initialization-of-vector-in-a-constructor-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!