提问者:小点点

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)   

共1个答案

匿名用户

您需要修复您的setName方法,它不返回任何内容,并且标记为返回字符串。

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

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|修|改用|堆栈|参数|构造|对象|数据)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?