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;}总结
以上是内存溢出为你收集整理的c – std :: swap用于不可复制但可移动的结构全部内容,希望文章能够帮你解决c – std :: swap用于不可复制但可移动的结构所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)