【问题标题】:What is the difference between object.operator bool() and (bool) object?object.operator bool() 和 (bool) 对象有什么区别?
【发布时间】:2016-04-19 01:11:51
【问题描述】:

我有一个类,我已经像这样显式地重载了运算符 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++ 的内容,以防有人好奇我为什么不只使用第二种语法。

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

【问题讨论】:

  • FWIW,fooobj.operator bool()(bool)(fooobj) 在 C++ 中没有区别。我不知道它们在 gdb 中有什么不同。
  • @RSahu 这正是我的理解。但是,它似乎绝对不是那样工作的。
  • no difference。你的问题似乎更多是关于 GDB 的操作而不是关于 C++。
  • @KerrekSB 嗯,这可能是 gdb 的一个怪癖。
  • @owagh:有人告诉我 gdb 可能不是一个完整的 C++ REPL...

标签: c++ c++11 gdb clang++ conversion-operator


【解决方案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。

事实上,快速搜索发现:Is it possible to debug a gcc-compiled program using lldb, or debug a clang-compiled program using gdb?。所以,我尝试了lldb,它按预期工作。这与我在调查时添加的评论一致。

【讨论】:

  • 为了完整起见,您也可以尝试安装lldb 看看效果如何?
  • 写得很好的答案。接受!
猜你喜欢
  • 2011-09-19
  • 1970-01-01
  • 2018-08-07
  • 1970-01-01
  • 2011-03-02
  • 1970-01-01
  • 2016-07-21
  • 2011-06-12
  • 2018-08-29
相关资源
最近更新 更多