尚未调用移动构造函数

时间:2017-04-21 22:07:34

标签: c++ c++11 move-semantics

以下是代码:

#include <memory>
#include <iostream>

template<typename T>
class Foo
{
public:
    Foo(T&& val) :
        val(std::make_unique<T>(
            std::forward<T>(val)))
    {
    }

    Foo(Foo&& that) :
        val(std::move(that.val))
    {
        std::cout << *val << std::endl;
    }

    std::unique_ptr<int> val;
};

template<typename T>
void Func(Foo<T>&& val)
{
    std::cout << *val.val << std::endl;
}

int main()
{
    Foo<int> instance(10);
    Func(std::move(instance));

    return 0;
}

问题是我希望这里有两行输出(来自我的自定义移动构造函数和'Func'函数),但我只得到一行。为什么呢?

1 个答案:

答案 0 :(得分:2)

您的Foo<int>对象根本没有被移动。 std::move不会移动它;它只能使它可用于移动(通过将其转换为xvalue)。但是,由于Func通过引用获取其参数,因此在调用时不会构造Foo<int>对象,因此不会调用移动构造函数。

相关问题