Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

pointers

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 i.e.:

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

what is the proper syntax for this? How do I get the value rather than the pointer?

like image 486
James Allan Avatar asked Dec 06 '22 14:12

James Allan


2 Answers

someType getX() {return *x;}

Note though that this returns x by value, i.e. 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).

like image 150
Péter Török Avatar answered Dec 15 '22 00:12

Péter Török


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.

like image 30
Fred Foo Avatar answered Dec 14 '22 22:12

Fred Foo