gpt4 book ai didi

c++ - rdbuf的生命周期和使用

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

以下代码有效,它看起来不像是提供了一些不良或不需要的行为,例如未定义的行为或不正确的结果。代码按预期工作,我的观点是:为什么?

std::vector<char> v{std::istreambuf_iterator<char>{
std::ifstream{"yourFile.txt", std::ios::in}.rdbuf()},
std::istreambuf_iterator<char>{}};

这是对与迭代器一起工作的 std::vector 的构造函数的调用,我的观点是关于 rdbuf() 调用的生命周期,事实上rdbuf 是一个指针而不是一个对象,你不能只复制 rdbuf 并假装它总是会到达你的文件的内容,你也不能真正复制整个不使用迭代器的文件内容。

我期待的是:

  • 有一个临时的 ifstream 对象
  • 从这个临时调用 rdbuf
  • rdbuf 现在在 istreambuf_iterator 的构造函数中并且 ifstream 对象消失了
  • std::vector 的构造函数现在应该使用指向不再存在的对象的指针拷贝

我很惊讶这件事能奏效,有人可以说明我为什么错了,一步一步发生了什么? ifstream 对象不应该是 RAII 兼容的并且只存在于 istreambuf_iterator 的范围内?

最佳答案

临时对象(当没有通过绑定(bind)到引用来延长生命周期时)在封闭的完整表达式的末尾被销毁(C++11 12.2/3):

When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor (12.4). Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

每 1.9/10:

A full-expression is an expression that is not a subexpression of another expression. [ Note: in some contexts, such as unevaluated operands, a syntactic subexpression is considered a full-expression (Clause 5). —end note ] If a language construct is defined to produce an implicit call of a function, a use of the language construct is considered to be an expression for the purposes of this definition. A call to a destructor generated at the end of the lifetime of an object other than a temporary object is an implicit full-expression. Conversions applied to the result of an expression in order to satisfy the requirements of the language construct in which the expression appears are also considered to be part of the full-expression.

您的声明v “产生函数的隐式调用”:双迭代器 vector 构造函数。因此它被认为是一个完整的表达式,所以临时的 ifstream对象- 更不用说两个临时std::istreambuf_iterator<char>对象 - 在构造函数调用完成之前不会被销毁。

关于c++ - rdbuf的生命周期和使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24207546/

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