Effective C++ .05 一些不自动生成copy assigment操作的情况

主要讲了

1. 一般情况下编译器会为类创建默认的构造函数,拷贝构造函数和copy assignment函数

2. 执行默认的拷贝构造/copy assignment函数时,如果成员有自己的拷贝构造/copy assignment函数就执行它,否则就按bit拷贝/赋值

3. 几种编译器不会为类生成默认的copy assigment操作的情况

这几种情况如下:

a. 类里面已经有了相应的的构造函数,拷贝构造函数,copy assignment函数。此时再生成默认的这些函数就失去其原来的意义了。

b. 其他情况是由于2中的一些步骤不能执行或者如果执行而违反了C++的一些设计规范

    b.1 一些成员(或父类)的copy asignment函数是私有的,导致拷贝步骤无法执行,默认函数也就不生成了

class Age {
    public:
        Age(int _age) : age(_age) {}
    private:
        int age;
        
        Age& operator=(const Age& rhs) {
            if (&rhs != this) {
                this->age = rhs.age;
            }
            return *this;
        }
};

class Man {
private:
    Age age;
public:
    Man(int _age): age(_age) {}
};


    Man man1(12);
    Man man2(22);
    man1 = man2;

编译器提示:

 [Note] 'Man& Man::operator=(const Man&)' is implicitly deleted because the default definition would be ill-formed:

 [Error] 'Age& Age::operator=(const Age&)' is private                  

    b.2 类中成员有些是const的或者是引用类型,我们知道,const变量在赋值后不能再被assignment,而引用类型变量也是如此(指向的对象不能被改变)

#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

class NamedObject {
public:
    string& name;
    int& age;
    NamedObject(string& _name, int& _age):name(_name), age(_age) {}
};

int main() {
    string n1("obj1");
    int a1 = 123;

    string n2("obj2");
    int a2 = 321;
    
    NamedObject obj1(n1, a1);
    
    NamedObject obj2(n2, a2);
    
    obj1 = obj2;
    
    return 0;
}

obj1 = obj2,就相当于对const变量重新赋值和更改引用指向对象,显然这是不能被支持的,所以编译器不能创建默认行为的copy assignment函数,而必须由自己进行处理。 

原文地址:https://www.cnblogs.com/lailailai/p/4176628.html