c++ - gcc 6.1.0 段错误 - gcc 错误?

标签 c++ gcc gcc6

让我们考虑以下代码。事实上,这是我使用 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/

相关文章:

c++ - 在桌面图标后面放一个窗口

c++ - QWebEngineView 在外部浏览器中打开

c++ -/usr/lib/libstdc++.so.6 : version `GLIBCXX_3.4.15' not found

gcc - GPROF 平面轮廓空结果

c++ - Boost union 在 1.67 中不起作用,但在 1.61 中起作用。为什么?

c++ - 如何声明 handel 数组?

c++ - constexpr 唯一标识,使用 clang 编译但不使用 gcc

c - 带有内置函数的奇怪 GCC6 优化

c++ - std::unique_ptr<T[]>::reset 在 gcc 6 中的实现

c - 我的 C 代码遇到 sigsegv 错误