銷燬已經被破壞的物體

在此示例中,為稍後將自動銷燬的物件顯式呼叫解構函式。

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

std::unique_ptr<T> 指向具有自動或靜態儲存持續時間的 T 時,會出現類似的問題。

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

另一種兩次銷燬物件的方法是讓兩個 shared_ptr 都管理物件而不互相共享所有權。

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 s separately
// NB: this is correct:
// std::shared_ptr<S> sp(p);
// f(sp, sp);