在 C 或 C++ 中返回结构是否安全?

2021-12-23 00:00:00 function c struct c++ return-type

我的理解是不应该这样做,但我相信我已经看到过这样做的例子(注意代码不一定在语法上是正确的,但想法是存在的)

typedef struct{国际a,b;}我的结构;

然后是一个函数

mystruct func(int c, int d){mystruct retval;retval.a = c;retval.b = d;返回 retval;}

我知道如果我们想做这样的事情,我们应该总是返回一个指向 malloc 结构的指针,但我很肯定我已经看到了做这样的事情的例子.这个对吗?就我个人而言,我总是要么返回一个指向 malloc 结构的指针,要么只是通过对函数的引用进行传递并修改那里的值.(因为我的理解是,一旦函数的作用域结束,用于分配结构的任何堆栈都可以被覆盖).

让我们为问题添加第二部分:这是否因编译器而异?如果是,那么最新版本的桌面编译器的行为是什么:gcc、g++ 和 Visual Studio?

对此事的想法?

解决方案

这是完全安全的,而且这样做并没有错.另外:它不会因编译器而异.

通常,当(如您的示例)您的结构不是太大时,我认为这种方法甚至比返回 malloc 结构更好(malloc 是一项昂贵的操作).

What I understand is that this shouldn't be done, but I believe I've seen examples that do something like this (note code is not necessarily syntactically correct but the idea is there)

typedef struct{
    int a,b;
}mystruct;

And then here's a function

mystruct func(int c, int d){
    mystruct retval;
    retval.a = c;
    retval.b = d;
    return retval;
}

I understood that we should always return a pointer to a malloc'ed struct if we want to do something like this, but I'm positive I've seen examples that do something like this. Is this correct? Personally I always either return a pointer to a malloc'ed struct or just do a pass by reference to the function and modify the values there. (Because my understanding is that once the scope of the function is over, whatever stack was used to allocate the structure can be overwritten).

Let's add a second part to the question: Does this vary by compiler? If it does, then what is the behavior for the latest versions of compilers for desktops: gcc, g++ and Visual Studio?

Thoughts on the matter?

解决方案

It's perfectly safe, and it's not wrong to do so. Also: it does not vary by compiler.

Usually, when (like your example) your struct is not too big I would argue that this approach is even better than returning a malloc'ed structure (malloc is an expensive operation).

相关文章