复制构造函数调用析构函数C ++ [英] Copy constructor calls destructor c++

查看:113
本文介绍了复制构造函数调用析构函数C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个测试类来制作自己的字符串函数.复制析构函数有问题.

I have a test class of my to make my own string functions. I have a problem with the copy destructor.

我有2个字符串:s1和s2. 我将函数称为s3 = s1 + s2;

I have 2 strings: s1 and s2. I call the function s3 = s1 + s2;

它首先调用operator +函数,并在完成后调用析构函数.因此,operator =函数中的字符串对象为空.我该如何解决?

It first calls the operator+ function and when it's finished it calls the destructor. Because of this the string object in the operator= function is empty. How can I fix this?

析构函数:

String::~String() {
  if (this->str)
    delete[] str;
  str = NULL;
  len = 0;
}

复制构造函数:

String::String(const String& string) {
  this->len = string.len;
  if(string.str) {
    this->str = new char[string.len+1];
    strcpy(this->str,string.str);
  } else {
    this->str = 0;
  }
}

operator=:

String & String::operator= (const String& string) {
  if(this == & string)
    return *this;

  delete [] str;

  this->len = string.len;

  if(string.str) {
    this->str = new char[this->len];
    strcpy(this->str,string.str);
  } else {
    this->str = 0;      
  }

  return *this;
}

operator+:

String& operator+(const String& string1 ,const String& string2)
{
  String s;

  s.len = string1.len + string2.len;
  s.str = new char[string1.len + string2.len+1];
  strcpy(s.str,string1.str);
  strcat(s.str,string2.str);

  return  s;
}

推荐答案

operator+不应通过引用返回局部变量.

operator+ should not return a local variable by reference.

将返回类型从operator+更改为String.即,签名:

Change the return type of operator+ to String. Ie, make the signature:

String operator+( String const& lhs, String const& rhs )


您可能还想为您的String类编写一个移动构造函数":String( String&& other )如果您使用C ++ 11编写代码.


You probably also want to write a "move constructor" for your String class: String( String&& other ) if you are writing your code in C++11.

一个简单的move构造函数:

A simple move constructor:

String::String( String&& other ): len(other.len), str(other.str) {
  other.len = 0;
  other.str = nullptr;
}

这不是必需的,因为在非平凡的优化级别下,编译器可能会清除" operator+的return语句中的副本,但这仍然是很好的做法.

This isn't required, because the copy in the return statement of your operator+ will probably be "elided" by your compiler under non-trivial optimization levels, but still good practice.

这篇关于复制构造函数调用析构函数C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆