C++ 深入理解系列-构造函数的技巧

来源:互联网 发布:淘宝网千人千面 编辑:程序博客网 时间:2024/06/14 15:22

**

引言

**
有时候我们会不希望当前类被复制,因为有可能类中的成员不建议被复制比如锁,一些智能引数等,这个时候想到的办法就是禁止类中拷贝构造函数和重载操作符=这两个成员函数的禁用了,有以下两种方法可以解决这个问题。

用delete关键字

// c++ 11以上均可用class TestDeleteCopy{public:    TestDeleteCopy(int count): m_count(count) {}public:    TestDeleteCopy(const TestDeleteCopy&) = delete;    TestDeleteCopy& operator=(const TestDeleteCopy&) = delete;private:    int m_count;    pthread_mutex_t m_Mutex;};

以上用delete关键字将两个具有拷贝功能的函数给屏蔽了。

函数私有化

// 任何版本均可用class TestPrivateCopy{public:    TestPrivateCopy(int count): m_count(count) {}private:    TestPrivateCopy(const TestPrivateCopy&);    TestPrivateCopy& operator=(const TestPrivateCopy&);private:    int m_count;    pthread_mutex_t m_Mutex;};

私有化这两个函数,外部是无法成功调用的。

通常的c++类:

class TestCopyConstructor{public:    TestCopyConstructor(int count): m_count(count) {}public:    TestCopyConstructor(const TestCopyConstructor& other){        this->m_count = other.m_count;        std::cout<<"copy constructor called!"<<std::end;    }    TestCopyConstructor& operator=(const TestCopyConstructor&other){        this->m_count = other.m_count;        std::cout<<"operator = called!"std::end;        return *this;    }private:    int m_count;    //pthread_mutex_t m_Mutex;};

测试拷贝过程的调用过程:

TestCopyConstructor a(1);TestCopyConstructor b = a;//copy constructor called!b=a;//operator = called!TestCopyConstructor c(a);//copy constructor called!

这说明声明一个新的类变量的时候赋值其实是拷贝构造函数在生效。