pointers - Using * operator when dealing with abstract data types in C++ -


while doing project dealing graph theory, used objects such:

class node{ vector<node> nodelist; }; node n = new node(); node = new node(); n.nodelist.push_back(a); 

after creating 20 nodes each average of 3 connections other nodes, program hang.

to fix that, changed object declarations to

class node{ vector<node*> nodelist; }; node* n = new node(); node* = new node(); n.nodelist.push_back(a); 

and program ran through 50 nodes 10 connections instantly.

the second example ran faster because adding pointers lists, opposed actual nodes, right?

but c++ documentation says new keyword returns pointer created object. why entire object put vector in first example opposed pointer?

is there reason standard in c++ copy entire object data structure instead of pointer?

edit: apologize, right first example should not compile. don't have first example anymore on drive anymore, , can't remember how was. sorry.

is there reason standard in c++ copy entire object data structure instead of pointer?

traditionally, standard library container classes work value semantics opposed reference semantics.
values semantics means containers create internal copies of elements , return copies of elements, while reference semantics mean containers contain references objects elements. obvious way achieve using pointers container elements. standard library uses values semantics because:

  • implementing value semantics simpler.
  • reference semantics can error prone. 1 needs deal actual object being valid time during life cycle of container element.
  • if 1 needs explicit reference semantics can choose using pointers container elements.

the first code example show cannot work is. use of new mandates pointer. because pointer needs point object on freestore. object non pointer data type cannot that. probably, have in code assigning derived class object base class object, resulting in object slicing.


if need reference semantics idea use smart pointer container element raw pointer using now.


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 -