相关疑难解决方法(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万
查看次数

移动构造函数和std :: move混淆

我正在阅读有关std::move移动构造函数和移动赋值运算符的内容.说实话,我现在得到的只是困惑.现在我有一节课:

class A{
  public:
    int key;
    int value;
    A(){key = 3; value = 4;}
    //Simple move constructor
    A(A&& B){ A.key = std::move(B.key); 
              A.value = std::move(B.value);}
};
Run Code Online (Sandbox Code Playgroud)
  1. 我认为这B是一个右值参考,为什么你可以申请std::moveravlue参考的成员?
  2. 之后B.keyB.value已被移动,都已经失效,但如何B作为类的一个对象A被失效?
  3. 如果我有A a(A()),A()显然是一个rvlaue,可以A()被移动std::move,为什么?
  4. 同样,如果我有一个功能

    int add(int && z){ int x = std:move(z); int y = std:move(z); return x+y; }

如果我打电话add(5),怎么可以5移动,为什么?并且注意到z已经移动了两次,在z第一次移动之后,它已经失效,你怎么能再次移动它?

  1. 在定义foo (T …

c++ move rvalue-reference c++11

7
推荐指数
1
解决办法
4215
查看次数

标签 统计

c++ ×2

c++11 ×2

move ×1

rvalue-reference ×1