简体   繁体   English

如何返回指针指向的值?

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

I have a class member defined as: 我有一个类成员定义为:

someType* X;

and I get it like: 我觉得它像:

someType* getX() {return x;}

I would like to get the value rather than the pointer ie: 我想得到的值而不是指针,即:

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

what is the proper syntax for this? 这个的正确语法是什么? How do I get the value rather than the pointer? 我如何获得值而不是指针?

someType getX() {return *x;}

Note though that this returns x by value , ie it creates a copy of x at each return*. 请注意,这会按值返回x ,即它会在每次返回*时创建x的副本。 So (depending on what someType really is) you may prefer returning a reference instead: 所以(取决于someType是什么)你可能更喜欢返回引用

someType& getX() {return *x;}

Returning by reference is advisable for non-primitive types where the cost of construction may be high, and implicit copying of objects may introduce subtle bugs. 对于非基本类型,建议通过引用返回,其中构造成本可能很高,并且对对象的隐式复制可能会引入细微的错误。

* This may be optimized away in some cases by return value optimization , as @paul23 rightly points out below. * 在某些情况下,可以通过返回值优化对此进行优化 ,正如@ paul23在下面正确指出的那样。 However, the safe behaviour is not to count on this in general. 但是,安全行为一般不依赖于此。 If you don't ever want an extra copy to be created, make it clear in the code for both the compiler and human readers, by returning a reference (or pointer). 如果您不希望创建额外的副本,请通过返回引用(或指针)在编译器和人类读取器的代码中明确说明。

someType getX() const { return *x; }

or alternatively, if someType is expensive to copy, return it by const reference: 或者,如果someType复制someType很昂贵,请通过const引用返回:

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

Note that const qualifier on the method. 注意方法上的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;
}

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

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