Adrian
Adrian

Reputation: 10911

Is there a way to prevent an element in a vector to be destructed?

I have a vector of some type, and I want to destruct the elements in some random order without moving the other elements in the vector. At a later time I may inplace new in those destructed holes (or not). When I destroy the vector, I don't want to call the destructor for an element that is already destructed, so is it possible to do so and if so how?

I've been thinking about using char[sizeof(T)] as the vector element type, but I see that std::align_of and std::aligned_storage are only suitable for POD storage. So, how do I ensure that this will work for non POD types?

Is there some other way of doing this?

I'm working on MSVS2010 and may be upgrading soon to 2013.

Upvotes: 2

Views: 205

Answers (3)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

std::vector<boost::optional<T>> v;
...
v[i] = boost::none; // destroy an object

If you can't use boost, then implementing your own optional class is fairly trivial. Just use std::aligned_storage<T> along with a bool indicating whether the object is valid or not.

Upvotes: 6

Sinn
Sinn

Reputation: 274

Use an array?

Type * a = new Type[BASE_SIZE];

when inserting, if you need to extend use this

Type * tmp = new Type[BIGGER_SIZE];
std::copy(a, a + a.length, temp);
delete[] a;
a = tmp;

when delete just replace NULL or w/e, and replace it with a deletion mark, or w/e.

Upvotes: -1

Kindread
Kindread

Reputation: 966

If I understand your problem correctly, you can solve this by using a vector of shared_ptrs. When you want to get rid of an element, assign it to a nullptr shared_ptr.

Upvotes: 0

Related Questions