删除和默认函数真实世界的例子

Ast*_*aut 8 c++ c++11

我正在研究C++ 11的新功能,其中一个让我感到困惑,因为我无法找到在Real World中使用它的方法.

它是删除和默认函数,有没有人有现实世界的例子,或者它只是添加一些糖的那些功能之一?

Jam*_*lis 9

用户声明的特殊成员函数并不简单.如果一个类具有任何重要的特殊成员函数,则该类不是POD.因此,这种类型是POD:

struct S {
    S() = default;
    S(int) { }
};
Run Code Online (Sandbox Code Playgroud)

但这种类型不是POD:

struct S {
    S() { }
    S(int) { }
};
Run Code Online (Sandbox Code Playgroud)


Vit*_*tus 8

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
}
Run Code Online (Sandbox Code Playgroud)

假设我们的默认构造函数没有做任何特殊的操作,并且(或多或少)等于编译器生成的一个.我们可以通过编写我们自己的默认构造函数来解决它(如果我们的类有很多非静态成员,这会很繁琐),或者使用以下= default语法:

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

  int data;
};
Run Code Online (Sandbox Code Playgroud)

当我们想要禁止使用特定的重载或模板特化,或仅仅禁止复制(或移动)对象时,删除函数非常有用.

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

当你想禁止复制(即线程对象)时,通常惯用的方法是声明私有拷贝构造函数而不实现(是的,或者使用boost :: noncopyable).虽然这适用于大多数情况,但有时您可能会遇到一些模糊的链接器错误.考虑:

struct A
{
  A() = default;

  friend void foo();

private:
  A(const A&);
};

void foo()
{
  A a;
  A b(a); // results in linker error in gcc
}
Run Code Online (Sandbox Code Playgroud)

制作A(const A&)中删除,我们避免潜在的连接错误,使我们的意图(禁止复制)很清楚.