fix(buffer): remove const from char constructor to prevent UB

- Change: explicit buffer(char const & c) → explicit buffer(char & c)
- Remove dangerous const_cast in implementation
- Before: buffer(const_cast<char*>(&c), 1) [UB if c is truly const]
- After: buffer(&c, 1) [safe, requires non-const char]
- Prevents undefined behavior from modifying compile-time constants
- Constructor now correctly requires mutable char reference
- Aligns with buffer's mutable data semantics

The previous implementation with const_cast could lead to:
- Modifying string literals (undefined behavior)
- Modifying const variables (undefined behavior)
- Runtime crashes or data corruption

Example of prevented misuse:
  buffer buf('X');           // Now: compile error ✓
  char c = 'X';
  buffer buf(c);             // Now: works correctly ✓
  const char cc = 'Y';
  buffer buf(cc);            // Now: compile error ✓
This commit is contained in:
木头云 2025-11-30 05:00:57 +00:00
parent 8103c117f1
commit de76cf80d5
2 changed files with 3 additions and 3 deletions

View File

@ -24,7 +24,7 @@ public:
explicit buffer(byte_t (& data)[N]) explicit buffer(byte_t (& data)[N])
: buffer(data, sizeof(data)) { : buffer(data, sizeof(data)) {
} }
explicit buffer(char const & c); explicit buffer(char & c);
buffer(buffer&& rhs); buffer(buffer&& rhs);
~buffer(); ~buffer();

View File

@ -46,8 +46,8 @@ buffer::buffer(void* p, std::size_t s)
: buffer(p, s, nullptr) { : buffer(p, s, nullptr) {
} }
buffer::buffer(char const & c) buffer::buffer(char & c)
: buffer(const_cast<char*>(&c), 1) { : buffer(&c, 1) {
} }
buffer::buffer(buffer&& rhs) buffer::buffer(buffer&& rhs)