Skip to content

败犬日报 2025-07-17

1. std::shared_ptr 基类指针有偏移,怎么正确释放

往期提到,基类地址相对于子类有偏移,因此 std::shared_ptr 不一定指向子类。

答案是 std::shared_ptr 在初始化时已经决定了怎么释放;更详细地,shared_ptr 的 Deleter 是一个类似 std::function 的东西,它捕获了原始指针。

2. 图这样的数据结构怎么管理生命周期

所有权统一管理(用对象池),然后裸指针互相指。不要想花里胡哨的,该裸指针就裸指针。

3. shared_ptr 别名构造函数

不同类型,但是共享引用计数。

4. 模式匹配提案

https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2688r5.html

有点怪。

5. 学 C++ 推荐什么

《现代C++32讲》,或 CS106L +《C++ Core Guidelines》。

6. std::string::c_str() 的值移动后失效

cpp
#include <cstdio>
#include <string>
#include <vector>

int main() {
    std::vector<std::string> a{"123"};
    auto p = a[0].c_str();
    printf("%s\n", a[0].c_str());  // 输出 123
    a.push_back("456");
    printf("%s\n", a[0].c_str());  // 输出 123
    printf("%s\n", p);             // 可能没有输出(GCC 15.1 不加编译参数)
    return 0;
}

SSO(小字符串优化)导致的。

按照标准的话,用来移动构造其他对象的 string,所有迭代器和指针都失效了。所以即使不满足 SSO 也不要这么用。

由此看出,用 vector<string> 当作 pool 容易触发这个问题,所以更好的实践是整个 std::hive 类似的对象池。

与之不同的是,std::vector::data() 的值移动后不会失效,https://zh.cppreference.com/w/cpp/container/vector/vector.html 的 Notes 章节。