gpt4 book ai didi

C++11构造函数和析构函数顺序

转载 作者:行者123 更新时间:2023-11-28 00:08:25 25 4
gpt4 key购买 nike

我有下面的代码,它给了我以下输出:

Constructing stream s1
Destructing stream s1
Output1
Test
Constructing stream s2
Destructing stream s2
Test

#include <iostream>
#include <utility>
#include <memory>
#include <string>

using std::cout;

class Stream {
public:
Stream(const std::string &name) : s(name) {
cout << "Constructing stream " << name << std::endl;
}

virtual ~Stream(){
cout << "Destructing stream " << s << std::endl;
}

friend Stream &&operator<<(Stream &&rhs, const std::string &str) {
cout << str << std::endl;
return std::move(rhs);
}

std::string s;
};

Stream &&getStream(const std::string &name){
Stream stream(name);
return std::move(stream);
}

int main(int argc, const char **argv) {
getStream("s1") << "Output1" << "Test";
getStream("s2") << "Test";
}

我对输出的期望是这样的:

Constructing stream s1
Output1
Test
Destructing stream s1
Constructing stream s2
Test
Destructing stream s2

为什么在调用<<运算符之前调用析构函数?

最佳答案

正如 Kerrek 正确指出的那样,原因是这个函数:

Stream &&getStream(const std::string &name){
Stream stream(name);
return std::move(stream);
}

这里您创建了一个类型为“Stream”的对象作为本地变量“stream”。当函数返回时,变量“stream”被破坏。这显然发生在打印“Output1”之前。

关于C++11构造函数和析构函数顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34234525/

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