[英]Can I call a Constructor inside of an assignment operator?
我可以在赋值运算符内调用对象的构造函数吗?
我有这个代码。
class ActiveArea
{
public:
ActiveArea(const ActiveArea& active_area) : m_name(active_area.GetName()),
m_boundary(active_area.GetBoundary()),
m_day_music(active_area.GetDayMusic()),
m_night_music(active_area.GetNightMusic()),
m_custom_script(active_area.GetCustomScript()),
m_hp_regen(active_area.GetHPRegen()),
m_mp_regen(active_area.GetMPRegen()),
m_pvp_ability(active_area.GetPVPAbility()),
m_is_ladianes_suffle(active_area.IsLadianesSuffle()),
m_is_no_pvp(active_area.IsNoPVP()),
m_is_no_stamina(active_area.IsNoStamina()),
m_is_no_booth(active_area.IsNoBooth()),
m_is_under_siege(active_area.IsUnderSiege()),
m_is_no_minimap(active_area.IsNoMiniMap()),
m_is_no_attack(active_area.IsNoAttack()),
m_can_teleport_from(active_area.CanTeleportFrom()),
m_can_teleport_to(active_area.CanTeleportTo()),
m_can_login_to(active_area.CanLoginTo()),
m_min_level_required(active_area.GetMinLevelRequired()),
m_max_level_required(active_area.GetMaxLevelRequired())
{
};
ActiveArea &operator=(const ActiveArea &rhs)
{
return ActiveArea(rhs);
}
private:
const std::string m_name;
const Boundary* m_boundary;
const std::string m_day_music;
const std::string m_night_music;
const std::string m_custom_script;
const int m_hp_regen;
const int m_mp_regen;
const std::string m_pvp_ability;
const bool m_is_ladianes_suffle;
const bool m_is_no_pvp;
const bool m_is_no_stamina;
const bool m_is_no_booth;
const bool m_is_under_siege;
const bool m_is_no_minimap;
const bool m_is_no_attack;
const bool m_can_teleport_from;
const bool m_can_teleport_to;
const bool m_can_login_to;
const int m_min_level_required;
const int m_max_level_required;
};
但是,当我尝试使用该程序编译程序时,我收到一堆警告,说“返回本地变量或临时地址”。
由于我将警告视为错误,因此我想使此工作正常进行...
我本质上希望能够做到这一点...
ActiveArea area;
ActiveArea area2;
area = area2;
我可以在赋值运算符内部调用对象的构造函数吗?
是的,在这方面没有限制。 但是,您必须确保赋值运算符的语义是强制性的。 在您的情况下,此运算符
ActiveArea &operator=(const ActiveArea &rhs)
可以期望修改对其调用的对象,使其状态等于rhs
,并返回对该对象的引用。 您的示例不满足这些条件之一,并且还返回了对本地对象的引用。 使用该引用将是不确定的行为。 通常,您将设置对象的状态,然后return *this
。
ActiveArea &operator=(const ActiveArea &rhs)
{
// set the state of this object using rhs
...
return *this;
}
使用构造函数的有效示例是在copy and swap惯用语中使用copy构造函数:
ActiveArea &operator=(const ActiveArea &rhs)
{
ActiveArea tmp(rhs); // copy ctor call
swap(tmp); // assume swap is a member function
return *this;
}
请注意,可以通过将参数从引用更改为值来隐式完成复制
ActiveArea &operator=(ActiveArea rhs)
{
swap(rhs); // assume swap is a member function
return *this;
}
最后,请注意您的特定类已包含const
数据成员。 这意味着在这种情况下分配实际上没有任何意义,因为真正的分配会修改对象的状态,并且您不能修改const
数据成员。
警告来自以下行:
return ActiveArea(rhs);
在您重载的运算符中。 该行的作用是创建一个临时实例,并返回其地址。 这正是警告所言。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.