Reset an object without invoking copy constructor?

匿名 (未验证) 提交于 2019-12-03 02:38:01

问题:

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(); }


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!