Skip to content

refactor: 使用 std::copy 替代 memcpy/memmove#15

Merged
CPythoner merged 2 commits intomasterfrom
refactor/optimize-copy
Apr 3, 2026
Merged

refactor: 使用 std::copy 替代 memcpy/memmove#15
CPythoner merged 2 commits intomasterfrom
refactor/optimize-copy

Conversation

@CPythoner
Copy link
Copy Markdown
Owner

优化 memcpy 使用

背景

既然 buffer 已经改用 std::vector 管理,部分 memcpy 可以替换为更 C++ 风格的 std::copy。

修改内容

替换为 std::copy

  • getBytes: 使用 std::copy 替代 memcpy
  • compact: 使用 std::copy 替代 memmove

保留 memcpy

  • read 和 append: 保留 memcpy,用于类型双关(type punning)
    • 这是 C++ 中安全处理类型双关的标准方式
    • 避免严格别名问题
    • 编译器会优化为高效指令

新增依赖

  • 添加 头文件

代码统计

  • 新增 4 行
  • 删除 3 行
  • 净增 1 行

测试结果

All tests passed (110 assertions in 40 test cases)

- 问题 1.2: equals() 方法添加 const 限定符
- 问题 2.1: 使用 std::vector<uint8_t> 替代 calloc/free 进行内存管理
- 问题 2.3: compact() 方法使用 memmove 替代循环逐字节复制

主要改动:
- 移除 p_buffer_ 裸指针,改用 buffer_ (std::vector<uint8_t>)
- 析构函数改为 default
- 移动语义使用 std::move 管理 vector
- checkSize 使用 vector::resize 替代 realloc
- getBytes 使用 buffer_.data() 访问底层数据
@CPythoner CPythoner merged commit 6e4e9fb into master Apr 3, 2026
6 checks passed
@CPythoner CPythoner deleted the refactor/optimize-copy 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