简体   繁体   中英

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

We are all aware of the powerful functionality of the std::move function that is implemented in the C++ standard 11, where it moves the elements in a specific range into a new range.

I would like to know if I can develop such a functionality in pure C code. My code is written in C and I want to have something similar to the std::move function of C++, where I can move the range of integer elements into a new range without using a temporary buffer.

Regarding your text:

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

and:

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

I think the thing you're after is memmove . It's like memcpy but handles overlapping regions without issue.

For example, the following code moves (copies, really) elements from the range 3 through 6 (zero-based) to the range 2 through 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;
}

which basically does:

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

If you take a look to a possible implementation of std::move :

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

You'll see that std::move all it does is to static_cast its input argument to a rvalue reference. Thus, there's no "move" from std::move .

Now, the move mechanism in C++11 and beyond is based on rvalue references. C doesn't have even simple references. Consequently, it's nearly impossible to implement such a mechanism in C, since the basic facilities are absent.

In C you'll have to stick to moving around data via pointers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM