相关疑难解决方法(0)

什么是复制和交换习语?

这个成语是什么,什么时候应该使用?它解决了哪些问题?当使用C++ 11时,成语是否会改变?

虽然在许多地方已经提到过,但我们没有任何单一的"它是什么"问题和答案,所以在这里.以下是前面提到的地方的部分列表:

c++ c++-faq copy-constructor assignment-operator copy-and-swap

1907
推荐指数
5
解决办法
34万
查看次数

最佳C++移动构造函数实现实践

我试图理解move-constructor的实现.我们都知道如果我们需要管理C++类中的资源,我们需要实现五阶规则(C++编程).

微软给我们举了一个例子:https://msdn.microsoft.com/en-us/library/dd293665.aspx

这是更好的一个,它使用copy-swap来避免代码重复: 动态分配一个对象数组

     // C++11
     A(A&& src) noexcept
         : mSize(0)
         , mArray(NULL)
     {
         // Can we write src.swap(*this);
         // or (*this).swap(src);
         (*this) = std::move(src); // Implements in terms of assignment
     }
Run Code Online (Sandbox Code Playgroud)

在move-constructor中,直接:

         // Can we write src.swap(*this);
         // or (*this).swap(src);
Run Code Online (Sandbox Code Playgroud)

因为我觉得(*this) = std::move(src)有点复杂.因为如果我们(*this) = src无意中写,它会调用普通赋值运算符而不是move-assignment-operator.

除了这个问题,在微软的例子中,他们编写了这样的代码:在move-assignment-operator中,我们是否需要检查自我赋值?有可能发生吗?

// Move assignment operator.
MemoryBlock& operator=(MemoryBlock&& other)
{
   std::cout << "In operator=(MemoryBlock&&). length = " 
             << other._length << "." << std::endl;

   if (this != &other)
   { …
Run Code Online (Sandbox Code Playgroud)

c++ move move-constructor c++11

4
推荐指数
2
解决办法
2477
查看次数