Garciat
9/26/2016 - 10:11 AM

leaking.cpp

#include <algorithm>
#include <iostream>
#include <memory>
#include <typeinfo>
#include <vector>
#include <cassert>

using namespace std;

template <typename T>
struct leaking {
    union {
        T data;
    };
    leaking() {
        new(&data) T();
    }
    template <typename... A>
    leaking(A&&... args) {
        new(&data) T(std::forward<A>(args)...);
    }
    template <typename U>
    leaking(std::initializer_list<U> inli) {
        new(&data) T(inli);
    }
    ~leaking() {
        // leak
    }
    T& get() {
        return data;
    }
    explicit operator T&() {
        return data;
    }
    auto operator ->() {
        return &data;
    }
};

struct hello {
    static int dtor;
    ~hello() {
        dtor += 1;
    }
};
int hello::dtor = 0;

int main() {
    {
        leaking<hello> vec;
    }

    assert(hello::dtor == 0);

    {
        hello vec;
    }

    assert(hello::dtor == 1);

    system("pause");
    return 0;
}