C++ 标准 11 在 C 中实现的 std::move 函数

An std::move function of C++ standard 11 implementation in C

我们都知道 C++ 标准 11 中实现的 std::move 函数的强大功能,它将特定范围内的元素移动到新的范围内。

我想知道我是否可以用纯 C 代码开发这样的功能。我的代码是用 C 编写的,我希望有一些类似于 C++ 的 std::move 函数的东西,我可以在其中将整数元素的范围移动到一个新的范围而无需使用临时缓冲区。

关于您的文字:

... moves the elements in a specific range into a new range.

和:

... where I can move a range of integer elements into a new range without using a temporary buffer.

我想你想要的是memmove。它类似于 memcpy,但可以毫无问题地处理重叠区域。

例如,以下代码将元素从范围 3 到 6(从零开始)移动(实际上复制)到范围 2 到 5:

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[]) {
    int xyzzy[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    memmove (&(xyzzy[2]), &(xyzzy[3]), sizeof(*xyzzy) * 4);
    printf ("{ %d", xyzzy[0]);
    for (int i = 1; i < sizeof(xyzzy) / sizeof(*xyzzy); i++)
        printf (", %d", xyzzy[i]);
    printf (" }\n");

    return 0;
}

这基本上是:

 {0 1 2 3 4 5 6 7 8 9}
        | | | |
       / / / /
      | | | |
      V V V V
 {0 1 3 4 5 6 6 7 8 9}

如果您查看 std::move 的可能实现:

template <typename T>
typename remove_reference<T>::type&& move(T&& arg) {
  return static_cast<typename remove_reference<T>::type&&>(arg);
}

您会看到 std::move 它所做的只是 static_cast 它的输入参数为右值引用。因此,std::move.

中没有 "move"

现在,C++11 及更高版本中的移动机制基于右值引用。 C 甚至没有简单的引用。因此,在 C 中实现这样的机制几乎是不可能的,因为基本设施不存在。

在 C 中,您必须坚持通过指针移动数据。