gpt4 book ai didi

templates - 为什么使用可变参数模板参数初始化我的对象需要定义移动构造函数?

转载 作者:行者123 更新时间:2023-12-01 05:00:27 25 4
gpt4 key购买 nike

我想创建一些 typename 的本地对象Type在模板函数中:

template <typename Type, typename... Args>
void create_local(Args... args)
{
Type val(args...);
}

现在,当我不带参数调用此函数时(其中 Type 是一个具有不可复制成员的类):
struct T {
std::mutex m;
};

int main()
{
T t; // OK: No use of move constructor
create_local<T>(); // Error: Requires deleted move constructor!!!
}

(coliru link)

g++(从 4.7.3 到 5.2)编译失败,需要定义 T 的移动构造函数? clang 3.7 编译成功。

此外,如果我 (1) 删除 std::mutex来自 T 的成员,(2) 为 T 声明默认构造函数,以及 (3) 为 T 声明一个已删除的复制构造函数:
struct T {
T() = default;
T(const T&) = delete;
};

int main()
{
T t; // OK: No use of move constructor
create_local<T>(); // OK: No use of move constructor
}

所有版本的 g++ 和 clang 都编译成功。为什么 g++ 不能为任何类型编译 Type与不可复制的成员?

最佳答案

根据 Andrey Zholos 在 this 中的评论错误报告:

I also stumbled onto this bug, and bug 59141 is a duplicate.

It appears the empty parameter pack is expanded as t({}) rather than t().

There is a similar example in 14.5.3p6 that indicates obj should be value-initialized (not copy-constructed), and clang accepts this code.

关于templates - 为什么使用可变参数模板参数初始化我的对象需要定义移动构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33385979/

25 4 0