2

所以我有以下课程

class Community
{
private:
  char* Name;
  char foundationDate[11];
  Person* founder;
  int maxMembersCount;
  int membersCount;
  Person* members;
  static int communitiesCount;

......

我想实现一个复制构造函数:

Community::Community(const Community& other)
{
    this->Name = new char[strlen(other.Name)+1];
    strcpy(this->Name,other.Name);
    strcpy(this->foundationDate,other.foundationDate);
    this->founder = other.founder;
    this->maxMembersCount = other.maxMembersCount;
    this->membersCount = other.membersCount;
    this->members = new Person[this->maxMembersCount];
    this->members = other.members;
    communitiesCount++;
}

但是每当我说 Community A=B; 时,这段代码就会崩溃;所以对我来说,这段代码似乎是合法的,但是当我开始调试时,会出现消息:this->“无法读取内存”。如果您需要更多代码示例,请帮助我,请告诉我。


Community::Community(const char* name , char foundDate[],Person* founder,int maxMembers) {

    this->Name = new char[strlen(name)+1];
    strcpy(this->Name,name);
    strcpy(this->foundationDate,foundDate);
    this->founder = new Person(founder->getName(),founder->getEGN(),founder->getAddress());
    this->maxMembersCount = maxMembers;
    this->membersCount = 2;
    this->members = new Person[this->maxMembersCount];
    communitiesCount++;

}

这是类的主要构造函数,它工作得很好......

4

2 回答 2

1

首先,检查other.Name是否填充了指向以空字符结尾的字符串的指针,该字符串other.foundationDate包含以空字符结尾的字符串。也就是说,您将良好的指针传递给strlenand strcpy

如果这是真的,请检查B作业中是否可以完全访问。

如果这也是真的,printf一切。并调试发生异常的确切位置。或发布可编译并重现错误的整个代码。

还要注意这里:

this->members = new Person[this->maxMembersCount];
this->members = other.members;

第一个分配什么都不做(实际上是泄漏内存),而第二个双重在对象销毁时删除您的内存(如果您正确的话delete[] members)。

于 2013-06-13T16:58:45.417 回答
1

There are multiple problems here, any of whichi could be part or all of the problem.

  • If Name or foundationDate is not null-terminated on the right-hand side, it will run off and copy bad memory.
  • If founder or members are owned by the object, you will either leak memory if you don't delete them in the destructor, or cause a whole variety of memory-related problems when you shallow-copy and then delete twice, etc.

To fix this, just make your Name and foundationDate std::string, and then make founder and members be owned by value rather than by pointer. If you absolutely have to allocate them on the heap use a smart pointer such as shared_ptr to hold it instead of a bug-prone raw pointer.

于 2013-06-13T17:18:26.260 回答