简体   繁体   中英

What method do you use to initialize member variables?

Suppose I have a class Foo , with a member variable that is a std::vector of floats, bar . I then create an instance of Foo , called foo . Let's say that I do not know the length of bar before the program runs, but at the point when foo 's constructor is called, I know that it's length should be x .

There are three ways I can think of to initialize the length of bar , and I'm just wondering which of the three most people tend to use. I have ranked them in order of what I would consider to be "best practice", but I'm more curious about what method people "actually" use in practice. Sometimes I use methods which make the code clearer to follow, rather than necessarily following best practice...

  1. bar is a private member, and I resize it during foo's constructor, eg Foo foo(x){bar.resize(x)};

  2. bar is a private member, and I call foo.ResizeBar(x) which resizes bar internally, after creating foo .

  3. bar is a public member, and I call foo.bar.resize(x) , after creating foo .

Or, in code:

1.

class Foo
{
private:
    std::vector<float> bar;
public:
    Foo(int x)
    {
        bar.resize(x);
    };
};

int main()
{
    Foo foo(100);
    return 0;
}

2.

class Foo
{
private:
    std::vector<float> bar;
public:
    Foo()
    {
    };
    void ResizeBar(int x)
    {
        bar.resize(x);
    };
};

int main()
{
    Foo foo;
    foo.ResizeBar(100);
    return 0;
}

3.

class Foo
{
public:
    std::vector<float> bar;
    Foo()
    {
    };
};

int main()
{
    Foo foo;
    foo.bar.resize(100);
    return 0;
}

The problem with all three of your methods is that you're needlessly invoking the default initializer for your vector, and then modifying the already initialized vector to suit your needs.

You should be invoking the correct initializer using the initializer list:

Foo::Foo(std::size_t x) : bar(x, 0) { }

The best method is not in the list of options you posted. The best method is to initialize bar using member initializer lists .

Foo::Foo(int x) : bar(x) {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM