【发布时间】:2020-11-08 20:48:33
【问题描述】:
伙计们,我似乎无法对存储在向量中的容器对象成员进行简单修改。该成员本身就是一个对象。容器及其成员都在堆栈上分配。我认为它在分配新设备时试图释放设备原始名称的堆栈变量。
请告诉我如何在保持变量分配在堆栈上的同时解决此问题。
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)
【问题讨论】:
-
你读过警告了吗:prog.cpp:x:y: warning: no return statement in function return non-void [-Wreturn-type]
标签: c++ vector stack allocation