Chưa phân loại

C++ Tutorial – Pass a pointer by reference to a function

This tip will show you the simple way to pass a pointer by reference to a function. It’s very simple.

#include 		// For NULL
#include 		// For IO

using namespace std;

//////////////////////////////////////////////////////////////////////////
// Function:	CreateHandle
// Brief:		Dynamically allocate memory for an int
// Return:		A pointer to int
//////////////////////////////////////////////////////////////////////////
int* CreateHandle() {
	return new int;
}

//////////////////////////////////////////////////////////////////////////
// Function:		ReleaseHandle
// Parameter [in]:	handle
// Brief:			Deallocate memory of handle and set it NULL
//////////////////////////////////////////////////////////////////////////
void ReleaseHandle(int*& handle) {
	if(handle != NULL) {
		delete handle;
		handle = NULL;
	}
}

int main() {

	int* handle = CreateHandle();

	ReleaseHandle(handle);

	if(handle == NULL) {
		cout << "Handle is NULL";
	}
	else {
		cout << "Handle is NOT NULL";
	}

	cin.get();

	return 0;
}

The result is:
Handle is NULL

 

Happy coding!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s