在构造函数中初始化嵌套成员的语法?

时间:2016-08-01 15:06:13

标签: c++ constructor initialization

编译以下代码时:

foo.h中

#include <memory>
#include <vector>

struct external_class;

struct A {
    struct B {
        std::vector<external_class> bad_vector;
    };
    std::vector<external_class> good_vector;
    std::shared_ptr<B> b;
    A();
};

Foo.cpp中

#include "foo.h":

struct external_class {};     // implement external_class

A::A() : 
    good_vector(),            // <- easy to initialize via default constructor
    b(std::make_shared<B>())  // <- does not involve bad_vector::ctor -> warning
{ }

int main() { A a; }

..使用-Weffc++标志(gcc)我收到警告

foo.cpp:9:12: warning: ‘A::B::bad_vector’ should be initialized in the member initialization list [-Weffc++]
     struct B {
            ^

我完全清楚这一点,但我想知道如何摆脱它。

出于依赖性原因,我需要external_class的前向声明,因此无法进行类内初始化。我可以为A::B提供构造函数并在foo.cpp中实现它,但我仍然希望通过为A::b提供初始化程序来初始化A::B::bad_vector的方法很短(类似于A::good_vector)。

是吗?什么是语法(我应该用Google搜索来找到解决方案?)或者我是否必须为B提供构造函数?

1 个答案:

答案 0 :(得分:5)

你的代码很好。

警告基本上是B没有明确默认初始化bad_vector的构造函数。但B的默认构造函数已默认初始化bad_vector。即使B() = default;没有使警告静音,您实际上也必须写出B() : bad_vector() { }。那对我来说,-Weffc++可能在C ++ 11中已经过时了。

相关问题