gpt4 book ai didi

c++ - C++17 中的显式默认构造函数

转载 作者:IT老高 更新时间:2023-10-28 22:04:20 25 4
gpt4 key购买 nike

在 C++17 中,标准库中的空标记类型现在具有标记为 explicit 的默认构造函数,并且也是 = default。例如,std::piecewise_construct_t现在定义为

struct piecewise_construct_t { explicit piecewise_construct_t() = default; };

我的问题很简单,从 C++14 发生这种变化的原因是什么?显式默认的显式默认构造函数 (!) 对空类意味着什么?

(为了避免被标记为骗子:this question 从 2010 年开始询问显式默认构造函数的目的,但那是 C++11 之前的版本,而且是很久以前的事了,所以事情可能已经发生了变化。This question是较新的,但答案似乎表明无论是否存在默认构造函数都会执行聚合初始化,所以我很好奇最新标准中这种变化的原因。)

最佳答案

库更改的理由在 LWG 2510 "Tag types should not be DefaultConstructible" :

std::experimental::optional, for certain reasons, specifies its nullopt type to not be DefaultConstructible. It doesn't do so for its tag type in_place_t and neither does the standard proper for any of its tag types. That turns out to be very unfortunate, consider the following:

#include <memory>
#include <array>

void f(std::array<int, 1>, int) {} // #1
void f(std::allocator_arg_t, int) {} // #2

int main()
{
f({}, 666); // #3
}

The call at #3 is ambiguous. What's even worse is that if the overload #1 is removed, the call works just fine. The whole point of a tag type is that it either needs to mentioned in a call or it needs to be a forwarded argument, so being able to construct a tag type like that makes no sense.

LWG 问题与 CWG 1518 "Explicit default constructors and copy-list-initialization" 并存。 ,具有有用的背景。

关于c++ - C++17 中的显式默认构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44170174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com