Reputation: 351
Below is a chunk of code how i implemented a linked list to traverse with the currentElem Pointer through my Game-Options. This code is working well. However, just for testing purposes i wrote to a LogFile from the destructor of the OptionElem-Class so i could count how many OptionElem objects have been instantiated all together. There are 9 Entrys in the Logfile. So 9 Objects have been instantiated and destroyed. I expected only 3 objects (e1, e2 and e3), because i instantiated them once in the GameState constructor and then moved them to the optionElems-vector. I dont understand where the other 6 OptionElem objects have been instantiated.
#include "OptionElem.h"
#include <vector>
class GameState
{
std::vector<OptionElem> optionElems;
OptionElem* currentElem;
public:
GameState();
};
GameState::GameState()
{
OptionElem e1("Start Game");
optionElems.push_back(std::move(e1));
OptionElem e2("Options");
optionElems.push_back(std::move(e2));
OptionElem e3("Exit");
optionElems.push_back(std::move(e3));
optionElems[0].Connect(optionElems[1]);
optionElems[1].Connect(optionElems[2]);
currentElem = &optionElems[0];
}
Edit: I changed the lines
OptionElem e1("Start Game");
optionElems.push_back(std::move(e1));
to:
optionElems.emplace_back("Start Game");
and did the same change to the similar code below as suggested by sftrabbit and the Logfile changed to 3 entries, so only 3 OptionElem objects gets instantiated when using the emplace_back method instead moving the local variables to the vector. I consider this as more efficient since less objects get instantiated for the same operation (adding them to a vector)
Upvotes: 1
Views: 329
Reputation: 110658
Moving an object doesn't make that object magically disappear. It just steals the contents of the object (if the move constructor is implemented properly, that is) to put in the new object. The original object still exists and should eventually be destroyed, and each move still involves the construction of another object which will also eventually be destroyed.
Perhaps it's a problem with the word "move". It doesn't really involve moving the object in memory - what it really involves is moving the contents of the object to the new object.
Anyway, you might be interested in the emplace_back
function which constructs vector elements in place:
optionElems.emplace_back("Start Game");
optionElems.emplace_back("Options");
optionElems.emplace_back("Exit");
Or even just initialising your std::vector
like so:
std::vector<OptionElem> optionElems = {"Start Game", "Options", "Exit"};
A brief note on naming conventions: calling a collection somethingElems
is putting information about the type in the name. You could just call it options
and it's obvious that it has elements because it's plural (without saying Elems
). Then currentElem
would be called currentOption
, which is much more understandable, right?
Upvotes: 8