这篇文章主要介绍了C++拷贝构造函数中的陷阱,拷贝构造函数大家都比较熟悉,通俗讲就是传入一个对象,拷贝一份副本。不过看似简单的东西,实际不注意的话就会产生问题,下面我们就来看看C++拷贝构造函数中都有哪些陷阱吧

转自微信公众号:CPP开发前沿

拷贝构造函数大家都比较熟悉,通俗讲就是传入一个对象,拷贝一份副本。
不过看似简单的东西,实际不注意的话就会产生问题!

#include<iostream>
using namespace std;
class CExample
{
public:
int a,b,c;
char *str;
public:
//构造函数
    CExample(int tb)
    {
        a = tb;
        b = tb+1;
        c = tb+2;
        str=(char *)malloc(sizeof(char)*10);
strcpy(str,"123456789");
cout<<"creat: "<<endl;
    }
 
//析构函数
    ~CExample()
    {
cout<< "delete: "<<endl;
    }
void Show ()
{
cout<<a<<endl;
    }
//拷贝构造
//CExample(const CExample& C)
//{
//    str=(char *)malloc(sizeof(char)*10);
//    strcpy(str,C.str);
//    cout<<"copy"<<endl;
/