加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – std :: swap用于不可复制但可移动的结构

发布时间:2020-12-16 10:26:08 所属栏目:百科 来源:网络整理
导读:根据 C++ reference std :: swap相当于 T c(std::move(a)); a=std::move(b); b=std::move(c); 这应该允许交换两个不可复制但可移动的物体.所以我不明白为什么 #includeutilitystruct Foo { Foo() = delete; Foo(int) {}; Foo(Foo ) = delete; Foo(Foo ) {};
根据 C++ reference std :: swap相当于

T c(std::move(a)); a=std::move(b); b=std::move(c);

这应该允许交换两个不可复制但可移动的物体.所以我不明白为什么

#include<utility>

struct Foo {
  Foo() = delete;
  Foo(int) {};
  Foo(Foo &) = delete;
  Foo(Foo &&) {};
  ~Foo() {};
};

int main() {
  Foo a(1),b(2);
  std::swap(a,b);
}

被编译器拒绝

In file included from /usr/include/c++/4.8/bits/stl_pair.h:59:0,from /usr/include/c++/4.8/utility:70,from swap.cpp:1:
/usr/include/c++/4.8/bits/move.h: In instantiation of ‘void std::swap(_Tp&,_Tp&) [with _Tp = Foo]’:
swap.cpp:13:16:   required from here
/usr/include/c++/4.8/bits/move.h:176:11: error: use of deleted function ‘Foo& Foo::operator=(const Foo&)’
       __a = _GLIBCXX_MOVE(__b);
           ^
swap.cpp:3:8: note: ‘Foo& Foo::operator=(const Foo&)’ is implicitly declared as deleted because ‘Foo’ declares a move constructor or move assignment operator
 struct Foo {
        ^
In file included from /usr/include/c++/4.8/bits/stl_pair.h:59:0,from swap.cpp:1:
/usr/include/c++/4.8/bits/move.h:177:11: error: use of deleted function ‘Foo& Foo::operator=(const Foo&)’
       __b = _GLIBCXX_MOVE(__tmp);

注意:这是GCC 4.8和4.9,但clang也抱怨.

解决方法

你声明了一个移动构造函数.但是,您需要std :: swap的移动赋值运算符.您应该添加以下两个运算符:

auto operator=(const Foo& rhs) & -> Foo& = delete;
auto operator=(Foo&& rhs) & noexcept -> Foo&
{
    // ...
    return *this;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读