您的位置:首页 > 产品设计 > UI/UE

The structue data returned in C

2004-10-31 21:25 429 查看
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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐