是通过传递引用还是返回来初始化结构的更好的风格? [英] Is it better style to initialize a structure by passing a reference or returning it?

查看:82
本文介绍了是通过传递引用还是返回来初始化结构的更好的风格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有以下:

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

更好的做法是创建一个新的 myStruct 通过传递一个空的引用,或者通过从函数返回 myStruct ,函数?

Is it better practice to create a new myStruct with a function by passing a reference to an empty one, or by returning a myStruct from a function?

void init(myStruct* s){
    //some code
}

int main(){
    myStruct s;
    init(&s);
    return 0;
}

vs

myStruct init(){
    myStruct r;
    //some code
    return r;
}

int main(){
    myStruct s = init();
    return 0;
}


推荐答案

第一种样式在C代码中更常见,第二种在C ++代码中更常见。

It's basically just convention. The first style is more common in C-code, the second is more common in C++ code.

在C ++中,他们会说第二种是首选,如果你分配一个结构,但忘记调用 init ,那么你可能会有一个混乱的情况,一个无头对象被传递。

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.

在C ++中, init 函数通常只是一个构造函数,因此没有初始化失败的可能性。

In C++ the init function would normally just be a constructor, so that there's no possibility of failure to initialize.

在C ++中,如果你打开优化,效率就没有什么区别,编译器会做复制elision和优化第二个,使它看起来和第一个类似。

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.

这篇关于是通过传递引用还是返回来初始化结构的更好的风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆