美文网首页白话C++编程成长、财富
Tips of C++11 std::move与完美转发std:

Tips of C++11 std::move与完美转发std:

作者: 小宁静致远 | 来源:发表于2019-03-22 08:35 被阅读0次

C++11 std::move 和 std::forward 用法:

当知道类型时, 用 std::move得到一个右值.
当需要推导类型时, 用 std::forward来完美转发, 则可能得到一个左值或右值.
对已知类型使用完美转发std::forward 可能会阻止编译器的优化, 并有可能引起不必要的麻烦或者不期望的结果.
当使用std::move时, 尽量在函数或者逻辑的最后使用它, 避免出现空值,或者得不到自己期望的值.

如 std::move


#include <iostream>
#include <utility>
#include <vector>
#include <string>
 
int main()
{
    std::string str = "Hello";
    std::vector<std::string> v;
 
    // uses the push_back(const T&) overload, which means 
    // we'll incur the cost of copying str
    v.push_back(str);
    std::cout << "After copy, str is \"" << str << "\"\n";
 
    // uses the rvalue reference push_back(T&&) overload, 
    // which means no strings will be copied; instead, the contents
    // of str will be moved into the vector.  This is less
    // expensive, but also means str might now be empty.
    v.push_back(std::move(str));
    std::cout << "After move, str is \"" << str << "\"\n";
 
    std::cout << "The contents of the vector are \"" << v[0]
                                         << "\", \"" << v[1] << "\"\n";
}

Possible output:(可能结果)


After copy, str is "Hello"
After move, str is ""
The contents of the vector are "Hello", "Hello"

又如: std::forward


#include <iostream>
#include <memory>
#include <utility>
 
struct A {
    A(int&& n) { std::cout << "rvalue overload, n=" << n << "\n"; }
    A(int& n)  { std::cout << "lvalue overload, n=" << n << "\n"; }
};
 
class B {
public:
    template<class T1, class T2, class T3>
    B(T1&& t1, T2&& t2, T3&& t3) :
        a1_{std::forward<T1>(t1)},
        a2_{std::forward<T2>(t2)},
        a3_{std::forward<T3>(t3)}
    {
    }
 
private:
    A a1_, a2_, a3_;
};
 
template<class T, class U>
std::unique_ptr<T> make_unique1(U&& u)
{
    return std::unique_ptr<T>(new T(std::forward<U>(u)));
}
 
template<class T, class... U>
std::unique_ptr<T> make_unique2(U&&... u)
{
    return std::unique_ptr<T>(new T(std::forward<U>(u)...));
}
 
int main()
{   
    auto p1 = make_unique1<A>(2); // rvalue
    int i = 1;
    auto p2 = make_unique1<A>(i); // lvalue
 
    std::cout << "B\n";
    auto t = make_unique2<B>(2, i, 3);
}

Output:(结果:)


rvalue overload, n=2
lvalue overload, n=1
B
rvalue overload, n=2
lvalue overload, n=1
rvalue overload, n=3

相关文章

网友评论

    本文标题:Tips of C++11 std::move与完美转发std:

    本文链接:https://www.haomeiwen.com/subject/rlbkvqtx.html