65,210
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
using namespace std;
int main()
{
int i=10;
i=i;//这里有一个self assignment
cout<<i<<endl;
return 0;
}Message& Message::operator=(const Message &rhs)
{
if (&rhs != this) {
remove_Msg_from_Folders(); // update existing Folders
contents = rhs.contents; // copy contents from rhs
folders = rhs.folders; // copy Folder pointers from rhs
// add this Message to each Folder in rhs
put_Msg_in_Folders(rhs.folders);
}
return *this;
} HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++rhs.ptr->use; // increment use count on rhs first
if (--ptr->use == 0)
delete ptr; // if use count goes to 0 on this object, delete it
ptr = rhs.ptr; // copy the U_Ptr object
val = rhs.val; // copy the int member
return *this;
}文中说:"不管怎么说,左边的ptr的内容都要被去掉"这句是错的,例如 int* i = new int(1);int* j = new int(2);如果接着执行i = j;则之前的i指向的值为1的那块内存就没有释放掉。C中指针赋值的意思是把左边指针指向(即指针的地址赋值为)右边的对象,原来指针所指向的内存还在那里。指针赋值不像一般的对象赋值,对象赋值是对象不动,把对象的值擦除再写新值(例如 int i =3;i = 4;)。
HasPtr& HasPtr::operator=(const HasPtr &rhs)
{
++rhs.ptr-> use;
if(--ptr-> use == 0)
delete ptr;
ptr = rhs.ptr;
val = rhs.val;
return *this;
}
//注意到ptr是指针,按上面的赋值,虽然避免了自赋值,但导致了两个对象拥有了同一个指针
HasPtr obj1, obj2, obj3;
obj3 = obj1; //这里obj3.ptr = obj1.ptr
obj3 = obj2; //这里delete obj3.ptr;将导致obj1错误...
#include<iostream> #include<iostream>