问题描述
这是有点主观的,我想;我不知道这个意见是否一致(我已经看到很多代码片段返回了引用)。
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.
当然,没有什么错误只是:
And of course, there's nothing wrong with just:
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 ++引用变量的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!