放置 new 和 uninitialized_fill() 的行为

Behavior of placement new and uninitialized_fill()

本文关键字:fill new uninitialized 放置      更新时间:2023-10-16

我看到以下uninitialized_fill实现中使用了新放置。 有谁知道放置 new 的底层实现或在 g++ 中在哪里可以找到它?

我假设运算符在调用复制构造函数后获取指向对象应放置位置的指针以及对Value(value)哪个是右值的引用?

谢谢

template<class ForwardIt, class T>
void uninitialized_fill(ForwardIt first, ForwardIt last, const T& value)
{
typedef typename std::iterator_traits<ForwardIt>::value_type Value;
ForwardIt current = first;
try {
for (; current != last; ++current) {
::new (static_cast<void*>(std::addressof(*current))) Value(value);
}
}  catch (...) {
for (; first != current; ++first) {
first->~Value();
}
throw;
}
}
placement-new

指定地址构造一个对象,是的。

在表达式::new (static_cast<void*>(std::addressof(*current))) Value(value);中,*current返回对指定迭代器范围内元素的引用,然后将该元素的地址转换为void*并传递给placement-new,然后 在该地址构造一个新的Value类型(迭代器的value_type(,将输入value传递给该类型的复制构造函数。

此代码中没有使用右值。Value(value)不是传递给placement-new的右值。Valueplacement-new构造的类型,value作为Value's构造函数的输入。 如果Value被命名为更像ValueTypeTypeToConstruct的东西,也许代码会更有意义。

new (address) Type(params)表达式类似于new Type(params)表达式,只是使用额外的address参数作为输入。