我刚刚听完了Scott Meyers关于C++ 0x的软件工程电台播客采访.大多数新功能对我来说都很有意义,我现在对C++ 0x感到兴奋,除了一个.我仍然没有得到移动语义 ......它们究竟是什么?
例如:
Beta_ab&&
Beta::toAB() const {
return move(Beta_ab(1, 1));
}
Run Code Online (Sandbox Code Playgroud) 函数应该返回RValue Reference是否有原因?技巧,技巧,或成语或模式?
MyClass&& func( ... );
Run Code Online (Sandbox Code Playgroud)
我知道一般返回引用的危险,但有时我们会这样做,不管我们(T& T::operator=(T)只是一个惯用的例子).但是怎么样T&& func(...)?我们会从中获得这样的一般场所吗?与仅仅客户端代码相比,当编写库或API代码时,可能会有所不同?
阅读关于从函数返回右值引用的这个答案让我思考,如何id在C++ 0x中编写函数.
基本上,我想做id一个什么都不做的功能,这个功能对程序没有任何可观察的影响.
我的第一次尝试如下:
#include <iostream>
class X
{
public:
X(std::string&& s) : s(std::move(s)) {};
X(const std::string& s) : s(s) {};
std::string s;
~X() { std::cout << "Destroying: " << s << std::endl; }
private:
X(const X&) {};
X(X&&) {};
};
template <class T>
T&& id(T&& x) { return static_cast<T&&>(x); }
int main()
{
auto&& x1 = X("x1");
std::cout << "Line 1" << std::endl;
auto&& x2 = id(X("x2"));
std::cout << "Line 2" << std::endl; …Run Code Online (Sandbox Code Playgroud) 如果你看一下get辅助函数std::tuple,你会注意到以下的重载:
template< std::size_t I, class... Types >
constexpr std::tuple_element_t<I, tuple<Types...> >&&
get( tuple<Types...>&& t );
Run Code Online (Sandbox Code Playgroud)
换句话说,当输入元组本身是右值引用时,它返回一个右值引用.为什么不按值返回,调用move函数体?我的论点如下:get的返回将被绑定到引用,或者绑定到一个值(它可能被绑定到我想的任何东西,但这不应该是一个常见的用例).如果它与一个值绑定,那么移动构造无论如何都会发生.所以你不会因为价值回归而失去一切.如果绑定到引用,则返回右值引用实际上可能不安全.举个例子:
struct Hello {
Hello() {
std::cerr << "Constructed at : " << this << std::endl;
}
~Hello() {
std::cerr << "Destructed at : " << this << std::endl;
}
double m_double;
};
struct foo {
Hello m_hello;
Hello && get() && { return std::move(m_hello); }
};
int main() {
const Hello & x = foo().get();
std::cerr << x.m_double; …Run Code Online (Sandbox Code Playgroud)