在此背景下T
是某种类型并且allocator
是该类型的分配器对象。默认情况下是std::allocator<T>
但这不一定是真的。
我获得了一块内存allocator.allocate(n)
。我也有一个容器con
of T
对象(例如,一个std::vector<T>
)。我想用以下命令初始化该内存块T
对象。
内存块的位置存储在T* data
.
这两个代码示例总是相同吗?
#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);
}
根据这个解释 http://www.cplusplus.com/reference/std/memory/他们也应该这样做,因为allocator::construct
据说构造了该对象并且std::uninitialized...
还构造对象。但我不知道标准到底说了什么以及在实施自己的标准时您有什么自由allocator::construct
.
EDIT:好的,C++03 标准在第 20.1.5 §2 表 32 中规定,construct(p,t)
应该有同样的效果new ((void*)p) T(t)
(对于任何符合标准的分配器,不仅std::allocator
)。在 20.4.4.1 §1 中,uninitialized_copy
应该有同样的效果
for (; first != last; ++result, ++first)
new (static_cast<void*>(&*result))
typename iterator_traits<ForwardIterator>::value_type(*first);
在 20.4.4.2 §1 中,uninitialized_fill
有效果
for (; first != last; ++first)
new (static_cast<void*>(&*first))
typename iterator_traits<ForwardIterator>::value_type(x);
所以我认为这不会给他们留下任何不同行为的空间。所以回答你的问题:是的,确实如此。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)