3

I try to compile very simple tree node with std::shared_ptr. In my compiler options I use -Weffc++ and -Werror but it throws 2 errors which I don't understand thus I can't imagine a solution.

The minimal example (t.cpp):

#include <memory>

struct node {
    std::shared_ptr<node> left;
    std::shared_ptr<node> right;
    std::shared_ptr<int> value;
};

int main() {
    node n;
    return 0;
}

The output from compiler is:

$ LANG=en_US g++ -std=c++14 -Weffc++ t.cpp
t.cpp: In constructor 'constexpr node::node()':
t.cpp:3:8: warning: 'node::left' should be initialized in the member initialization list [-Weffc++]
 struct node {
        ^
t.cpp:3:8: warning: 'node::right' should be initialized in the member initialization list [-Weffc++]
t.cpp:3:8: warning: 'node::value' should be initialized in the member initialization list [-Weffc++]
t.cpp: In function 'int main()':
t.cpp:10:10: note: synthesized method 'constexpr node::node()' first required here 
     node n;
          ^

The only similiar thing I could find is this question but it does not answer on my question unfortunately.

Community
  • 1
  • 1
VP.
  • 15,509
  • 17
  • 91
  • 161

2 Answers2

1

With the Effective C++ warning enabled, the compiler is warning that you haven't followed the guideline to prefer explicit initialisation of the member fields in the initialiser list.

Adding an explicit constructor will probably get rid of this:

node() : left(), right(), value()
{}
russw_uk
  • 1,267
  • 8
  • 10
1

The more concise way to specify default constructors:

struct node {
    std::shared_ptr<node> left {};
    std::shared_ptr<node> right {};
    std::shared_ptr<int> value {};
};

This worked for me to fix "should be initialized..." warnings.

LVitya
  • 528
  • 4
  • 11