gpt4 book ai didi

c++ - 为什么我的代码中没有调用移动构造函数?还有为什么不调用 dtor 只是为了销毁临时对象?

转载 作者:行者123 更新时间:2023-12-04 14:55:49 27 4
gpt4 key购买 nike

<分区>

我的代码行

student g1(student("Larry"));//why move ctor is not called after overloaded ctor???
student g2 = "Delta";//Also here,why move ctor is not called after overloaded ctor???

还有为什么 dtor 没有被调用之后创建的未命名的临时对象????

实际上,当调用 move ctor 时,我完全感到困惑。另一方面,我还观察到,如果我尝试将一个临时对象推回到一个期望对象类型元素的 vector 中,则会调用 move ctor,

vector<student> list{};
list.push_back(student("vickey"));

在这里,首先创建 vickey temp 对象,然后通过调用移动构造函数移动到 vector,因为 student("vickey") 是一个右值。不是吗?

如果上面是有效的那么为什么这里无效?

student g1(student("Larry"));
student g2 = "Delta";

这是我的代码

#include <iostream>
#include <cstring>
using namespace std;
//===================class declaration============================
class student{
private:
char *name;
public:
student();
student(const char *str);
~student();
student(student &&rhs) noexcept;

};
//======================impelmentation=========================
student::student(){
cout<<"default"<<endl;
name = new char[5];
strcpy(name, "None");
}
student::student(const char *str)
:name{nullptr}{
cout << "overloaded" << endl;
if(str == nullptr){
name = new char[5];
strcpy(name, "None");
}else{
name = new char[strlen(str) + 1];
strcpy(name, str);
}
}

student::student(student &&rhs) noexcept
:name{rhs.name}{
cout << "Move ctor" << endl;
rhs.name = nullptr;

}

student::~student(){
if(name == nullptr)
cout<<"dtor : nullptr"<< endl;
else{
cout<<"dtor : "<<name<< endl;
delete [] name;
}
}

//===================================main=====================================
int main() {
student g1(student("Larry"));
student g2 = "Delta";
cout<<"\n=========================================================\n"<<endl;
return 0;
}

输出:

overloaded
overloaded

=========================================================

dtor : Delta
dtor : Larry

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com