为什么我们可以在`const`对象上使用`std :: move`? [英] Why can we use `std::move` on a `const` object?

查看:928
本文介绍了为什么我们可以在`const`对象上使用`std :: move`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++ 11中,我们可以编写以下代码:

In C++11, we can write this code:

struct Cat {
   Cat(){}
};

const Cat cat;
std::move(cat); //this is valid in C++11



< :move ,这意味着我想移动对象,即我将更改对象。要移动 const 对象是不合理的,为什么 std :: move 不限制此行为?

when I call std::move, it means I want to move the object, i.e. I will change the object. To move a const object is unreasonable, so why does std::move not restrict this behaviour? It will be a trap in the future, right?

这里trap意味着布兰登在评论中提到的:

Here trap means as Brandon mentioned in the comment:


我认为他的意思是陷阱他鬼鬼祟祟地偷偷摸摸,因为如果他不
意识到,他最终得到一个不是他想要的副本。

" I think he means it "traps" him sneaky sneaky because if he doesn't realize, he ends up with a copy which is not what he intended."

在Scott Meyers的书Effective Modern C ++中,他举了一个例子:

In the book 'Effective Modern C++' by Scott Meyers, he gives an example:

class Annotation {
public:
    explicit Annotation(const std::string text)
     : value(std::move(text)) //here we want to call string(string&&),
                              //but because text is const, 
                              //the return type of std::move(text) is const std::string&&
                              //so we actually called string(const string&)
                              //it is a bug which is very hard to find out
private:
    std::string value;
};

如果 std :: move 操作在 const 对象上,我们可以很容易地找到错误,对吧?

If std::move was forbidden from operating on a const object, we could easily find out the bug, right?

推荐答案

struct strange {
  mutable size_t count = 0;
  strange( strange const&& o ):count(o.count) { o.count = 0; }
};

const strange s;
strange s2 = std::move(s);

这里我们看到使用 std :: move T const 。它返回一个 T const&& 。我们有 strange 的移动构造函数,它正好是这种类型。

here we see a use of std::move on a T const. It returns a T const&&. We have a move constructor for strange that takes exactly this type.

它被调用。

现在,这个奇怪的类型比你的建议修复的bug更为罕见。

Now, it is true that this strange type is more rare than the bugs your proposal would fix.

但是,在另一方面,现有的 std :: move 在通用代码中工作得更好,其中你不知道你正在使用的类型是 T T const

But, on the other hand, the existing std::move works better in generic code, where you don't know if the type you are working with is a T or a T const.

这篇关于为什么我们可以在`const`对象上使用`std :: move`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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