landigio
landigio

Reputation: 583

Insert object into std::deque that does not allow copy constructor

Im using a std::deque to hold some objects, and it works great as long as I can add new elements with deque.emplace_front. However, now I want to replace an element of the deque with an already existing object. When I try to do the following

auto it = mydeque.begin();
++it;
mydeque.insert(it, object);
mydeque.erase(it);

I get an error because my object does not allow copying. How can I get around this issue?

EDIT:

Upvotes: 0

Views: 740

Answers (1)

eerorika
eerorika

Reputation: 238401

The reason I can not use emplace is because this method constructs a new object, while I want to insert my existing one.

The element of a container is always a distinct object. If you insert an existing object, then the object must be copied or moved.

I get an error because my object does not allow copying. How can I get around this issue?

If the type allows moving, then you can use std::move. Othewise, you cannot insert a pre-existing object into the container.


Some XY-solutions for non-movable types:

  • Avoid the problem by creating the object within the container initially, using emplace.
  • Use indirection. Instead of storing hp::DoFHandler<dim> objects in the container, rather store something that refers to such object like a pointer for example. This approach has the drawback of having to ensure that the lifetime of the pointer doesn't exceed the lifetime of the pointed object. Using shared ownership (std::shared_ptr) is an easy way to make sure of that, but it has other potential drawbacks.

Upvotes: 4

Related Questions