小赖子的英国生活和资讯

C++: auto_ptr智能指针被弃用

阅读 桌面完整版

为什么 auto_ptr 在 C++ 中被弃用

TLDR; 很久之前看到auto_ptr就觉得挺好,和auto一样,反正不用自己管,C++会自动推导智能指针的类型。不过这个关键字已经在C++ 11中被弃用/deprecated。

弃用与移除

为什么 auto_ptr 被弃用?

std::auto_ptr<int> p1(new int(42));
std::auto_ptr<int> p2 = p1; // 所有权被转移
std::cout << *p2 << std::endl; // 正常
std::cout << *p1 << std::endl; // 未定义行为(p1 变成 nullptr)

应该使用什么替代?

#include <memory>
#include <iostream>

int main() {
    std::unique_ptr<int> p1(new int(42));
    std::unique_ptr<int> p2 = std::move(p1); // 转移所有权
    std::cout << *p2 << std::endl;
}

对比表

特性 std::auto_ptr std::unique_ptr
可拷贝性 是(但不安全)
移动语义
引入/移除 C++98 / C++17 中移除 C++11 引入

结论

在现代 C++ 中,使用 std::unique_ptrstd::shared_ptr 进行内存管理。不要在新的项目中再使用 auto_ptr

C/C++编程

英文:Why auto_ptr is Deprecated in C++?

强烈推荐

微信公众号: 小赖子的英国生活和资讯 JustYYUK

阅读 桌面完整版
Exit mobile version