每次调用私有成员getter调用class析构函数
Calling private member getter call class destructor every time
我正在做一个 C++ 项目,我遇到了这种奇怪的行为。
我有一个武器 class 定义如下:
class Weapon
{
public:
Weapon(std::string type);
Weapon(void);
~Weapon(void);
void setType(std::string type);
std::string const &getType(void) const;
private:
std::string _type;
};
而这个人 class:
class HumanA
{
public:
HumanA(std::string name, Weapon &Wp);
~HumanA(void);
void attack(void) const;
void setName(std::string name);
void setWeapon(Weapon Wp);
std::string getName(void) const;
Weapon getWeapon(void) const;
private:
Weapon &_weapon;
std::string _name;
};
问题是,当我从 HumanA
调用 getWeapon
时,每次都会调用武器析构函数。
这是我的主要代码:
int main()
{
{
Weapon club = Weapon("crude spiked club");
HumanA bob("Bob", club);
bob.attack(); <--- getWeapon function get used here
club.setType("some other type of club");
bob.attack();
}
return (0);
}
输出如下:
A weapon has been called.
A HumanA has been called.
Bob attacks with his crude spiked club
A weapon has been down. <------- And Here
Bob attacks with his some other type of club
A weapon has been down. <------- Here
HumanA has been backedoff.
A weapon has been down.
我不知道这是否正常,但任何人都可以帮助解释这种奇怪的行为。
按值返回对象时,会创建一个临时 对象。所以每次调用这个函数都会调用析构函数
即使您已将 HumanA
class 的 _weapon
成员定义为对 Weapon
的 reference, getWeapon
函数被声明为 returning 一个实际的 Weapon
object (按值);因此,当被调用时,它将制作成员引用的 Weapon
对象的副本,并且 return 复制的对象在脱离上下文时将被销毁(并且它的析构函数被调用)。
您应该将 getWeapon
函数声明为 returning reference,然后 return 相关人员的(副本) _weapon
成员:
Weapon& HumanA::getWeapon(void) const {
return _weapon;
}
我正在做一个 C++ 项目,我遇到了这种奇怪的行为。
我有一个武器 class 定义如下:
class Weapon
{
public:
Weapon(std::string type);
Weapon(void);
~Weapon(void);
void setType(std::string type);
std::string const &getType(void) const;
private:
std::string _type;
};
而这个人 class:
class HumanA
{
public:
HumanA(std::string name, Weapon &Wp);
~HumanA(void);
void attack(void) const;
void setName(std::string name);
void setWeapon(Weapon Wp);
std::string getName(void) const;
Weapon getWeapon(void) const;
private:
Weapon &_weapon;
std::string _name;
};
问题是,当我从 HumanA
调用 getWeapon
时,每次都会调用武器析构函数。
这是我的主要代码:
int main()
{
{
Weapon club = Weapon("crude spiked club");
HumanA bob("Bob", club);
bob.attack(); <--- getWeapon function get used here
club.setType("some other type of club");
bob.attack();
}
return (0);
}
输出如下:
A weapon has been called.
A HumanA has been called.
Bob attacks with his crude spiked club
A weapon has been down. <------- And Here
Bob attacks with his some other type of club
A weapon has been down. <------- Here
HumanA has been backedoff.
A weapon has been down.
我不知道这是否正常,但任何人都可以帮助解释这种奇怪的行为。
按值返回对象时,会创建一个临时 对象。所以每次调用这个函数都会调用析构函数
即使您已将 HumanA
class 的 _weapon
成员定义为对 Weapon
的 reference, getWeapon
函数被声明为 returning 一个实际的 Weapon
object (按值);因此,当被调用时,它将制作成员引用的 Weapon
对象的副本,并且 return 复制的对象在脱离上下文时将被销毁(并且它的析构函数被调用)。
您应该将 getWeapon
函数声明为 returning reference,然后 return 相关人员的(副本) _weapon
成员:
Weapon& HumanA::getWeapon(void) const {
return _weapon;
}