简体   繁体   中英

Constructor initilizer list for a class with multiple arrays (C++11 is ok, boost and std::vector are not)

I don't understand the new C++11 syntax yet for initializing an array in a constructor initilizer list. I'm no longer stuck with C++03 but I can't use boost or std::vector because of program constraints.

An instance of FOO must be sized by the constructor call and behave as though the sizes of x and y were statically known. Does the new C++11 features allow this?

I'm not sure if or how std::initializer_list<> can help.

class FOO
{
public:
    // this constructor needs to size x = count and y = count * 4
    FOO(int count) : 
    {
        // interate over x and y to give them their initial and permenent values
    }
private:
    const BAR x[];
    const TAR y[];
};

#include "foo.h"
void main(void)
{
    // both need to work as expected
    FOO alpha(30);
    FOO * bravo = new FOO(44);
}

You can't do what you're trying to do. The sizes of arrays must be compile-time constants. And while the values provided to the constructors in your particular use cases may be compile-time constants, C++ can't know that.

Furthermore, as a statically-typed language, C++ requires being able to compute the size of the class at compile-time. sizeof(Foo) needs to have an exact, single value. And your's can't.

Initializer lists aren't going to help you. You want two runtime-sized arrays; that's what std::vector is for. If you want compile-time sized arrays, you need to use a template type:

template<int count>
class FOO
{
public:
    FOO(initializer_list<Whatever> ilist)
    {
        // interate over x and y to give them their initial and permenent values
    }

private:
    const BAR x[count];
    const TAR y[count * 4];
};

#include "foo.h"
void main(void)
{
    // both need to work as expected
    FOO<30> alpha;
    FOO<44> * bravo = new FOO<44>;
}

Besides the answer from Nicol Bolas using template parameters to make the size compile-time configurable, you can also allocate memory on the heap:

class FOO
{
public:
    // this constructor needs to size x = count and y = count * 4
    FOO(int count) : x(new BAR[count]), y(new TAR[count])
    {
        // interate over x and y to give them their initial and permenent values
    }

    // Need a destructor to free the memory we allocated in the constructor
    ~FOO()
    {
        delete [] y;
        delete [] x;
    }
private:
    const BAR* x;
    const TAR* y;
};

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