1

When compiling the following code:

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; }

.. with the -Weffc++ flag (gcc) I get the warning

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

Which is totally clear to me but I wonder how I should get rid of it.

For dependency reasons I need the forward declaration for external_class, so in-class-initialization is not possible. I could provide a constructor for A::B and implement it inside foo.cpp but I still hope there is a very short way to initialize A::b by providing an initializer for A::B::bad_vector (similar to A::good_vector).

Is that right? What's the syntax (and should I have googled for to find the solution?) Or do I have to provide a constructor for B?

frans
  • 8,868
  • 11
  • 58
  • 132
  • 2
    @juanchopanza [Not true](http://eel.is/c++draft/vector#overview-3) – Barry Aug 01 '16 at 15:14
  • Maybe I have to add a thing: `A::good_vector` would really be a problem without the actual definition. In my example it only shows the way I'd like to initialize `A::B::bad_vector`. – frans Aug 01 '16 at 15:20

1 Answers1

4

Your code is fine.

The warning is basically about B not having a constructor that explicitly default-initializes bad_vector. But the default constructor for B already default-initializes bad_vector. Even B() = default; doesn't silence the warning, you actually have to write out B() : bad_vector() { }. That to me suggests that -Weffc++ may be obsolete in C++11.

Barry
  • 286,269
  • 29
  • 621
  • 977
  • So there isn't a way to initialize `A::B::bad_vector` inside `A::A()` via something _like_ an initializer list for `A::b`? – frans Aug 01 '16 at 15:26
  • Why wouldn't there be? a) user-defined constructor b) aggregate initialization – LogicStuff Aug 01 '16 at 15:27
  • What would aggregate initialization look like in this example? I think this term is what I've been looking for but I how I would do it in this case. – frans Aug 02 '16 at 06:29
  • @Barry: does [this](http://stackoverflow.com/a/27118551/1668622) answer tell me that what I'd like to do is possible with C++14? – frans Aug 02 '16 at 06:43