C++对象在未创建的情况下被销毁

C++ object destroyed without being create?

本文关键字:情况下 创建 对象 C++      更新时间:2023-10-16

我尝试了以下代码(从learncpp.com修改(

#include <iostream>
#include <string>
using namespace std;
class Point2D
{
private:
int m_nX;
int m_nY;
public:
// A default constructor
Point2D()
    : m_nX(0), m_nY(0)
{
}
// A specific constructor
Point2D(int nX, int nY)
    : m_nX(nX), m_nY(nY)
{
  cout<<"Point is created"<<endl;
}
~Point2D(){cout<<"Point is destroyed"<<endl;}
// An overloaded output operator
friend std::ostream& operator<<(std::ostream& out, const Point2D &cPoint)
{
    out << "(" << cPoint.GetX() << ", " << cPoint.GetY() << ")";
    return out;
}
// Access functions
void SetPoint(int nX, int nY)
{
    m_nX = nX;
    m_nY = nY;
}
int GetX() const { return m_nX; }
int GetY() const { return m_nY; }
};
class Creature
{
private:
std::string m_strName;
Point2D m_cLocation;
// We don't want people to create Creatures with no name or location
// so our default constructor is private
Creature() { }
public:
Creature(std::string strName, const Point2D &cLocation)
    : m_strName(strName), m_cLocation(cLocation)
{
  cout<<"Creature is created"<<endl;
}
~Creature(){cout<<"Creature is destroyed"<<endl;}
friend std::ostream& operator<<(std::ostream& out, const Creature &cCreature)
{
    out << cCreature.m_strName.c_str() << " is at " << cCreature.m_cLocation;
    return out;
}
void MoveTo(int nX, int nY)
{
    m_cLocation.SetPoint(nX, nY);
}
};

int main()
{
using namespace std;
cout << "Enter a name for your creature: ";
std::string cName;
cin >> cName;
Creature cCreature(cName, Point2D(4, 7));
while (1)
{
    cout << cCreature << endl;
    cout << "Enter new X location for creature (-1 to quit): ";
    int nX=0;
    cin >> nX;
    if (nX == -1)
        break;
    cout << "Enter new Y location for creature (-1 to quit): ";
    int nY=0;
    cin >> nY;
    if (nY == -1)
        break;
    cCreature.MoveTo(nX, nY);
    }
return 0;
}

当我运行程序时,我得到以下信息:

Enter a name for your creature: gabar
Point is created
Creature is created
Point is destroyed
gabar is at: (4,7)
Enter new X location for creature (-1 to quit): 2
Enter new Y location for creature (-1 to quit): 3
gabar is at: (2,3)
Enter new X location for creature (-1 to quit): -1
Creature is destroyed
Point is destroyed

我有两个问题:

为什么第一个"点被破坏"被称为?为什么只有一个"点已创建"提示,却有两个"点被销毁"提示。

感谢

我不知道你用什么来跟踪构造函数和析构函数,但我怀疑它没有检测到复制构造函数。

此行创建第一个Point2D:

Creature cCreature(cName, Point2D(4, 7));

Creature的构造函数通过引用获取它,但随后将它分配给m_cLocation,后者复制它(调用我怀疑没有跟踪的Point2D复制构造函数(。

第一个Point2D是瞬态的,从未存储,然后被销毁。CCD_ 6在最后被破坏。

在此语句中

Creature cCreature(cName, Point2D(4, 7));

创建临时对象CCD_ 7作为第二参数。完成语句后,此对象将被删除。

在您的程序中,有两个类型为Point的对象。第一个是上面提到的临时对象,第二个是Creature类的成员。构造函数cCreature将临时对象复制到成员对象中后,它被删除。

因为您只是用普通构造函数构造一个Point2D,而这种情况发生在您的主方法中。

第二个Point2D是成员变量m_cLocation,它不是通过复制构造函数构造的,而是通过复制构造函数初始化的,在您的情况下,它是由编译器隐含定义的,而不是由控制台打印跟踪的。此构造函数具有签名Point2D (const Point2D& other)

第一个点在用于初始化成员变量后立即被销毁,因为它是一个右值,在使用后不再需要它。