Home > front end >  Reference to a Structure
Reference to a Structure

Time:11-29

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 which new 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 pointer ptr 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 use delete to free memory allocated by new when the memory is no longer needed. A call to clone() conceals the call to new, 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 ?

CodePudding user response:

As far as I know for best practices you should never dereference a pointer without initializing it

That's not just a "best practice", but it's absolutely mandatory to not do so. You must never indirect through an uninitiliased pointer.

How the new operator is automatically called when calling the function ?

new operator isn't called.


free_throws * ptr;

The first statement creates a nameless free_throw structure.

This is completely wrong. The first statement creates a pointer, and no instance of a structure at all. The quoted text doesn't match the code.

free_throw & jolly = clone(three);

This makes jolly a reference to the new structure.

This is also wrong. clone returns a reference to const, and the reference to non-const jolly cannot be bound to it. This initialisation is ill-formed.


I would assume that the code is a mistake, and there was an intention to use new in there, but the author forgot. Most important part to understand is in the third quote that explains that the function has a problem; As such, the function is useless even if it were "fixed" to use new as was probably intended.

  • Related