让我们考虑以下代码。事实上,这是我使用 gmock 和模拟 void(void) 方法发现的缩小问题。
class Base {
public:
virtual ~Base() {}
};
class Derived : public Base
{
public:
void GetValueAndDelete() { delete this; } //here we crash
};
int main() {
Derived* p = 0;
p->GetValueAndDelete();
}
构建它:
/tools/gcc6.1/bin/g++ --version
g++ (GCC) 6.1.0
优化级别不同于 -O0 并且运行结果会导致段错误。
是 gcc bug 还是 c++ 代码的问题(是的,是的,我知道它使用副作用,但它可以与其他编译器一起使用并且也没有优化)
最佳答案
Is it gcc bug
没有。
or something with c++ code
是的。您在未指向有效对象的指针上使用箭头运算符。这具有未定义的行为。
Dereferencing null pointer and calling method in this way that does not use any members is fine.
根据标准,它很好。是 UB。
What is calling method on pointer?
是特定于实现的。
Deleting this is nothing special.
删除this
是很特别的。
You should only take care of not using any member after
是的,和您必须确保只有new
用于创建调用该函数的所有实例。没有自动对象,没有静态对象,没有 new[]
,没有 malloc
+ placement new。
所以是的,您可以删除它
,但要小心。
关于c++ - gcc 6.1.0 段错误 - gcc 错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38352381/