effectiveC++(十七)(二)

2010-12-26 23:20:34 · 作者: · 浏览: 4423
bsp;     //

  ~string();                    // 函数定义参见条款11
                                //
  ...

  string& operator=(const string& rhs);

private:
  char *data;
};

// 忽略了给自己赋值的情况
// 的赋值运算符
string& string::operator=(const string& rhs)
{
  delete [] data;    // delete old memory

  // 分配新内存,将rhs的值拷贝给它
  data = new char[strlen(rhs.data) + 1];
  strcpy(data, rhs.data);

  return *this;      // see item 15
}

看看下面这种情况将会发生什么:

string a = "hello";

a = a;               // same as a.operator=(a)

赋值运算符内部,*this和rhs好象是不同的对象,但在现在这种情况下它们却恰巧

是同一个对象的不同名字。可以这样来表示这种情况:

*this  data ------------>