Is the allocator.construct loop equal to std :: uninitialized_copy?

In this context, T is a specific type, and allocator is a distributor object for this type. By default, this is std::allocator<T> , but this is optional.

I have a piece of memory obtained by allocator.allocate(n) . I also have a container of con objects of T (let's say a std::vector<T> ). I want to initialize this piece of memory with T objects.

The location of the memory block is stored in T* data .

Are these two code examples the same?

 #include <memory> // example 1 std::uninitialized_copy(con.begin(), con.end(), data) // example 2 std::vector<T>::const_iterator in = con.begin(); for (T* out = data; in != con.end(); ++out, ++in) { allocator.construct(out, *in); } 

And for these two?

 #include <memory> T val = T(); // could be any T value // example 3 std::uninitialized_fill(data, data + n, val) // example 4 for (T* out = data; out != (data + n); ++out) { allocator.construct(out, val); } 
+7
source share
1 answer

According to this explanation They should do the same thing as saying that allocator::construct should build an object, and std::uninitialized... also creates objects, But I don’t know what the standard says and what freedom you have when you implement your own allocator::construct .

EDIT: Well, the C ++ 03 standard in section 20.1.5 Β§2 of table 32 that construct(p,t) should have the same effect as new ((void*)p) T(t) (for any standard compatible distributor, not just std::allocator ). And in clause 20.4.4.1 Β§ 1, that uninitialized_copy should have the same effect as

 for (; first != last; ++result, ++first) new (static_cast<void*>(&*result)) typename iterator_traits<ForwardIterator>::value_type(*first); 

and in 20.4.4.2 Β§ 1, that uninitialized_fill has the effect

 for (; first != last; ++first) new (static_cast<void*>(&*first)) typename iterator_traits<ForwardIterator>::value_type(x); 

Therefore, I think this leaves no room for them to behave differently. Therefore, to answer your question: yes, it is.

+6
source

All Articles