Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap method with const members

I want to implement a Swap() method for my class (let's call it A) to make copy-and-swap operator=(). As far as I know, swap method should be implemented by swapping all members of the class, for example:

class A 
{
  public:
    void swap(A& rhv) 
    {
        std::swap(x, rhv.x);
        std::swap(y, rhv.y);
        std::swap(z, rhv.z);
    }
  private:
    int x,y,z;
};

But what should I do if I have a const member? I can't call std::swap for it, so I can't code A::Swap().

EDIT: Actually my class is little bit more complicated. I want to Serialize and Deserialize it. Const member is a piece of data that won't change (its ID for example) within this object. So I was thinking of writing something like:

class A
{
  public:
    void Serialize(FILE* file) const
    {
        fwrite(&read_a, 1, sizeof(read_a), file);
    }

    void Deserialize(FILE* file) const
    {
        size_t read_a;
        fread(&read_a, 1, sizeof(read_a), file);
        A tmp(read_a);
        this->Swap(tmp);
    }

 private:
   const size_t a;
};

and call this code:

A a;
FILE* f = fopen(...);
a.Deserialize(f);

I'm sorry for such vague wording.

like image 624
f0b0s Avatar asked Feb 05 '10 21:02

f0b0s


2 Answers

I think what you really want is to have an internal data structure that you can easily exchange between objects. For example:

class A 
{
   private:

     struct A_Data {
       int x;
       int y;
       const int z;

       A_Data(int initial_z) : z(initial_z) {}
    };

    std::auto_ptr<A_Data> p_data;

  public:

     A(int initial_z) : p_data(new A_Data(initial_z)) {}

     void swap(A& rhv) {
        std::swap(p_data, rhv.p_data);
     }
};

This keeps the z value constant within any instance of A object internal data, but you can swap the internal data of two A objects (including the constant z value) without violating const-correctness.

like image 179
Tyler McHenry Avatar answered Nov 08 '22 03:11

Tyler McHenry


After a good nights sleep I think the best answer is to use a a non-const pointer to a const value -- after all these are the semantics you are trying to capture.

like image 34
Hassan Syed Avatar answered Nov 08 '22 04:11

Hassan Syed