gpt4 book ai didi

c++ - 是否可以初始化不可复制类型的成员变量(或基类)?

转载 作者:行者123 更新时间:2023-12-01 12:07:24 24 4
gpt4 key购买 nike

考虑 following code :

struct S
{
S() = default;
S(S const&) = delete;
// S(S&&) = delete; // <--- uncomment for a mind-blowing effect:
// MSVC starts compiling EVERY case O_O
};

S foo() { return {}; }

struct X : S
{
// X() : S(foo()) {} // <----- all compilers fail here
};

struct Y
{
S s;
Y() : s(foo()) {} // <----- only MSVC fails here
};

struct Z
{
S s = {}; // ... and yet this is fine with every compiler
Z() {}
};

//S s1(foo()); // <-- only MSVC fails here
//S s2 = foo(); // <-- only MSVC fails here
问题:
  • 看起来没有办法用纯右值初始化不可复制的基类——这是正确的吗?看起来标准有缺陷(或者我尝试过的所有编译器都不符合标准)
  • MSVC 无法初始化成员变量——这是否意味着它不合规?有没有办法解决这个问题?
  • 为什么要添加 S(S&&) = delete;导致 MSVC 编译 案件?
  • 最佳答案

    所以,我想我找到了标准的相关部分,我认为编译器在 X 方面有错误。 . (所有链接都指向标准草案,所以很可能它在 C++17 中有所不同,我稍后会检查。但是 gcc10 和 clang10 也失败了 -std=c++20 ,所以这并不重要)。
    关于基类的初始化(重点是我的):class.base.init/7

    The expression-list or braced-init-list in a mem-initializer is used to initialize the designated subobject (or, in the case of a delegating constructor, the complete class object) according to the initialization rules of [dcl.init] for direct-initialization.


    我想这告诉我们, X() : S(foo()) {}不应与 S s = foo() 不同,但让我们看看 dcl.init/17.6.1

    If the initializer expression is a prvalue and the cv-unqualified version of the source type is the same class as the class of the destination, the initializer expression is used to initialize the destination object. [Example: T x = T(T(T())); calls the T default constructor to initialize x. — end example]


    这对我来说意味着 X() : S(foo()) {}应该调用默认构造函数。我也测试过(完全符合例子) X() : S(S()) {}这在 clang 和 g++ 上也失败了。所以在我看来,编译器有缺陷。

    关于c++ - 是否可以初始化不可复制类型的成员变量(或基类)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62921397/

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