繁体   English   中英

为什么在这种情况下调用非const rvalue移动构造函数?

[英]Why is a non-const rvalue move constructor called in this case?

我已经看到了相关的问题,他们主要谈论我们是否应该将const rvalue引用作为参数。 但我仍然无法解释为什么在以下代码中调用非const移动构造函数

    #include <iostream>
    using namespace std;

    class A 
    {
    public:
      A (int const &&i) { cout << "const rvalue constructor"; }
      A (int &&i) { cout << "non const rvalue constructor"; }
   };


   int const foo (void)
   {
     const int i = 3;
     return i;
   }

  int main (void)
  {
     A a(foo());
  }

以下是您的代码的略微修改版本:

#include <iostream>

#if 0
using T = int;
#else
struct T {T(int){}};
#endif

    using namespace std;
    class A {
      public:
      A (T const &&i) { cout << "const rvalue constructor"; }
      A (T &&i) { cout << "non const rvalue constructor"; }
   };


   T const
   foo (void)
   {
     const T i = 3;
     return i;
   }

  int main()
  {
    A a(foo());
  }

T == int ,你得到非const重载。 T是类类型时,您将获得const重载。 此行为属于8.2.2 [expr.type] / p2部分:

如果prvalue最初具有类型“ cv T ”,其中T是cv非限定的非类非数组类型,则在进行任何进一步分析之前将表达式的类型调整为T

翻译:该语言没有const -qualified标量p​​rvalues。 他们根本就不存在。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM