Using * return types (pointers)

I'm looking to know the intricate or definitive details on when to use pointers as return types or just the actual type, and when to use reference or pointers as paramaters as well as using the const keyword.


Also, If you can, can you tell me the effect of using stacked keywords in headers like
1
2
3
4
typedef struct [name];
//or
struct typedef [name];
//etc 
Line 1. This is something from C, where you had to write "struct MyStruct" instead of just "MyStruct", but you could use a typedef to write "MyStructTypedef".
Line 3 is not valid syntax.


As for pointers as return types, you should only do this is the data being pointed to will exist after the function call or if the data might not need to be returned. An example is std::string::c_str() returning a char * to the start of its character buffer, which will exist as long as the string does. Another example is a function that *may* return an error, or will return null (0) to signify no error.

For pointers and references as parameters:
	If the parameter is optional:
		If you can use function overloading:
			Use function overloading
		Otherwise:
			Pass it by pointer, using 0 to mean not passed.
	Otherwise:
		For Primitives:
			If you do not need to modify the original outside the function:
				Pass it by value
			Otherwise:
				Pass by reference (to modify the original outside the function)
		For Other Types (classes, structs, ect):
			If you do not need to modify the original outside the function:
				Pass it by const reference
			Otherwise if you don't need your own copy:
				Pass it by reference
			Otherwise:
				Pass it by value (for automagic copy)
Last edited on
Disclaimer: Yes someone could make a reference refer to a dereferenced null pointer... Don't do this.

References must refer to an object, they are required to be initialized. Pointers has no such restriction. The fact that there is no such thing as null references means that they can be more efficient than pointers, because you don't have to check the validity of the reference (where you would want to check for NULL before using a pointer).

Another important difference is that pointers can be reassigned to point to other objects, a reference always refers to the object with which it was initialized. In general use a pointer whenever you need to take into account the possibility that there is nothing to refer to, in which case the pointer can be set to NULL. You should use a reference whenever you know there will always be an object to refer to and you also know that once you're referring to that object, you'll never want to refer to anything else.

If you have a choice when passing parameters and none of the above statements apply and you aren't dealing with primitive types, prefer to pass by const reference.
clanmjc, my post has undergone massive construction. Please let me know if I messed up the when-to-use-for-functions logic.
Topic archived. No new replies allowed.