返回C ++参考变量的做法是否有害? [英] Is the practice of returning a C++ reference variable evil?

查看:107
本文介绍了返回C ++参考变量的做法是否有害?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为这有点主观;我不确定这种意见是否会一致(我已经看到很多返回引用的代码段)。

This is a little subjective I think; I'm not sure if the opinion will be unanimous (I've seen a lot of code snippets where references are returned).

根据对我刚刚问过的有关初始化引用的问题,返回引用可以是邪恶的原因是,[据我了解],这样做很容易错过删除它,这可能导致内存泄漏。

According to a comment toward this question I just asked, regarding initializing references, returning a reference can be evil because, [as I understand] it makes it easier to miss deleting it, which can lead to memory leaks.

这让我担心,因为我遵循了示例(除非我在想像),并在几个地方做到了……我误会了吗?是邪恶的吗?如果是这样,到底有多邪恶?

This worries me, as I have followed examples (unless I'm imagining things) and done this in a fair few places... Have I misunderstood? Is it evil? If so, just how evil?

我觉得这是因为我的指针和引用混合在一起,再加上我对C ++还是陌生的事实关于什么时候使用什么,我的应用程序一定是内存泄漏地狱……

I feel that because of my mixed bag of pointers and references, combined with the fact that I'm new to C++, and total confusion over what to use when, my applications must be memory leak hell...

此外,我知道使用智能/共享指针通常被认为是避免出现错误的最佳方法内存泄漏。

Also, I understand that using smart/shared pointers is generally accepted as the best way to avoid memory leaks.

推荐答案

通常,返回引用是完全正常的,并且一直在发生。

In general, returning a reference is perfectly normal and happens all the time.

如果您的意思是:

int& getInt() {
    int i;
    return i;  // DON'T DO THIS.
}

这真是种邪恶。堆栈分配的 i 将消失,您什么也没指。这也是邪恶的:

That is all sorts of evil. The stack-allocated i will go away and you are referring to nothing. This is also evil:

int& getInt() {
    int* i = new int;
    return *i;  // DON'T DO THIS.
}

因为现在客户最终不得不做奇怪的事情:

Because now the client has to eventually do the strange:

int& myInt = getInt(); // note the &, we cannot lose this reference!
delete &myInt;         // must delete...totally weird and  evil

int oops = getInt(); 
delete &oops; // undefined behavior, we're wrongly deleting a copy, not the original

请注意,右值引用是

如果您要分配超出函数范围的内容,请使用智能指针(或在一般而言,是一个容器):

If you want to allocate something that lives beyond the scope of the function, use a smart pointer (or in general, a container):

std::unique_ptr<int> getInt() {
    return std::make_unique<int>(0);
}

现在客户端存储了一个智能指针:

And now the client stores a smart pointer:

std::unique_ptr<int> x = getInt();

对于访问那些您知道生命周期在更高级别保持开放状态的东西也可以使用引用,例如:

References are also okay for accessing things where you know the lifetime is being kept open on a higher-level, e.g.:

struct immutableint {
    immutableint(int i) : i_(i) {}

    const int& get() const { return i_; }
private:
    int i_;
};

在这里,我们知道可以返回对 i _ ,因为任何调用我们的东西都可以管理类实例的生命周期,因此 i _ 的寿命至少会长到这一点。

Here we know it's okay to return a reference to i_ because whatever is calling us manages the lifetime of the class instance, so i_ will live at least that long.

当然,没有什么错。

int getInt() {
   return 0;
}

如果将生命周期留给调用者,而您只是

If the lifetime should be left up to the caller, and you're just computing the value.

摘要:如果对象的生命周期在调用后不会结束,则可以返回引用。

Summary: it's okay to return a reference if the lifetime of the object won't end after the call.

这篇关于返回C ++参考变量的做法是否有害?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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