我试图创建临时对象的方式有错误吗

Is there any error in the way I am trying to create temporrary object

本文关键字:方式 有错误 临时对象 创建      更新时间:2023-10-16

下面是我的代码:我不明白为什么不调用move构造函数。

Mystring.h:

#ifndef _MYSTRING_H
#define _MYSTRING_H
#include<iostream>
#include<cstring>
#endif
class Mystring{
private:
char * str;
public:
Mystring();                         //No arg constructor
Mystring(char *str);                //Overloaded constructor
Mystring(const Mystring &source);   //Copy constructor
Mystring(Mystring &&source);        //Move constructor
//operator overloading
bool operator==(const Mystring &rhs);
bool operator!=(const Mystring &rhs);
bool operator<(const Mystring &rhs);
bool operator>(const Mystring &rhs);
Mystring &operator+(const Mystring &rhs);
};

Mystring.cpp:

#include"mystring.h"

Mystring::Mystring():str{nullptr}{
std::cout<<"No args constructor"<<std::endl;
}
Mystring::Mystring(char *str){
this->str = nullptr;
this->str = new char[strlen(str)+1];
strcpy(this->str,str);
std::cout<<"Overloaded constructor called"<<std::endl;
}
Mystring::Mystring(const Mystring &source){
delete[] this->str;
this->str = nullptr;
this->str = new char[strlen(source.str) + 1];
strcpy(this->str,source.str);
std::cout<<"copy constructor called"<<std::endl;
}
Mystring::Mystring(Mystring &&source){
this->str  = source.str;
source.str = nullptr;
std::cout<<"Move constructor called"<<std::endl;
}
bool Mystring::operator==(const Mystring &rhs){
std::cout<<"operator == called"<<std::endl;
return strcmp(this->str,rhs.str);
}
bool Mystring::operator!=(const Mystring &rhs){
std::cout<<"operator != called"<<std::endl;
return !(operator==(rhs));
}
bool Mystring::operator <(const Mystring &rhs){
std::cout<<"operator < called"<<std::endl;
if(strcmp(this->str,rhs.str) < 0){
return 0;
}
else 
return 1;
}
bool Mystring::operator >(const Mystring &rhs){
std::cout<<"operator > called"<<std::endl;
return(!(operator<(rhs)));
}
Mystring & Mystring::operator+(const Mystring &rhs){
std::cout<<"operator+ called"<<std::endl;
char *temp = new char[strlen(this->str) + strlen(rhs.str)+ 1];
strcat(temp,this->str);
strcat(temp,rhs.str);
}

main.cpp:

#include"Mystring.h"

int main(){
Mystring A {"cat"}; //Overloaded constructor
Mystring B {"dog"}; //Overloaded constructor
Mystring C {A};     //Copy constructor
Mystring D {Mystring{"Hello"}};  //Overloaded and then move constructor
return 0;
}

Myquestions:

语句Mystring D {Mystring{"Hello"}};从不调用move构造函数。我不明白为什么Mystring {"Hello"}不生成任何临时对象,然后应该调用move构造函数。

语句Mystring D {Mystring{"Hello"}};从不调用移动构造函数

因为复制省略;在这种情况下,这是由C++17保证的。

当一个对象从相同类型的prvalue初始化时(忽略cv限定(,它将直接从初始化器初始化。不会创建临时文件,也不会进行复制或移动。这有时被称为"保证拷贝省略",尽管与拷贝省略不同,它是强制性的,不是优化。

这意味着给定Mystring D {Mystring{"Hello"}};D直接从"Hello"初始化。无临时操作,无复制/移动操作。