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

如何在C++中将const结构体指针传递给setter方法

错误原因

  • setContainer方法要求的入参类型是const Container *(指向Container结构体的const指针),你调用时直接传入了container2栈对象实例,类型不匹配因此触发编译报错。

解决方案

方案1:C++14 智能指针实现(优先推荐)

使用std::make_unique创建独占智能指针管理结构体实例,调用智能指针的get()方法获取原生指针传入setter即可,修改后的完整代码如下:

#include <iostream>
#include <memory>

class Class // Class definition
{
public:
    struct Container    // Container definition
    {
        double value = 0.0;
    };

    Class() { } // constructor
    ~Class() { } // destructor

    void setContainer(const Container * pContainer)
    {   
        mContainer = *pContainer; // setter
    }

    const Class::Container & getContainer() const
    {
        return mContainer; // getter
    }

private:
    Container mContainer;
};

int main()
{    
    Class objClass; 

    const auto container1 = objClass.getContainer();
    std::cout << "container1.value: " << container1.value << std::endl; 
    
    // 用unique_ptr管理Container实例
    auto container2 = std::make_unique<Class::Container>();
    container2->value = 5.0; 

    std::cout << "container2.value: " << container2->value << std::endl; 
    
    // 调用get()获取智能指针管理的原生指针传入
    objClass.setContainer(container2.get()); 
    
    const auto container3 = objClass.getContainer();
    std::cout << "container3.value: " << container3.value << std::endl; 

    return 0;
}

说明:setContainer内部仅拷贝指针指向的结构体内容,不会持有传入的指针、也不会操作指针指向的内存生命周期,因此用智能指针管理结构体完全安全,不会出现内存泄漏、野指针问题。

方案2:原生指针极简实现

如果不需要使用智能指针,直接对栈上的container2对象取地址传入即可,仅需修改调用setContainer的一行代码:

objClass.setContainer(&container2);

两种方案运行后均可得到期望输出container3.value: 5.0。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:57:03