复制构造函数首先被调用,而不是仅在传递 R 值引用时才调用移动构造函数

Copy constructor is being called first instead of only move constructor on passing even R-value reference

您好!我正在制作自己的字符串 class 命名字符串

传递 R 值移动构造函数和移动赋值运算符时被调用 这是主要功能,我所做的只是传递 R 值引用,但在调试时仅复制或同时移动和复制。

    int main()
   {
    strings s1="hey!";
       cout<<"\n";
    s1=strings("bye");
       cout<<"\n";
    s1="Hello";
       cout<<"\n";
   strings s2= strings{"Rhythm"};
    s2.print();
    return 0;
   }

   

 //move comstructor
strings::strings(strings &&obj):s{obj.s}
{
  std::cout<<"Calling move const\n";
  obj.s=nullptr;
}
   

 //move assinment operator
   strings& strings::operator=(strings &&obj)
{
    std::cout<<"Using move\n";
    if(this==&obj){
        return *this;
    }
    delete[] s;
    s=obj.s; 
    obj.s=nullptr;
    return *this;
}
       
     //copy constructor;
strings::strings(const strings &obj)
{
   s=new char[strlen(obj.s)+1];
   strcpy(this->s,obj.s);
} 
 

移动赋值(不是赋值初始化)需要移动 operator=(strings&&)。如果您定义了自己的复制构造函数,则它不可用。请注意,在这种情况下

struct S {
    S() {}
    S(const S &obj) {  std::cout << "Copy ctor" << std::endl;}
    S(S &&obj) {  std::cout << "Move ctor" << std::endl;}
    S& operator=(const S &obj) {  std::cout << "Copy =" << std::endl; return *this;}
    S& operator=(S &&obj) {  std::cout << "Move =" << std::endl; return *this;}
};

int main()
{
    S a = S();
    a = S();
}

对于 C++11 编译器,声明行甚至不会产生输出,因为没有发生复制或移动,它被省略了。