【C++】类中拷贝构造注意事项与strcpy_s和memcpy_s注意事项

   vector等一系列容器在添加或者插入元素时,都是创建新的实例然后将需要添加的对象进行拷贝,例如push_back()或者insert(),调用的都是类的构造函数 class (class ),默认的直接给对应的成员赋值,对于指针则只会拷贝指针指向的地址,当需要添加的元素析构或者删除后,则会影响容器内的元素。
   所以需要重写拷贝构造函数。
    A(const A& b) 以及 A& operator=(const A&b),此处必须用引用,否则需要添加临时的类对象,则又会调用默认构造函数,然后析构,然后报错。。。。。

1、浅拷贝

#include<iostream>
#include<vector>
using namespace std;
class  test
{
public:
	test() :name(NULL) { cout << "调用默认构造"; };  //1、浅拷贝
	test(const char*name, const int age)
	{
		if (this->name != nullptr)
		{
			delete[] this->name;
			this->name = nullptr;
		}
		this->name = new char[strlen(name) + 1];
		//this->name = nullptr;
		const int size = strlen(name) + 1;
		cout << "大小" << size << "参数 " << name << endl;
		// 第二个参数表示目标缓冲区大小,大于或等于源串的长度 + 1(存放结束符'/0')。如果没有第二个参数,就没有方法来保证有效的缓冲区尺寸,
	   //不然只能假定缓冲足够大来容纳要拷贝的字符串(strcpy函数)。在程序运行时,这将导致不可预料的行为。
		cout << "step1" << endl;
		//cin.get();
		const char* tem = name;
		cout << sizeof(name)<< endl;
		strcpy_s(this->name,size , tem);
		//memcpy_s(this->name,  size,name,size);
		//*this->name = *name;
		cout << "step2" << endl;
		this->age = age;
	};

2、拷贝构造(深拷贝)

	//修改 拷贝构造(2、深拷贝)
	test(const test &t1)
	{
		if (this->name != nullptr)
		{
			cout << "此时需要释放name" << this->age<<endl;
			delete [ ] this->name;
			this->name = nullptr;
		}
		cout << "此时name: " << t1.name << "age: " << t1.age <<endl;
		this->name = new char[strlen(t1.name) + 1];
		const int size = strlen(t1.name) + 1;
		cout << "此时拷贝构造对象的大小:  " <<size<< endl;
		cout << "this->name_size:" << sizeof(this->name) << endl;
		strcpy_s(this->name, size, t1.name);
		this->age = t1.age;
	};


	test& operator=(const test &t1)
	{
		if (this->name != nullptr)
		{
			delete[] this->name;
			this->name = nullptr;
		}
		cout << "此时name: " << t1.name << "age:" << t1.age << endl;
		this->name = new char[strlen(t1.name) + 1];
		const int size = strlen(t1.name) + 1;
		strcpy_s(this->name, size, t1.name);
		this->age = t1.age;
		return *this;
	}

	void  print()
	{
		cout << this->name << endl;
	}


	~test()
	{
		cout << "尝试调用析构函数" << endl;
		if (this->name != nullptr)
		{
			delete[] this->name;
			this->name = nullptr;
		}

	};

private:
	char *name =nullptr;
	int age;
};

void  main()
{
	test t1("kaka",25);
	vector<test> v1;
	v1.push_back(t1);
	t1.~test();
	v1.at(0).print();
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值