A base class has a protected shared_ptr member var_
which is used as a local variable, the pointing type is a very complex struct. Now I have a derived class, it needs to iteratively modify *var_
, but at the beginning of each iteration, I want *var_
is exactly the same as I called the constructor of derived class. I can only call the derived class constructor once in the main function.
So the question is, how can I reset this *var_
for each iteration, such that the modification in the previous iteration won't impact the following iterations. Now I can only make the iteration for just one time, since I'm using pass by reference, in the second iteration, I don't know how to reset it, so some overlying modification crashes the program.
I've tried pass by value simply. But I have to use lots of helper maps, which are located in the base class, for writing my derived class functions. Every time I use them, the generated data is associated with *var
, but not the copied object in my derived class.
Please note I can't modify the base class too much, like converting the local member to member function parameters, etc.
If the local member variable is a simple container, like std::vector, I can simply reset it at the beginning of each iteration, and fill it inside the iteration later. I want the shared_ptr var_
does the similar thing, or even better, make a "true" copy of it, since it's relatively big, and generating it needs some time, such that I can use the original one in each iteration, can I ?
You want a virtual clone()
method. In general, if you have a Base
pointer and don't know the actual derived class, you can only create a new Base
object (slicing). The clone
pattern requires cooperation from each derived class, because they do know their own identities. Still, that's just a matter of doing return new Derived(*this)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.