【问题标题】:Strange this-> behaviour奇怪的 this-> 行为
【发布时间】:2013-06-13 16:50:25
【问题描述】:

所以我有以下课程

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++;

}

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

【问题讨论】:

  • 您确定NamefoundationDate 已终止或正确初始化null?此外,您正在为 this->memebers 分配新内存,然后立即覆盖指针,尽管我认为这不会导致您看到的问题。

标签: c++ class memory this


【解决方案1】:

这里有多个问题,其中任何一个都可能是问题的一部分或全部。

  • 如果 NamefoundationDate 在右侧不是以空值结尾的,它将跑掉并复制坏内存。
  • 如果 foundermembers 归对象所有,如果你不在析构函数中删除它们,你要么会泄漏内存,要么在浅拷贝然后删除两次等。

要解决此问题,只需将 NamefoundationDate std::string,然后将 foundermembers 设置为值而不是指针。如果您绝对必须在堆上分配它们,请使用诸如shared_ptr 之类的智能指针来保存它,而不是使用容易出错的原始指针。

【讨论】:

    【解决方案2】:

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

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

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

    还要注意这里:

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

    第一个赋值没有做任何事情(实际上是泄漏内存),而第二个 double 会在对象销毁时删除你的内存(如果你正确地delete[] members)。

    【讨论】:

    • 我认为您对members 成员的说法不正确,您是否编辑错误?
    • 除了复制构造函数和 operator= 之外,没有任何东西可以完美运行。即使我只说这个,它也会崩溃-> membersCount = other.membersCount ...
    • 我根本没有编辑它。通知是正确的,第二个分配使第一个无用。我想看一个最小的例子来重复你的错误。
    • 问题已解决... in this->members = other.members;我的程序试图双重删除对象。谢谢大家的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2014-04-27
    • 2012-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多