dPol
dPol

Reputation: 475

c++ std::list::push_back without copying existing instance

I want to append an element to a list without copying any already existing variable.

int some_big_int = 123456789;
struct heavy_struct {
  std::vector<double> vec(some_big_number, 0);
};

std::list<heavy_struct> my_list;
heavy_struc new_item;
my_list.push_back(new_item);

If I understand correctly this is what happens:

Is it possible to just append a new heavy_struct, without copying already existing structure? This copying process is heavy and useless in this case.

Upvotes: 0

Views: 1150

Answers (2)

MichaelCMS
MichaelCMS

Reputation: 4763

You could use a list of pointers to your heavy struct, thus changing the heavy deep copy to a pointer asignment

std::list<heavy_struct*> my_list;

If you don't want to handle memory management either, go with shared pointers instead of raw ones.

Upvotes: 1

Stack Overflow is garbage
Stack Overflow is garbage

Reputation: 248109

Yes:

my_list.emplace_back();

Will pass its arguments (none in this case) to the heavy_struct object being constructed in-place in the list.

Upvotes: 9

Related Questions