lundi 2 juillet 2018

replace existing object on the stack with default constructed one

I would like to know the best/correct way to get back to the initial values of an object without playing with delete and new (everything must stay on the stack)

With this 2 classes:

static const int defaultValue{15};
class Foo
{
  private: 
     int val1{defaultValue};
     short val2{4};
} 
class LongStandingObject
{
   public:
     void resetFoo(int index);
   private:
     Foo foos[100];
}

If I need to reset some foos to their default values, what is the best way?

  1. Create reset method in Foo

    void Foo::reset()
    {
       val1 = defaultValue;
       val2 = 4;
    }
    
    

    I don't really like the idea to have the values coming from 2 differents places and I do like to have the defaults values in the header next to the variable declaration.

  2. Replace by a locally created Foo

    void LongStandingObject::resetFoo(int index)
    {
       foos[index] = Foo();
    }
    
    

    Am I heading to trouble when the local variable is destroyed?

  3. Use memcpy

    void LongStandingObject::resetFoo(int index)
    {
       Foo foo;
       memcpy(foos[index], &foo, sizeof(Foo));
    }
    
    

    Maybe less readable...

  4. Any other method?

Aucun commentaire:

Enregistrer un commentaire