I read this portion from a book called C++ Primer Plus
(Page no. 400. Chapter:8 - Adventures in Functions)
A second method is to use
new
to create new storage. You've already seen examples in whichnew
creates space for a string and the function returns a pointer to that space. Here's how you chould do something similar with a referece:
const free_throws & clone(free_throw & ft)
{
free_throws * ptr;
*ptr = ft;
return *ptr;
}
The first statement creates a nameless
free_throw
structure. The pointerptr
points to the structure, so*ptr
is the structure. The code appears to return the structure , but the function declaration indicates that the function really reutrns a reference to this structure. You could use this function this way:
free_throw & jolly = clone(three);
This makes
jolly
a reference to the new structure. There is a problem with this approach: YOu should usedelete
to free memory allocated bynew
when the memory is no longer needed. A call toclone()
conceals the call tonew
, making it simpler to forget to use delete later.
My doubts:
As far as I know for best practices you should never dereference a pointer without initializing it and declaring a pointer to certain structure will only allocate space for the pointer only not for the whole structure, you must allocate space separately for the structure.
According to this book the declaring a pointer automatically allocates space to the whole structure and the pointer is dereferenced without initializing.
How the new
operator is automatically called when calling the function ?