`
joyhope
  • 浏览: 2384 次
最近访客 更多访客>>
社区版块
存档分类
最新评论

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.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics