0

when I use the codes in VS2017,I failed. And these codes are from C++ Prime Plus 8.2.4-3

const free_throws & clone (free_throws & ft)
{
    free_throws * pt;    //  sequence 1
    *pt = ft;            // sequence 2
    return *pt; 
}

free_throws is a struct

struct {
 std::string name;
 int made;
 int attempts;
 float percent;
}

In this book,he said there is a new() function without name that was used; my question is: where the new() used?
sequence 1 or sequence 2 or it's a wrong code.

  • 1
    The `clone()` in the first snippet looks very wrong to me. `free_throws * pt;` declaring a pointer without initialization (i.e. doesn't point to allocated storage). `*pt = ft;` assigns the contents of `ft` to the non-allocated storage. This is [U.B.](https://en.cppreference.com/w/cpp/language/ub) – Scheff's Cat Dec 01 '20 at 11:43
  • Assuming, the first line would be `free_throws * pt = new free_throws();` then it wouldn't be anymore U.B. But it still would have a smell of a potential memory leak... – Scheff's Cat Dec 01 '20 at 11:46
  • When I read C++ Prime Plus something was ringing in my head and googled a bit (out of curiosity). While C++ Primer seems to be a well accepted book this is not C++ Primer Plus. I found some bashing about the latter. These might be opinionated but this one appears reasonable: [ACCU](https://accu.org/bookreviews/1998/bramer_854/) two stars (while [C++ Primer](https://accu.org/bookreviews/2012/glassborow_1848/) got 5). I'm afraid you bought the wrong one... (Both are mentioned in [The Definitive C++ Book Guide and List](https://stackoverflow.com/a/388282/7478597) as well.) – Scheff's Cat Dec 01 '20 at 12:03

0 Answers0