Friday, 15 January 2010

c++ - Can I return a pointer in a reference return type? -



c++ - Can I return a pointer in a reference return type? -

i'm coding templated class, , have this:

template<class t> class ... { t x, y, z; t& operator[](int index) { switch (index) { case 0: homecoming this->x; break; case 1: homecoming this->y; break; case 2: homecoming this->z; break; } } }

i've considered changing this:

t& operator[](int index) { homecoming *(&this->x + index); }

however, i'm returning in original code actual variable (aka reference), , what's intended (myobj[1] = 123; /*changes actual object*/), while in sec example, i'm returning value of pointer.

i alter return (&this->x + index) homecoming pointer, both cases compile (visual studio 2013), , don't know choose, because i've never done this.

so, question: there way can utilize pointer arithmetic dynamically homecoming right variable, or need switch?

the pointer arithmetic approach causes undefined behavior. compiler may add together padding between 3 variables, example, create pointer arithmetic approach malfunction. may work type t , might fail another.

you either need utilize switch approach, or alter members t x, y, z; t coords[3];, allow utilize index approach defined , right behavior.

regarding topic of question, yes, safe convert pointer reference reference. homecoming reference pointed-to object. reason it's not approach in case because pointer arithmetic results in undefined behavior.

c++ templates pointers

No comments:

Post a Comment