简体   繁体   中英

C2057 error on const value definie in constructor inialization list

I'm having a C2057 error (on Visual Studio 2010) and I'm not sure why. I understand that to initialize an array on the stack, the size must be known at compile time which is why you need to use a const value (at least on Visual Studio since variable length array are not permitted like in gcc). I have a const value member in my class and I define his value in the initialization list. So technically, the value is known at compile time right? I'd like to understand why it doesn't work ? Here's a snippet:

class Dummy
{
    Dummy() : size(4096) {}

    void SomeFunction()
    {
        int array[size]; //return C2057 
        //...
    }

    const unsigned int size;
};

Thanks

Unfortunately, this const value is not a compile time constant. You would need an enum, a static integral type, or a C++11 constexpr .

Another option is to make Dummy a class template, taking a non-type parameter:

template <unsigned int SIZE>
class Dummy
{
    void SomeFunction()
    {
        int array[SIZE];
        //...
    }
};

size is const, but it is not known at compile-time to be 4096.

The default constructor creates a Dummy with size 4096, but who says that a Dummy class isn't constructed with a different size? If there was another constructor that allowed a different size, then the compiler could not assume that size was always 4096, so it gives the compile-time error instead.

Having a const data member with the same value for all objects is probably not what you want. If you want to nest a symbolic constant in a class, you have two options:

class Dummy
{
    // ...

    static const unsigned int size = 4096;
    enum { another_size = 4096 };
};

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