简体   繁体   中英

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*. So (depending on what someType really is) you may prefer returning a reference instead:

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. 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 const &getX() const { return *x; }

Note that const qualifier on the method.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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