简体   繁体   English

C ++-组合复制/移动运算符和构造函数

[英]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) FooClass(const FooClass& CopyConstructor)等于FooClass& operator=(const FooClass& CopyAssignment)

and

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

You mean like 你的意思是像

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

where rhs is constructed with either the copy- or the move-constructor? rhs是用复制构造器还是移动构造器构造的? (Given you provide swap , which is a good idea in general) (鉴于您提供swap ,这通常是个好主意)


After you updated the question, maybe this works for you: 更新问题后,也许这对您有用:

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

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

If your class is trivial (you only have primitive types and STL objects) very likely the default implementation just works. 如果您的类很琐碎(只有原始类型和STL对象),则默认实现很可能起作用。 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. 如果内部有一些特殊的东西(例如,一些不可移动的类),则需要定义它们,但仍可以将实现委派给另一个或另一个方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM