I am reading the book c++ primer plus and I feel confused about the reference variables and pointers. Here are two pieces of code extracted from page 400 of the book.
const free_throws & clone(free_throws & ft)
{
free_throws * pt;
*pt = ft;
return *pt;
}
const free_throws & clone2(free_throws & ft)
{
free_throws newguy;
newguy = ft;
return newguy;
}
The book said that the first one is okay but the second one is invalid. Is it true that a pointer variable will still exist after the function terminates even if it is declared within the function? Another question is why can we omit the new keyword in the first piece of code? If we can just create a nameless structure and assign something to it, why do we need the new keyword? Thank you in advance.
For the first one, the book provided a few lines of explanation.
The first statement creates a nameless free_throws structure. The pointer pt points to the structure, so *pt is the structure. The code appears to return the structure, but the function declaration indicates that the function really returns a reference to this structure.