小编Adr*_*oot的帖子

std::unique_ptr、pimpl 和对象生命周期

以下示例使用 Linux 上的 gcc 11 (GNU STL) 和 FreeBSD 上的 clang 12 (Clang STL) 进行编译。在 Linux 上,它运行并打印值 1 和 2。在 FreeBSD 上,它打印值 1,然后因 SEGV 崩溃。我不太了解对象的生命周期——所以整个事情可能是 UB 并且运行时行为可能不相关。我确实知道这两个 STL的实现在一个重要方面有所不同:Clang STL在析构函数的开头重置 a 的内部指针,而 GNU STL 则单独保留该指针std::unique_ptrstd::unique_ptrnullptr

#include <iostream>
#include <memory>

struct C {
    struct Private {
        C* m_owner;
        int m_x;
        Private(C* owner) : m_owner(owner), m_x(0) {}
        ~Private() { m_owner->cleanup(); }
        void cleanup() { std::cout << "Private x=" << ++m_x << '\n'; }
    };
    
    std::unique_ptr<Private> …
Run Code Online (Sandbox Code Playgroud)

c++ undefined-behavior c++17

2
推荐指数
1
解决办法
124
查看次数

标签 统计

c++ ×1

c++17 ×1

undefined-behavior ×1