C++类中的特殊成员函数

栏目: C++ · 发布时间: 5年前

内容简介:转载请注明文章出处:看定义容易迷糊,上代码就会很清晰:

转载请注明文章出处: https://tlanyan.me/special-member-functions-in-cpp-class/

C++ 类中有几个特殊的 非静态 成员函数,当用户未定义这些函数时,编译器将给出默认实现。 C++11 前有四个特殊函数, C++11 引入 移动语义 特性,增加了两个参数为 右值 的特殊函数。这六个函数分别是:

  1. 默认构造函数

    默认构造函数指 不需要参数 就能初始化的构造函数。包含 无参所有参数有默认值 两种类型的构造函数。

  2. 复制构造函数

    复制构造函数指使用 该类的对象作为参数 的构造函数。可以有其他参数,但必须提供默认值。

  3. 复制赋值运算符

    重载等号 = ,将该类的对象 赋值已定义对象

  4. 析构函数

    没啥可说的。

  5. 移动构造函数

    C++11 新增,该类的 右值 对象为参数的构造函数,其余同 复制构造函数

  6. 移动复制运算符

    复制赋值运算符 ,唯一不同是参数为 右值

看定义容易迷糊,上代码就会很清晰:

#include <iostream>
#include <string>

class Foo {

public:
    std::string s;

    // 默认构造函数
    Foo() { std::cout << "default constructor" << std::endl; }
    // 复制构造函数
    Foo(const Foo& foo) { std::cout << "copy constructor" << std::endl; s = foo.s; }
    // 复制赋值运算符
    Foo& operator=(const Foo& foo) { std::cout << "copy assignment operator" << std::endl; s = foo.s; return * this;}
    // 移动构造函数
    Foo(Foo&& foo) { std::cout << "move constructor" << std::endl; s = std::move(foo.s); }
    // 移动赋值运算符
    Foo& operator=(Foo&& foo) { std::cout << "move assignment operator" << std::endl; s = std::move(foo.s); return *this;}
};

int main() {
    Foo foo1;
    Foo foo2(foo1);
    foo1 = foo2;
    Foo foo3(std::move(foo1));
    foo2 = std::move(foo3);
}

g++ 或者 clang 编译,加上 -fno-elide-constructors -std=c++0x 选项。执行程序输出如下:

default constructor
copy constructor
copy assignment operator
move constructor
move assignment operator

结果是我们预期的。需要注意的是 Foo foo3 = foo1 的形式会调用 复制构造函数 ,不会调用 复制赋值运算符 。原因是 Foo foo3 = xxx 声明和定义一个新对象,而赋值是作用在 已定义对象移动赋值运算符 同理。

C++11 新增了 =default=delete 函数修饰符,提示编译器使用默认或者删除默认的特殊函数。需要注意的是这两个修饰符 只能 修饰上述特殊函数,用户可以用其对特殊函数进行裁剪。一个例子:

struct Test {
    // 使用默认构造函数
    Test() = default;
    // 删除复制赋值运算符
    Test& operator=(const Test& test) = delete;
    // 使用默认析构函数
    ~Test() = default;
};

参考

  1. https://en.cppreference.com/w/cpp/language/member_functions
  2. https://stackoverflow.com/questions/43349808/extended-lifetime-of-an-object-returned-from-function

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Zen of CSS Design

The Zen of CSS Design

Dave Shea、Molly E. Holzschlag / Peachpit Press / 2005-2-27 / USD 44.99

Proving once and for all that standards-compliant design does not equal dull design, this inspiring tome uses examples from the landmark CSS Zen Garden site as the foundation for discussions on how to......一起来看看 《The Zen of CSS Design》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具