Why do I get these warnings in Visual C++ 2008 when building a struct?

前端 未结 3 782
太阳男子
太阳男子 2021-01-18 10:37

I have this code

typedef struct
{
    const char* fooString;
    const bool  fooBool;
}fooStruct;

And this initializer:

sta         


        
相关标签:
3条回答
  • 2021-01-18 10:50

    It's exactly what the compiler says: it can't generate a default constructor or assignment operator for your struct because it has a const member in it (const bool fooBool). struct members which are const or which are references cannot be default-initialized, so they must be explicitly initialized in a user-written constructor or assignment operator.

    One solution is to write your own default constructor and assignment operator (and in line with the rule of three, you should also write a copy constructor; a destructor isn't strictly necessary but is good practice). The alternative, easier solution is just to make fooBool non-const. Then, the compiler will happily generate the default constructor and assignment operator for you.

    Since you're already creating an array of const instances of these with static const fooStruct foo[] = ..., the extra const on fooBool is pointless.

    0 讨论(0)
  • 2021-01-18 10:52

    The C4610 warning is incorrect. This is a known bug in Visual C++. See the Microsoft Connect bug "Improper issuance of C4610."

    Adam Rosenfield explains why the other two warnings (C4510 and C4512) are emitted.

    0 讨论(0)
  • 2021-01-18 11:00

    Also if you do partial initialization then MSVC2008 will throw errors (as does MSVC2010) which is incorrect behavior as defined by C++03 and C++11. I posted more on this in another thread on stack overflow which you can read here

    // Partial initialization, leaving it to the compiler
    // to do aggregate value-initialization
    fooStruct foo ={"file1", /*missing true/false, compiler should set false*/ };
    

    MSVC will throw an error on this code along with the warnings you mentioned.

    0 讨论(0)
提交回复
热议问题