引用 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/