如何返回指针指向的值

How do I return the value pointed to by a pointer?

本文关键字:指针 何返回 返回      更新时间:2023-10-16

我有一个类成员定义为:

someType* X;

我得到它像:

someType* getX() {return x;}

我想获取值而不是指针,即:

someType getX() {return x;} //this is wrong

正确的语法是什么?如何获取值而不是指针?

someType getX() {return *x;}

请注意,这按返回x,即它在每次返回时创建一个x的副本*。因此(取决于someType到底是什么)您可能更喜欢返回引用

someType& getX() {return *x;}

对于构造成本可能很高的非基元类型,建议通过引用返回,并且对象的隐式复制可能会引入细微的错误。

*在某些情况下,这可以通过返回值优化来优化,如下@paul23正确指出的那样。但是,一般而言,安全行为并不指望这一点。如果您不希望创建额外的副本,请在代码中通过返回引用(或指针)为编译器和人类读者明确说明。

someType getX() const { return *x; }

或者,如果复制someType成本很高,请通过const引用将其返回:

someType const &getX() const { return *x; }

请注意,该方法const限定符。

SomeType getX()
{
  //  SomeType x = *x; // provided there is a copy-constructor if    
  //  user-defined type.
  // The above code had the typo. Meant to be.
  SomeType y = *x;
   return y;
}