简体   繁体   中英

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 :-

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

However, when I run the following two in gdb I get :-

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.

Note :- The second value (false) is the correct value that I want to be returned using the first syntax. 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.

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. 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. However, if gdb is used with code build using g++, then the p command behaves correctly. Yet when gdb is run on code built using clang++, I get:

(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.

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? . So, I tried lldb , and it worked as expected. This is consistent with the comment that was added as I was investigating.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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