Can compiler generate std::move for a last use of lvalue automatically?

前端 未结 3 1240
暖寄归人
暖寄归人 2020-11-29 11:51

A code like this is often seen in r-value references articles:

Dave Abrams: Move It With Rvalue References

void g(X);

void f()
{
    X b;
    g(b);          


        
3条回答
  •  甜味超标
    2020-11-29 12:29

    No. Consider:

    using X = std::shared_ptr;
    void g(X);
    void f() {
        X b = std::make_shared();
        int &i = *b;
        g(b);              // last use of 'b'
        i = 5;
    }
    

    In general, the compiler cannot assume that altering the semantics of copies, moves and destructors of X will be a legitimate change without performing analysis on all the code surrounding the use of b (i.e., the whole of f, g, and all the types used therein).

    Indeed, in some cases whole-program analysis may be necessary:

    using X = std::shared_ptr>;
    std::mutex i_mutex;
    int i;
    void g(X);
    void f() {
        X b = std::make_shared>(i_mutex);
        g(b);              // last use of 'b'
        i = 5;
    }
    

    If b is moved, this introduces a data race against other threads that synchronize access to i using i_mutex.

提交回复
热议问题