服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C/C++ - C++编程小心指针被delete两次

C++编程小心指针被delete两次

2021-01-22 11:48C++教程网 C/C++

这篇文章主要介绍了C++编程指针被delete两次的严重后果,以实例阐述了C++指针使用中的误区和注意点,需要的朋友可以参考下

C++类中,有时候会使用到传值调用(即使用对象实体做参数),当遇到这种情况,可要小心了!尤其是当你所传值的对象生命周期较长,而非临时对象(生命周期段)的时候。来看看下面的情况:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <iostream>
using namespace std;
class Text
{
private:
char * str;
public:
Text(){str = new char[20];
::memset(str,0,20);
}
void SetText(char * str)
{
strcpy(this->str,str);
}
char * GetText() const{return str;}
~Text()
{
cout << "~Text Destruction" << endl;
delete [] str;
cout << "~Text Over" << endl;
}
};
void Print(Text str)
{
cout << str.GetText() << endl;
}
int main()
{
Text t;
t.SetText("abc");
Print(t);
return 1;
}

上面执行的结果是程序崩溃了。原因是:

Print(Text str)在对str进行复制构造的时候,没有进行深度拷贝;当 Print退出的时候,因为是临时对象(函数初始时构造),对str进行析构,此时还没有出现任何问题;但回到main,继而退出main 的时候,又对t进行析构,但此时t内的str中的内容已经被销毁。由于对一内存空间实施了两次销毁,于是就出现了内存出错。

解决方法如下:

重写前拷贝。像以下版本,不同的情况要作出适当的调整:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <iostream>
using namespace std;
class Text
{
private:
char * str;
public:
Text(){str = new char[20];::memset(str,0,20);}
Text(Text &t)
{
str = new char[20];
strcpy(str,t.GetText());
}
void SetText(char * str)
{
strcpy(this->str,str);
}
char * GetText() const{return str;}
~Text()
{
cout << "~Text Destruction" << endl;
delete [] str;
cout << "~Text Over" << endl;
}
};
void Print(Text str)
{
cout << str.GetText() << endl;
}
int main()
{
Text t;
t.SetText("abc");
Print(t);
return 1;
}

此处推荐不使用传值调用。就像下面书写如下Print版本:

?
1
2
3
4
void Print(Text &str)
{
cout << str.GetText() << endl;
}

除非对象内所有的成员读属非指针内存内容,那么谨慎使用文章前面提到的用法。

延伸 · 阅读

精彩推荐