惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
Martin Fowler
Martin Fowler
A
About on SuperTechFans
H
Help Net Security
F
Full Disclosure
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
IT之家
IT之家
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
阮一峰的网络日志
阮一峰的网络日志
WordPress大学
WordPress大学
H
Heimdal Security Blog
博客园_首页
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
T
Tailwind CSS Blog
Recent Announcements
Recent Announcements
B
Blog RSS Feed
Last Week in AI
Last Week in AI
V2EX - 技术
V2EX - 技术
The Register - Security
The Register - Security
Security Archives - TechRepublic
Security Archives - TechRepublic
G
GRAHAM CLULEY
美团技术团队
S
Securelist
MyScale Blog
MyScale Blog
Vercel News
Vercel News
L
LINUX DO - 最新话题
Hacker News: Ask HN
Hacker News: Ask HN
W
WeLiveSecurity
M
MIT News - Artificial intelligence
宝玉的分享
宝玉的分享
月光博客
月光博客
Attack and Defense Labs
Attack and Defense Labs
大猫的无限游戏
大猫的无限游戏
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Microsoft Security Blog
Microsoft Security Blog
I
InfoQ
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Forbes - Security
Forbes - Security
罗磊的独立博客
O
OpenAI News
AI
AI
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
雷峰网
雷峰网
S
Security @ Cisco Blogs
MongoDB | Blog
MongoDB | Blog
Schneier on Security
Schneier on Security
P
Proofpoint News Feed
Webroot Blog
Webroot Blog
V
Visual Studio Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
Beyong New and Delete: from auto_ptr to unique_ptr
Wang - C++ D · 2026-05-19 · via DEV Community

This guide walks through a legacy pattern built around std::auto_ptr, something still found in many older C++ codebases. The pattern usually involves a helper like cdup that deep‑copies an object and returns it as an auto_ptr, and classes that store these copies and access them through get() checks and raw pointer calls. It worked in its time, but it no longer fits modern C++ and creates unnecessary ownership confusion.

Here, we break down how the pattern works, why it causes problems, and how to refactor it step by step using std::unique_ptr. The goal is not just to replace one smart pointer with another, but to make ownership explicit, improve readability, and align the code with modern C++ practices.


The Legacy Pattern

A typical example looks like this: a cdup utility that deep‑copies an object into an auto_ptr, and a class that stores those copies and uses get() for access and null checks.

namespace sys_Util {
    template <typename T>
    inline std::auto_ptr<T> cdup(T* t) {
        return t ? std::auto_ptr<T>(new T(*t))
                 : std::auto_ptr<T>(0);
    }
}

class WidgetOwner {
    std::auto_ptr<Widget> m_widget;
public:
    explicit WidgetOwner(Widget* w)
        : m_widget(sys_Util::cdup(w)) {}

    void process() {
        if (m_widget.get()) {
            m_widget.get()->doWork();
        }
    }

    Widget* getWidget() { return m_widget.get(); }
};

Enter fullscreen mode Exit fullscreen mode

At first glance, this seems harmless. But once you look closer, the cracks show.


Evaluation of the Pattern

The pattern deep‑copies the object, wraps it in auto_ptr, and uses defensive get() checks before access.

The Problems of the Pattern

  1. auto_ptr is deprecated and removed

    It was deprecated in C++11 and removed entirely in C++17, so the code simply won’t compile on modern standards.

  2. Broken copy semantics

    Copying an auto_ptr silently transfers ownership, leaving the source null. This is one of the most dangerous behaviors in old C++ codebases.

std::auto_ptr<Widget> a(new Widget);
std::auto_ptr<Widget> b = a;  // a becomes null! (silent move)

Enter fullscreen mode Exit fullscreen mode

  1. Confusing ownership Passing a raw pointer to the constructor looks like ownership transfer, but the class actually makes a deep copy. The caller must still delete the original pointer, which is easy to forget.
WidgetOwner owner(raw);  // Does it take ownership? No, it copies.
delete raw;              // Must remember to delete (if not leaked)

Enter fullscreen mode Exit fullscreen mode

  1. Clunky access syntax m_widget.get()->method() is verbose and error‑prone compared to modern pointer semantics.
m_widget.get()->doWork();     // Too verbose
(*m_widget.get()).property;   // Ugly

Enter fullscreen mode Exit fullscreen mode

  1. Awkward null checks

    Every access requires if (ptr.get()), which is harder to read than necessary.

  2. Raw pointer exposure

    Returning T* invites accidental deletion or dangling references.

Widget* getWidget() { return m_widget.get(); }
// Caller might delete it, or hold it past owner lifetime

Enter fullscreen mode Exit fullscreen mode

  1. Exception safety issues new T(*t) can leak if the copy constructor throws an exception.
new T(*t)  // If T(const T&) throws, memory leaks

Enter fullscreen mode Exit fullscreen mode

Thread Safety of the Pattern

No synchronization, no atomicity — not safe for concurrent access. Copy operation on auto_ptr are not atomic.

Memory Safety of the Pattern

The pattern itself doesn’t leak, but raw pointer containers or circular references with auto_ptr can cause trouble.


Refactoring: Moving to unique_ptr

We keep the original behavior: the pointer may be null, and deep copies must still work. But we want clearer ownership and modern syntax.

Step 1: Replace auto_ptr with unique_ptr

std::unique_ptr<Widget> m_widget;

Enter fullscreen mode Exit fullscreen mode

This immediately removes silent moves and clarifies ownership.

Step 2: Remove the cdup Utility

Instead of a custom deep‑copy helper, use std::make_unique directly:

auto copy = original
    ? std::make_unique<Widget>(*original)
    : nullptr;

Enter fullscreen mode Exit fullscreen mode

This eliminates an entire utility and makes intent clearer .

Step 3: Fix the Constructor

The old constructor took a raw pointer and deep‑copied it, which was ambiguous.

We replace it with two explicit options: copy or move (take ownership).

explicit WidgetOwner(const Widget& w)
    : m_widget(std::make_unique<Widget>(w)) {}

explicit WidgetOwner(std::unique_ptr<Widget> w)
    : m_widget(std::move(w)) {}

Enter fullscreen mode Exit fullscreen mode

Null handling becomes explicit and predictable.

Step 4: Add Natural Access Operators

To avoid get() everywhere, we add operator->, operator*, and operator bool.

Widget* operator->() { return m_widget.get(); }
Widget& operator*()  { return *m_widget; }
explicit operator bool() const { return m_widget != nullptr; }

Enter fullscreen mode Exit fullscreen mode

This makes usage clean and modern:

if (m_widget) {
    m_widget->doWork();
}

Enter fullscreen mode Exit fullscreen mode

Step 5: Improve Null Check Syntax

Instead of:

if (m_widget.get())

Enter fullscreen mode Exit fullscreen mode

We now simply write:

if (m_widget)

Enter fullscreen mode Exit fullscreen mode

Or use a guard clause:

if (!m_widget) return;

Enter fullscreen mode Exit fullscreen mode

Step 6: Fix Raw Pointer Exposure

Returning raw pointers is risky. We replace it with safer alternatives:

Widget& getWidget() {
    if (!m_widget) throw std::runtime_error("Widget is null");
    return *m_widget;
}

Enter fullscreen mode Exit fullscreen mode

Or, if needed:

Widget* getWidget() { return m_widget.get(); }  // Document: can be null

Enter fullscreen mode Exit fullscreen mode


Complete Refactored Example

Before: Legacy Code

// sys_util.h
namespace sys_Util {
    template<typename T>
    inline std::auto_ptr<T> cdup(T* t) {
        return t ? std::auto_ptr<T>(new T(*t)) : std::auto_ptr<T>(0);
    }
}

// database_handler.h
class DatabaseHandler {
    std::auto_ptr<Database> m_db;
    std::auto_ptr<Logger> m_logger;

public:
    DatabaseHandler(Database* db, Logger* logger) 
        : m_db(sys_Util::cdup(db))
        , m_logger(sys_Util::cdup(logger)) {}

    void query(const std::string& sql) {
        if (m_db.get()) {
            m_db.get()->execute(sql);
        }
        if (m_logger.get()) {
            m_logger.get()->log(sql);
        }
    }

    Database* getDatabase() { return m_db.get(); }
    Logger* getLogger() { return m_logger.get(); }
};

// main.cpp
Database* db = new Database("localhost:5432");
Logger* logger = new Logger("app.log");
DatabaseHandler handler(db, logger);
handler.query("SELECT * FROM users");
delete db;      // Confusing - does handler own this?
delete logger;  // Did we just double delete?

Enter fullscreen mode Exit fullscreen mode

After: Modern Code

// sys_util.h - DELETED (no longer needed)

// database_handler.h
class DatabaseHandler {
    std::unique_ptr<Database> m_db;
    std::unique_ptr<Logger> m_logger;

public:
    // Clear: we make copies
    explicit DatabaseHandler(const Database& db, const Logger& logger) 
        : m_db(std::make_unique<Database>(db))
        , m_logger(std::make_unique<Logger>(logger)) {}

    // Clear: we take ownership (handles null case)
    explicit DatabaseHandler(std::unique_ptr<Database> db, std::unique_ptr<Logger> logger) 
        : m_db(std::move(db))
        , m_logger(std::move(logger)) {}

    void query(const std::string& sql) {
        if (m_db) {          // Clean bool check
            m_db->execute(sql);  // Natural syntax
        }
        if (m_logger) {
            m_logger->log(sql);
        }
    }

    // Safe access with reference
    Database& getDatabase() {
        if (!m_db) throw std::runtime_error("Database not initialized");
        return *m_db;
    }

    // Or optional access
    Database* getDatabaseOrNull() { return m_db.get(); }

    // Natural operators for direct use
    explicit operator bool() const { return m_db && m_logger; }
    Database* operator->() { return m_db.get(); }
};

// main.cpp - clear ownership
Database db("localhost:5432");     // Stack object
Logger logger("app.log");           // Stack object
DatabaseHandler handler(db, logger); // Clear: we copy
handler.query("SELECT * FROM users");
// No confusion - everything automatically cleaned up

// Handling null case
std::unique_ptr<Database> maybe_db = getDatabaseOrNull();  // Could be null
std::unique_ptr<Logger> maybe_logger = getLoggerOrNull();
DatabaseHandler nullable_handler(std::move(maybe_db), std::move(maybe_logger));
if (nullable_handler) {
    nullable_handler.query("SELECT * FROM users");
}

Enter fullscreen mode Exit fullscreen mode


Migration Summary Table

A concise comparison of old vs. new patterns can be found here.
| Aspect | Before (auto_ptr) | After (unique_ptr) |
|--------|--------------------|---------------------|
| Smart pointer | std::auto_ptr<T> | std::unique_ptr<T> |
| Copy utility | sys_Util::cdup(t) | std::make_unique<T>(*t) |
| Null check | if (ptr.get()) | if (ptr) |
| Member access | ptr.get()->method() | ptr->method() |
| Dereference | *ptr.get() | *ptr |
| Constructor | explicit A(T* t) | explicit A(const T& t) or explicit A(std::unique_ptr<T> t) |
| Exposure | T* get() (dangerous) | T& get() (safe) or T* get() (documented) |
| Bool check | Manual get() | explicit operator bool() |


Migration Checklist

A practical step‑by‑step list covering mechanical replacement, operator additions, interface cleanup, and correctness verification.

Phase 1: Mechanical Replacement

  • [ ] Replace std::auto_ptr<T> with std::unique_ptr<T>
  • [ ] Replace cdup(ptr) with ptr ? std::make_unique<T>(*ptr) : nullptr
  • [ ] Change raw pointer constructor parameters to const T& or std::unique_ptr<T>
  • [ ] Delete the cdup utility function

Phase 2: Add Convenience Operators

  • [ ] Add operator->() and operator*()
  • [ ] Add explicit operator bool() for null checks
  • [ ] Keep get() temporarily for compatibility

Phase 3: Clean Up Access Patterns

  • [ ] Replace ptr.get()->method() with ptr->method()
  • [ ] Replace if (ptr.get()) with if (ptr)
  • [ ] Replace *ptr.get() with *ptr

Phase 4: Improve Interfaces

  • [ ] Change T* get() to T& get() with null check (if never null)
  • [ ] Or keep T* get() but document null possibility
  • [ ] Consider encapsulation instead of exposing pointers

Phase 5: Verify Correctness

  • [ ] Ensure all null handling preserved
  • [ ] Run tests to verify behavior unchanged
  • [ ] Compile with C++17 or later to confirm no auto_ptr usage

Common Pitfalls and Solutions

Covers the three main issues: missing null checks, losing null checks during migration, and constructors that can’t represent null.

Pitfall 1: Forgetting Null Checks

// Wrong - if m_widget is null, this crashes
m_widget->doWork();

// Right - check first
if (m_widget) m_widget->doWork();

Enter fullscreen mode Exit fullscreen mode

Pitfall 2: Losing the Null Check During Migration

// Before - had check
if (m_widget.get()) { ... }

// After - still need check, just cleaner
if (m_widget) { ... }  // Not removed!

Enter fullscreen mode Exit fullscreen mode

Pitfall 3: Not Handling Null in Constructor

// Wrong - assumes non-null
explicit WidgetOwner(const Widget& w) : m_widget(std::make_unique<Widget>(w)) {}
// Can't represent null owner

// Right - handle null case
explicit WidgetOwner(std::unique_ptr<Widget> w) : m_widget(std::move(w)) {}
WidgetOwner null_owner(nullptr);  // Works

Enter fullscreen mode Exit fullscreen mode


Conclusion

The migration from auto_ptr to unique_ptr is more than a mechanical replacement—it's an opportunity to:

  1. Clarify ownership - unique_ptr makes exclusive ownership explicit
  2. Improve syntax - Operators provide natural pointer semantics
  3. Enhance safety - No silent moves, clear null handling
  4. Modernize code - Comply with C++11/14/17 standards

The pattern preserves the original behavior (deep copy with optional null) while making the code cleaner, safer, and more maintainable. Every auto_ptr replaced is a step toward modern C++.