【问题标题】:Move constructor hasn't been called移动构造函数尚未被调用
【发布时间】:2017-09-19 01:07:34
【问题描述】:

代码如下:

#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' 函数),但我只得到一个。为什么?

【问题讨论】:

  • Func 中的任何内容都不需要移动。编译器可能会说,把它弄掉,然后忽略你。
  • Func 更改为auto val2(std::move(val)); std::cout &lt;&lt; *val2.val &lt;&lt; std::endl;,您将看到移动构造。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2019-05-27
    • 2015-06-27
    • 2016-07-12
    • 2018-06-01
    • 2011-05-22
    • 2021-08-06
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    相关资源
    最近更新 更多