Say I have the following:
typedef struct {
int x;
int y;
char a;
char b;
} myStruct;
Is it better practice to create a new
It's basically just convention. The first style is more common in C-code, the second is more common in C++ code.
In C++ they would say that the second is preferred because in the first, if you allocate one of the structs but forget to call init
then you can have a confusing situation with a "headless object" being passed around.
In C++ the init
function would normally just be a constructor, so that there's no possibility of failure to initialize.
In C++ there won't be any difference in efficiency if you turn on optimizations, the compiler will do "copy elision" and optimize the second so that it will look similar to the first.