它是安全的C或C ++返回一个结构? [英] Is it safe to return a struct in C or C++?

查看:155
本文介绍了它是安全的C或C ++返回一个结构?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的理解是,这不应该做的,但我相信我已经看到了这样做的例子(注意code不一定语法正确但这个想法是有)

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;

和那么这里是一个函数

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

我明白了,我们应该一个指针总是回到一个malloc分配结构,如果我们想要做这样的事,但我敢肯定我见过的例子是做这样的事情。它是否正确?个人而言,我总是要么返回一个指针malloc分配结构或只是参考的功能做了一通,并修改值出现。 (因为我的理解是,一旦函数的范围已经结束,无论是堆用于分配的结构可以覆盖)。

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).

让我们的第二部分增加了一个问题:这是否由编译器有什么不同?如果确实如此,那么什么是编译器用于台式机的最新版本的行为:GCC,G ++和Visual Studio

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?

对此事的看法?

推荐答案

这是完全安全的,这是没有错这样做。另外:它不被编译器而异

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

通常,当(如你的例子),你的结构是不是太大,我认为,这种方法比返回malloc分配结构更好(的malloc 是一个昂贵的操作)。

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).

这篇关于它是安全的C或C ++返回一个结构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆