C ++ 11接口纯虚拟析构函数 [英] C++11 interface pure virtual destructor

查看:252
本文介绍了C ++ 11接口纯虚拟析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UPD .有一个标记,它是这个问题的重复.但是在那个问题中,OP要求HOW如何使用default定义纯虚拟析构函数.这个问题是关于有什么区别.

UPD. There is a mark that it is a duplicate of this question. But in that question OP asks HOW to use default to define pure virtual destructor. This question is about what the difference.

在C ++(可能的最新标准)中,使用空主体实现定义纯虚拟析构函数和仅空主体(或默认主体)之间的真正区别是什么?

In C++ (latest standard if possible) what the real difference between defining pure virtual destructor with empty body implementation and just a empty body (or default)?

变种1:

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

Variant 2.1:

Variant 2.1:

class I21 {
public:
    virtual ~I21() = 0;
};

I21::~I21() {}

Variant 2.2:

Variant 2.2:

class I22 {
public:
    virtual ~I22() = 0;
};

I22::~I22() = default;

更新,我发现变体1和变体2.1/2.2之间至少存在1个差异:

Update I found at least 1 difference between Variant 1 and Variants 2.1/2.2:

std::is_abstract::value对于变体1是false,对于变体2.1和2.2是true.

std::is_abstract::value is false for Variant 1, and true for Variants 2.1 and 2.2.

演示

也许有人可以发现2.1和2.2之间的区别?

May be someone can found difference between 2.1 and 2.2?

推荐答案

I1和I2 *之间的区别在于,添加= 0会使类抽象.实际上,当您没有任何其他函数成为纯虚拟的时,将析构函数纯为虚拟的是技巧,以使类抽象.我说这是一个技巧,因为如果您要销毁析构函数的任何派生类(在这里您将要进行销毁),则不能不取消定义析构函数,那么您仍然需要定义析构函数,可以为空或默认.

The difference between I1 and I2*, as you pointed out, is that adding = 0 makes the class abstract. In fact, making the destructor pure virtual is a trick to make a class abstract when you don't have any other function to be pure virtual. And I said it's a trick because the destructor cannot be left undefined if you ever want to destruct any derived class of it (and here you will), then you still need to define the destructor, either empty or defaulted.

现在,空的或默认的析构函数/构造函数(I21和I22)之间的区别更加晦涩,没有太多内容.推荐的方法是使用default,这既是使您的意图更清晰的新用法,又显然是使编译器有机会进行优化.引用 msdn

Now the difference between empty or defaulted destructor/constructor (I21 and I22) is way more obscure, there isn't much written out there. The recommended one is to use default, both as a new idiom to make your intentions clearer, and apparently, to give the compiler a chance for optimization. Quoting msdn

由于琐碎的特殊成员函数的性能优势,我们建议您在需要默认行为时,宁愿自动生成特殊成员函数,也不愿使用空函数体.

Because of the performance benefits of trivial special member functions, we recommend that you prefer automatically generated special member functions over empty function bodies when you want the default behavior.

除了可能的性能改进之外,两者之间没有明显的区别. = default是从C ++ 11开始的方法.

There are no visible differences between the two, apart from this possible performance improvement. = default is the way to go from C++11 on.

这篇关于C ++ 11接口纯虚拟析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆