A simple question here, I have several classes in my code, but only one of them exhibits this issue and I cannot for the life of me work out why. When I create an instance of the class, the destructor is called straight after, yet the instance of the class does not actually appear to be deleted.
Maybe I could live with that if there were not delete[] operations in the destructor that DO affect the instance of the class.
I read somewhere about the ‘rule of three’ or something, so attempted to see what I was missing. I already have a default constructor as well as a user-defined one. I then added what I think is called a copy-constructor, something like this:
MyClass::MyClass(const MyClass &duplicate)
{
variable1 = duplicate.variable1;
variable2 = duplicate.variable2;
// etc
}
What am I missing here that could cause this issue?
EDIT: The requested code. I’ve renamed everything so that it’s all clear (this code still compiles with the issue). First, the header file, MyClass.h:
#ifndef MYCLASS_H
#define MYCLASS_H
#ifndef UNICODE
#define UNICODE
#endif
#include <string>
class MyClass
{
public:
MyClass();
MyClass::MyClass(const MyClass &);
MyClass(int, std::wstring inputWord, int);
~MyClass();
int intOne;
int intTwo;
};
#endif
Next MyClass.cpp:
#include "MyClass.h"
#include <Windows.h>
MyClass::MyClass(const MyClass &duplicate)
{
intOne = duplicate.intOne;
intTwo = duplicate.intTwo;
}
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
MessageBox(NULL, TEXT("TEST"), TEXT("TEST"),0);
}
MyClass::MyClass(int intOneInput, std::wstring stringInput, int intTwoInput)
{
intOne = intOneInput;
intTwo = intTwoInput;
}
And finally how I’m creating my object:
MyClass test(0, TEXT("TEST"), 0);
[Copied from op’s comment]
Actually, scratch my last comment, the deconstructor is NOT called with that particular line (until it goes out of scope), the line that does is words.push_back(MyClass(0, TEXT("TEST"), 0)); declared as std::vector<MyClass> words
The destructor should be called when the object is destroyed. If you create the object with
new, The destructor will be called when you calldeleteon the object. Otherwise it should be called when it goes out of its scope. You can set breakpoint inside its destructor and see the callstack to check what is calling the destructor. Hope it helps.[Update]
Try to add the below
printffor all ctor and dtor to make it sure you are not confused with temporarily created objects.[Update]
This creates a temporary object as stl containers(like
vector) always “copy” things to store. (Unless “move” happens. I don’t want to start explaining “move” and rvalue here.)