You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

普通指针double * pNormal = &xNormal的智能指针等价写法是什么?

普通指针与std::unique_ptr的等价写法问题

原代码

#include <iostream>
#include <memory>

int main()
{
    double xNormal{5};
    double * pNormal = &xNormal;
    xNormal = 10;
    std::cout<<"value of variable we are pointing to is : "<<*pNormal<<std::endl;
        
    double xSmart{5};
    std::unique_ptr<double> pSmart = std::make_unique<double>(xSmart);
    xSmart = 10;
    std::cout<<"value of variable we are pointing to through a smart pointer is : "<<*pSmart<<std::endl;
}

代码输出

value of variable we are pointing to is : 10
value of variable we are pointing to through a smart pointer is : 5

问题核心

普通指针double * pNormal = &xNormal指向原变量的内存地址,修改原变量后解引用指针能同步拿到新值;但用std::make_unique创建的unique_ptr却做不到,想知道这段普通指针代码的智能指针等价写法。

原因分析

你用std::make_unique<double>(xSmart)时,实际是在堆上分配了一块新内存,把xSmart的值拷贝进去,pSmart指向的是这块堆内存,和原变量xSmart是完全独立的两个内存区域,所以修改xSmart不会影响pSmart指向的值。

等价写法

如果要让unique_ptr和普通指针一样指向已存在的变量地址,需要自定义删除器(避免unique_ptr销毁时尝试释放栈内存,导致未定义行为),写法如下:

#include <iostream>
#include <memory>

int main()
{
    double xSmart{5};
    // 定义空删除器,什么都不做
    auto noop_deleter = [](double*) {};
    // 用自定义删除器构造unique_ptr,指向xSmart的地址
    std::unique_ptr<double, decltype(noop_deleter)> pSmart(&xSmart, noop_deleter);

    xSmart = 10;
    std::cout<<"value of variable we are pointing to through a smart pointer is : "<<*pSmart<<std::endl;
}

这段代码运行后会输出10,和普通指针的行为完全一致。

注意事项

这种用法并非智能指针的设计初衷,std::unique_ptr的核心作用是管理动态分配的堆内存,自动释放避免泄漏。如果只是要指向栈上已存在的变量,直接用普通指针更合适,没必要强行使用智能指针。

内容的提问来源于stack exchange,提问作者Novice_Developer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 13:32:17