相关疑难解决方法(0)

为什么我们可以在`const`对象上使用`std :: move`?

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

struct Cat {
   Cat(){}
};

const Cat cat;
std::move(cat); //this is valid in C++11
Run Code Online (Sandbox Code Playgroud)

当我打电话时std::move,这意味着我想移动对象,即我将改变对象.移动const对象是不合理的,为什么不std::move限制这种行为呢?这将是未来的陷阱,对吧?

陷阱意味着布兰登在评论中提到:

"我认为他的意思是"偷偷摸摸"他鬼鬼祟祟偷偷摸摸,因为如果他没有意识到,他最终得到的副本并不是他想要的."

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

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;
};
Run Code Online (Sandbox Code Playgroud)

如果 …

c++ c++11

96
推荐指数
3
解决办法
2万
查看次数

标签 统计

c++ ×1

c++11 ×1