开发者

warning #411: class foo defines no constructor to initialize the following:

I have some legacy code built with c++ compiler giving the error in the subject line

typedef struct foo {
    char const * const str;
 } Foo;

and a lot of places in the code (meaning I cannot change all of them) use it in a C style in开发者_JAVA百科itialization:

 Foo arr[] ={
     {"death"},
     {"turture"},
     {"kill"}
  }

What is the good workaround to remove the stupid warning?


You can't modify the const pointer after construction. You need a constructor initializer to initialize 'str'.

struct Foo
{
  const char* const str;
  explicit Foo(const char* str_) : str(str_) {}
};

Note that 'typedef' is not required in C++ for a case like this.

EDIT:

If you can't use a constructor, then you must make your pointer non-const:

struct Foo
{
  const char* str;
};

ANOTHER EDIT:

After litb's comment, I tried the original code and it does indeed compile (g++ 4.1.2 and XL C/C++ 8.0) with no warnings. Perhaps the compiler in question is doing a construction followed by assignment in this case? I used less violent strings, but I doubt that would make a difference. ;v)


Check the compiler's documentation to see if there's a workaround. Your code is perfectly compliant, so without any more information, it's impossible to help.


If it works anyway, you might as well disable the warning in the command line for those files.

With gcc I think it's something like -wd411.

Not so elegant, but if it works and if the code appears to be compliant to the standard (in this order) there's no point sweating over it!


Intel compiler did this. Seems to be a bug. The trick is to remove the second "const" from the structure.

You can still make the array const and this will prevent modification of the pointer. IE:

typedef struct foo {
  char const * str;
} Foo;

const Foo arr[] ={
    {"death"},
    {"turture"},
    {"kill"}
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜