蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

实测 C++17 unique_ptr/shared_ptr/weak_ptr 析构计数、allocator_traits 与 std::align

CPP本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。explore-cpp-libs-memory.cpp
explore-cpp-libs-memory.cpp146 行
#include <cstdint>
#include <cstdio>
#include <iostream>
#include <memory>
#include <string>
#include <vector>

namespace lab {

struct Case {
    std::string name;
    std::string expected_json;
    std::string actual_json;
    bool passed;
};

std::string esc(const std::string& s) {
    std::string out = "\"";
    for (unsigned char c : s) {
        switch (c) {
            case '\"': out += "\\\""; break;
            case '\\': out += "\\\\"; break;
            case '\n': out += "\\n"; break;
            case '\r': out += "\\r"; break;
            case '\t': out += "\\t"; break;
            default:
                if (c < 0x20) {
                    char buf[8];
                    std::snprintf(buf, sizeof(buf), "\\u%04x", c);
                    out += buf;
                } else {
                    out += static_cast<char>(c);
                }
        }
    }
    out += "\"";
    return out;
}

std::string jbool(bool v) { return v ? "true" : "false"; }

void emit(const std::vector<Case>& cases) {
    std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
    for (std::size_t i = 0; i < cases.size(); ++i) {
        if (i) std::cout << ", ";
        std::cout << "{\"name\": " << esc(cases[i].name)
                  << ", \"expected\": " << cases[i].expected_json
                  << ", \"actual\": " << cases[i].actual_json
                  << ", \"passed\": " << jbool(cases[i].passed) << "}";
    }
    std::cout << "]}\n";
}

} // namespace lab

namespace {

struct Tracker {
    static int live;
    int value;
    explicit Tracker(int v) : value(v) { ++live; }
    ~Tracker() { --live; }
};
int Tracker::live = 0;

struct Node {
    static int live;
    int id;
    std::shared_ptr<Node> next;
    std::weak_ptr<Node> prev;
    explicit Node(int i) : id(i) { ++live; }
    ~Node() { --live; }
};
int Node::live = 0;

} // namespace

int main() {
    std::vector<lab::Case> cases;

    // Case 1: std::unique_ptr exclusive ownership and move semantics
    bool c1 = false;
    {
        auto u1 = std::make_unique<Tracker>(99);
        bool after_create = (Tracker::live == 1 && u1->value == 99);
        auto u2 = std::move(u1);
        bool after_move = (u1 == nullptr && u2 != nullptr && u2->value == 99 && Tracker::live == 1);
        c1 = after_create && after_move;
    }
    c1 = c1 && (Tracker::live == 0);
    cases.push_back({"unique_ptr_exclusive_ownership", lab::jbool(true), lab::jbool(c1), c1});

    // Case 2: std::shared_ptr reference counting lifecycle
    bool c2 = false;
    {
        auto s1 = std::make_shared<Tracker>(7);
        bool count1 = (s1.use_count() == 1 && Tracker::live == 1);
        bool count2 = false;
        {
            auto s2 = s1;
            count2 = (s1.use_count() == 2 && s2.use_count() == 2 && s2->value == 7);
        }
        bool count_back = (s1.use_count() == 1 && Tracker::live == 1);
        c2 = count1 && count2 && count_back;
    }
    c2 = c2 && (Tracker::live == 0);
    cases.push_back({"shared_ptr_reference_counting", lab::jbool(true), lab::jbool(c2), c2});

    // Case 3: std::weak_ptr breaks cyclic reference between Nodes
    std::weak_ptr<Node> observer;
    bool lock_ok = false;
    {
        auto n1 = std::make_shared<Node>(1);
        auto n2 = std::make_shared<Node>(2);
        n1->next = n2;
        n2->prev = n1;
        observer = n1;
        auto locked = n2->prev.lock();
        lock_ok = (locked != nullptr && locked->id == 1 && Node::live == 2);
    }
    bool c3 = lock_ok && (Node::live == 0) && observer.expired();
    cases.push_back({"weak_ptr_breaks_cycle", lab::jbool(true), lab::jbool(c3), c3});

    // Case 4: std::allocator via std::allocator_traits + std::align
    std::allocator<int> alloc;
    using Traits = std::allocator_traits<std::allocator<int>>;
    int* p = Traits::allocate(alloc, 1);
    Traits::construct(alloc, p, 42);
    bool alloc_val_ok = (*p == 42);
    Traits::destroy(alloc, p);
    Traits::deallocate(alloc, p, 1);

    alignas(16) char raw_buf[64];
    void* ptr = raw_buf + 3; // intentionally misaligned
    std::size_t space = sizeof(raw_buf) - 3;
    void* aligned = std::align(16, sizeof(int), ptr, space);
    bool align_ok = (aligned != nullptr) &&
                    (reinterpret_cast<std::uintptr_t>(aligned) % 16 == 0) &&
                    (aligned == ptr) && (space == 64 - 16);
    bool c4 = alloc_val_ok && align_ok;
    cases.push_back({"allocator_traits_and_std_align", lab::jbool(true), lab::jbool(c4), c4});

    lab::emit(cases);
    return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。

入口文件:projects/cplusplus-cpp-libs-memory-lab/explore-cpp-libs-memory.cpp

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-cpp-libs-memory.cpp,或下载右侧课程工程包。
  2. 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:C++

课程关联工程包(登记关联99章) · 含当前章节或实例 · mbskycom202612a2307.zip

下载课程关联工程包:C++

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a2358.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习