STL containers with reference to objects

Vendetta picture Vendetta · Oct 10, 2011 · Viewed 23.1k times · Source

I know STL containers copy the objects. So say I have a

list<SampleClass> l;

each time when I do

SampleClass t(...);
l.push_back(t);

a copy of t will be made. If SampleClass is large, then it will be very costly.

But if I declare l as a container of references,

list<SampleClass&> l;

When I do

l.push_back(t);

Will it avoid copying the objects?

Answer

Kerrek SB picture Kerrek SB · Oct 10, 2011

If you know what you're doing, you can make a vector of references using std::reference_wrapper:

#include <functional>
#include <vector>

int main()
{
  std::vector<std::reference_wrapper<int>> iv;

  int a = 12;
  iv.push_back(a);  // or std::ref(a)

  // now iv = { 12 };

  a = 13;

  // now iv = { 13 };
}

Note of course that any of this will come crashing down on you if any of the referred-to variables go out of scope while you're still holding references to them.