可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have an object that cannot be copied, a NetGame because it has a stringstream in it.
I have it declared in my class as:
NetGame m_game;
Later in the code, I just want to reset it, which should not need to copy anything.
void ServerTable::setActive( bool active ) { //reset for now if(m_active && !active) { m_inProgress = false; m_game = NetGame(); } m_active = active; }
What can I do to do this without heap reallocation each time?
I could make it a pointer and simply new, delete each time but that shouldn't be necessary in this case. I'm not using polymorphism.
Thanks
回答1:
Disclaimer: I don't think the question makes much sense. You claim that the object has many fields that are not initialized in the constructor, and that in turn means that your code will not touch those fields... so the definition of reset does not seem to be precise.
At any rate, technically you can call the destructor and then construct in place:
m_game.~NetGame(); new (&m_game) NetGame();
Technically you don't even need to call the destructor if it does not have side effects or if the program does not depend on such side effects... but I would call the destructor anyway if you decide to follow this path.
But I urge you to reconsider the design and actually offer a reset()
member function that initializes all the members of NetGame
that need to be reset.
回答2:
You can just write a reset method for class NetGame.
void NetGame::reset() { /*u can just reset the attribute u need*/ }
Then you can invoke the method in the setAcitvity function.
void ServerTable::setActive( bool active ) { //reset for now if(m_active && !active) { m_inProgress = false; } m_active.reset(); }