3

I am using totalview as a linux C++ debugger. Functions in our code often look something like this

double foo() {
    int a = 2;
    int b = 3;
    return bar(a,b);
}

where some preliminary work is done and than a more or less complex function bar is called a the return statement.

This is hard to debug with totalview, since the interesting return value can not be observed easily. Totalview can not evaluate the expressing bar(a,b). I can rewrite the code as

double foo() {
    int a = 2;
    int b = 3;
    const auto retVal = bar(a,b);
    return retVal;
}

Now, I can place a breakpoint at the return value and observe the in- and output of my function bar.

How can I do this without introducing a new (useless) variable?

schorsch312
  • 5,553
  • 5
  • 28
  • 57

1 Answers1

0

Let the compiler optimise out the "useless" variable, by a process called named return value optimisation, and leave it in. (Personally though I would help the compiler as much as possible by using the return type of the function explicitly rather than auto; so there's no potential type conversion at the return stage.). For what it's worth, I do this all the time, even with heavy objects such as std::vector. You can always check the generated assembler if you suspect the compiler is making superfluous copies.

Then you can set a breakpoint at the appropriate place as you know.

In some debuggers you can inspect the function return value directly by peeking at a register, but this is by no means universal.

Reference: http://en.cppreference.com/w/cpp/language/copy_elision

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I can do that. The problem is that the case without the additional return variable is within our large code base. Thus, I would need to edit all files for debugging. – schorsch312 Dec 05 '17 at 08:38
  • @schorsch312: Well, only the ones you need, on a step-by-step basis. – Bathsheba Dec 05 '17 at 08:39