【发布时间】:2014-09-22 01:13:47
【问题描述】:
我正在尝试精简移动语义,并编写了这个示例。我想将临时 r 值移动到堆栈上的对象中。
class MemoryPage
{
public:
size_t size;
MemoryPage():size(0){
}
MemoryPage& operator= (MemoryPage&& mp_){
std::cout << "2" <<std::endl;
size = mp_.size;
return *this;
}
};
MemoryPage getMemPage()
{
MemoryPage mp;
mp.size = 4;
return mp;
}
int main() {
MemoryPage mp;
mp = getMemPage();
std::cout << mp.size;
return 0;
}
我在 getMemPage() 返回时收到此错误:
error: use of deleted function 'constexpr MemoryPage::MemoryPage(const MemoryPage&)'
【问题讨论】:
-
MemoryPage的复制(和移动)构造函数被隐式定义为已删除/未声明,因为您提供了自定义移动赋值运算符。返回一个对象,如return mp;需要一个复制或移动构造函数(即使它没有被调用)。确保遵循五法则。 -
顺便说一下,错误信息应该告诉你 DyP 做了什么。不确定您是否出于问题的目的对其进行了裁剪。
note: 'constexpr MemoryPage::MemoryPage(const MemoryPage&)' is implicitly declared as deleted because 'MemoryPage' declares a move constructor or move assignment operator
标签: c++ c++11 move-semantics