C++ this指针(3) - 删除this指针
来源:互联网 发布:申请域名知乎 编辑:程序博客网 时间:2024/06/11 10:12
通常通常情况下,delete操作符不应该用于删除this指针。但是,一旦使用了delete this, 则需要考虑到下面的这些情况。
1) delete 操作符只允许与使用new分配的对象配套使用。
如果对象是用new创建的,则可以使用delete this, 否则会导致未知的行为。
如果对象是用new创建的,则可以使用delete this, 否则会导致未知的行为。
class A{ public: void fun() { delete this; }};int main(){ //下面的3行是正常的 A *ptr = new A; ptr->fun(); ptr = NULL // 避免野指针 //下面的2行会导致异常 A a; a.fun(); return 0;}
2) 一旦this指针被delete, 则这个对象的任何成员都不能再被访问。
#include<iostream>class A{ int x; public: A() { x = 11;} void fun() { delete this; //下面这行可能会导致异常 std::cout<<x; }};int main(){ A a; a.fun();}
最好的方法是不使用delete删除this指针。
不过需要注意的是,因为静态成员不需要特定对象来访问,所以即使this指针被删除后,类中的静态成员任然可以正常访问。
见下面例子:
#include<iostream>class Test{public: void func() { delete this; } static int a;};int Test::a = 11;int main(){ Test *obj = new Test; obj->func(); std::cout<<"a = "<<Test::a; return 0;}
编译正常,输出:
a = 11
更多参考:
https://www.securecoding.cert.org/confluence/display/cplusplus/OOP05-CPP.+Avoid+deleting+this
http://en.wikipedia.org/wiki/This_%28computer_science%29
0 0
- C++ this指针(3) - 删除this指针
- 【C/C++】this指针
- C++this指针、智能指针
- 【C++】this 指针
- C++this指针
- C++this指针
- C++this指针
- C++this指针
- C++this指针
- c++this指针
- C++this指针
- C++this指针
- C++this指针(二)
- C++-this指针
- c++this指针
- C++this指针
- C ++的this指针
- C++this指针详解
- 硬编码学习(四)
- 判断当前登录的终端是PC端还是移动端
- 图像处理编程实现中需要注意的数据类型问题
- PHP输入流php://input介绍
- web开发笔记(7):jQuery自带的前台日历插件WdatePicker
- C++ this指针(3) - 删除this指针
- 更换 CentOS 7 的下载源为阿里云
- java通过外网ip获取本地城市地理位置
- ora-12519错误分析解决
- Java8的新特性以及与C#的比较
- 第12周 程序阅读-多重继承1
- Codeforces 500B - New Year Permutation(最短路)
- 关于Kruskal算法的一点想法
- 支付宝、微信、银联三种支付平台链接