删除和默认的函数Real World Examples [英] Deleted and Defaulted Functions Real World Examples

查看:148
本文介绍了删除和默认的函数Real World Examples的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在看C ++ 11的新功能,其中一个让我困惑,因为我不能弄清楚一种方法在现实世界中使用它。

I was looking at the C++11 new features and one of them confuses me, because I can't figure out a way to use it in Real World.

它是已删除和默认函数,有没有人有真实的例子,它的用法或只是其中一个功能,只是添加一些糖?

It's Deleted and Defaulted Functions, does anyone have real world examples of it's usage or is it just one of those features that just adds some sugar?

推荐答案

struct A
{
  A(const A& arg) : data(arg.data)
  {
    do_something_special();
  }

  // by writing copy constructor, we suppress the generation of
  // implicit default constructor A::A()

  int data;
};

void foo1()
{
  A a; // does not work, since there's no default constructor
}

构造函数不做任何特殊的,并且(或多或少)等于编译器生成的一个。我们可以通过编写我们自己的默认构造函数(如果我们的类有很多非静态成员,可以很乏味)或通过使用 = default 语法来修复它: p>

Let's say that our default constructor does not do anything special and is (more or less) equal to the compiler generated one. We can fix it by either writing our own default constructor (which can get tedious if our class has many non-static members), or by using the = default syntax:

struct A
{
  A() = default;
  A(const A& arg) : data(arg.data)
  {
    do_something_special();
  }

  int data;
};






当我们要禁止使用时,删除函数很有用特定的重载或模板专用化,或只是禁止复制(或移动)对象。


Deleting functions is useful when we want to forbid using specific overloads or template specializations, or just for forbidding copying (or moving) objects.

void foo(char c) {}
void foo(int i) = delete; // do not allow implicit int -> char conversion

当你想禁止复制(即线程对象)时,通常的惯用方式是声明私有拷贝构造函数没有实现(是,或使用boost :: noncopyable)。虽然这在大多数情况下都有效,但有时可能会导致一些模糊的链接器错误。考虑:

When you want to forbid copying (i.e. thread objects), the usual idiomatic way is to declare private copy constructor without implementation (yeah, or use boost::noncopyable). While this works for most cases, you can get into some obscure linker errors sometimes. Consider:

struct A
{
  A() = default;

  friend void foo();

private:
  A(const A&);
};

void foo()
{
  A a;
  A b(a); // results in linker error in gcc
}

使 A (const A&)删除,我们避免潜在的链接器错误,并使我们的意图(禁止复制)非常清楚。

Making A(const A&) deleted, we avoid potential linker errors and make our intent (disallow copying) very clear.

这篇关于删除和默认的函数Real World Examples的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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