I've seen two different solutions on how to allocate memory for an argument within a function:
Using **:
template <class T>
void funcPP(T ** ppnDynamicInt) {
*ppnDynamicInt = new T;
}
vs
Using *&
template <class T>
void funcRP(T *& pnDynamicInt) {
pnDynamicInt = new T;
}
Example using the functions ->
int * pnDynamicInt;
funcPP(&pnDynamicInt);
funcRP(pnDynamicInt);//memory leak I know ;)
What is considered a safer/better style? Is one solution more efficient?
(Note: I know it would be better with smart pointers :))
As you are only considering between the two alternatives shown,
I'd suggest funcRP, since the language guarantees that pnDynamicInt is never null (references can't be null) but *ppnDynamicInt = new T; could cause undefined behaviour if ppnDynamicInt is a null pointer. Other than that they are identical (except that funcRP uses neater syntax)
Note: depending on how your using the functions, you may want to delete the previous value, such as with delete pnDynamicInt.
Edit: By 'guarantees' I mean there is no non-undefined way of having a null-reference, whereas null pointers are well-defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With