简体   繁体   中英

Warning when dynamically allocating memory

I'm using dynamic allocation for the first time and the compiler gives me this warning which I couldn't find anywhere else:

warning: non-static data member initializers only available with 
-std=c++11 or -std=gnu++11

Is there a way to make it desappear? Should I care? Thanks!

The problem:

It has nothing to do with dynamic allocation .

You are probably using one of this methods for data member initialization which are part of C++11:

class S
{
    int n;                // non-static data member
    int& r;               // non-static data member of reference type
    int a[10] = {1, 2};   // non-static data member with initializer (C++11)
    std::string s, *ps;   // two non-static data members
    struct NestedS {
        std::string s;
    } d5, *d6;            // two non-static data members of nested type
    char bit : 2;         // two-bit bitfield
};

Source

The compiler tells you that you are using a feature (non-static data member initializers) that is only exist in C++11 (and above).

Solving the problem:

  • You may simply compile your code with -std=c++11 flag.
  • Alternatively, you may avoid using this feature if you want to stick with older standard (eg C++98) for some reason (like you are targeting some system where no C++ 11 compiler is avaible).

Should I care?

Absolutely, yes. No giving attention to warnings may leads to many problems like overflows and undefined behaviours.

Always care about warnings! Warnings are useful, in fact, you should always compile with -Werror .

It is warning you that you are compiling in pre-C++11, but are using C++11 in-class initializers in your code:

struct foo {
    int i = 0; // initialization of non-static POD
};

You'll have to compile with -std=c++11 , or stop using that feature and initialize the data members in the constructor.

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