rahman
rahman

Reputation: 4948

C++ , passing optimal argument and return type for large data

I have a number of sender and receiver functions that pass data to each other hierarchically:

class singleton
{
 TYPE3 var; //data populated from a hierarchy
 void Receive(TYPE3 a){ var = a;}
}

class C
{
  void Receiver_from_B(TYPE2 a);
  TYPE3 intermediate_value;
  make_TYPE3(&intermediate_value){....;}//pseudo
  TYPE3 Sender(){ return intermediate_value; }  //finally sends it to a noncopyable class object
};

class B
{
  void Receiver_from_A(TYPE1 a);
  TYPE2 intermediate_value;
  make_TYPE2(&intermediate_value){....;}//pseudo
  TYPE2 Sender_to_A(){ return intermediate_value; } 
};

class A
{
  TYPE_I a;
  TYPE_II b;
  void Receiver_from_down_the-tree(TYPE_I a_){ a = a_};
  void Receiver_from_down_the-tree_(TYPE_II b_){ b = b_};
  TYPE1 intermediate_value;
  void make_TYPE1(&intermediate_value, a , b) {.....;}//pseudo
  TYPE1 Sender_to_B(){ return intermediate_value;} 
};

the amount of data accumulated from such a tree is relatively large and I would like to skip copying data from sender to receiver.

I guess I need a combination of const and reference for the types of arguments and return values. I appreciate if you kindly suggest me the best type for arguments and return values.

Hope i explained the problem well. thanks

Upvotes: 0

Views: 286

Answers (1)

masoud
masoud

Reputation: 56479

A standard way to pass an object to a method/function to avoid heavy copying is using a reference to a const:

void my_method(const BigObject & big)
{
  // do something with big
}

The & makes it a reference and avoids deep-copy of object. The const grantees no the further modifications.

You have many other ways in C++ to avoid copying, such as move-constructor patterns, passing pointers (I suggest wrap them in std::shared_ptr)... . It depends on your design.

Upvotes: 1

Related Questions