CSDN博客

img joyhope

The structue data returned in C

发表于2004/10/31 21:25:00  463人阅读

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.
阅读全文
0 0

相关文章推荐

img
取 消
img