码迷,mamicode.com
首页 > 编程语言 > 详细

C++深层复制解决指针悬挂

时间:2016-04-19 22:52:56      阅读:432      评论:0      收藏:0      [点我收藏+]

标签:

代码:

 1 #include <iostream>
 2 #include <cstring>
 3 
 4 using namespace std;
 5 
 6 class mystring{
 7     public:
 8         mystring(string s){
 9             cout<<"Constructor called."<<endl;
10             ptr = new char[s.length()+1];
11             strcpy(ptr,s.c_str());
12         }
13         ~mystring(){
14             cout<<"Destructor called.---"<<ptr<<endl;
15             delete ptr;
16         }
17         mystring &operator=(const mystring&);
18     private:
19         char* ptr;
20 };
21 
22 mystring& mystring::operator=(const mystring& s){
23     if(this == &s) return *this;
24     cout<<this<<" "<<sizeof(this)<<endl;
25     delete ptr;
26     ptr = new char[strlen(s.ptr)+1];
27     strcpy(ptr,s.ptr);
28     return *this;
29 }
30 
31 int main(){
32     mystring p1("hello");
33     mystring p2("OK");
34     p1 = p2;
35 
36     return 0;
37 }

输出:

Constructor called.
Constructor called.
0x7ffeb8555900 8
Destructor called.---OK
Destructor called.---OK

 分析:

显式定义赋值运算符重载函数,在复制时释放动态分配的内存空间并重新分配新的空间。假如没有重载赋值运算符,p1和p2指向同一块内存空间,程序结束时会导致对同一块内存空间的两次释放,这是不允许的。详见《C++面向对象程序设计教程》(第三版) 5.2.6节

C++深层复制解决指针悬挂

标签:

原文地址:http://www.cnblogs.com/hu983/p/5410514.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!