C ++修改使用堆栈参数构造的对象数据

C++ modifying Object data constructed with stack arguments

伙计们,我似乎无法对存储在向量中的容器对象成员进行简单修改。该成员本身就是一个对象。容器及其成员都分配在堆栈上。我认为它正在尝试在分配新设备时释放设备原始名称的堆栈变量。

请告诉我如何解决这个问题,同时保持变量在堆栈上的分配。

class Device{
    public:
        Device(string name):m_name(name)
        {}
        string getName(){
            return m_name;
        }
        string setName(string  newName){
            m_name = newName;
        }
        
    private:
        string m_name;
         
};

然后有一个包含设备的服务器:

class Server
{
    public:
        Device & getDevice(int i)
        {
            return devices.at(i);
        }
        void addDevice(Device && dev)
        {
            devices.push_back(dev);
        }
    private:
        vector<Device> devices;
};

我是这样测试的:

int main()
{
    Server s{};
    
    s.addDevice(Device{"ONE"});
    s.addDevice(Device{"TWO"});
    s.addDevice(Device{"THREE"});
    
    cout<<s.getDevice(0).getName()<<endl;
    s.getDevice(0).setName("XXX");
    cout<<s.getDevice(0).getName()<<endl;
    return 0;
}

我要说的是:

ONE                                                                                                                                           
                                                                                                                                              
*** Error in `./a.out': double free or corruption (fasttop): 0x0000000000617c20 ***                                                           
Aborted (core dumped)   

您需要修正您的 setName 方法,没有 returning 任何东西并且被标记为 return 一个字符串。

string setName(string  newName)
{
     m_name = newName;
     return m_name; //this is missing in the original code
}