C++ 指针与引用返回类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7813728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 17:32:06  来源:igfitidea点击:

Pointer vs. reference return types

c++pointersreference

提问by eran otzap

i'm trying to come up with a concrete reasoning why to use a pointer over a reference as a return type from a function ,

我试图想出一个具体的推理,为什么要使用引用上的指针作为函数的返回类型,

my reasoning is that if inadvertently a null value is returned to a reference type it could not be checked , and could lead to run-time errors

我的推理是,如果无意中将空值返回给引用类型,则无法对其进行检查,并可能导致运行时错误

  int& something(int j)
  {
      int* p = 0 ;  
      return *p;
  }

  void main()
  {
      int& i = something(5);
      i = 7;   // run-time error 
  }

if i had used a pointer i could check it and avoid the error the pointer return value would act as a contract to that a value must be returned.

如果我使用了一个指针,我可以检查它并避免错误,指针返回值将作为必须返回值的契约。

 void main()
 {
         int* i = something(5);
         if( i != null )
             *i = 7;
 }

any thoughts would be appreciated again ,

任何想法都会再次受到赞赏,

what would you use and why reference or pointer

你会使用什么以及为什么引用或指针

thanks in advance.

提前致谢。

回答by Andy Thomas

You could use a pointer instead of a reference if:

如果出现以下情况,您可以使用指针而不是引用:

  • Null is a valid return value
  • You dynamically constructed something in the function, and the recipient becomes the owner. (In this case, you might consider returning a smart pointer such as std::unique_ptr or boost::shared_ptr.)
  • Null 是有效的返回值
  • 您在函数中动态构建了一些东西,接收者成为所有者。(在这种情况下,您可能会考虑返回一个智能指针,例如 std::unique_ptr 或 boost::shared_ptr。)

Regardless, you would not want to return either a pointer or a reference to a local variable.

无论如何,您不希望返回一个指针或对局部变量的引用。

回答by Carl

References are a different way of thinking. Think of references as "pointers to existing objects". Once you do that, you'll understand why they can't be NULL - the object exists and the reference points to it.

参考是一种不同的思维方式。将引用视为“指向现有对象的指针”。一旦你这样做了,你就会明白为什么它们不能为 NULL - 对象存在并且引用指向它。

Therefore, if your function returns a reference to something that it creates, it needs to guarantee that it actually does create a valid object. If it does not, or is unable to, then that is grounds to throw an exception.

因此,如果您的函数返回对其创建的对象的引用,则需要保证它确实创建了一个有效的对象。如果它没有,或者不能,那么就是抛出异常的理由。

Contrast that with a pointer. A pointer can be NULL and the caller will have to deal with a NULL return value. Therefore, if your function cannot guarantee that it will return a valid reference and you don't want to throw exceptions, you will need to use pointers.

将其与指针进行对比。指针可以为 NULL,调用者必须处理 NULL 返回值。因此,如果你的函数不能保证它会返回一个有效的引用并且你不想抛出异常,你将需要使用指针。

回答by Marcelo Cantos

If you inadvertently return a null value, that's a bug. You can just as easily place the check inside something()and throw an exception if it's null.

如果您无意中返回了一个空值,那就是一个错误。您可以轻松地将检查放入其中something()并在它为空时抛出异常。

Having said that, the historical convention is to return heap objects via pointers, even if they are guaranteed to be non-null.

话虽如此,历史惯例是通过指针返回堆对象,即使它们保证非空。

回答by John Dibling

If your function is intended to "always" return a value, then your function should return a reference.

如果您的函数旨在“始终”返回一个值,那么您的函数应该返回一个引用。

In those cases where, for some exceptional reason, you cannot find the value to return, you should throw an exception.

在由于某些特殊原因找不到要返回的值的情况下,您应该抛出异常。

You should not rely on there being a run-time error generated when you try to return a reference to a null or wild pointer. The behavior is undefined. Anything could happen.

当您尝试返回对空指针或野指针的引用时,您不应依赖会产生运行时错误。行为未定义。什么事情都可能发生。

回答by David Heffernan

C++ references cannot be null. The bug is dereferencing a null pointer. That's undefined behaviour.

C++ 引用不能为空。该错误是取消引用空指针。这是未定义的行为。

回答by Mranz

It is usually dependent on what you are trying to accomplish, but I generally treat return values this way:

它通常取决于您要完成的任务,但我通常这样处理返回值:

Return pointer - Caller owns memory (and cleanup)

返回指针 - 调用者拥有内存(和清理)

Reference - Callee owns the memory. DO NOT return a dynamically allocated point unless the callee manages it as well.

参考 - Callee 拥有内存。除非被调用者也管理它,否则不要返回动态分配的点。