[ad_1]
I’m having an issue with some code I have written in C++. I have created two classes MyClass and Server. MyClass has member called list of type std::vector<std::string>. The Server class has a method called RegisterRoute which is used to bind a callback method to a string (API route) and adds the binding to a std::map member called routemap. When the server receives a request, it looks up the path in the request url and calls the corresponding function that has been bound.
I instantiate instances of MyClass and Server called MyClass::MyObject and Server::MyServer in my main program, I bind a callback lambda to a route using MyServer.RegisterRoute(). In this lambda I pass MyObject to the lambda by reference, and I call a method that adds and item to the std::vector<>. The issue is that out side of the scope of the lambda, the object does not seem to be modified. Hence each time I call the route, the list seems to be unaffected by previous lambda calls. The form of the lambda is as shown below.
[&MyObject](std::string item)
MyObject.addItem(item);
MyObject.showList();
If I call the MyObject.showlist() method in the lambda after the MyObject.addItem(), the list is shown as modified. However, when I hit a route to show the list (which calls the MyObject.showlist()), it shows the original list created when the object before the last addItem route was called. Also If I call the addItem method outside the lambda, the list is modified.
int main()
MyClass MyObject(“new list”); //Constructor to take string and add it to std::vector<std::string> list
Server MyServer(4564); //Constructor to create server and bind port to socket
MyServer.RegisterRoute(“/additem”,[&MyObject](std::string item)
MyObject.addItem(item);
MyObject.show();
return “added”;
);
MyObject.addItem("Dummy Item"); //This item is seen in the list when show list calls
MyServer.StartServer();
return 0;
I thought that passing the object by reference would allow the modifications made in the lambda to affect the original object,Can someone advise on what I am maybe missing?
[ad_2]
لینک منبع