3

我有一个类,我已经像这样显式地重载了运算符 bool:-

class Foo {
  explicit operator bool() {
    // return_something_here
  }
};

但是,当我在 gdb 中运行以下两个时,我得到:-

gdb) p fooobj.operator bool()
$7 = true
gdb) p (bool)(fooobj)
$8 = false

这两个调用有什么区别,为什么它们返回不同的东西?

编辑:- 我正在使用 clang 编译器。

注意:- 第二个值 (false) 是我希望使用第一种语法返回的正确值。我正在使用代码生成器,因此我无法完全控制生成的 c++,以防有人好奇我为什么不只使用第二种语法。

即使在那种情况下,两者之间的差异仍然是一个悬而未决的问题。

4

1 回答 1

1

我刚刚进行了一些快速测试,似乎 gdb 不能很好地处理使用 clang 编译的代码。这是一个测试程序:

#include <iostream>

using namespace std;

class Foo {
public:
  Foo() : m_Int(0) {}
  operator bool() {
    return true;  // also tried false here
  }
private:
  int m_Int;
};

int main()
{
  Foo f;
  if (f.operator bool()) cout << "operator bool is true.\n";

  if ((bool)f)  cout << "(bool)f is true.\n";

  return 0;
}

运行二进制文件时,输出与预期一样,即 (bool)f 与 f.operator bool() 相同,与编译器无关。但是,如果 gdb 与使用 g++ 的代码构建一起使用,则该p命令的行为正确。然而,当 gdb 在使用 clang++ 构建的代码上运行时,我得到:

(gdb) print f.operator bool()
Couldn't find method Foo::operatorbool
(gdb) 

我在 Ubuntu 14.04 上运行 clang v. 3.4、gcc v. 4.8.4。

事实上,快速搜索发现:是否可以使用 lldb 调试 gcc 编译的程序,或者使用 gdb 调试 clang 编译的程序?. 所以,我尝试lldb了,它按预期工作。这与我在调查时添加的评论一致。

于 2016-01-14T05:22:58.373 回答