c++ - use a pointer in operation with non pointer -


i'm quite new c++ , don't understand pointers yet.

this ok, have 2 non pointer object:

vec2d a(0, 0), b(10, 10); vec2d c = a-b; 

but if 1 pointer?

vec2d::minus(vec2d b) {     vec2d = vec2d(this->x(), this->y());     return that-b; } 

so question: how can use pointer this - operation b?

and also, don't understand how many object constructed in methods , how can optimize memory consumption passing reference..

if got question correctly.. "this pointer, how can operate on , other pointers using methods require non-pointer?"

you use dereference operator * example:

vec2d = *this; 

to answer second question:

  • an object created pass parameter of minus
  • an object created vec2d(this->x(), this->y()) (but erased away temp optimizing compiler)
  • an object created on stack (that)
  • depending on how implemented them, , on how compiler is, may create object in copy constructor/operator=
  • an object (or more) may created operator- in that-b
  • an object created returned (only one, not two, return value optimization done compliers afaik)

how can optimize it? use references...

vec2d vec2d::minus(const vec2d& b) {    return that-*this; } 

and implement operator- on vec2d use refereces too... in general, pass parameters (const) references.

obviously, cannot same return value (try, compiler complain..); there techniques these (especially in cg/games, vectors, have seen object pools used lot; returning reference/pointer possible, rather advanced stuff)


Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -