【C++】类成员初始化小细节

Problem

请注意如下例子是否有问题c++

class Apple {
    public:
        Apple(char ch, int count) : array(count, 1), buffer(count, ch) {}
    private:
        std::string buffer;
        std::vector<int> array;
};

Warning

g++ 4.8.4使用-Wall -std=c++11编译时,会出现一个警告,内容以下c++11

xxx.cpp:11:15: warning: ‘Apple::buffer’ will be initialized after [-Wreorder]

Conclude

出现这个警告的缘由是由于初始化的顺序和类成员声明的顺序不同(在某些不推荐的状况下,类成员的初始化可能含有依赖关系),作以下改变就好了code

Apple(char ch, int count) : buffer(count, ch), array(count, 1) {}

或者在编译参数中打开-Wno-reorderstring

相关文章
相关标签/搜索