简体   繁体   English

object.operator bool()和(bool)对象有什么区别?

[英]What is the difference between object.operator bool() and (bool) object?

I have a class for which I have overloaded the operator bool explicitly like this :- 我有一个类,我明确地重载了​​运算符bool,如下所示: -

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

However, when I run the following two in gdb I get :- 但是,当我在gdb中运行以下两个时,我得到: -

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

What's the difference between the two invocations and why do they return different things? 两次调用之间有什么区别?为什么它们会返回不同的东西?

Edit :- I'm using the clang compiler. 编辑: - 我正在使用clang编译器。

Note :- The second value (false) is the correct value that I want to be returned using the first syntax. 注意: - 第二个值(false)是我想要使用第一个语法返回的正确值。 I'm using a codegen so I don't have complete control over what c++ gets generated in case anyone is curious why I don't just use the second syntax. 我正在使用codegen所以我无法完全控制c ++生成的内容,以防有人好奇为什么我不只是使用第二种语法。

Even in that case, the difference between the two would still be an unanswered question. 即使在这种情况下,两者之间的差异仍然是一个悬而未决的问题。

I just ran a few quick tests, and it appears to be that gdb doesn't handle code compiled with clang well. 我刚刚运行了一些快速测试,似乎gdb不能处理用clang编译的代码。 Here is a test program: 这是一个测试程序:

#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;
}

When the binary is run, the output is as expected, ie (bool)f is the same as f.operator bool(), regardless of the compiler. 运行二进制文件时,输出是预期的,即(bool)f与f.operator bool()相同,无论编译器如何。 However, if gdb is used with code build using g++, then the p command behaves correctly. 但是,如果gdb与使用g ++的代码构建一起使用,则p命令行为正确。 Yet when gdb is run on code built using clang++, I get: 然而,当gdb运行在使用clang ++构建的代码上时,我得到:

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

I'm running clang v. 3.4, gcc v. 4.8.4 on Ubuntu 14.04. 我在Ubuntu 14.04上运行clang v.3.4,gcc v.4.8.4。

In fact, a quick search revealed this: Is it possible to debug a gcc-compiled program using lldb, or debug a clang-compiled program using gdb? 实际上,快速搜索显示: 是否可以使用lldb调试gcc编译的程序,或使用gdb调试clang编译的程序? . So, I tried lldb , and it worked as expected. 所以,我尝试了lldb ,它按预期工作。 This is consistent with the comment that was added as I was investigating. 这与我正在调查时添加的评论一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM