【发布时间】:2019-03-28 17:24:24
【问题描述】:
C++17 添加了std::destroy_at,但没有对应的std::construct_at。这是为什么?就不能这么简单的实现吗?
template <typename T, typename... Args>
T* construct_at(void* addr, Args&&... args) {
return new (addr) T(std::forward<Args>(args)...);
}
这可以避免那种不完全自然的放置新语法:
auto ptr = construct_at<int>(buf, 1); // instead of 'auto ptr = new (buf) int(1);'
std::cout << *ptr;
std::destroy_at(ptr);
【问题讨论】:
-
在我的无知中,我很想知道
destroy_at有什么好处;) -
@user463035818 - 如何对
std::string对象进行伪析构函数调用?不要误会,我不是说不可能,我只是想让你形象地想象所需的表达方式。 -
@StoryTeller 让我再天真一点,但
auto s = new string{"test"}; s->~string();有什么问题?我错过了问题的前提吗?我想在复合模板类型上调用伪析构函数将是语法噩梦,但typedef就足够了。destroy_at是否解决了与make_*包装器相同的问题? -
@luk32 没有称为
~string()的析构函数。您必须调用s->~basic_string();。std::destroy_at(s);没问题。 -
@luk32 因为你使用了
using namespace std;,所以它起作用了。否则,你不能写成s->~std::string();,或者,至少,编译器不会编译它(参见,例如,这里:stackoverflow.com/q/24593942/580083 的相关讨论)。这就是std::destroy_at提供帮助的地方。
标签: c++ c++17 placement-new