Reputation: 583
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:
hp::DoFHandler<dim>
, documented here: https://www.dealii.org/current/doxygen/deal.II/classhp_1_1DoFHandler.html.emplace
is because this method constructs a new object, while I want to insert my existing one.Upvotes: 0
Views: 740
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:
emplace
.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