简体   繁体   English

通过引用返回C ++

[英]Returning by reference in C++

I know that it's alright to return by reference if the referenced variable was also passed into the function by reference. 我知道,如果引用的变量也通过引用传递到函数中,则可以通过引用返回。 For example: 例如:

int& foo(int& bar)
{
    bar++;
    return bar;
}

However, I'm wondering if it's possible to also return by reference if you're returning an object that was created in the function via the new keyword. 不过,我想知道是否有可能通过引用返回,如果你回到那是函数通过创建的对象new关键字。 I tried something like the following, but got a compiler error: 我尝试了类似以下的操作,但出现了编译器错误:

vector<int>& baz()
{
    return new vector<int>();
}

Is there a way to return the new vector by reference that makes sense, or is it better to just return a pointer? 有没有一种方法可以通过有意义的引用返回新向量,还是仅返回一个指针更好?

Technically, you can of course return a dynamically allocated object by reference: 从技术上讲,您当然可以通过引用返回动态分配的对象:

vector<int>& baz()
{
    return *new vector<int>();
}

Note the * used to dereference the pointer returned by new . 注意*用于取消引用new返回的指针。

Whether it's wise to do that is an entirely different kettle of fish. 这样做是否明智,完全是另一回事。 It's a prime candidate for a memory leak. 它是内存泄漏的主要候选者。 If you do it, the caller is responsible for calling delete on the returned object, otherwise it's leaked. 如果执行此操作,则调用者负责对返回的对象调用delete ,否则它将被泄漏。 Note that this could happen very easily with either of these scenarios: 请注意,在以下两种情况下都可能很容易发生这种情况:

std::vector<int> v1 = baz(); // leak!
auto v2 = baz(); // leak!, auto doesn't deduce references

In modern C++, you should simply return the vector by value and let move semantics and/or (Named) Return Value Optimisation do its job: 在现代C ++中,您应该仅按值返回向量,然后移动语义和/或(命名)返回值优化即可完成其工作:

std::vector<int> baz()
{
  return std::vector<int>();
}

If you need dynamic allocation for some reason, you should at least return a suitable smart pointer to ensure no memory leaks can happen: 如果出于某种原因需要动态分配,则至少应返回一个合适的智能指针,以确保不会发生内存泄漏:

std::unique_ptr<std::vector<int>> baz()
{
  return std::unique_ptr<std::vector<int>>(new std::vector<int>());
}

Regarding: Is there a way to return the new vector by reference that makes sense, or is it better to just return a pointer? 关于: Is there a way to return the new vector by reference that makes sense, or is it better to just return a pointer?

A double no no. 双重否

Just return by value and take advantage of copy-elision (See: What are copy elision and return value optimization? ) and move-semantics (See: What are move semantics? ) 只需按值返回并利用复制省略(请参阅: 什么是复制省略和返回值优化? )和移动语义(请参阅: 什么是移动语义? )。

new vector<int>();

actually returns a pointer. 实际上返回一个指针。

If you really like to memory leak, write this: 如果您真的想内存泄漏,请编写以下代码:

return *(new std::vector<int>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM