我想排序實現移動賦值運算符的類的向量。此代碼在Microsoft和Intel C++中正常工作。在GCC 4.8.1中,複製構造函數被刪除,似乎導致問題。GCC C++ 11刪除移動賦值類的拷貝賦值崩潰std :: sort?
c:\mingw\lib\gcc\mingw32\4.8.1\include\c++\bits\stl_algo.h:2164:11: error: use of deleted function 'constexpr MoveOnly::MoveOnly(const MoveOnly&)'
__val = _GLIBCXX_MOVE(*__i);
^
test.cpp:6:11: note: 'constexpr MoveOnly::MoveOnly(const MoveOnly&)' is implicitly declared as deleted because 'MoveOnly' declares a move constructor or move assignment operator
,並與馬修M.幫助,this page解釋了爲什麼拷貝構造函數被刪除。
#include <vector>
#include <algorithm>
#include <iostream>
#include <type_traits>
class MoveOnly {
public:
int data;
MoveOnly& operator = (const MoveOnly && rhs) {
data = rhs.data;
return *this;
}
MoveOnly& operator = (const MoveOnly & rhs) {
data = rhs.data;
return *this;
}
bool operator < (const MoveOnly& j) const {
return data<j.data;
}
};
int main() {
std::cout<<"Is move_assignable:"<<std::is_move_assignable<MoveOnly>::value<<std::endl;
std::cout<<"Is copy_assignable:"<<std::is_copy_assignable<MoveOnly>::value<<std::endl;
std::vector<MoveOnly> vMoveOnly;
//std::sort(vMoveOnly.begin(), vMoveOnly.end());
return 0;
}
這不是崩潰,這是一個編譯錯誤。 –
您是否嘗試添加複製構造函數? –
@Kiril權利不會崩潰。對不起我的英語不好。 – user1662078