BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / iwhisper / #6905995同步于 2024/3/9
该镜像源已超过 30 天没有更新,可能在源站已被删除。
IWhisper机器人发帖

C++选手请进,求教个问题

IWhisper#456
2024/3/9镜像同步9 回复
要不问问gpt?
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
IWhisper#456机器人#0 · 2024/3/9
#include <iostream> #include <vector> #include <string> using namespace std; class Example6 { string* ptr; public: Example6(const string& str) : ptr(new string(str)) {} ~Example6() { delete ptr; } // 移动构造函数 Example6(Example6&& x) noexcept : ptr(x.ptr) { x.ptr = nullptr; } // 移动赋值运算符 Example6& operator= (Example6&& x) noexcept { if (this != &x) { delete ptr; ptr = x.ptr; x.ptr = nullptr; } return *this; } // access content: const string& content() const { return *ptr; } // addition: Example6 operator+(const Example6& rhs) { return Example6(content() + rhs.content()); } }; int main() { Example6 foo("Exam"); //Example6 foo1("ple"); Example6 bar = Example6("ple"); Example6 bar2(move(foo)); bar = bar2 + bar; cout << "bar's content: " << bar.content() << '\n'; return 0; } 想问一下,main函数中Example6 bar = Example6("ple");调用的是默认的拷贝构造函数,还是移动构造函数哈,可以解答下吗,最后正常运行bar's content: Example,如果调用默认的拷贝构造函数(浅拷贝)也没发生内存重复释放,但是我没有用move,不应该调用的移动构造函数吧
IWhisper#572机器人#1 · 2024/3/9
要不问问gpt?
IWhisper#456机器人#2 · 2024/3/9
gpt一直在抱歉说错了
IWhisper#143机器人#3 · 2024/3/9
编译器默认优化?
IWhisper#749机器人#4 · 2024/3/9
虽然我没看,但是不是编译器背着你做了优化
IWhisper#866机器人#5 · 2024/3/9
帮你问了下 gpt4,说是调用了移动构造函数。我没细看
IWhisper#429机器人#6 · 2024/3/9
ple是字符串字面量,本身就是右值
IWhisper#429机器人#7 · 2024/3/9
这一行调用的可能是普通的构造函数,不确定const char*能不能转化成const string& : #include <vector> : #include <string> : ............
IWhisper#86机器人#8 · 2024/3/9
是移动构造函数,右边的变量是一个右值。