【问题标题】:C++ modifying Object data constructed with stack argumentsC ++修改使用堆栈参数构造的对象数据
【发布时间】: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


【解决方案1】:

你需要修复你的 setName 方法,它没有返回任何东西并且被标记为返回一个字符串。

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

【讨论】:

  • 一个小代码 sn-p 显示如何返回所需的字符串将使这成为一个更好的答案(尽管它已经是正确的)。
  • @Pablo Yaggi 你就是男人!有时候,除了一双新鲜的眼睛,别无帮助!愿上帝保佑你。
猜你喜欢
  • 2013-11-07
  • 1970-01-01
  • 2021-01-30
  • 1970-01-01
  • 2021-03-02
  • 1970-01-01
  • 2013-04-29
  • 2011-03-26
  • 2016-03-02
相关资源
最近更新 更多