Is it better style to initialize a structure by passing a reference or returning it?

前端 未结 4 1840
栀梦
栀梦 2021-01-20 02:54

Say I have the following:

typedef struct {
    int x;
    int y;
    char a;
    char b;
} myStruct;

Is it better practice to create a new

4条回答
  •  花落未央
    2021-01-20 03:17

    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.

提交回复
热议问题