gpt4 book ai didi

c++ - 具有已删除特殊成员函数的自定义类型 std::variant 的赋值运算符?

转载 作者:行者123 更新时间:2023-12-04 11:29:19 27 4
gpt4 key购买 nike

考虑:

#include <variant>

struct A {
A() = default;
A(A&&) = delete;
};

struct B {
B() = delete;
B(A&&) {};
};

int main() {
std::variant<A, B> v{};
v = A{};
}
MSVC 接受了, while GCC and Clang rejected it with the same error message :
opt/compiler-explorer/gcc-snapshot/lib/gcc/x86_64-linux-gnu/12.0.0/../../../../include/c++/12.0.0/variant:1465:3: error: call to deleted member function 'operator='
operator=(variant(std::forward<_Tp>(__rhs)));
^~~~~~~~~
<source>:15:5: note: in instantiation of function template specialization 'std::variant<A, B>::operator=<A>' requested here
v = A{};
^
我应该信任哪个编译器?

最佳答案

编辑
最初,没有 language-lawyer标签,这就是我使用 cppreference 进行分析的原因。但是,查看最新草案( relevant section ),我没有看到任何会使它无效的内容。

我相信 MSVC 是不正确的。根据documentation :

  1. Converting assignment.
  • Determines the alternative type T_j that would be selected by overload resolution for the expression F(std::forward<T>(t)) if there was an overload of imaginary function F(T_i) for every T_i from Types... in scope at the same time, except that:

    • An overload F(T_i) is only considered if the declaration T_i x[] = { std::forward<T>(t) }; is valid for some invented variable x;

一些虚函数具有转发引用参数并用 A{} 调用它参数, A x[] = { std::forward<T>(t) }; B x[] = { std::forward<T>(t) }; 时无效是。因此, T_j应解析为 B .现场演示: https://godbolt.org/z/fM67e7oGj .
然后:
  • If *this already holds a T_j...

这不适用,因为 v不持有 B .
下一个:
  • Otherwise, if std::is_nothrow_constructible_v<T_j, T> || !std::is_nothrow_move_constructible_v<T_j> is true...

这也不适用,因为这个表达式是 false ;现场演示: https://godbolt.org/z/x674rnbcj (并且,MSVC 同意: https://godbolt.org/z/5Techn8jG )。
最后:
  • Otherwise, equivalent to this->operator=(variant(std::forward<T>(t))).

但是,此调用无法使用 MSVC 编译: https://godbolt.org/z/cWr4f6EhK .

关于c++ - 具有已删除特殊成员函数的自定义类型 std::variant 的赋值运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68998153/

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