Skip to content

Instantly share code, notes, and snippets.

@liuguiyangnwpu
Created August 2, 2016 07:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuguiyangnwpu/30338a97f853574f2596f80b7a24cc2e to your computer and use it in GitHub Desktop.
Save liuguiyangnwpu/30338a97f853574f2596f80b7a24cc2e to your computer and use it in GitHub Desktop.
How to free the pointer which allocated on the heap, use different method !
  • when using containers of newed pointers, remember to delete the pointers before the container is destroyed.
void doSomething() {
	vector<Widget*> vwp;
	for(int i=0;i<NUMS;++i) {
		vwp.push_back(new Widget);
	}
}
// Widgets are leaked here !
  • you should delete the memory which you allocate
void doSomething() {
	vector<Widget*> vwp;
	for(int i=0;i<NUMS;++i) {
		vwp.push_back(new Widget);
	}
	//////// do something
	for(vector<Widget*>::iterator it=vwp.begin(); it!=vwp.end(); ++it) {
		delete *it;
	}
}
  • you can also use for_each to free the memory
template<typename T>
struct DeleteObject {
	public unary_function<const T*, void> {
		void operator()(const T *ptr) const {
			delete ptr;
		}
	}
};

Now you can do this:

void doSomething() {
	... // as before
	for_each(vwp.begin(), vwp.end(), DeleteObject<Widget>);
}
  • you can also use another defination to simplify the maintain
struct DeleteObject {
	template<typename T>
	void operator()(const T* ptr) const {
		delete ptr;
	}
};

void doSomething() {
	deque<SpecialString*> dssp;
	... //fill the containers
	for_each(dssp.begin(), dssp.end(), DeleteObject()); 
	// ah! well-defined behavior, Straightforward and type-safe, just the wat we like it.
}
  • Use Smart Pointer to revoke the memory
void doSomething() {
	typedef std::shared_ptr<Widget> SPW;
	vector<SPW> vwp;
	for(int i=0;i<NUMS;++i) {
		vwp.push_back(SPW new Widget);
	}
}
// No Widgets are leaked here, not even if an exception is thrown in the code above
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment