使用指向从函数返回的结构的指针

Using a pointer to struct returned from a function

我有一个函数可以克隆一个结构的成员和 return一个结构(不是指针)。这个新创建的对象是短暂的。

struct my_struct {
   int a;
   int b;
};

inline struct my_struct my_struct_clone(struct my_struct src, int members){
   struct my_struct copy = {0};
   //... Do copy based on args
   return copy;
}

我不能 return 指针,因为它会指向已释放的内存。如何将克隆函数的 return 值作为指向第二个函数的指针传递?类似于以下内容,但不使用中间占位符。

void do_sth(struct my_struct const *p);

struct my_struct val = my_struct_clone(&other, 123);
do_sth(&val);

以下失败(需要左值作为一元“&”操作数):

do_sth(&(my_struct_clone(&other, 123)));

但是声明一个结构内联是可能的

do_sth(&(struct my_struct){.a = 1, .b = 2});

解决一些关于使用中间体的评论。问题是关于避免创建一个,而不是 "I can't use one because..."。我最近遇到了一个编码结构,我认为我可以但发现我不能,因此出现了这个问题。此外,将已分配的实例传递给克隆函数仍然需要一个中间体。我宁愿不要用像这样短暂的变量声明来混淆函数头。

函数返回的值是一个rvalue, 这意味着它的地址不能被占用。

但是compound literals are lvalues这意味着他们的地址可以被占用。

您需要临时变量才能将克隆函数的结果作为指针传递。

我个人会做类似的事情:

inline void my_struct_clone(const struct my_struct src, struct my_struct *srcCopy, int members){
   //... Do copy based on args
   srcCopy->a = src.a;
   srcCopy->b = src.b;
}

所以你会这样调用和声明克隆:

struct my_struct strClone;
my_struct_clone(str, &strClone, 123);
do_sth(strClone); // Call to strClone