3

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.

owagh
  • 3,428
  • 2
  • 31
  • 53
  • 1
    FWIW, there is no difference between `fooobj.operator bool()` and `(bool)(fooobj)` in C++. I don't know how they are different in gdb. – R Sahu Jan 13 '16 at 21:30
  • @RSahu That is exactly what my understanding was. However, it definitely doesn't seem to be working that way. – owagh Jan 13 '16 at 21:32
  • There is [no difference](https://ideone.com/V88alD). Your question seems to be more about the operation of GDB than about C++. – Kerrek SB Jan 13 '16 at 21:39
  • @KerrekSB Hmm, It may be the case that this is a quirk of gdb. – owagh Jan 13 '16 at 21:58
  • 2
    @owagh: Something tells me that gdb probably isn't a complete C++ REPL... – Kerrek SB Jan 13 '16 at 22:33

1 Answers1

1

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, i.e. (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.

Community
  • 1
  • 1
Anatoli P
  • 4,791
  • 1
  • 18
  • 22