문제

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?

도움이 되었습니까?

해결책 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.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top