Skip to content

fix: 修复严格别名问题和 position() 返回值#8

Merged
CPythoner merged 1 commit intomasterfrom
fix-strict-aliasing-and-position
Apr 3, 2026
Merged

fix: 修复严格别名问题和 position() 返回值#8
CPythoner merged 1 commit intomasterfrom
fix-strict-aliasing-and-position

Conversation

@CPythoner
Copy link
Copy Markdown
Owner

描述

本 PR 修复了 Code Review 中发现的两个严重问题。

变更内容

1. 修复严格别名问题 (Issue #6)

问题: read<T>(index) 方法通过指针类型转换访问内存,违反 C++ strict aliasing 规则,可能导致未定义行为。

修改前:

template <typename T>
T read(uint32_t index) const
{
    if (!p_buffer_ || index + sizeof(T) > limit_)
        return 0;

    return *((T*)&p_buffer_[index]);  // ⚠️ 违反严格别名规则
}

修改后:

template <typename T>
T read(uint32_t index) const
{
    if (!p_buffer_ || index + sizeof(T) > limit_)
        return 0;

    T data;
    std::memcpy(&data, &p_buffer_[index], sizeof(T));
    return data;
}

2. 修复 position() 方法缺少返回值

问题: position(uint32_t) 方法声明返回 ByteBuffer& 但缺少 return *this;

修改前:

ByteBuffer& position(uint32_t newPosition)
{
    position_ = newPosition;
    // ⚠️ 缺少 return *this;
}

修改后:

ByteBuffer& position(uint32_t newPosition)
{
    position_ = newPosition;
    return *this;
}

影响

  • 避免潜在的未定义行为
  • 修复编译警告
  • 支持链式调用 position() 方法

- 使用 std::memcpy 替代指针类型转换,避免未定义行为
- 修复 position() 方法缺少 return *this 的问题
@CPythoner CPythoner merged commit 9c30aa4 into master Apr 3, 2026
@CPythoner CPythoner deleted the fix-strict-aliasing-and-position branch April 4, 2026 08:39
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant