为什么删除移动构造函数后仍使用复制构造函数?

问题描述 投票:0回答:1

作为主题,相关代码为:

#include <iostream>     

class ABC     
{  public:  
    ABC() 
    {
        std::cout<< "default construction" << std::endl;
    }

    ABC(const ABC& a) 
    {
        std::cout << "copy construction" << std::endl;
    } 

    ABC(const ABC&& a) 
    {
        std::cout << "move construction" << std::endl;
    }
};                         

int main()   
{  
   ABC c1 = ABC();  

   return 0;  
}

带有-fno-elide-constructors -std = c ++ 11的输出

default construction
move construction

如果我删除上面的move构造函数,则输出为:

default construction
copy construction

为什么删除copy constructor后仍使用move constructor根据某些文档,编译器提供了默认的move constructor所以,为什么编译器不使用默认的move constructor?] >

我是C ++的新手。对于这个问题,我将不胜感激。

作为主题,相关代码为:#include class ABC {public:ABC(){std :: cout <

根据某些文档,编译器提供默认的move constructor

让我们看一些文档。以下来自cppreference.com

如果[条件]

,则编译器将声明移动构造函数为其类的非显式内联公共成员,并带有签名T::T(T&&)

你是对的。编译器确实在正确的条件下提供了defualt move构造函数。 但是,这些条件很重要。

您似乎意识到的第一个条件:不能有用户定义的move构造函数。这样就只剩下条件列表了:
  • 没有用户声明的副本构造函数;
  • 没有用户声明的副本分配运算符;
  • 没有用户声明的移动分配运算符;
  • 没有用户声明的析构函数;

然后你去。用户定义的副本构造函数阻止编译器提供默认的move构造函数。因此,没有移动构造函数可以使用。

c++ c++11 constructor copy-constructor move-semantics
1个回答
0
投票

根据某些文档,编译器提供默认的move constructor

© www.soinside.com 2019 - 2024. All rights reserved.