Evaluating an expression with overloaded operators in c++ lldb

Daniel Golden picture Daniel Golden · Dec 5, 2013 · Viewed 8.5k times · Source

I'm debugging a C++ program in Xcode 5 using lldb, and I would like to evaluate arbitrary expressions in the debugger, particularly those that use overloaded operators.

For example, I created a very simple Xcode 5 C++ project with the following main.cpp and all compiler/linker/etc options set to the default:

#include <iostream>
#include <vector>

int main(int argc, const char * argv[])
{
  std::vector<int> vec;
  vec.push_back(42);
  std::cout << "vec[0] = " << vec[0] << std::endl;
  return 0;
}

I set a breakpoint on the return 0; line and ran the program.

Then, at the lldb prompt, printing the vector as a whole works fine:

(lldb) expr vec
(std::__1::vector<int, std::__1::allocator<int> >) $0 = size=1 {
  [0] = 42
}

However, I can't access its members using the overloaded operator[]:

(lldb) expr vec[0]
error: call to a function 'std::__1::vector<int, std::__1::allocator<int> >::operator[](unsigned long)' ('_ZNSt3__16vectorIiNS_9allocatorIiEEEixEm') that is not present in the target
error: The expression could not be prepared to run in the target

Similarly, I can't get the iterator (though I have less experience here, so my syntax may be wrong):

(lldb) expr vector<int>::iterator it = vec.begin()
error: use of undeclared identifier 'vector'
error: expected '(' for function-style cast or type construction
error: expected '(' for function-style cast or type construction
error: 3 errors parsing expression

and

(lldb) expr (vector<int>::iterator) vec.begin()
error: use of undeclared identifier 'vector'
error: expected '(' for function-style cast or type construction
error: expected '(' for function-style cast or type construction
error: 3 errors parsing expression

Analogously, printing a simple string works fine:

(lldb) expr string("a")
(std::__1::string) $0 = "a"

However, a simple string concatenation fails:

(lldb) expr string("a") + string("b")
error: invalid operands to binary expression ('string' (aka 'std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char> >') and 'string')
error: 1 errors parsing expression

What am I doing wrong? Does lldb support evaluation with overloaded operators?

Thank you in advance!

Answer

Dimaleks picture Dimaleks · Apr 15, 2014

I just ran into the same issue and apparently found a simple work-around. You can access i-th element of a vector vec like this:

(lldb) p vec.__begin_[i]
(int) $1 = 100