使用decltype和\or std :: remove_reference调用析构函数 [英] Calling destructor with decltype and\or std::remove_reference
问题描述
是否可以使用decltype和\or std :: remove_reference调用析构函数(无操作符删除)?下面是一个例子:
Is it possible to call destructor(without operator delete) using decltype and\or 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;
}
推荐答案
获取一个非限定类型名称,当你有一个合格的类型名称。以下应该工作
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>();
请注意,如果 remove_reference
它仍然是危险的,因为通过限定类型名称,您将禁止虚拟析构函数调用。通过使用别名模板,虚拟析构器仍然可以工作。
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.
请注意,GCC4.8似乎接受
Note that GCC4.8 appears to accept
ptr->std::remove_reference<decltype(*ptr)>::type::~type();
Clang拒绝此操作。我长期放弃了试图理解析构函数名称查找的工作原理(如果你查看clang源,你会注意到clang开发人员也不遵循规范,因为他们说这在这里没有意义)。存在包含析构函数调用语法和如何混乱的DR。因此,我建议不要使用任何复杂的语法。
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.
这篇关于使用decltype和\or std :: remove_reference调用析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!