为什么destructer被operator = function调用 [英] Why is destructer being called by operator = function

查看:73
本文介绍了为什么destructer被operator = function调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

即使即时通过refrenced参数t =运算符什么是破坏性破坏......

输出如下

你好

world

-------

=运算符被调用

des被调用//这个destructer被称为

你好

des被称为

des被称为



什么我试过了:



even though i m passing refrenced argument t = operator what is destructer destroying......
the output is as follows
hello
world
-------
= operator is called
des is called //what is this destructer called for
hello
des is called
des is called

What I have tried:

#include <iostream>
#include<string.h>

using namespace std;
class strin{
    int len;
    char *ptr;
    public:

    strin(){len=0;ptr=NULL;}
    strin(   const char  *s)
    {
          len=strlen(s);
         ptr=new char[len+1];
         strcpy(ptr,s);
    }
    strin( const strin &A)
    {
        len=A.len;
        ptr=new char[len+1];
        strcpy(ptr,A.ptr);
        cout<<"cpy cnst is called\n";

    }
    void print(void)
    {
        cout<<ptr<<"\n";
    }


    strin operator + ( const strin  &obj )
    {
     strin temp;
     temp.len=len+obj.len;
      temp.ptr=new char[temp.len+1];
     strcpy(temp.ptr,ptr);
     strcat(temp.ptr,obj.ptr);
     cout<<"+ is called \n";
     return temp;
    }
~strin()
{
    delete[]ptr;
    cout<<"des is called\n";
}
strin operator = (const strin &x)
{
    len=x.len;
    ptr=new char[len+1];
    strcpy(ptr,x.ptr);
    cout<<"= operator is called\n";

}
};

int main()
{


  strin x("hello");
  strin y("world");
  x.print();
  y.print();

  cout<<"--------\n";

  y=x;
  y.print();

  }

推荐答案

这是因为很可能你的返回值(按值)进入必杀技并且将会被破坏......有问题......



这是 Operator = 的正确实现,也不会调用析构函数:

That is because most probably your return value (by value) goes into nirvana and will be destructed ... questionable ...

This is the correct implementation of Operator= which will also not call the destructor:
const strin& operator = (const strin &x)
{
    cout<<"= operator is called\n";
    if (this != &x)
    {
       // TODO: In case ptr allready has Memory allocated, one Need to release it 
       //       first. 
       // 

       // Assign
       len=x.len;
       ptr=new char[len+1];
       strcpy(ptr, x.ptr);
    }
    return(*this);
}



注意,可能的内存泄漏

上述情况仍然不太正确。你还需要检查第一个这个已经分配了内存并先发布它以防万一。这将是你的运动





附注,我个人喜欢的方式我如何结合 operator = 和复制构造函数



a。)复制构造函数


Attention, possible memory leak
The above is still not quite correct. You Need also check first wheter this has allready allocated Memory and release it first in case. That will be your exercise


A side note, my personal preferenced way how I combine operator= and copy constructor

a.) Copy constructor

MyClass::MyClass (const MyClass &rhs)
	: InitMember_1(),
          .....
	  InitMember_N()
{
	operator= (rhs);
}



b。)operator =


b.) operator=

const MyClass& MyClass::operator=(const MyClass &rhs)
{
   if (this != &rhs)
   {
     // TODO: Implement 
   }
   return(*this);
}


复制赋值运算符 - cppreference.com [ ^ ] 。


以下示例给出了强有力的保证,这是您应该努力的目标。

您应该使用断言(此!= & rhs)在开发过程中捕捉自我分配错误。检查自我分配只有两个原因:(1)避免不需要的分配,(2)该对象旨在保存大量数据。



The following examples give the strong guarantee, which is what you should strive for.
You should use assert(this != &rhs) to catch self assignment mistakes during development. There are only two reasons for checking self assignment: (1) avoid unneeded allocations, (2) the object is intended to hold large amounts of data.

// Add swap to your class
// swap is one of your best friends
// because it is guaranteed not to throw.
void swap(strin& x) noexcept
{
	using std::swap;
	swap(len, x.len);
	swpa(ptr, x.ptr);
}

// Version 1
// This version behaves the same in all cases,
// even on the rare occasion you do self assignment
strin& operator=(const strin& rhs)
{
	cout << "= operator is called" << endl;
	// Using a constructor here provides the strong
	// guarantee that this object will not be modified
	// if an exception is thrown.
	strin temp(rhs);
	swap (*this, temp);
    return(*this);
}

// Version 2
// The difference between this and version 1
// is that temporary object is built on the stack
// when the operator is called.
strin& operator=(strin rhs)
{
	cout << "= operator is called" << endl;
	swap (*this, rhs);
    return(*this);
}

// Version 3
// Basically the same as version 1
strin& operator=(const strin& rhs)
{
	cout << "= operator is called" << endl;
	// first use temporaries in case an exception is thrown.
	char temp_ptr = new char [rhs.len+1];
	strcpy(temp_ptr, rhs.ptr);
	
	// No exception were thrown, so we can modify this.
	delete [] ptr;
	ptr = temp_ptr;
	len = rhs.len;
	
    return(*this);
}


这篇关于为什么destructer被operator = function调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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