c++ - 奇怪的这个->行为

标签 c++ class memory this

所以我有以下类(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++;

}

这是该类的主要构造函数,运行良好......

最佳答案

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

  • 如果 NamefoundationDate 在右侧不是以 null 结尾,它将运行并复制错误内存。
  • 如果 Foundermembers 属于该对象,如果不在析构函数中删除它们,就会导致内存泄漏,或者导致内存崩溃- 浅复制然后删除两次等相关问题

要解决此问题,只需设置您的名称foundationDate std::string,然后设置Founder成员 由值而不是指针拥有。如果您绝对必须在堆上分配它们,请使用诸如 shared_ptr 之类的智能指针来保存它,而不是容易出现错误的原始指针。

关于c++ - 奇怪的这个->行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17092723/

相关文章:

c++ - OpenCV 小屏幕显示延迟?

class - JsDoc 链接到类的属性

设置最大堆大小时,Java Applet 无法正常启动

c++ - 我如何理解 C++ 中是否删除了指针

python - 为什么在类级别使用列表压缩时会引发 NameError?

c - 如何避免变量自动分配到我的指针指向的内存单元的情况?

c# - 如何对图像应用 3D 变换?

c++ - 有没有一种在 VS 中构建预编译 header 的方法不会使我的代码难以在 GCC 中构建?

c++ - 如果没有重载赋值运算符,我怎么能复制结构 vector ?

C++11 如何在其他类或源文件中引用类方法