[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
[lmi-commits] [lmi] master 048b2cc 4/6: Demonstrate a peril
From: |
Greg Chicares |
Subject: |
[lmi-commits] [lmi] master 048b2cc 4/6: Demonstrate a peril |
Date: |
Thu, 5 Aug 2021 17:10:00 -0400 (EDT) |
branch: master
commit 048b2cc9dc3798b0adb79490fe4985d398de7abc
Author: Gregory W. Chicares <gchicares@sbcglobal.net>
Commit: Gregory W. Chicares <gchicares@sbcglobal.net>
Demonstrate a peril
---
null_stream_test.cpp | 38 ++++++++++++++++++++++++++++++++++++++
1 file changed, 38 insertions(+)
diff --git a/null_stream_test.cpp b/null_stream_test.cpp
index 3406f26..ae584ac 100644
--- a/null_stream_test.cpp
+++ b/null_stream_test.cpp
@@ -159,6 +159,44 @@ void test_fundamentals()
<< " And the notion I cannot endure!\n"
<< std::flush
;
+
+ // Demonstrate a peril.
+ {
+ LMI_TEST_EQUAL(&null_streambuf(), os0.rdbuf());
+ LMI_TEST_EQUAL(&null_streambuf(), os1.rdbuf());
+ // First stream: substitute a non-discarding streambuf.
+ std::ostringstream oss0;
+ os0.rdbuf(oss0.rdbuf());
+ os0 << "This text is not to be discarded." << std::endl;
+ // Second stream: likewise.
+ std::ostringstream oss1;
+ os1.rdbuf(oss1.rdbuf());
+ os1 << "Neither is this." << std::endl;
+ LMI_TEST_UNEQUAL(&null_streambuf(), os0.rdbuf());
+ LMI_TEST_UNEQUAL(&null_streambuf(), os1.rdbuf());
+ }
+
+ // Now rdbuf() would return a dangling pointer for each stream.
+ LMI_TEST_UNEQUAL(&null_streambuf(), os0.rdbuf());
+ LMI_TEST_UNEQUAL(&null_streambuf(), os1.rdbuf());
+
+ // This would be okay:
+ std::ostream new_os1(&null_streambuf());
+ LMI_TEST_EQUAL(&null_streambuf(), new_os1.rdbuf());
+ // But this would not:
+ std::ostream& new_os0 = null_stream();
+ LMI_TEST_UNEQUAL(&null_streambuf(), new_os0.rdbuf());
+
+ // This would segfault:
+// os0 << "But while he was seeking with thimbles and care" << std::endl;
+ // As would this:
+// os1 << "A Bandersnatch swiftly drew nigh" << std::endl;
+ // These do not segfault, but remembering to reset the
+ // streambuf manually requires too much smiles and soap:
+ os0.rdbuf(&null_streambuf());
+ os0 << "Segfault avoided with thimbles and care." << std::endl;
+ os1.rdbuf(&null_streambuf());
+ os1 << "Segfault avoided with forks and hope." << std::endl;
}
void assay_speed()
- [lmi-commits] [lmi] master updated (7a6262f -> a102012), Greg Chicares, 2021/08/05
- [lmi-commits] [lmi] master 50c1d57 1/6: Don't write solve trace to statusbar, Greg Chicares, 2021/08/05
- [lmi-commits] [lmi] master 440c67d 2/6: Add a null_stream unit test, Greg Chicares, 2021/08/05
- [lmi-commits] [lmi] master 52456de 3/6: Demonstrate the speed advantage of 'badbit', Greg Chicares, 2021/08/05
- [lmi-commits] [lmi] master 048b2cc 4/6: Demonstrate a peril,
Greg Chicares <=
- [lmi-commits] [lmi] master 4bc0910 5/6: Test std::ostream(nullptr) as well, Greg Chicares, 2021/08/05
- [lmi-commits] [lmi] master a102012 6/6: Generally avoid using null_stream(), Greg Chicares, 2021/08/05