Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
601 views
in Technique[技术] by (71.8m points)

c++ - Calling destructor with decltype andor std::remove_reference

Is it possible to call destructor(without operator delete) using decltype andor std::remove_reference? Here's an example:

#include <iostream>
#include <type_traits>

using namespace std;

class Test
{
    public:
    Test() {}
    virtual ~Test() {}
};

int main()
{
    Test *ptr;

    ptr->~Test(); // works
    ptr->~decltype(*ptr)(); // doesn't work
    ptr->~std::remove_reference<decltype(*ptr)>::type(); // doesn't work

return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use an alias template to get an unqualified type name when all you have is a qualified type name. The following should work

template<typename T> using alias = T;
ptr->~alias<std::remove_reference<decltype(*ptr)>::type>();

Note that if the remove_reference thing worked, it would still be dangerous, because by the qualified type name, you would inhibit an virtual destructor call. By using the alias template, virtual destructors still work.

Note that GCC4.8 appears to accept

ptr->std::remove_reference<decltype(*ptr)>::type::~type();

Clang rejects this. I have long given up trying to understand how destructor name lookup works (if you look into the clang source, you will note that the clang developers also do not follow the spec, because they say that it makes no sense here). There exist DRs that cover destructor call syntax and how they are messed up. Therefor, I would recommend not using any complicated syntax here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...