【问题标题】:copy constructor failure... overloading, dynamic allocation复制构造函数失败...重载,动态分配
【发布时间】:2015-05-15 15:28:09
【问题描述】:

我正在使用动态字符串,复制构造函数和重载存在问题。 我正在使用 operator+ 来重载。重载函数用于插入两个 char * 字符串。 这里只是代码的摘录:

  MyString::~MyString()
  {
    delete[] text; //char *text, as my private data
  }
MyString::MyString(const MyString & obj)//copy constructor here
{
    text = new char[obj.len];
    for (int i = 0; i < obj.len; i++)
    {
        text[i] = obj.text[i];
    }
    len = obj.len;
}
MyString MyString::operator+(MyString & s)
{
    MyString temp;
    temp.len = len + s.len + 1;
    int i;
    for (i = 0; i < len; i++)
    {
        temp.text[i] = this->text[i];
    }
    for (int i = 0; i < s.len; i++)
    {
        temp.text[i + len] = s.text[i];
    }
    temp.text[len + s.len] = 0;
    return temp;//PROBLEM HERE
}

这是我的问题: operator+ 函数在返回 temp 之前调用复制构造函数和析构函数 尽管有一个复制构造函数,但返回的是一个已删除的 [] 数组。 有什么问题?谢谢

【问题讨论】:

  • 你的默认构造函数是做什么的? temp.text 是否分配了足够的空间?好像不能。
  • 它确实有足够的空间。
  • 如果是这样,那将是一个非常奇怪的实现。您必须知道字符串的最大可能大小并为此分配足够的内存。这听起来不太像动态字符串。
  • 你能建议我一个更常见的实现吗?
  • 这段代码是精神分裂症。复制 ctor 的实现就像 len 包含终止 '\0' 或字符串不是以空值终止的,然后 operator+ 实现就像 len 不包含终止 '\0' 和字符串以 null 结尾。

标签: c++ operator-overloading destructor copy-constructor


【解决方案1】:

假设您有以下代码

MyString s1;  // Initialized to something
MyString s2;  // Initialized to something else

MyString s3 = s1 + s2;

然后表达式s1 + s2 创建一个临时 副本(由您的operator+ 函数返回的副本)。然后将此临时副本传递给复制构造函数以创建s3随后销毁临时对象。

这就是理论,实际上编译器会省略复制。

【讨论】:

  • 好吧,我这样做了。但返回的不是 s1+s2 的插值,它只是一个 char *,其值看起来像一个地址。比如:0x0025ad10
  • @Potter6000 制作一个小测试用例(就像我的答案中的那个),在调试器中运行,在复制构造函数和析构函数以及operator+ 函数中设置断点,并确保通过逐行单步执行,代码的行为符合预期。
【解决方案2】:

进行这些更改并尝试: 1. temp.text[len + s.len] = '\0'; //空终止

  1. MyString**&** MyString::operator+(MyString & s) { . . . } //通过引用返回,你会得到正确的结果。

【讨论】:

  • 不,您不应该通过引用返回本地对象。
猜你喜欢
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多