【发布时间】:2021-10-17 14:50:54
【问题描述】:
假设我将在函数中返回一个大型结构,如下所示:
#include <stdio.h>
// this is a large struct
struct my_struct {
int x[64];
int y[64];
int z[64];
};
struct my_struct get_my_struct_from_file(const char *filename) {
int tmp1, tmp2; // some tmp. variables
struct my_struct u;
// ... load values from filename ...
return u;
}
int main() {
struct my_struct res = get_my_struct_from_file("tmp.txt"); // <-- here
printf("x[0] = %d\n", res.x[0]);
// ... print all values ...
}
在here 标记的地方,我是否必须假设这个大结构被复制了,还是编译器可能会采取一些措施来避免这种情况?
谢谢
【问题讨论】:
-
唯一知道的方法是检查生成的程序集。但 NRVO 似乎是一个合理的优化,即使在 C 语言中(ABI 愿意)。
-
您的
get_my_struct_from_file是否总是与对其的任何调用在同一个翻译单元中,或者它是否可以在外部链接单元中,例如对象库?如果是后者,那么避免完整副本似乎很棘手。