Questions tagged [destructor]
A special method in object-oriented programming which is invoked when an object is destroyed
3,187
questions
0
votes
0
answers
17
views
Special case of "Delete called on base class that is abstract but has non-virtual destructor"
This is a minimal reproducable example matching my setup :
(using Qt, but the QList can easily be replaced with any kind of std container I guess)
class DataType
{
};
class DerivedDataType : public ...
0
votes
1
answer
64
views
Why isn't __del__ called twice?
I want to use an object's __del__ method to automatically write the object data to either an external database or a local cache (a global dict), depending on certain conditions. A context manager ...
-5
votes
0
answers
38
views
Writting simple c class [closed]
I have used typed pionter on methods (ime this in c++ methods), then redirected its instance to a correct class definitivno by using macro (#define c(x) (*(x-> = x)) ) witch is im the file class.h. ...
2
votes
2
answers
89
views
Controlling class member layout AND destructor order
I have a class with two members.
class C {
typeA a;
typeB b;
};
Assume that there is no inheritance. There are three things I'm concerned about with this class.
the order in which the ...
0
votes
1
answer
51
views
Destruction order when jthread is a class member
I have a class which handles synchronization of some threads.
class ThreadHandler {
std::vector<std::jthread> threads;
std::mutex mut;
std::condition_variable cv;
int some_int;
...
-2
votes
0
answers
34
views
Destructor and dynamic memory allocation [duplicate]
I have some problem with my destructor and dynamic allocated attribute called *ime
#include <iostream>
#include <cstring>
#include <string>
using namespace std;
class Student {
...
1
vote
0
answers
51
views
Exception in destructor - UB or "may result in UB"? [duplicate]
I know it's a very common topic but I haven't been able to find the answer to my specific question.
Everyone knows throwing (and not handling) exceptions in destructors is a bad idea and you shouldn't ...
0
votes
0
answers
21
views
Class Destructor call when using multithreading on socketcan
I am trying to understand why the class destructor is being called right at the beginning after the program starts !?
Here is my program snippet:
#include <iostream>
#include <string>
#...
0
votes
2
answers
163
views
Which of these destructor calls are excecuted multiple times?
I am learning C++ right now, coming from Java. I do know that I should use vectors instead of arrays, however I want to also understand the fundamentals.
I've written a struct that I want to access ...
1
vote
1
answer
123
views
c++ when do vector push_back deep copy objects?
I created a vector and used push_back to put several node objects into it. However, I can't predict when its going to use the move constructor or copy constructor.
Is there any pattern to when ...
2
votes
1
answer
65
views
About clang AST and odr-use of destructors
For the following code
struct X {
int a;
};
int main() {
X x;
return 0;
}
The clang AST does not show a DestructorDecl:
CXXRecordDecl 0x55a415f54f00 </home/gkxx/exercises/smfgen/tmp/../tmp/...
0
votes
1
answer
55
views
Object instance still accessible after destruction
I have an Animal struct that has Dog struct as a data member, my question is why the Dog instance that is created (inside the Animal) is still accessible through the allocated instance of Animal even ...
2
votes
1
answer
101
views
Disable generation of deleting destructor
I am developing a program for embedded system that will not use dynamic memory allocation. How can I prevent the GCC from producing deleting destructor (the destructor with D0 in its mangled name)? It ...
-2
votes
1
answer
93
views
{ "error": "Cannot destructure property 'title' of 'req.body' as it is undefined." }
following are the code snippets for a Node.js application:
// src/models/workoutsModel.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const workoutSchema = new ...
0
votes
1
answer
129
views
Class destructor in C++
I created a class book with some class properties such as name and author (nothing dynamically allocated), then I created a class library which contains dynamic book array (like book* set) and its ...
0
votes
1
answer
75
views
Understanding Copy Constructor and Temporary Object Creation in C++ When Passing Objects by Value
Given the next code:
#include <iostream>
#include <vector>
#include <cstring>
class Person
{
public:
Person(const char *i_Name = "Unknown", int i_Age = 0)
: ...
7
votes
3
answers
187
views
std::vector, incomplete type and inherited constructors
I have a class with a vector member variable whose T is declared, but not defined. This can be a problem if no destructor for the class is defined, since the compiler might pick some other translation ...
3
votes
1
answer
135
views
Does `unordered_map::erase()` always call the destructor immediately?
Say I have std::unordered_map<int, Foo> myMap;. If I call myMap.erase(1);, will Foo's destructor always be called immediately? Or is the standard library allowed to hang on that instance of Foo ...
0
votes
0
answers
35
views
Understanding the Consequences of Moving and Accessing Resources in C++ Destructors
I have the following code to provide context for my question. When move_test() is called within main(), a will be moved first, causing a._str to be moved and then destructed. However, I am attempting ...
0
votes
0
answers
12
views
Destruct twice after reset on shared pointer
Here the source code :
unique_lock<mutex> lock(_activeFQDNMutex);
activeFQDNs.swap(shadowFQDNs);
shadowFQDNs.reset(new TrieRegexInterface());
After reset, there is a core file, ...
3
votes
2
answers
119
views
How to properly terminate a C++ program with calls to destructors outside the scope of main
Do current C++ standards provide any tools to close a program from anywhere (e.g. from inside a function, like exit()), but respecting the resources set aside on the heap?
I know that the exit() ...
0
votes
1
answer
59
views
Deleting a struct that has a class member
I have a struct:
struct holder
{
int val;
std::unordered_map<int, int> num_to_addr;
};
I dynamically allocate a struct holder:
struct holder* handle = new struct holder;
I do work and ...
3
votes
3
answers
94
views
Destructor is not being invoked
I have written the following code to implement a stack.
#include<iostream>
using namespace std;
class stack
{
public:
int *top;
int size, capacity;
stack(int c):...
6
votes
3
answers
138
views
Enforce a member destruction order compile-time in C++
I have a C++ class A like this:
// third-party classes / methods, unable to change
class C {};
class B {
public:
C* getC();
};
B* legacyAPIToGetB(const char*);
// the target class
class A {
...
3
votes
3
answers
228
views
Finalizer C#. Why Finalizer not calling?
Why is my finalizer not being called?
using System;
class Program
{
static void Main(string[] args)
{
Test test = new Test();
}
}
class Test
{
public Test()
{
...
0
votes
0
answers
32
views
Using pointers with parent class type triggers parent class destructor rather than child class destructor [duplicate]
I am struggling a bit with the details of using pointers with parent classes as a type, when I want to actually trigger the destructor of child classes. This is my (very simplified version) ...
0
votes
1
answer
71
views
Polymorphic Destructor: Confusion About What Qualifies As A "Similar" [conv.qual] Types"
I just read through a rough copy of C++ standard (https://eel.is/c++draft/) and found this in section [expr.delete] paragraph 3:
In a single-object delete expression, if the static type of the object ...
7
votes
1
answer
124
views
Different observable order of local variable destruction and its return
I have a program that behaves differently in GCC and Clang. After simplification the minimal reproducible example is
struct A {
int i;
};
struct Finisher {
A & a;
~Finisher() { a.i = ...
4
votes
0
answers
119
views
How do I prevent an arbitrary object's destructor from ever running in Python?
Context
I have a troublesome object from third-party code in a Python (3.10) program. The object is not written in pure Python; it's provided by an extension module.
Due to a bug in the third party ...
0
votes
0
answers
12
views
Unclear sequence of constructor calls fro two objects
Check of when an constructor being called for two different objects. Unexpected constructor call (unclear sequence)
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
public:
...
0
votes
1
answer
136
views
Compiler differences when throwing exception from a destructor
I have found following C++ question (cppQuiz #323):
According to the C++17 standard, what is the output of this program?
#include <iostream>
#include <stdexcept>
struct A {
A(char c) :...
0
votes
1
answer
42
views
C++ Compilation problem with creating an array of struct from the heap
I'm getting a compilation error and warning when I compile this.
#include <iostream>
struct {
uint8_t m_data;
int size;
} BufferCustom;
class MyClass
{
private:
int x, y;
...
0
votes
1
answer
121
views
How do I increment and decrement a static variable when objects are created and destroyed using constructors and destructors in C++?
I have an Owner class that stores information about ownership.
For some needs I need to know how many owners were created in total so I created a static variable amountOfOwners inside the Owner class. ...
0
votes
1
answer
130
views
Why is my C destructor not getting called?
I have two parts of my project: an example.c (which contains our main function) and an api.c (which contains all APIs). They are compiled separately, and the binaries generated by the API are used by ...
3
votes
0
answers
78
views
Why does this object get destroyed twice? [duplicate]
I have this C++ code:
#include <iostream>
#include <vector>
class Obj {
public:
Obj() {
std::cout << "build" << std::endl;
}
~Obj() {
std::cout <<...
0
votes
1
answer
79
views
Is the destructor deleting the correct instance [duplicate]
I am using Visual C++ in the Community edition of Visual Studio 2022 with the latest updates. In the C++ code below, main creates an instance of ShowBug and assigns it to the variable sb. The next ...
0
votes
1
answer
91
views
Is std::getenv() safe to call after main returns?
Does the standard guarantee that std::getenv() and std::setenv() have the same access protections as cout? For which the standard allows access after main returns, in the destructor (and constructor) ...
2
votes
2
answers
205
views
Can self-destroying std::stop_callback objects destroy themselves during construction?
As said on cppreference.com(link), std::stop_callback object is allowed to destroy itself inside its callback function. So the code below should be fine.
template <typename F>
void doAfterStop(...
1
vote
0
answers
62
views
Does the destructor get called when a C++ temporary object is destroyed? Why does this code only output three "deconstruction" messages? [duplicate]
class demo{
private:
int x;
public:
demo(int t):x(t) {cout<<"constructor"<<endl;}
demo(const demo& t):x(t.x) {cout<<"copy constructor"<&...
0
votes
1
answer
96
views
Memory not being freed properly
I am wokring on my Hash Table assigment where a huge chunk of data is being read (from a csv file) into the Hash table. A requirement for this assignment is to use raw pointers (no #include <memory&...
0
votes
2
answers
66
views
Will the default constructor call MPI_Comm_free?
Lets say we have the following code :
#include <iostream>
#include <vector>
#include <mpi.h>
class MyClass {
public:
MyClass(std::vector<double>& v0,
...
6
votes
1
answer
225
views
What came first, the destructor or delete() ? C++
Many answers on this site mentions that delete() calls destructor. But the sample code below seems to call delete() inside the destructor. What is the correct usage of delete() when object is ...
0
votes
1
answer
120
views
Destructor called twice with Return Value Optimization
In order to understand copy elision I wrote a small example
#include "iostream"
using namespace std;
struct Foo
{
Foo() { cout << "constructor was called" << endl;...
1
vote
1
answer
207
views
Why is clearing a tbb::concurrent_unordered_map so much slower than clearing a std::unordered_map?
I have a tbb::concurrent_unordered_map<size_t, std::vector<size_t>> - or, alternatively, an std::unordered_map<size_t, std::vector<size_t>>.
Clearing the map, either by calling ...
0
votes
1
answer
123
views
Base class has inacessible destructor
The following code tries to define a self-similar datastructure JSON using the std containers std::vector and std::unordered_map but does not compile. It all seems to come down to std::unordered_map's ...
5
votes
2
answers
352
views
What is called first: destructor of static object or atexit handler?
Is the order guaranteed in this case or is it UB?
#include <iostream>
#include <cassert>
using namespace std;
struct TraceHelper
{
TraceHelper()
{
cout << "...
1
vote
1
answer
68
views
A breakpoint instruction (__debugbreak() or similar.. Debug Assertion Failed: _CrtIsValidHeapPointer(block)
I'm getting this error, I dissected the code even to make sure that I didn't miss a step. I added a extra size when allocating to make sure no memory leakage, I deleted [] . can you guys see what ...
0
votes
0
answers
61
views
C++ Destroy object with a mutex
I am making a command prompt that can create and remove (destroy) objects.
You can interact with the objects via another commands and the values are sometimes exported (on request).
What if someone ...
0
votes
0
answers
34
views
Problem about destructor function called immediately [duplicate]
I am learning c++ and having hard time on this exercise of my internet course. It takes data from user through constructer and print it. However, the destructor function is called immediately after ...
0
votes
2
answers
267
views
Destructing std::promise immediately when state is ready
Consider the following code:
void runSomething() {
std::promise<void> promise;
startWorkAndCallBackFromDifferentThread([&]{
promise.set_value();
});
promise.get_future().get(...