Question

I have a class that has a few int and a const int member with a constructor defined.

class SomeContainer
{
    public:
        SomeContainer():
            member1(0),
            member2(staticMethod())
        {}
    private:
         static int staticMethod();
         int member1;
         const int member2;
}

I need to create an assignment operator since I use this class in another class MainClass and code

MainClass* p1;
MainClass* p2
{
    //...
    *p1 = *p2 // fails since SomeContainer doesn't have copy assignment operator
}

Should this code be enough or am I missing anything?

{
    SomeContainer(const SomeContainer& other): // copy ctor
        member1(other.member1),
        member2(other.member2)
    {}


    SomeContainer& operator=(const SomeContainer& other)  // assignment operator
    {
      member1 = other.member1;
    }
}

what about move ctor and move assignment? Should I need to implement those as well?

Was it helpful?

Solution 2

What you have written is sufficient.

When no move constructor exists then the copy constructor will be used instead, and there's really no purpose in move semantics here.

OTHER TIPS

First of all if p1 and p2 are pointers then you can just assign them.

In case move constructor is not present then copy constructor will be used instead.

It remains for me hard to understand what is the logical meaning of allowing assignment on something that has constant non-static parts.

Just remove const from that member if you really need assignment

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top