c++ - 删除表达式

标签 c++ destructor delete-operator incomplete-type

引用 here

That destructor will also implicitly call the destructor of the auto_ptr object. And that will delete the pointer it holds, that points to the C object - without knowing the definition of C! That appeared in the .cpp file where struct A's constructor is defined.

这很好奇然后

5.3.5/5 states - "If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined."

我的问题是,为什么这样一个试图删除指向不完整类型的指针的程序不被视为格式错误?为什么它被插入有条件的领域(整个类有一个非平凡的析构函数..)“未定义行为”?

”意味着什么?

编辑 2:

下面的代码格式是否正确? VS 和 Gcc/CLang 编译,但 Comeau 给出警告。我猜所有这些都是标准中提到的未定义行为的一部分。我的问题是“为什么这不是病态的而是未定义的”?

#include <iostream>
#include <memory>
using namespace std;

struct C;
                        // Is this the POI for auto_ptr<C>? $14.6.4.1/3
struct A{
    A();
    auto_ptr<C> mc;
    ~A(){}             // how does it link to C::~C at this point?
};

struct C{};

A::A():mc(new C){}

int main(){
    A a;
}

最佳答案

在我写这篇文章时,您的文字显示“引用 [此处][1]”,但没有任何引用。

但本质上,该标准允许您删除一个指向不完整类型的指针,这样您就可以利用编译器没有的知识,即该类型的析构函数什么都不做。

std::auto_ptr 是一个问题的例子,尤其是对于 PIMPL 习语(一个臭名昭著的错误例子是 Herb Sutter 在 PIMPL 上的 GOTW,他错误地使用了 std::auto_ptr). boost::shared_ptr 是一个没有问题的例子(通常)。这是因为 boost::shared_ptr 的构造函数存储了一个删除函数,并且必须在构造时知道指针对象的完整类型。

干杯,

关于c++ - 删除表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3956807/

相关文章:

C++(使用 <windows.h> 的串行通信)- 我如何事先知道 ReadFile() 方法将读取多少个字符

c++ - 如何在std::getline中自定义分隔符

c++ - Qt Creator错误无限循环

C++ 重载运算符 +

c++ - 大数组指针删除

c++ - delete[] (ptr, 0) 的行为

c++ - 修改 C++ 字符串对象的底层 char 数组

C++ 析构函数调用了错误的对象?

C++构造函数、析构函数、类型转换错误

c++ - delete[] 操作如何在析构函数成功时崩溃? (在 C++ 中)