How do I call the class's destructor?
You should not call your destructor explicitly.
When you create your object on the stack (like you did) all you need is:
int main()
{
date ob2(12);
// ob2.day holds 12
return 0; // ob2's destructor will get called here, after which it's memory is freed
}
When you create your object on the heap, you kinda need to delete
your class before its destructor is called and memory is freed:
int main()
{
date* ob2 = new date(12);
// ob2->day holds 12
delete ob2; // ob2's destructor will get called here, after which it's memory is freed
return 0; // ob2 is invalid at this point.
}
(Failing to call delete on this last example will result in memory loss.)
Both ways have their advantages and disadvantages. The stack way is VERY fast with allocating the memory the object will occupy and you do not need to explicitly delete it, but the stack has limited space and you cannot move those objects around easily, fast and cleanly.
The heap is the preferred way of doing it, but when it comes to performance it is slow to allocate and you have to deal with pointers. But you have much more flexibility with what you do with your object, it's way faster to work with pointers further and you have more control over the object's lifetime.
How to call class destructor / constructor
In your code a controller
owns a testing
. The implication to anyone reading the code is that it is the same testing
for the lifetime of the controller
. This is certainly also how C++ see it - it will construct the testing
during construction of a controller
and destroy the testing
when the controller
is destroyed.
Two possible solutions:
- Instead of trying to replace
testing
, reset it. This is what @LogicStuff was talking about in his comment on your question._testing = testing();
constructs a newtesting
and then copies its state to the existing instance, making the exisiting instance look like a new one. You could (should?) make this explicit by givingtesting
aReset
method (whose implementation should typically be that assignment*this = testing();
rather than a hand-coded resetting of each member variable.) - Do this only if resetting atesting
makes business sense. - If resetting
testing
doesn't make sense on a business level, and you are in fact wanting to replace it, then havecontroller
own astd::unique_ptr<testing>
instead. Then you canreset
orswap
a newly constructed instance in whenever you need to and still be sure that destructors will be called automatically.
How to call destructor of C++ class safely from a Python wrapper class using ctypes?
As per Python's data model doc:
Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether...
...
Some objects contain references to “external” resources such as open files or windows. It is understood that these resources are freed when the object is garbage-collected, but since garbage collection is not guaranteed to happen, such objects also provide an explicit way to release the external resource, usually a close() method. Programs are strongly recommended to explicitly close such objects. The
try…finally
statement and thewith
statement provide convenient ways to do this.
So even if in most cases __del__
method of an object is being called by GC, it is not guaranteed. with
statement (from PEP 343) on the other hand guarantees that if __enter__
method of the object succeeded, then __exit__
method will be called at the end of the statement, both in case of normal execution and in case of exception. (More detailed in this question)
An example could be as below, with the usage of "object-closing" context manager from PEP 343 examples, and a wrapper class with close
method which calls native object's destructor:
class NativeObjectWrapper(object):
def __init__(self):
self.nativeObject = nativeLib.CreateInstance()
def close(self):
nativeLib.DestructorFunction(self.nativeObject)
class closing(object):
def __init__(self, obj):
self.obj = obj
def __enter__(self):
return self.obj
def __exit__(self, *exc_info):
try:
close_it = self.obj.close
except AttributeError:
pass
else:
close_it()
#example of usage
with closing(NativeObjectWrapper()) as objectWrapper:
... #some usage of native wrapper
Calling private member getter call class destructor every time
Even though you have defined the _weapon
member of your HumanA
class as a reference to a Weapon
, the getWeapon
function is declared as returning an actual Weapon
object (by value); so, when called, it will make a copy of the Weapon
object referenced by the member and return that – the copied object will be destroyed (and it's destructor called) when it goes out of context.
You should declare your getWeapon
function as returning a reference, and then return (a copy of) the relevant human's _weapon
member:
Weapon& HumanA::getWeapon(void) const {
return _weapon;
}
C++ destructor called after calling constructor
In this assignment statement
*a = Foo(10);
there is created a temporary object of the type Foo
that is assigned to the object specified by the expression *a
using the default copy assignment operator (neither copy or move constructor is called here). After the assignment the temporary object is deleted. The undeclared variable cow
(it seems it is a data member of the class Foo
) of the object pointed to by the pointer a
now contains the same value 10
. And in the end of the program the object pointed to by the pointer a
is also deleted.
As a result you will get two messages
10 ~ Foo -
10 ~ Foo -
The first one is generated by the destructor of the temporary object and the second one is generated by the object pointed to by the pointer a
.
Related Topics
Immediate Exit of 'While' Loop in C++
Direct C Function Call Using Gcc's Inline Assembly
C++ Get Description of an Exception Caught in Catch(...) Block
Can You Start a Class Name with a Numeric Digit
Hide the Console of a C Program in the Windows Os
Problem with Compiling Rinside Examples Under Windows
What Is the Simplest Way to Convert Char[] To/From Tchar[] in C/C++(Ms)
Does Calling a Destructor Explicitly Destroy an Object Completely
How to See the Output of the Visual C++ Preprocessor
String Comparison with the Most Similar String
Disable Sleep Mode in Windows Mobile 6
Understanding Virtual Base Classes and Constructor Calls
Check If a Type Is Passed in Variadic Template Parameter Pack
Why the Sequence-Operation Algorithms Predicates Are Passed by Copy