我有一个函数,它可以克隆结构体的成员并返回结构体(而不是指针)。这个新创建的对象寿命很短。
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;
}
我不能返回指向已释放内存的指针。如何将clone函数的返回值作为指针传递给第二个函数?类似于以下示例,但不使用中间占位符。
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});
针对一些有关使用中间件的评论。问题是要避免创建中间件,并不是"我不能使用一个因为..."。我最近遇到了一个编码结构,我认为我可以,但发现我不能,因此提出了这个问题。此外,将已经分配的实例传递给克隆函数仍然需要一个中间计算结果。我希望不要在函数头中添加短暂的变量声明等混乱内容。
my_struct_clone()
函数并提供一个新分配的结构体指针呢?当然,你需要在函数外释放内存来设计你的程序,但这将防止你做出奇怪的尝试。 - Roberto Caboni