所以我有以下类(class)
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++;
}
但是每当我说社区 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++;
}
这是该类的主要构造函数,运行良好......
最佳答案
这里有多个问题,其中任何一个都可能是问题的一部分或全部。
- 如果
Name
或foundationDate
在右侧不是以 null 结尾,它将运行并复制错误内存。 - 如果
Founder
或members
属于该对象,如果不在析构函数中删除它们,就会导致内存泄漏,或者导致内存崩溃- 浅复制然后删除两次等相关问题
要解决此问题,只需设置您的名称
和foundationDate
std::string
,然后设置Founder
和成员
由值而不是指针拥有。如果您绝对必须在堆上分配它们,请使用诸如 shared_ptr
之类的智能指针来保存它,而不是容易出现错误的原始指针。
关于c++ - 奇怪的这个->行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17092723/