考虑以下几点:
std::ostream out(nullptr);
这合法且定义明确吗?
如果我现在这样做呢:
out << "hello world\n";
这是否合法且定义明确?如果是这样,大概是一种无操作?
最佳答案
是的,实例化该流是合法且定义明确的。您可以安全地将其与另一个流交换,或者稍后给它一个新指针(这次指向现有缓冲区)。输出操作本身确实是空操作。
原因如下:
构造没有非空前置条件,只有这个后置条件:
[C++11: 27.7.3.2/2]:
Postcondition:rdbuf() == sb
.有趣的是,它明确指出不得对
sb
执行任何操作。在构造函数中:[C++11: 27.7.3.2/4]:
Remarks: Does not perform any operations onrdbuf()
.但也要注意:
[C++11: 27.7.3.2/1]:
Effects: Constructs an object of classbasic_ostream
, assigning initial values to the base class by callingbasic_ios<charT,traits>::init(sb)
(27.5.5.2).那个
init(sb)
call具有设置badbit
的效果直播时sb
为空:[C++11: 27.5.5.2/3]:
Postconditions: The postconditions of this function are indicated in Table 128.[C++11: Table 128]:
[..]rdstate()
:goodbit
ifsb
is not a null pointer, otherwisebadbit
. [..]输出操作会导致相当于取消引用空指针的操作:
[C++11: 27.7.3.1/2]:
Two groups of member function signatures share common properties: the formatted output functions (or inserters) and the unformatted output functions. Both groups of output functions generate (or insert) output characters by actions equivalent to callingrdbuf()->sputc(int_type)
. They may use other public members ofbasic_ostream
except that they shall not invoke any virtual members ofrdbuf()
exceptoverflow()
,xsputn()
, andsync()
.除了它从来没有走到这一步,因为对于
basic_ostream::sentry
build :[C++11: 27.7.3.4/3]:
If, after any preparation is completed,os.good()
istrue
,ok_ == true
otherwise,ok_ == false
.对于
explicit operator basic_ostream::sentry::bool() const;
:[C++11: 27.7.3.4/5]:
Effects: Returnsok_
.和:
[C++11: 27.7.3.7/1]:
Each unformatted output function begins execution by constructing an object of classsentry
. If this object returnstrue
, while converting to a value of typebool
, the function endeavors to generate the requested output. [..]...这意味着当
badbit
时根本不发生任何输出操作。已经设置好了。
关于c++ - 从空缓冲区构造 `std::ostream` 是否有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25690636/