1

I stumbled across this piece of code, and could not understand how the new operator was used in this case:

student* setname(string name)
{
  student* stu=(student*)malloc(sizeof(student));
  new(stu) student;
  stu->age=12;
  stu->name=name;
  return  stu;
}

I would expect new to be used like stu = new student;. How is new(stu) student different?

KamilCuk
  • 120,984
  • 8
  • 59
  • 111
megamonium
  • 463
  • 3
  • 7
  • 1
    See e.g. https://en.cppreference.com/w/cpp/language/new#Placement_new . – Bob__ Apr 25 '20 at 08:24
  • 2
    As Bob said, placement new - BUT *please never use code like this*! I don't speak Chinese (or should I say Mandarin?), so I can only read a translated version of the blog where this seems to come from - so maybe I'm missing something, but I don't understand why anyone teaching you C++ would recommend using malloc (which comes from C) and placement new instead of C++'s normal new operator. ALSO C++ functions should never return a raw pointer to freshly allocated memory (because someone *is* going to forget to delete it) --- AND why does a function called 'setname' *create a new student* anyway? – Allison Lock Apr 25 '20 at 08:39

0 Answers0