移动POD-ish类型的语义 [英] Move Semantics for POD-ish types

查看:103
本文介绍了移动POD-ish类型的语义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一点为仅包含基本类型的结构或类实现了一个移动构造函数和一个移动赋值运算符?例如,

Is there any point implementing a move constructor and move assignment operator for a struct or class that contains only primitive types? For instance,

struct Foo
{
    float x;
    float y;
    float z;

    /// ... ctor, copy ctor, assignment overload, etc...


};

我可以看到,如果我有更复杂的东西,例如:

I can see that, if I had something more complex, like:

struct Bar
{
    float x,y,z;
    std::string Name;
};  

我宁愿移动Name而不是复制它,移动ctor还是有道理的.但是,移动"浮动对我而言(看来)是没有意义的.

where I'd rather move Name than copy it, a move ctor would make sense. However, "moving" a float doesn't (semantically) make sense to me.

有想法吗?

推荐答案

即使您具有该std::string成员,也没有必要实现move构造函数.隐式move构造函数将已经移动了每个成员,在float的情况下,将仅复制它,而在std::string的情况下,将其移动.

Even if you have that std::string member, it doesn't make sense to implement a move constructor. The implicit move constructor will already move each of the members, which in the case of float will just copy it, and in the case of std::string will move it.

仅在类正在执行其自己的某些内存管理时才真正需要提供move构造函数.也就是说,如果要在构造函数中分配内存,则需要在移动过程中将指针转移到已分配的内存中.参见五人制.

You should only really need to provide a move constructor when your class is doing some of its own memory management. That is, if you're allocating memory in the constructor, then you'll want to transfer the pointer to that allocated memory during a move. See the Rule of Five.

如果您始终依靠智能指针为您处理分配的内存,则可以完全避免这种情况.参见零规则.

It's possible to avoid this situation entirely if you always rely on smart pointers to handle your allocated memory for you. See the Rule of Zero.

这篇关于移动POD-ish类型的语义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆