The structue data returned in C

阅读更多
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 &
}

This is a bug refereed by lee, because 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.

你可能感兴趣的:(C,C++,C#)