#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
class CA
{
public:
CA()
{
printf("CA()\n");
cData = new char[1024];
memcpy(cData, "A", 1);
}
~CA()
{
printf("~CA()\n");
if (cData)
{
delete cData;
cData = NULL;
}
}
CA(CA &a)
{
printf("CA(&ca)\n");
cData = new char[1024];
if (a.cData)
{
printf("cp str!\n");
memcpy(cData, a.cData, strlen(a.cData));
}
else
printf("cp error!\n");
}
///如果没有重载=,需要调用拷贝构造函数
CA &operator = (const CA &other)
{
memcpy(this->cData, other.cData, strlen(other.cData));
}
char *cData;
};
class CB
{
public:
CB() { printf("CB()\n"); }
~CB() { printf("~CB()\n"); }
void getb(CA &ca)
{
printf("getb()\n");
///即,此处如果没有重载=,直接=是赋值操作是错误的会double free,并不会调用拷贝构造函数
ca = m_CA;
///赋值操作
//memcpy(ca.cData, m_CA.cData, strlen(m_CA.cData));
}
private:
CA m_CA;
};
void test()
{
CA ca;
///初始化调用拷贝构造函数,跟其他地方使用=是赋值操作不一样
CA c2 = ca;
const char* cstr = "Hello A!";
int len = strlen(cstr);
memcpy(ca.cData, cstr, len);
ca.cData[len] = '\0';
CB cb;
cb.getb(ca);
}
int main()
{
test();
return 0;
}
带深拷贝的类对象传引用赋值操作的注意事项
最新推荐文章于 2024-07-29 18:34:43 发布