warning C4150: 删除指向不完整“XXX”类型的指针;没有调用析构函数

简介:

 

情况源于我的之前一片博客《C++ 智能指针》,在我写demo代码的时候。

 

向前申明了class Phone, 然后再U_ptr类析构函数中delete Phone的指针。

出现warning C4150: 删除指向不完整“XXX”类型的指针;没有调用析构函数

 

 

这个waring会导致内存泄露。前向申明的类的析构函数没有被调用

 

 

出现warning的代码如下:

 

#include <iostream> using namespace std; class ConnectManager; class CommManager; class Phone; class U_ptr { friend class ConnectManager; friend class CommManager; public: U_ptr(Phone *pH): use(0), pPhone(pH) { } ~U_ptr() { delete pPhone; } private: Phone *pPhone; size_t use; }; class Phone { public: Phone() { cout << "Hello World!" << endl; } ~Phone() { cout << "Bye!" << endl; } }; class ConnectManager { public: ConnectManager(U_ptr *p): pUptr(p) { ++pUptr->use; cout << "ConnectManager: Hi I get the Phone" << endl; cout << pUptr->use << " users" << endl; } ~ConnectManager() { cout << "ConnectManaer: Can I delete the Phone?" << endl; if (--pUptr->use == 0) { cout << "Yes, You can" << endl; delete pUptr; } else { cout << "No, You can't, The Phone is in use" << endl; cout << pUptr->use << " users" << endl; } } private: U_ptr *pUptr; }; class CommManager { public: CommManager(U_ptr *p): pUptr(p) { ++pUptr->use; cout << "CommManager: Hi I get the Phone" << endl; cout << pUptr->use << " users" << endl; } ~CommManager() { cout << "CommManager: Can I delete the Phone" << endl; if (--pUptr->use == 0) { cout << "Yes, You can" << endl; } else { cout << "No, You can't. The Phone is in use" << endl; cout << pUptr->use << " users" << endl; } } private: U_ptr *pUptr; }; int main(void) { Phone *symbian = new Phone(); U_ptr *pU = new U_ptr(symbian); ConnectManager connManager = ConnectManager(pU); CommManager commManager = CommManager(pU); }  

 

 

出现原因:

 

class Phone;这种方式向前申明,其后面的类只能申明其指针,前向申明以后的类无法看到其类实体。

 

所以,delete的时候,Phone的析构函数对后面的类是透明不可见的,除非使用头文件包含。

目录
相关文章
|
20天前
|
存储 安全 Go
深入理解 Go 语言中的指针类型
【8月更文挑战第31天】
8 0
|
3月前
|
编译器 C++
函数指针和函数对象不是同一类型怎么替换
函数指针和函数对象不是同一类型,为何可替换用作同一函数的参数
|
3月前
|
Java 程序员 Linux
探索C语言宝库:从基础到进阶的干货知识(类型变量+条件循环+函数模块+指针+内存+文件)
探索C语言宝库:从基础到进阶的干货知识(类型变量+条件循环+函数模块+指针+内存+文件)
36 0
|
3月前
|
图形学 Windows
程序技术好文:记录类型指针
程序技术好文:记录类型指针
17 0
|
4月前
|
存储 安全 C语言
void指针类型详解
void指针类型详解
42 2
|
3月前
|
JSON Go 数据格式
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(4)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
3月前
|
Java 编译器 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(3)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
3月前
|
存储 安全 Go
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(2)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
3月前
|
Java Go 索引
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】(1)
Go 语言基础之指针、复合类型【数组、切片、指针、map、struct】
|
4月前
|
存储 安全 C语言
深入解析void指针类型
深入解析void指针类型
55 0