3

I'm wondering is there any predefined macro or something in C++ that could possible to trace back where the destructor is triggered?

It could be something like this:

    class myClass{
    myClass();
    ~myClass();
    };
    myClass::~myClass(){
        printf("Object destroyed in %s.\n", __TRACEBACKMACRO__);
    }

    int main(){
    myClass tempClass;
    return 0;
    }

It should output something like this:

    Object destroyed in main().

It's better to output the scope and namespace information as well.

Additional information: FUNCTION or func macro seems only work in functions not in structs and classes. reference. Any macros that work in struct and class?

Charles Chow
  • 1,027
  • 12
  • 26
  • 1
    http://stackoverflow.com/questions/16100090/how-can-we-know-the-caller-functions-name – Ashalynd May 07 '14 at 21:53
  • 1
    Thank you, but how about scope and namespace information? – Charles Chow May 07 '14 at 21:54
  • Is this for debugging? Then set a breakpoint on the destructor in the debugger. Are you on Linux? – kec May 07 '14 at 22:01
  • Do not try to figure it out for each object just allocate them dynamically and dallocate them when ever you want. – Mahmoud Fayez May 07 '14 at 22:01
  • 5
    You're basically asking how to find the stack trace. That's not a standard thing, but both GCC and MSVC appear to have (different) methods to do so. http://stackoverflow.com/questions/3899870/print-call-stack-in-c-or-c http://stackoverflow.com/a/691742/321772 – Adam May 07 '14 at 22:02
  • In my program the destructor get called 50+ times, breakpoint is too much works.... I'm working on Windows – Charles Chow May 07 '14 at 22:04
  • The Itanium ABI for C++ specifies an unwinding API. You could probably use that to obtain a call trace (or use a ready-made library). – Kerrek SB May 07 '14 at 22:04
  • @Ashalynd Your link shows a nice debugging trick - having that in release code is plain wrong –  May 07 '14 at 22:07

1 Answers1

4

You could use the backtrace library though the avalability depends on the platform and compiler:

  • with gcc compiler (Linux or MacOS X) to display the stacktrace in C++:

    include "execinfo.h" and use backtrace -> backtrace_symbols -> __cxa_demangle

  • with Windows:

    include StackWalker.h and use StackWalker class

Have a look at this article http://oroboro.com/stack-trace-on-crash/ for ulterior details.

Alternatively you could use Boost.Call_stack: http://melintea.github.io/Boost-Call_stack/index.html

Andrea Luciano
  • 461
  • 3
  • 5