0
struct Solution {
  double power_peak;
  valarray<int> assignment;
};
list<Solution> list;
list.pop_back();

list<Solutions *> list2;
list2.pop_back();
function(list2);

Hello i still don't understand how these containers work with respect to their content. Assume they get filled before. When i call pop_back on the first list. i assume everything gets destroyed (including the int's in the Valarray) When i call pop_back on the second list. the content will still live.

When i do a function call. Does the list behave like a pointer to an array? so only the pointer is copied but they still point to the same content.

Is this correct?

Would a vector or valarray behave other in terms of copying?

ildjarn
  • 62,044
  • 9
  • 127
  • 211
user3613886
  • 231
  • 3
  • 7

2 Answers2

2

When you pop_back() an element from a list, or any of the sequence containers that support pop_back(), it will always result in destruction of the last element. The difference is that in the second case the list contains pointers, and the destructor of a pointer is a NOP. That's why the content pointed to by the pointer still lives on.

This is also the reason sticking raw pointers into containers is frowned upon. It means you'll have to manage memory manually, which can be error prone. Using a list<unique_ptr<T>>, or some other smart pointer, means you no longer need manual memory management.

When i do a function call. Does the list behave like a pointer to an array? so only the pointer is copied but they still point to the same content.

It depends on how the function is defined. If it is one of the following:

return_type function(list_type&);
return_type function(list_type const&);

no copy will be made. A reference to the list will be passed to the function. On the other hand, if it is defined as:

return_type function(list_type);

then the list will be copied.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

When i do a function call. Does the list behave like a pointer to an array?

No, it behaves like a list of pointers to objects. Just what it is.

so only the pointer is copied but they still point to the same content.

Correct.

i assume everything gets destroyed (including the int's in the Valarray)

As you could have read here, pop_back destroys the last element in a sequence container, and if its a class, then self-evidently also its members.

When i call pop_back on the second list. the content will still live.

As the pointers are not smart, they don't own the objects they point at. So if you destroy the pointer, the object is not affected.

Columbo
  • 60,038
  • 8
  • 155
  • 203