0%

Incomplete class types for C++

先從 C++ Standard看起

The C++ Standard allows, in 5.3.5/5, pointers to incomplete class types to be deleted with a delete-expression. When the class has a non-trivial destructor, or a class-specific operator delete, the behavior is undefined. Some compilers issue a warning when an incomplete type is deleted, but unfortunately, not all do, and programmers sometimes ignore or disable warnings.

當呼叫deleter時,僅會釋放pointer所佔據的空間,由於不知道他的Destructor有沒有其他的行為,因此不會呼叫其Destructor。

以下是一個範例

在各大編譯器下給出的錯誤訊息

Visual Studio

1
warning C4150: deletion of pointer to incomplete type 'Object'; no destructor called

GCC

1
2
3
4
5
deleter.cpp: In function 'void delete_object(Object*)':
deleter.cpp:4: warning: possible problem detected in invocation of delete operator:
deleter.cpp:2: warning: 'p' has incomplete type
deleter.h:1: warning: forward declaration of 'struct Object'
deleter.cpp:4: note: neither the destructor nor the class-specific operator delete will be called, even if they are declared when the class is defined.

clang

1
2
3
4
5
6
7
8
deleter.cpp:4:2: warning: deleting pointer to incomplete type 'Object' may cause
undefined behaviour
delete p;
^ ~
./deleter.h:1:7: note: forward declaration of 'Object'
class Object;
^
1 warning generated.

解決方式也很簡單,在deleter.cpp中加入 #include “object.h” 即可。

或是參考 Check Delete Item