C++ 拷贝构造函数 和 六大函数

1.  C++什么时候会调用 拷贝构造函数?

a.一个对象作为函数参数,以值传递的方式传入函数体;

b.一个对象作为函数返回值,以值传递的方式从函数返回;(实际使用时,会被编译器优化掉)

c.一个对象用于给另外一个对象进行初始化(常称为赋值初始化)

如:

Animal a;
Animal b(a);

// 或者
Animal a;
Animal b = a;

2. C++ 6大函数

1.构造函数

2.move构造函数

3.move赋值操作符

4.复制构造函数

5.赋值操作符

6.析构函数

关于move构造函数 和 move赋值操作符,可以提高性能:

// 测试 move
class Animal{

public:

    Animal(){}
    Animal(const char* name,int age){
        _age = age;
        _name = new char[strlen(name)];
        strcpy(_name,name);
    };

    // 拷贝构造函数
    Animal(const Animal& other){
        if (_name) {
            printf("[Animal  拷贝构造函数]看看会不会调用\n");
            delete [] _name;
            _name = nullptr;
        }

        cout << "[Animal Copy Constructor]  called" << endl;
        _name = new char[strlen(other._name)];
        strcpy(_name,other._name);
        _age = other._age;
    }

    // 赋值
    Animal& operator=(const Animal& other){

        if (this == &other) {
            return *this;
        }

        if (_name) {
            printf("[Animal   赋值]看看会不会调用\n");
            delete [] _name;
            _name = nullptr;
        }
        cout << "[Animal Assign Constructor]  called" << endl;
        _name = new char[strlen(other._name)];
        strcpy(_name,other._name);
        _age = other._age;
        return *this;
    }

    // move copy constructor
    Animal(Animal&& other){
        cout << "move copy constructor called." << endl;
        _name = other._name;
        _age = other._age;
        other._name = nullptr;
    }

    // move assign constructor
    Animal& operator=(Animal&& other){
        if (this == &other) {
            return *this;
        }

        if (_name) {
            delete [] _name;
            _name = nullptr;
        }

        cout << "move assign constructor called." << endl;
        _name = other._name;
        _age = other._age;
        other._name = nullptr;
        return *this;
    }

    void show(){
        cout << "name:" << _name << ";  age :" << _age << endl;
    }

    ~Animal(){
        cout << "Animal Deconstructor" << endl;
        if (_name) {
            delete [] _name;
        }
    }

private:

    ;
    char* _name = nullptr;
};

Animal genAnimal(){
    );
}

测试:

int main(){

    // 会调用 move copy constructor
    vector<Animal> V;
    V.push_back(Animal());

    // 会调用  move assign constructor
//    Animal a("zhangsan",1);
//    a = genAnimal();

    ;
}

主要需要明白什么时候调用   copy  constructor,什么时候调用 assign operator.

上一篇:HDU 5437 & ICPC 2015 Changchun Alisha's Party(优先队列)


下一篇:hdu 5437(优先队列模拟)