主要观点:不能简单认为使用智能指针 everywhere 就能使 C++像 Circle 或 Rust 那样“安全”,原因是存在不受控制类型中的内部原始指针。
关键信息:
- 以
std::vector
为例,其迭代器是原始指针,push_back
操作会导致数组重新分配,使之前的迭代器指向无效内存,引发heap-use-after-free
错误。 std::span
(C++20)和std::lock_guard
(C++11)也会出现类似错误,TSan 和 Valgrind 能捕获但 ASan 不行。- Circle 中的
std2::lock_guard
和 Rust 中的std::sync::MutexGuard
都有“lifetime annotations”。
重要细节: - 如
for (auto element : my_vector)
循环中对my_vector
进行push_back
操作会导致迭代器失效。 shared_ptr<int>*
(指向shared_ptr<int>
的指针)可能会悬空,类似于int**
在指向的int*
被销毁时会悬空。std::lock_guard
在my_mutex.reset()
后,其析构函数中调用my_mutex->unlock()
会导致使用已释放内存的错误。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。