欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

The structue data returned in C CC++C# 

程序员文章站 2022-05-29 13:13:54
...
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#