【发布时间】:2019-11-04 16:23:28
【问题描述】:
我有一个从中创建临时对象的类。我可以将 const 引用绑定到这个临时对象,它按预期工作。但是,如果我在这个临时对象上调用一个返回 std::move(*this) 的成员函数,并绑定到这个返回值,它就不会像我预期的那样工作。下面的短代码重现了我的问题并且不言自明。
#include <iostream>
#include <cstdlib>
#include <vector>
class myval {
public:
std::vector<int> i;
myval(int i) : i({i}) {}
myval(const myval& v) = delete;
myval(myval&& v) : i(std::move(v.i)) {}
myval&& addone() && {
i[0]++;
return std::move(*this);
}
};
int main()
{
//Object is moved, works like expected
const auto moved_value = myval{7}.addone();
std::cout << moved_value.i[0] << std::endl;
//Const reference is supposed extend the lifetime of a temporary object
const auto& u = myval{7};
//Prints 7, as expected
std::cout << u.i[0] << std::endl;
const auto& v = myval{7}.addone();
//Why does this print 0?
std::cout << v.i[0] << std::endl;
return 0;
}
编辑:
考虑到对此的解释,是否有可能完成这项工作以使分配“
const auto& v = ....”有效?-
为什么下面的作业有效而我的无效?
const auto& s = std::string("hi")[1]; std::cout << s;
【问题讨论】: