“ = default”和“ = default”之间有什么区别?析构函数和空析构函数? [英] What's the difference between "= default" destructor and empty destructor?

查看:678
本文介绍了“ = default”和“ = default”之间有什么区别?析构函数和空析构函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想防止班级用户将其用作自动变量,所以我编写如下代码:

I want to prevent the user of my class from using it as an automatic variable, so I write code like this:

class A {
private:
  ~A() = default;
};

int main() {
  A a;
}

我希望代码不会被编译,但是g ++编译时不会错误。

I expect that the code won't be compiled, but g++ compiles it without error.

但是,当我将代码更改为:

However, when I change the code to:

class A {
private:
  ~A(){}
};

int main() {
  A a;
}

现在,g ++给出了〜A( )是私有的,这是我的期望。

Now, g++ gives the error that ~A() is private, as is my expectation.

=默认析构函数和空析构函数有什么区别?

What's the difference between a "= default" destructor and an empty destructor?

推荐答案

第一个示例不应编译。这表示确实会编译的编译器中的错误。此错误已在gcc 4.9及更高版本中修复。

Your first example should not compile. This represents a bug in the compiler that it does compile. This bug is fixed in gcc 4.9 and later.

= default 定义的析构函数是平凡的。可以使用 std :: is_trivially_destructible< A> :: value 来检测。

The destructor defined with = default is trivial in this case. This can be detected with std::is_trivially_destructible<A>::value.

更新

C ++ 11(和C ++ 14)指出,如果有人具有用户声明的析构函数(如果没有)没有用户声明的move特殊成员),则仍会隐式生成复制构造函数和复制赋值运算符,但是不建议使用该行为。这意味着如果您依靠它,编译器可能会向您发出弃用警告(或可能不会)。

C++11 (and C++14) state that if one has a user-declared destructor (and if you don't have either user-declared move special member), then the implicit generation of the copy constructor and copy assignment operator still happen, but that behavior is deprecated. Meaning if you rely on it, your compiler might give you a deprecation warning (or might not).

两者:

~A() = default;

和:

~A() {};

用户声明的,因此它们在这点。如果您使用这两种形式之一(并且不声明移动成员),则应显式默认,显式删除或显式提供副本成员,以避免依赖不赞成使用的行为。

are user-declared, and so they have no difference with respect to this point. If you use either of these forms (and don't declare move members), you should explicitly default, explicitly delete, or explicitly provide your copy members in order to avoid relying on deprecated behavior.

如果确实声明了移动成员(有或没有声明析构函数),则复制成员将被隐式删除。

If you do declare move members (with or without declaring a destructor), then the copy members are implicitly deleted.

这篇关于“ = default”和“ = default”之间有什么区别?析构函数和空析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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