【问题标题】:why move Constructor is not call?为什么移动构造函数不调用?
【发布时间】:2017-04-02 05:07:27
【问题描述】:

请看下面的示例代码:

    class testo
{
public:
    testo()
    {
        cout << " default " << endl;
    }

    testo(const testo & src)
    {
        cout << "copy " << endl;
    }
    testo(const testo && src)
    {
        cout << "move" << endl;
    }
    testo & operator=(const testo & rhs)
    {
        cout << " assigment" << endl;
        return *this;
    }
    testo & operator= (const testo && rhs)
    {
        cout << "move" << endl;
    }

};

这是我的功能和主要代码:

testo nothing(testo & input)
{
return input;
}

int main ()
{
testo boj1 ;
testo obj2(nothing(obj1) );
return 1;
}

当我编译并运行这段代码时,我希望看到:

default    // default constructor

copy       // returning from the function

move       // moving to the obj2

但是当代码被执行时它只是显示:

default 

copy

编译器是 Visual C++ 2015

【问题讨论】:

  • 请添加您用于测试课程的代码。
  • 从移动构造函数/移动赋值中移除 const 限定符
  • 对不起,我忘记了函数
  • 测试记录(测试和输入){返回测试}
  • 编译器很聪明。它看到没有任何东西的输出可以直接进入obj2,而无需任何额外的麻烦,所以它确实将返回时的副本构建到obj2的初始化中。

标签: c++ logic copy-constructor


【解决方案1】:

移动签名应该定义为T&amp;&amp;,而不是T const &amp;&amp;。虽然语言中没有任何内容阻止您声明 T const &amp;&amp;,但实际上这没有任何意义:您的意思是从该对象移出,但它是 const,因此不能更改其状态?这是一个自相矛盾的术语。

【讨论】:

  • 感谢您的回答,但是。删除 const 关键字.. 没有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 2014-01-24
  • 2023-03-16
相关资源
最近更新 更多