gpt4 book ai didi

c++ - 类的动态分配

转载 作者:行者123 更新时间:2023-11-30 00:44:05 27 4
gpt4 key购买 nike

我有一个关于对象数组分配的问题,问题是这样的:我有一个名为 person 的类:

class Person {
char* name;
int ID;


public:
Person(char* name = NULL, int ID = 0) :name(name), ID(ID) {};
}

我正在尝试制作一组​​这样的人:

Person *pArr = new Person[size];

然后我从文件中提取数据(char* 用于字符串,int 用于 ID)我使用 for 循环和构造函数将人员放在循环中,如下所示:

for (int j = 0; j < size3; j++) {
pArr[j] = Person(Name, id);
}

在我完成我的程序后,我想使用 Destructor 并释放存储在 char* 名称中的分配字符串,但是当我添加 Destructor 时,它会在循环结束后立即被触发,每个正在创建的人都会立即被销毁,我知道可以制作一个指针数组并分配给这个人,但在这个任务中我想这样做,有没有立即触发析构函数的正确方法?

最佳答案

在这一行:

pArr[j] = Person(Name, id);

您正在创建一个临时 Person 对象,然后将其分配给pArr[j] 对象。 Person 没有定义明确的复制赋值运算符,因此编译器会自动为您生成一个,它只是执行一个成员到成员的值从一个对象到另一个对象的复制。

当临时文件超出 ; 的范围时,它会自动销毁。编译器生成的赋值运算符将 name 指针按原样复制到 pArr[j] 对象,因此如果 Person 有一个释放的析构函数它的 namepArr[j] 对象将留下一个悬空的 name 指针,指向已释放的内存。

您的 Person 类不遵循 Rule of Three :

The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ (prior to C++11) that claims that if a class defines one (or more) of the following it should probably explicitly define all three:

  • destructor
  • copy constructor
  • copy assignment operator

由于您希望 Person 有一个释放 name 的析构函数,它还需要一个复制构造函数和一个复制赋值运算符,以便它可以复制 name 用于释放析构函数,例如:

class Person
{
char* name;
int id;

public:
Person(const char* Name = NULL, int ID = 0)
: name(new char[std::strlen(Name)+1]), id(ID)
{
std::strcpy(name, Name);
}

Person(const Person &src)
: name(new char[std::strlen(src.name)+1]), id(src.id)
{
std::strcpy(name, src.name);
}

~Person()
{
delete[] name;
}

Person& operator=(const Person &rhs)
{
if (&rhs != this)
{
Person tmp(rhs);

//std::swap(tmp.name, name);
char *p = tmp.name;
tmp.name = name;
name = p;

id = tmp.id;
}
return *this;
}
};

现在,回到这条线:

pArr[j] = Person(Name, id);

临时文件将被安全且正确地复制到pArr[j]。请注意,如果您事先动态分配了 Name,您现在必须在之后释放它,因为 Person 有自己的内部拷贝。


如果您可以将 char* 更改为 std::string,那么您就不必担心编译器会生成默认拷贝,因为 std: :string 符合三规则,将被正确复制:

class Person
{
std::string name;
int id;

public:
Person(const std::string &name = std::string(), int ID = 0)
: name(name), id(ID)
{
}

// no explicit copy constructor, destructor, or
// assignment operator is needed, as compiler-generated
// defaults will suffice...
};

关于c++ - 类的动态分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50768499/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com