Newbie question: When to return a pointer?


(hill lisa) #1

I want to ask Newbie question: When to return a pointer?


(Lutz Horn) #2

Return a pointer when you’ve received a pointer, have modified what it references and want your caller to know about this new reference.


(Ivan Matmati) #3

Plus certain objects can’t stand to be copied, example Mutex. From documentation : “A Mutex must not be copied after first use”. If you have a mutex in any struct, you mustn’t copy it.


(Inanc Gumus) #4

Most of the time do not return a pointer. Instead, accept a pointer as a parameter and work on it.

On the other hand, the best time to return a pointer is from constructor functions. That is: When you want to build a value for the first time and return a pointer to it.