为什么我们不在下面给出的代码中使用指针来实例化C++的实体对象?

Why we are not using a pointer in instantiating the entity object in the code given below of C++?

本文关键字:指针 实例化 C++ 对象 实体 在下面 我们 为什么 代码      更新时间:2023-10-16

在此代码的主函数中,这是什么意思(ScopedPtr ent = new Entity((( 为什么我们不按照C++实例化样式使用 (ScopedPtr*(

#include<iostream>
#include<string>
class Entity
{
public:
Entity()
{
std::cout << "Created Entity!" << std::endl;
}
void Print()
{
std::cout << "Print" << std::endl;
}

};
class ScopedPtr
{
private:
Entity* m_Ptr;
public:
ScopedPtr( Entity* ptr) 
: m_Ptr(ptr)
{}
/*ScopedPtr()
{   
std::cout << "Hello"; 
}*/
~ScopedPtr()
{
std::cout << "Deleted Pointer";
delete m_Ptr;
}
};
int main()
{
{
ScopedPtr ent = new Entity();
}
std::cin.get();
}

以及为什么 ScopedPtr(实体构造函数(没有采用 Entity* 参数并且代码成功运行。

ScopedPtr ent = new Entity();

右侧是类型Entity*的值,而不考虑详细信息。 所以它可以写成

Entity* t = new Entity();  // doesn't matter what it's = to, just note its type.
ScopedPtr ent = t;

现在您有一个变量定义T x = y;其中y不属于T类型。 因此,它隐式转换为正确的类型,这确实是

ScopedPtr ent = ScopedPtr(t);

这里的=是初始化而不是赋值,因此ent是用(转换的(右侧初始化的。

为什么我们不按照C++实例化风格使用(ScopedPtr*)

因为创建对象不需要newScopedPtr的全部意义在于将具有动态存储持续时间("在堆上"(的对象生存期与具有自动存储持续时间("在堆栈上"(的另一个对象的生存期联系起来。

相关文章: