This always is a confusion for me.
When is it safe and not safe to return reference to a pointer?
This always is a confusion for me.
When is it safe and not safe to return reference to a pointer?
Not sure if I understand the question. It should be safe depending on what you want to do.
Returning a reference to a pointer is not something you will do often. It is used when you want to return a static variable declared inside the function.
Sorry if I couldn't come up with a better example. But honestly couldn't think of a good one where it may make sense to use a function that returns a reference to a pointer.Code://Counts how many times the function was called and skips count by x. int*& SkipCounter(int x = 0) { static int counter = 0; ++counter += x; static int* value = &counter; return value; } int main() { int test = *SkipCounter(); // test = 1. It was called the first time int test2 = *SkipCounter(1); // test = 3, previous count + 1 + skip of 1 int test3 = *SkipCounter(); //test = 4, previous count + 1 int test4 = *SkipCounter(2); //test = 7, previous count + 1 + skip of 2 }
All in all, the whole thing could be written with a simple return of int.
Originally Posted by brewbuck:
Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.
Just combine the rules of when it is unsafe to return a reference to any type with the rules for when it is unsafe to return a pointer, and you have the rules for when it is unsafe to return a reference to a pointer. For example, it is unsafe to return a reference to any type if the object (or pointer) will go out of scope when the function ends. It is also unsafe to return a pointer if the pointer points to memory that will be destroyed when the function ends. So if the pointer points to an object about to be destroyed, or if the pointer itself is aboutto go out of scope, then it is unsafe to return it.
Thanks for the response!