移动构造函数删除与未生成的

发布于 2025-02-05 19:13:21 字数 549 浏览 0 评论 0原文

考虑此代码:

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

如果我正确,则编译器将自动生成默认解构器。但是,对于运动构造函数,它不会这样做。

但是,以上代码允许我这样做:

int main()
{
    A a1;
    A a2 = std::move(a1);
    return 0;
}

我的问题是:为什么?

如果我修改struct a的定义,则如下:

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

然后a2 = std :: move(a1)不编译,这是有道理的。

那么,删除构造函数和不生成它有什么区别?还是编译器会生成移动构造函数?

Consider this code:

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

If I'm correct, the compiler will automatically generated a default deconstructor. However, it will not do so for the movement constructor.

However, the above code allows me to do this:

int main()
{
    A a1;
    A a2 = std::move(a1);
    return 0;
}

My question is: why?

If I modify the definition of struct A as follows:

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

then A a2 = std::move(a1) does not compile, which makes sense.

So, what's the difference between deleting a constructor and not generating it? Or does the compiler generate the move constructor anyway?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文