保存指向自定义类型指针的容器的“清空”

#include <iostream>
#include <vector>

class Point {
public:
	Point(int ix, int iy) :m_ix(ix), m_iy(iy) {
		std::cout << "constructor" << std::endl;
	}
	~Point() {
		std::cout << "destructor" << std::endl;
	}
	void show() {
		std::cout << "(" << m_ix << "," << m_iy << ")" << std::endl;
	}
private:
	int m_ix;
	int m_iy;
};
int main()
{
	std::vector<Point*> vec;
	for (int i = 1;i <= 5;++i) {
		vec.push_back(new Point(i, i + 1));
	}

	for (const auto& elem : vec) {
		elem->show();
	}

	//for (auto& elem : vec) {
	//	delete elem;
	//	elem = nullptr;
	//}

	std::cout << "vector::size(): "<<vec.size() << std::endl;
	vec.clear();

	return 0;
}

运行上述代码可发现,若注释 delete elem 部分的代码,虽然调用了 vector::clear,却不会调用 Point 的析构函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于自定义类型指针的深拷贝需要按照以下步骤进行: 1. 在类中定义一个拷贝构造函数,在其中对指针指向的数据进行深拷贝。 例如,假设有一个自定义类型 `MyType`,其中包含一个指向 `int` 类型数据的指针: ```c++ class MyType { public: int* data; MyType() { data = nullptr; } MyType(const MyType& other) { if (other.data != nullptr) { data = new int(*other.data); } } ~MyType() { if (data != nullptr) { delete data; } } }; ``` 在上述代码中,`MyType` 类中定义了一个拷贝构造函数,该函数会对指针 `data` 指向的数据进行深拷贝。 2. 在类中定义一个拷贝赋值运算符函数(`operator=`),在其中对指针指向的数据进行深拷贝。 例如,假设有一个自定义类型 `MyType`,其中包含一个指向 `int` 类型数据的指针: ```c++ class MyType { public: int* data; MyType& operator=(const MyType& other) { if (this != &other) { if (other.data != nullptr) { data = new int(*other.data); } else { data = nullptr; } } return *this; } ~MyType() { if (data != nullptr) { delete data; } } }; ``` 在上述代码中,`MyType` 类中定义了一个拷贝赋值运算符函数,该函数会对指针 `data` 指向的数据进行深拷贝。 通过定义拷贝构造函数和拷贝赋值运算符函数,可以实现自定义类型指针的深拷贝。在进行指针赋值或者指针拷贝时,会自动调用拷贝构造函数或者拷贝赋值运算符函数,从而实现指针指向数据的深拷贝。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值