Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocating memory for an argument in a function using ** or *&

Tags:

c++

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 :))

like image 578
A.Fagrell Avatar asked Dec 06 '25 14:12

A.Fagrell


1 Answers

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.

like image 196
Isaac Avatar answered Dec 08 '25 04:12

Isaac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!