本文介绍了allocator.construct 循环是否等于 std::uninitialized_copy?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这种情况下,T 是某种类型,而 allocator 是该类型的分配器对象.默认情况下它是 std::allocator 但这不一定是真的.

In this context T is a certain type and allocator is an allocator object for that type. By default it is std::allocator<T> but this is not necessarily true.

我有一块由 allocator.allocate(n) 获取的内存.我还有一个 T 对象的容器 con(比如,一个 std::vector).我想用 T 对象初始化那块内存.

I have a chunk of memory acquired by allocator.allocate(n). I also have a container con of T objects (say, a std::vector<T>). I want to initialize that chunk of memory with the T object(s).

内存块的位置存储在T*数据中.

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

这两个代码示例总是相同的吗?

Are these two code examples always identical?

#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);
}

这两个呢?

#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);
}

推荐答案

根据这个解释 他们应该做同样的事情,因为 allocator::construct 被称为构造对象,而 std::uninitialized... 也构造对象.但我不知道,在实现自己的 allocator::construct 时,标准到底说了些什么,你有什么自由.

According to this explanations They should do the same, as allocator::construct is said to construct the object and std::uninitialized... also constructs the objects. But I do not know, what exactly the standard says and what freedom you have, when implementing your own allocator::construct.

好的,C++03 标准在第 20.1.5 节 §2 表 32 中指出,construct(p,t) 应该具有相同的效果作为 new ((void*)p) T(t) (对于任何符合标准的分配器,不仅仅是 std::allocator).而在 20.4.4.1 §1 中,uninitialized_copy 应该与

Ok, the C++03 standard states in section 20.1.5 §2 table 32, that construct(p,t) should have the same effect as new ((void*)p) T(t) (for any standard compliant allocator, not only std::allocator). And in 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);

在 20.4.4.2 §1 中,uninitialized_fill 的作用是

and in 20.4.4.2 §1, that uninitialized_fill has an effect of

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

所以我认为这不会给他们留下任何表现不同的空间.所以回答你的问题:是的,确实如此.

So I think that doesn't leave any room for them to behave differently. So to answer your question: yes, it does.

这篇关于allocator.construct 循环是否等于 std::uninitialized_copy?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 07:10