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



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

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

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方法,该方法不返回任何内容,并且被标记为返回字符串。

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

最新更新