Reset an object without invoking copy constructor?

后端 未结 2 1363
南方客
南方客 2021-01-23 11:23

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;
2条回答
  •  南方客
    南方客 (楼主)
    2021-01-23 12:04

    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.

提交回复
热议问题