rttrorg / rttr

C++ Reflection Library
https://www.rttr.org
MIT License
3.11k stars 429 forks source link

Repeated destructions #339

Open tkzcfc opened 2 years ago

tkzcfc commented 2 years ago

Hello, why is the destructor called twice for the first time?


class TestClass
{
public:
    TestClass()
    {
        printf("TestClass ctor\n");
    }

    ~TestClass() 
    {
        printf("~TestClass\n");
    }
};

RTTR_REGISTRATION
{
    registration::class_<TestClass>("TestClass")
        .constructor<>()(policy::ctor::as_object)
        .constructor<>()(policy::ctor::as_raw_ptr)
        .constructor<>()(policy::ctor::as_std_shared_ptr)
}

int main(int argc, char** argv)
{
    auto range = type::get<TestClass>().get_constructors();
    std::vector<constructor> ctor_list(range.cbegin(), range.cend());

    printf("00000000000000\n");
    {
        variant var = ctor_list[0].invoke();
    }

    printf("11111111111111\n");
    {
        variant var = ctor_list[1].invoke();
        type::get<TestClass>().destroy(var);
    }

    std::shared_ptr<TestClass> ptr;
    printf("22222222222222\n");
    {
        variant var = ctor_list[2].invoke();
        ptr = var.get_value<std::shared_ptr<TestClass>>();
    }

    printf("333333333333333333\n");
    ptr = NULL;
    printf("444444444444444444\n");
}

console output:

00000000000000 TestClass ctor ~TestClass ~TestClass 11111111111111 TestClass ctor ~TestClass 22222222222222 TestClass ctor 333333333333333333 ~TestClass 444444444444444444

deadlocklogic commented 2 months ago

@tkzcfc You are not taking the copy/move constructors into consideration. Add:

TestClass(const TestClass&) { printf("TestClass ctor\n"); }

TestClass(const TestClass&&) { printf("TestClass ctor\n"); }

And it works fine. Don't forget that with policy::ctor::as_object you are working with objects rather than pointers.