C++构造、复制、赋值、移动函数介绍

学习C++的难点之一就是构造函数的理解。

构造

本篇文章通过log输出的方式,查看C++语言是如何使用构造函数的。构建一个Person类

class class Person {
public:
    Person() : age_(0), name_("Hello") {
        LOG(INFO) << __FUNCTION__ << " default constructor";
    }

    explicit Person(int age) : age_(age), name_("Hello") {
        LOG(INFO) << __FUNCTION__ << " constructor with age " << age_;
    }

    Person(const Person& other) {
        LOG(INFO) << __FUNCTION__ << " copy constructor";
        this->age_ = other.age_;
        this->name_ = other.name_;
    }

    Person& operator=(const Person& other) {
        LOG(INFO) << __FUNCTION__ << " copy assignment operator";
        this->age_ = other.age_;
        this->name_ = other.name_;
        return *this;
    }

    Person(Person&& other)  noexcept : age_(other.age()),
            name_(std::move(other.name())) {
        LOG(INFO) << __FUNCTION__ << " move constructor";
    }

    Person& operator=(Person&& other) {
        LOG(INFO) << __FUNCTION__  << " move assignment operator";
        this->age_ = other.age_;
        this->name_ = other.name_;
        return *this;
    }

    ~Person() {
        LOG(INFO) << __FUNCTION__ << " default destructor";
    }

    [[nodiscard]] int age() const { return age_; }

    void set_age(int age) { age_ = age; }

    [[nodiscard]] std::string name() const { return name_; }

private:
    int age_;
    std::string name_;
};

Person包含几个重要的方法

Constructor(参数构造器)

class-name ( optional-parameter-list )

使用参数构造器构建实例

Person person2(10);

输出

Person constructor with age 10

Default Constructor(默认构造器)

class_name ( ) ;

使用默认构造器构造Person实例

Person person1;

输出

Person default constructor

Copy assignment operator(复制赋值运算符)

class-name & class-name :: operator= ( class-name )
class-name & class-name :: operator= ( const class-name & )

使用复制赋值运算符

person1 = person2;

输出

operator= copy assignment operator

Copy constructor(复制构造器)

class-name ( const class-name & )

使用复制构造器,需要注意的是赋值时如果对象没有构造,是不会使用复制赋值运算符的

Person person3 = person2;
Person person4(person2);

输出

Person copy constructor
Person copy constructor

Move assignment operator(移动赋值运算符)

class-name & class-name :: operator= ( class-name && )

使用移动赋值运算符

Person person5;
person5 = std::move(person1);

输出

operator= move assignment operator

Move constructor(移动构造器)

class-name ( class-name && )

使用移动构造器,和复制构造器有点类似

Person person6 = std::move(person3);
Person person7(std::move(person4));

输出

Person move constructor
Person move constructor

Destructor(析构器)

~ class-name ();
virtual ~ class-name ();

上述的实例在离开作用域前会全部释放

~Person default destructor
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章