总结类实例时 C++ 崩溃

标签 c++ c++11 constructor crash copy

这是一个简单的Hello World代码,应该使用复制构造函数来汇总对象

下面是代码及其生成的输出

我猜崩溃是因为析构函数调用了不应该调用的地方(或者是我的 C++ 学习书的作者没有预料到的,哈哈),但也许你可以给我一些建议

我使用带有额外选项的代码块的默认 GNU GCC 编译器 -std=c++11 -fno-elide-constructors (无论如何,它们在这种情况下并不重要)

#include <iostream>
#include <string>
#include <cstring>
#include <sstream>

using namespace std;

class MyString
{
private:
  char* Buffer;

  MyString(): Buffer(NULL)
  {
    cout << "Default constructor called" << endl;
  }

public:
  MyString( const char* InitialInput )
  {
    cout << "Constructor called for: " << InitialInput << endl;
    if(InitialInput != NULL)
    {
      Buffer = new char [strlen(InitialInput)+1];
      strcpy( Buffer, InitialInput );
    }
    else
      Buffer = NULL;
  }

  MyString operator+ (const MyString& AddThis)
  {
    cout << "operator+ called for '" << Buffer << "' to add: " << AddThis.Buffer << endl;
    MyString NewString;
    if (AddThis.Buffer != NULL)
    {
      NewString.Buffer = new char[GetLenght() + strlen( AddThis.Buffer ) + 1];
      strcpy( NewString.Buffer, Buffer );
      strcat( NewString.Buffer, AddThis.Buffer );
    }
  }

  MyString& operator= (const MyString& CopySource)
  {
    cout << "Copy assignment operator for '" << Buffer << "' to copy from: " << CopySource.Buffer << endl;
    if ((this != &CopySource) && (CopySource.Buffer != NULL))
    {
      if (Buffer != NULL)
        delete[ ] Buffer;
      // гарантирует глубокую копию с предварительным
      // резервированием собственного буфера
      Buffer = new char [strlen(CopySource.Buffer) + 1];
      // копирование оригинала в локальный буфер
      strcpy(Buffer, CopySource.Buffer);
    }
    return *this;
  }

  MyString( const MyString& CopySource )
  {
    cout << "Copy constructor for '" << Buffer << "' to copy from: " << CopySource.Buffer << endl;
    if(CopySource.Buffer != NULL)
    {
      Buffer = new char [strlen(CopySource.Buffer)+1];
      strcpy(Buffer,CopySource.Buffer);
    }
    else
      Buffer = NULL;
  }

  ~MyString()
  {
    cout << "Destructor called for: " << Buffer << endl;
    if( Buffer != NULL )
      delete [] Buffer;
  }

  int GetLenght()
  {
    return strlen(Buffer);
  }

  operator const char*()
  {
    return Buffer;
  }
};

int main( )
{
  MyString Hello("Hello ");
  MyString World("World");
  MyString CPP(" of C++");

  MyString sayHelloAgain ("overwrite this");
  sayHelloAgain = Hello + World + CPP;

  return 0;
}

输出为

构造函数调用:Hello
构造函数调用:World
C++ 的构造函数调用:
构造函数要求:覆盖此
Operator+ 调用“Hello”来添加:World
默认构造函数调用
析构函数调用:Hello World
C++的operator+调用'├РРРРР■'添加:
默认构造函数调用
析构函数调用:C++ 的├РРРРР■
将“覆盖此”的赋值运算符移至以下位置:
崩溃
进程返回-1073741819(0xC0000005)执行时间:37.566 s
按任意键继续。

最佳答案

您的错误位于复制构造函数的这一行

cout << "Copy constructor for '" << Buffer << "' to copy from: " << CopySource.Buffer << endl;

当对象在缓冲区中具有 NULL 时,您正尝试打印缓冲区

关于总结类实例时 C++ 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31692704/

相关文章:

C++11 exit() 和 abs() 不包含 <cstdlib>?

Javascript - 构造函数的属性和原型(prototype)

c++ - 在构造函数初始化程序中确定数组大小

c++ - 什么是 long long 类型?

c++ - 转发 C++0x 中的所有构造函数

c++ - thread::get_id (C++11) 是免费的吗?

java - 编译时错误 "final variable is not initialized"

c++ - 类和范围内的公共(public)结构

c++ - LNK2001: 未解析的外部符号 public: static class std::vector

c++ - 了解函数是否在运行时获取引用或值