this post was submitted on 24 Sep 2023
0 points (NaN% liked)
C++
1763 readers
1 users here now
The center for all discussion and news regarding C++.
Rules
- Respect instance rules.
- Don't be a jerk.
- Please keep all posts related to C++.
founded 1 year ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
view the rest of the comments
I see. Let me know if my hint doesn't take you further, then i take a closer look. It seems, that .destroy deallocates anyway and the later .deallocate deallocates the already deallocated memory again.
that makes sense, although is kinda weird because i also did a string implementation before doing the same thing and it worked, also the c++ reference and the book that im using to learn c++ says that .destroy() only destroys the object it doesnt deallocate
That's btw. another error. You byte-copy the elements and Call the destructor on the original ones. This will work only, if your element's type is trivially destructible.
Given your T has an allocating constructor and therefore an deallocating destructor:
Creating a T Calls
T::T()
that allocates memory.Resizing your deque Calls
T::~T()
by.destroy()
, deallocating this memory.Destructing your deque should destroy the elements. Thus you call the constructor once and the destructor 1+number of deque resizes.
so, that practice of calling .destroy() and then .deallocate() is redundant and error-prone
If you develop or debug a container, it is useful to have a special test class for the elements that covers potential container specific errors.
If I run your code with
ContainerTester
instead ofint
, i get:So it's more obvious that very bad things do happen :)
Oh and note, that
allocator::destroy
is deprecated in C++17 and was removed with C++20.i used tthe tester class with my code removing the .deallocate(), and although it doesnt crash, it still runs the destructor multiple times on the same element, i think its because im just pushing i into the container, and because that constructor creates an implicit conversion between int and ContainerTester, it creates a temporary object that gets destroyed once it is pushed into the deque, am i right?
-std=c++20
)dont worry, i have one more question, i should initialize variables with = or with {}?
Direct initialization is recommended over copy initialization (=).
Okay, to be fair: it's some sort of holy war, the answer depends on who you ask.