The structue data returned in C

博客通过三个案例分析函数返回结构体时的情况,指出函数返回结构体或对象值会导致拷贝,返回大对象不是好设计,还提及返回已销毁栈地址的问题。同时对比了Java,Java对象从堆分配,引用是值拷贝,处理更简单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Case study
Case 1:
struct A { ...}
void Caller()
{
struct A b=getA(); (1)

...
}

struct A getA()
{
struct A a;
a.xxx=xxx
....

return a;
}

The (1)
getA() really return the address of a, the address in the stack which is destroyed, but now no one is using this stack area.
= is the key part in this problem. = will cause the value copy (bitwise copy for the struct, copy construct for the object)

when (1) finished, the b get the value copy from a.

So the object or struct value returned in the function will caused a copy. It is not a good design if the large object returned from function.

Case 2:

struct A { ...}
void Caller()
{
struct A* b=getA(); (1)

...
}

struct A* getA()
{
struct A a;
a.xxx=xxx
....

return &
}

the destroyed stack address is used in the caller.

Case 3:

struct A { ...}
void Caller()
{
struct A b=*(struct A*)getA(); (1)

...
}

struct A* getA()
{
struct A a;
a.xxx=xxx
....

return &
}

This may be the same as the case 1, but only valid for the structure. It will be failed it an object is returned unless * operation is overloaded.

The object returned in Java is more simple.
All the object are allocate from heap, so do not worry about the object in the stack.

The reference (object handle) is value copy. It is simple.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值