rookie
rookie

Reputation: 7843

Constructor and destructor calls

How can I check if my constructor or destructor were ever called?

Because of implicit calls I don't know if they were actually called.

Upvotes: 2

Views: 266

Answers (6)

Ashish Yadav
Ashish Yadav

Reputation: 1697

One of the possible ways is to put properly labeled "std::cout"s with distinctive messages for each constructor and destructor.

Upvotes: 0

Steve Townsend
Steve Townsend

Reputation: 54128

If you want to avoid or better manage implicit calls, you can qualify the constructor as explicit. This will show you any implicit calls you might be missing at compile-time.

Once you've sorted out this usage, you can remove the qualification or leave in as you prefer.

If you want to track counts of ctor vs dtor calls, you could add a static counter for calls to each in the class and then use interlocked increment and decrement ops to count ctors and dtors respectively. This should show whether you are matching them up properly. You'd have to include copy ctor and any non-default ctors you have implemented in the class for this to work.

Upvotes: 1

Karel Petranek
Karel Petranek

Reputation: 15154

You can set a breakpoint to them and see if it gets hit. Or you can output a line to console:

class MyClass {
  MyClass()  { std::cout << "In constructor" << std::endl; }
  ~MyClass() { std::cout << "In destructor" << std::endl; }
};

Upvotes: 0

C.J.
C.J.

Reputation: 16081

  1. Run your application in a debugger and put a breakpoint in your constructor or destructor. If the debugger stops at that breakpoint, then your constructor or destructor got hit.
  2. Put in printf statements saying things like "class foo constructor got hit", or "class foo destructor got hit". Then when your application runs you can watch the standard output (output to the console window) and see what happened to your application. This is generally called tracing. It's very informative at times.

Upvotes: 0

Philipp
Philipp

Reputation: 11814

  • set a breakpoint in the c'tor in your IDE
  • write some debug output to the console/to a file/whereever you want
  • read a book to find out what the standard says when they are called.

Upvotes: 9

AndersK
AndersK

Reputation: 36082

Why don't you just put in a couple of cout << "I'm here" in your ctor/dtor or use the debugger and set break points there?

Upvotes: 6

Related Questions