move constructor and copy constructor in C++

后端 未结 2 1160
轮回少年
轮回少年 2021-01-14 11:52

My understanding is that a move constructor is called if it exists when we return a local object from a function. However, I ran into a situation where the copy constructor

2条回答
  •  被撕碎了的回忆
    2021-01-14 12:34

    The following code does not implicitly move the constructed object:

    tNode foo2()
    {
        std::unique_ptr up = std::make_unique(20);
        return *up;
    }
    

    This is because, however obvious/intuitive it might seem to us, the compiler cannot prove that it is safe to move-from the object contained by up. It's forced to return by copy.

    You could force it to return by R-value by explicitly casting the object as such:

    tNode foo2()
    {
        std::unique_ptr up = std::make_unique(20);
        return std::move(*up);
    }
    

提交回复
热议问题