Default constructor missing - but I'm not calling it?

大兔子大兔子 提交于 2019-11-29 17:07:01
NPE

The player_command() constructor first default constructs help and then assigns to it:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h) {
    cmd = c;
    help = h;
};

Change that to:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h)
:  cmd(c),
   help(h)
{
};

See Benefits of Initialization lists

The player_command struct contains a help_message (help), and there is no default constructor for help_message. When the player_command constructor is called, by default the help member variable will be default constructed. You are immediately assigning help to the given parameter but this will be after it is default constructed. Instead change the constructor to be something like:

Controller::player_command::player_command(const Controller::cmd_t& c, const help_message& h) : cmd(c), help(h) 
{}

This will invoke the copy constructor for both cmd and help member variables instead of doing default construction and then assignment.

You are not using the syntax which avoids the copy constructor. The argument is passed by reference (no copy constructor) but it is indeed copied when assigned to the ivar.

Class::Class(const Variable &var) {
  this->var = var; // assignment here, this invokes copy contructor!
}

You should use the following syntax:

Class::Class(const Variable &var) : var(var) { }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!