Grapes
Grapes

Reputation: 2563

C++ - Combining Copy/Move operators and constructors

As it stands right now, I have a class with the following structure:

struct FooClass {

    FooClass();
    FooClass(int CustomIndex);
    FooClass(const FooClass& CopyConstructor);
    FooClass(FooClass&& MoveConstructor);

    FooClass& operator=(const FooClass& CopyAssignment);
    FooClass& operator=(FooClass&& MoveAssignment);
};

Is there any way for me to combine the copy/move operators so that they don't need to be provided in the first place and copy/move constructors would be called instead?

if not, is it at least possible for me to call the copy/move constructor from the copy/move operator?

Essentially, I want:

FooClass(const FooClass& CopyConstructor) to equal to FooClass& operator=(const FooClass& CopyAssignment)

and

FooClass(FooClass&& MoveConstructor) to equal to FooClass& operator=(FooClass&& MoveAssignment)

Upvotes: 0

Views: 590

Answers (2)

Daniel Frey
Daniel Frey

Reputation: 56863

You mean like

FooClass& operator=(FooClass rhs)
{
    swap(rhs);
    return *this;
}

where rhs is constructed with either the copy- or the move-constructor? (Given you provide swap, which is a good idea in general)


After you updated the question, maybe this works for you:

FooClass(const FooClass& CopyConstructor)
{
    *this = CopyConstructor;
}

FooClass(FooClass&& MoveConstructor)
{
    *this = std::move(MoveConstructor);
}

Upvotes: 3

Sorin
Sorin

Reputation: 11968

If your class is trivial (you only have primitive types and STL objects) very likely the default implementation just works. Don't bother writing these down, they will be there by default. The copy and move will be done member by member using the respective copy move constructors.

If you have something special inside (some unmovable class for example) then you need to define these, but you can still delegate the implementation to one another or to another method.

Upvotes: 0

Related Questions