FAQ Database Discussion Community


Is it safe to declare non-virtual destructor in the derived class

c++,inheritance,destructor,virtual-functions
In the program: struct A { virtual ~A(){ } }; struct B : A { ~B(){ } }; int main(){ } The Standard N4296::12.4/9: If a class has a base class with a virtual destructor, its destructor (whether user- or implicitly-declared) is virtual. So, the compiler will redeclare the destructor...

Ambiguous destructor for QObject?

qt,destructor,qobject
Qt reference for QObject destructor says: All signals to and from the object are automatically disconnected, and any pending posted events for the object are removed from the event queue. However, it is often safer to use deleteLater() rather than deleting a QObject subclass directly. ... Warning: Deleting a QObject...

[c++]Why is my class destructor called twice?

c++,class,visual-studio-2013,destructor
I have such code like, #include <iostream> #include <string> using namespace std; class Heart { private: int bpm; public: Heart(int bpm) : bpm(bpm) {} int getBPM() { return bpm; } }; class Kidney { private: double PercentFunction; public: Kidney() : PercentFunction(0) {} Kidney(double pf) : PercentFunction(pf) {} double getPF() {...

When is it safe to call this-> in constructor and destructor

c++,c++11,constructor,destructor
I've not been able to find a conclusive answer to this so far. When is it safe to call this-> from within an object. And in particular from inside the constructor and destructor. And also, when using public inheritance. Is it safe to use up and downcasting on the result...

Strange Destruction of objects

c++,destructor
I am puzzled why the destructor is being called so many times. #include <iostream> #include <vector> class Box { public: int x; Box(int x); ~Box(); }; Box::~Box() { std::cout << x << " Destroyed\n"; } Box::Box(int x) { this->x = x; std::cout << x << " Created\n"; } int main()...

Insert in unordered map calls constructor

c++,c++11,containers,destructor,rvalue
In order to avoid duplication of elements, I'm building a class that holds elements and provide an acces to them. My elements (DynLibrary) are movable but not copyable class DynLibrary { public: DynLibrary() : _handle(nullptr) {} DynLibrary(const std::string& path) { DynLibrary::open(path); } DynLibrary(const DynLibrary&) = delete; DynLibrary(DynLibrary&&) = default; ~DynLibrary()...

Why is the destructor of an exception called twice?

c++,destructor
I have following program: #include <iostream> #include <stdexcept> #include <string> using namespace std; class MyError : public runtime_error { public: MyError(string mess = ""); ~MyError(void); }; MyError::MyError(string mess) : runtime_error(mess) { cout << "MyError::MyError()\n"; } MyError::~MyError(void) { cout << "MyError::~MyError\n"; } int main(void) { try { throw MyError("hi"); } catch...

Should all Objects that register events be IDisposable

c#,events,event-handling,destructor,idisposable
As per my understanding when an Object is no longer required it is best practice to unsubscribe all event handlers in any Objects that subscribes to events. This is done to avoid handling an event within an Object when the given Object may reside in a invalid state (no doubt...

Reason for debug assertion in this code

c++,destructor,c++03
Suppose that I have this code - this code does nothing and I understand that their is a memory leak as the destructor of car is not virtual. However I do not understand why I get a debug assertion for this code. I am using visual studio 2010. struct car...

What does it mean that the D garbage collector is “not guaranteed to run the destructor for all unreferenced objects”?

garbage-collection,d,destructor,finalizer
The D documentation at http://dlang.org/class.html#destructors states that "The garbage collector is not guaranteed to run the destructor for all unreferenced objects." However I am a little contused as to what this actually means. Is this saying that a GC implementation can choose to not call destructors when it collects the...

Destructor restrictions - access managed member from destructor

c#,memory,destructor,finalizer
Is it right that in C# Destructor (Finalizer) you can not access managed members of your class? If it is true, why is it? What other C# finalizer restrictions you know? Example: class MyClass { private FileStream _fs; private IntPtr _handle; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~MyClass() {...

Does Deleting a Dynamically Allocated Vector Clear It's Contents

c++,vector,destructor,clear,dynamic-allocation
Say I have: vector<string>* foo = new vector<string>(); I add a ton of stuff to it, use it, and then I just call: delete foo; Did I need to call foo.clear(); first? Or will the delete call the destructor. Please no comments regarding the folly of this, I know that...

Will dynamic arrays in fields of Delphi objects be automatically deallocated/freed when the object is destroyed?

delphi,destructor,dynamic-memory-allocation,dynamic-arrays
If I have a Delphi object containing a field with a dynamic array (containing for example strings), as follows: TClassWithDynArrayField = class(TObject) public some_dyn_array : array of string; end; will this array (and/or the contents of it) be automatically deallocated/freed when the object is destroyed, or will I have to...

emptying an std::queue through a function that returns the front() and pops()

c++,memory-management,destructor
I'm writing a template class that is supposed to provide a queue protected against concurrent access, basically to be able to write classes that can treat a list of items with a variable number of concurrent worker threads. The template class has a method: bool getFront(T &value) { CritSectEx::Scope scope(listLock);...

What is the difference between the Destroy method and the Finalize method on a Delphi object?

delphi,destructor,dynamic-memory-allocation
What is the difference between the "Destroy" method and the "Finalize" method on a Delphi object? This page (and other sources) mentions the "Finalize" method of Delphi objects, but the Delphi reference page about object methods strangely does not mention it at all (and even stranger, Google doesn't provide any...

Automatic calling of parent destructor in case of non-virtual destructor?

c++,destructor
I have a struct O, defined in third party code. As it is C code, it does NOT define a virtual destructor. (In my case it's the OVERLAPPED struct from win32 appi). The customer code that I am modifying has a class S, deriving from class A, deriving from struct...

Why my class field is destroyed in constructor

c++,constructor,attributes,destructor
In my constructor I initialize a field. The field is destroyed just after the initialization. Here's my code and my test: A.hpp class A { private: T t; public: A(); ~A(); void add(string name, string num); }; A.cpp A::A() { cout << "Creating A\n"; t = T(100); cout << "End\n";...

destruction of static storage duration objects & undefined behavior

c++,destructor,undefined-behavior
C++ standard section 3.6.1 says that Calling the function std::exit(int) declared in <cstdlib> terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration If std::exit is called to end a program during the destruction of an object with static storage duration, the...

Destructor direct call in C++

c++,destructor,new-operator,placement-new
Hence the code below. class A { int x; public: A() {x = 3;} }; int main() { void* mem = operator new(sizeof(A)); A* obj = static_cast<A*>(new(mem)(A)); std::cout << obj->x << std::endl; obj->A::~A(); std::cout << obj->x << std::endl; } My first question is: Why I can directly call the destructor...

Where C++ calls destructors?

c++,class,memory-management,destructor
Assuming Member and MyList are two user defined classes. In the following code: void fillList(MyList &list1) { Member m1("aaa"); Member m2("bbb"); list1.insert(m1); list1.insert(m2); } void func1() { MyList lst; fillList(lst); lst.printAll(); } int main() { func1(); return 0; } At which point does C++ call destructor of each m1, m2...

Error when deleting HashMap Element in xmemory0

c++,pointers,hashmap,destructor
Whenever I try to delete one the elements for my HashMap, I get an error in the C++ code (not my code...the C++ people's code - specifically, xmemory0). I am sure the error is on my end, but I have no clue where, since the debugger is telling me its...

Is the constructor not called for function parameters?

c++,constructor,destructor,pass-by-value
So, this might be kinda of an embarrassing question. I was re-enforcing my C++ basics and I ran into this curious case. The interesting part is that upon entering the function, the constructor is not called for the object lb but upon leaving the function the destructor is called for...

Member variables clearing while using desctructor

c++,inheritance,destructor
I was going through someonline quiz on C++ and below is the question I bumped into http://www.interqiew.com/ask?ta=tqcpp01&qn=3 class A { public: A(int n = 2) : m_i(n) { } ~A() { std::cout << m_i; } protected: int m_i; }; class B : public A { public: B(int n) : m_a1(m_i...

Memory corruption (double free) on class destruction

c++,destructor,free
Would anyone please explain this case: why I am facing 'double free' problem in this simple code? void Rreceive (myclass){} int main () { myclass msg (1); Rreceive(msg); return 0; } where myclass is: class myclass { private: HeaderType header; byte * text; public: myclass(int ID); ~myclass(); HeaderType getHeader(); byte...

Should Member Data Always be Cleared/Zeroed in the Destructor?

c++,destructor
Is there any good reason to not clear/zero an object's basic member data in the destructor? It seems like this should be considered standard practice for the sake of tidiness or privacy since there are conceivable ways to re-read the data from a deleted object: #include <iostream> class Box {...

Deleting inherited dict elements in python

python,python-3.x,dictionary,destructor
I have a dict of Objects which are to be destroyed as follows. class Elem: def __init__(self, name): self.name = name . . def __del__(self): print('destroying elem' + self.name) class DerivedDict(dict): def __init__(self): super(DerivedDict, self).__init__() def __del__(): for k in self.keys(): del self[k] elem = Elem('myname') ddict = DerivedDict() ddict['myname']...

C++11 Destructor = delete

c++,c++11,destructor
I've seen a constructor = delete explanation here but I'm wondering if I should forbid destructor calls as well. I'm trying to use a class like this: class A { public: static bool foo(const char* filePath); static void foo(const int something); private: A() = delete; ~A(); }; Should I also...

Is it safe to delete a POD object by a pointer to its base?

c++,c++11,destructor,pod
Actually I am thinking about trivially destructible objects, not only about POD (I am not sure POD can have base class). When I read this explanation for is_trivially_destructible from cppreference I notice this: Storage occupied by trivially destructible objects may be reused without calling the destructor. So, it is safe...

Do I have to manually delete object even after destructor?

c++,destructor
This question relates to C++ game engine, called AppGameKit (AGK). I've created a separate class for Text so that I don't have to call AGK functions when creating Text. Here's the simple class: Text.h class Text { private: int _ID; void Destory(); public: void AddText(); Text(int ID); ~Text(); }; Text::Destroy()...

Thread joining using a destructor

c++,multithreading,destructor
This is a continuation to my question: Thread creation inside constructor Now that I have successfully created a thread in a constructor, I know that it must be joined. As I am developing an API, I have no control over the main function so I can't join it there. Will...

Exception in destructor while using = overload function [closed]

c++,exception,destructor
I have a class for polynomials. Function of + overloading works but I couldn’t use = overloading function because of exception! I debugged the program and saw exception is in destructor, I don’t know how to fix it! polynomial::~polynomial() { delete[] coeff; } const polynomial& polynomial::operator=(const polynomial& p) { if(this...

Using global pointers and custom destructor - How to avoid memory leak?

c++,qt,memory-leaks,destructor
I've been studying C++ for my Thesis with Bjarne Stroustrup's book [ C++ 11 ]. Even so, I'm still not getting somethings about handling memory leak in C++. He says a lot in the book to avoid the use of new, delete and also custom destructors. I would like to...

Why is the constructor/destructor called once? [duplicate]

c++,c++11,constructor,destructor
This question already has an answer here: What are copy elision and return value optimization? 4 answers Here is my source code: #include <iostream> #include <memory> #include <vector> using namespace std; class Copy { public: Copy() { cout << "Constructor called" << endl; }; Copy(const Copy& copy) { cout...

Class destructor, runtime error: Unhandled exception - Stack overflow

c++,runtime-error,stack-overflow,destructor,unhandled-exception
The destructor for List appears to work, but having trouble with the destructor for Element and List_iter: Unhandled exception : 0xC00000FD: Stack overflow (parameters: 0x00000001, 0x002E2F78). List: #ifndef GUARD_List_h #define GUARD_List_h #include "Element.h" #include "List_iter.h" template <typename T> class List { public: List() : begins(new Element<T>), ends(new Element<T>), Element_count(0) {...

Confused by variable scope - destructor called unexpectedly

c++,c++11,scope,destructor
I have 3 classes, Fruit, Apple and Orange, with Fruit being the parent of both. I have a static method where I do the following: int32_t Fruit::frutificate(const Settings& settings) { Fruit listener; if (settings.has_domain_socket()) { listener = Apple(settings); } else { listener = Orange(settings); } return uv_run(listener.loop, UV_RUN_DEFAULT); } What...

Destroy-and-regenerate assignment operator: what if I'm careful?

c++,destructor,undefined-behavior
This is a bad pattern. Copy-and-swap is better. foo & operator = ( foo const & other ) { static_assert ( noexcept( new (this) foo() ), "Exception safety violation" ); this-> ~ foo(); try { new (this) foo( other ); } catch (...) { new (this) foo(); // does not...

want to declare arrays by using constructor with variables

c++,arrays,constructor,initialization,destructor
class matrix { public: matrix(); matrix(int row, int column); ~matrix(); private: const int DEFAULT_SIZE; int size_row, size_column; double *entry; }; // main function int main() { //make a matrix of default size matrix A; /* no error */ delete A; //make 5 matrices of default size matrix *B = new...

Why We Say Destructor Call When Object Goes out of Scope?

c++,destructor
I learned that the destructor is called when an object goes out of scope and also the destructor deletes the objects. Ok fine, but what's happening here? I'm calling the destructor explicitly, if it deletes the object then why is the destructor implicitly called? Even though there no object now...

C++: simple quest., destructors being called multiple times

c++,oop,design-patterns,destructor
I am learning how to do OOP in c++. Please take a look at my simple example, and tell me if my OOP approach is incorrect. I am looking to do this: create a "settings" type class that will be passed into a few other classes by reference. In the...

Why is a destructor not called when I click the close button on the console?

c++,windows-7,destructor,terminate
I have a command line application on Windows 7. It consists mainly of an endless loop. When I click on the close button of the command-line console window, it seems to be killed instantly. However, I close an SQLite database connection in the destructor, and so I am afraid that...

C# code calling C++/CLI class method - new instance still has old instance values

c#,memory-leaks,c++-cli,marshalling,destructor
I am a newbie in terms of working with both C# and C++/CLI code together. In my C# code, I am creating a new instance of a class FooClass and running a method FooClass:ParseCmdArgs, which takes in a System::String, converts to a std::string, and then pushes to a vector "bars"...

WA_DeleteOnClose delete all members?

c++,delete,heap,qt5,destructor
I'm in trouble with Qt5's WA_DeleteOnClose attribute. This is the situation: I have a class M that extends QMainWindow, and in this class I use an heap-allocated array. I read that with WA_DeleteOnClose when the window M is closed, and the destructor called, every member with M as parent is...

Using destructor in class

c++,class,constructor,copy,destructor
I've got a project in C++ that uses classes(quite basic elements). My class looks like this: class vehicule: public frane,public motor,public directie,public noxe,public caroserie { char tip[40]; int placfatacant,placfatatot; static const int placfatapret=18; int placspatecant,placspatetot; static const int placspatepret=15; public: vehicule() void settip(char) void verifauto() ;}; I've been told I...

Why destructor is being called but construction not being called when passing object as a parameter? [closed]

c++,constructor,destructor
If I write a class named Test and write a Test type show() function like #include <iostream> using namespace std; class Test{ public: int x; Test() { cout<<"Empty or Default Constructor"<<endl; } Test(int x) { cout<<"Valued constructor"<<endl; } ~Test() { cout<<"Destructor"<<x<<endl; } Test show(Test obj) { Test tt; tt.x=20; return...

Default destructor for pointers?

c++,pointers,destructor
Suppose I have a self-defined vector class and the destructor for the vector class is defined as below, ~vector(void) { for (uint64_t i = 0; i<len_elem; i++) { //destruct each elem front[i].~T(); } ::operator delete(head); head = nullptr; capacity = 0; } In my understanding, this destructor works fine for...

Object Returned from Function Calls Destructor

c++,function,object,return,destructor
In C++, I have a function which returns a first-class object by value, like this: Image Video::getFrame(int frame) { Image img(...); ... processing ... return img; } After the value is returned and img goes out of scope, the Image destructor is called, destroying all of the data inside the...

Thread object destroys itself immediately after creation?

c++,multithreading,c++11,destructor
I created a class, PrimaryThread, to handle most of my application's work outside of the main thread, where it wont be interfered with by code that needs to work on the main thread and might be blocking. I create the PrimaryThread object inside main() on the stack, and then... it...

why is it possible to make the destructor pure virtual [duplicate]

c++,destructor,pure-virtual
This question already has an answer here: Why do we need a pure virtual destructor in C++? 9 answers As I know in cpp, when we delete an object or when the main finishes, the destructors of all objects will be called. For those objects whose type are class...

What order are destructors called and member variables destroyed in C++ using inhertitance?

c++,inheritance,visual-studio-2008,destructor
Very similar question as these, except not exactly: What is the order in which the destructors and the constructors are called in C++ Order of member constructor and destructor calls I want to know: are the member variables of the derived class destroyed before or after the destructor of the...

Destructor execution order?

c#,destructor
I know that Destructors in c# do not have an execution order. The following Structure i do use in several Classes, it's to Desturct instances and the Static Information: public class MyClass { private static readonly Destructor DestructorObject = new Destructor(); ~MyClass() { Console.WriteLine("Destructor Called"); } static void Main(string[] args)...

C++ Correct way to free a vector of a custom class

c++,memory,vector,destructor,resource-management
I have my custom class, like: class MyClass { public: int i; std:string name; void DoSomeStuff(); } and another class with a list of my custom class: class MyClassList { public: std::vector<MyClasss> myClassList; } How shall be the list destructor in order to release all used vector space in memory:...

Why destructor isn't invoked?

c++,c++11,destructor,shared-ptr,weak-ptr
#include <memory> #include <iostream> struct Foo { Foo() { std::cout << "Constructor ...\n"; } void doSth() {std::cout << "hi" << std::endl;} ~Foo() { std::cout << "Destructor ...\n"; } }; int main() { {std::weak_ptr<Foo> jack = (*(new std::shared_ptr<Foo>(new Foo))); std::cout << (jack).use_count() << std::endl; // std::shared_ptr<Foo> ptr = jack.lock(); // std::cout...

My object is being destructed right after being constructed

c++,arrays,constructor,boolean,destructor
I'm trying to construct a two-dimensional boolean array with a class I've created called Grid. The Grid object is a private member class of another class called GameOfLife. Whenever I create a GameOfLife object with the parameters belove, the Grid object first gets created with the default constructor, then it...

C++ Cascading destructions of objects with static storage duration

c++,destructor,undefined-behavior,object-destruction
this link says about cascading destructions of objects with static storage duration is popular undefined behaviour in C++. What is it exactly? I can't understand. It will be more good if it is explained with a simple C++ program that can demonstrate this. Your help is greatly appreciated. Thanks

Is there destructor in typeScript

javascript,typescript,destructor
Is there destructor in TypeScript?If not, how can I delete an object? I tried destructor() and ~ClassName() but it not worded.

Segfault from dict destructor

python,c++,boost,dictionary,destructor
I have problem with boost python, base object destructor. When object boost::python::dict is created and destroyed in py_init scope then everything is fine. But in py_smth scope dict is only created success, after constructor executrion when local dict descructor is called then I have segmentation fault. class py_init { public:...

Error in DAG destructor

c++,destructor,directed-acyclic-graphs
I have a Dag class (Directed Acyclic Graph) that contains a vector of raw pointers to objects of the class Node. This vector is called m_roots and consists of all the nodes that do not have offsprings. (But they can have up to two parents) The Node objects form binary...

C++ Functions with no destructor

c++,destructor,bare-metal
I am writing a bare-metal C++ application that will enter an infinite loop and then never exit. I have a number of objects that will be constructed at the top of main() and will never leave scope. Memory (both code and RAM) is at a premium, as I only have...