为什么有两个std::allocator::construct函数?

why are there two std::allocator::construct functions?

本文关键字:allocator construct 函数 std 两个 为什么      更新时间:2023-10-16

标准在std::allocator<T>中给出了两个构造函数,用于在下面放置新语法:

void construct( pointer p, const_reference val );  (1)  (until C++11)
template< class U, class... Args >
void construct( U* p, Args&&... args );            (2)  (since C++11)
1) Calls new((void *)p) T(val)
2) Calls ::new((void *)p) U(std::forward<Args>(args)...) 

1)和2)除了将所有参数转发给2)中的构造函数之外,还有什么区别?我们为什么需要1)?

假设我们只有签名2),那么从(不存在的)第一个签名传递参数将导致调用:

::new((void *)p) T(std::forward<const_reference>val) 

应该调用复制构造函数T(val)吗?在这里,我要问的是,多签一个字有什么意义?不同的是一个叫new另一个叫全局函数::new

谢谢你的帮助:-)

答案在您发布的摘录中:一个是c++ 11之前的,一个是c++ 11之后的。construct最好通过完全转发参数来表达,而不是调用复制构造函数,但是完全转发仅在c++ 11中可用,因此我们必须在第一个选项成为现实之前使用第一个选项。