Vectors of references to objects

You can use std::reference_wrapper instead in C++11:

std::reference_wrapper is a class template that wraps a reference in a copyable, assignable object. It is frequently used as a mechanism to store references inside standard containers (like std::vector) which cannot normally hold references.

Example:

#include <functional>
#include <vector>
#include <iostream>

int main(int argc, char *argv[])
{

  int a = 5;
  int b = 6;
  std::vector<std::reference_wrapper<const int>> v;
  v.push_back(a);
  v.push_back(b);

  for (const auto& vi: v)
  {
    std::cout << vi << std::endl;
  }
  return 0;
}

https://en.cppreference.com/w/cpp/utility/functional/reference_wrapper


You can't do it. Use pointers.

The Boost library provides PTR_VECTOR which is a better solution than:

vector<T*> foo;

You can't have vector of references, as a reference is not copyable assignable and all STL containers are supposed to store copyable assignable items.

But you can make the container to hold pointers. Like this:

vector< Agents* > seenAgents;

This is a little dangerous. You need to be sure that these pointers will remain valid. I mean - if someone deletes an object, pointed by a pointer in this container, the pointer becomes invalid. You need to be sure that this will not happen, because you can't check it (you can't check for NULL, because a pointer will not become NULL, if someone deletes the pointed object).

The best solution here (provided by container with pointers) would be to use some smart pointers - some with reference count, for example; they will guarantee you that the object will exist and that the pointer is valid. And in case that the object, pointed by the smart pointer, is destroyed, you can check it for NULL.

Tags:

C++