【问题标题】:C++11 constructor & destructor orderC++11 构造函数和析构函数顺序
【发布时间】:2016-03-18 00:21:25
【问题描述】:

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

构造流 s1
破坏流 s1
输出1
测试
构建流 s2
破坏流 s2
测试

#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";
}

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

构造流 s1
输出 1
测试
破坏流 s1
构造流 s2
测试
破坏流 s2

为什么在

【问题讨论】:

  • 代码具有未定义的行为,因为您正在返回对局部变量的引用。
  • 对 Stream getStream(const std::string &name) 的更改将行为更改为:构造流 s1 破坏流 s1 输出 1 测试破坏流 s1 构造流 s2 破坏流 s2 测试破坏流 s2

标签: c++ c++11 constructor operator-overloading destructor


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2013-06-24
    • 1970-01-01
    • 2011-04-03
    • 2010-12-16
    • 2010-10-13
    • 2011-01-16
    • 1970-01-01
    相关资源
    最近更新 更多