Destroying an object that has already been destroyed

suggest change

In this example, a destructor is explicitly invoked for an object that will later be automatically destroyed.

#include <iostream>

struct S {
    ~S() { std::cout << "destroying S\n"; }
};
int main() {
    S s;
    s.~S();
} // UB: s destroyed a second time here

A similar issue occurs when a std::unique_ptr<T> is incorrectly made to own an object with automatic or static storage duration. A unique_ptr using its default deleter must own an object obtained with a compatible new expression.

#include <memory>

void f(std::unique_ptr<S> p);
int main() {
    S s;
    std::unique_ptr<S> p(&s);
    f(std::move(p)); // s destroyed upon return from f
}                    // UB: s destroyed

Another way to destroy an object twice is to create two independent shared_ptr control blocks for the same raw pointer. Instead, copy an existing shared_ptr so that both pointers share one control block.

#include <memory>

struct S {};

void f(std::shared_ptr<S> p1, std::shared_ptr<S> p2);
int main() {
    S* p = new S;
    // I want to pass the same object twice...
    std::shared_ptr<S> sp1(p);
    std::shared_ptr<S> sp2(p);
    f(sp1, sp2);
} // UB: both sp1 and sp2 will destroy the object separately
// NB: this is correct:
// std::shared_ptr<S> sp(p);
// f(sp, sp);

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents