Baz
Baz

Reputation: 13145

Adding Foo& to a std::vector

I'm writing a mock for the following interface:

virtual void store(const Foo& container) = 0;

So in the implementation I wish to save whats sent in each time in a vector, something like this:

virtual void store(const Foo& container)
{
    _storedContainers.push_back(container);
}

What type should _storedContainers have, where _storedContainers is a member of the mock?

Upvotes: 1

Views: 121

Answers (2)

hmjd
hmjd

Reputation: 122001

If you want to store a const reference to Foo then use boost::cref() and boost::reference_wrapper as plain references are not assignable and cannot be stored in a vector:

std::vector<boost::reference_wrapper<const Foo> > _storedContainers;

virtual void store(const Foo& container)
{
    _storedContainers.push_back(boost::cref(container));
}

However, the elements in _storedContainers have a potential to become dangling references if the objects passed to store() are destructed while still required. Online demo at http://codepad.org/VOokOm6i.

Example (using equivalent c++11 versions of cref() and reference_wrapper) http://ideone.com/0vVv8w .

Upvotes: 4

Joseph Mansfield
Joseph Mansfield

Reputation: 110738

The expression container has type const Foo, so you're trying to push a Foo object into _storedContainers. That means _storedContainers should probably be a container of Foos, such as std::vector<Foo>.

Upvotes: 2

Related Questions