在 C 中移动实现

Move implementation in C

我正在尝试实现一个移动功能,以便能够在不复制对象内容的情况下对移动对象进行排序。这就是我的意思:

static void foo(const char* moved_content){
   //use moved_content
}

const char *string = //...
foo(string);
string = NULL;

所以在我将 string 传递给 foo 之后,没有其他人可以访问该字符串。我认为这将使非法访问的调试更加容易,因为例如在 Linux 我最有可能收到 SEGV

我尝试了以下方法:

static inline void* move(void **ptr){
    void *tmp = *ptr;
    *ptr = NULL;
    return tmp;
}

但是我不能像这样使用它

const char *str = "string";
const char *moved = (char*) (move((void **)&str)); //this is non-conforming

我尝试使用 gcc 扩展编写一个宏,但这似乎无法从中 return 一个值:

#define MOVE(ptr) \
    do { \
        __typeof__(ptr) original_ptr = ptr; \
        __typeof__(*original_ptr) tmp = *original_ptr; \
        *ptr = NULL; \
    } while(0)

有没有办法统一实施?可能 _Generic 是一种方法......或者明确地将指针设置为 NULL 不是那么糟糕吗?

看来您愿意使用 C 语言的扩展,您的第二种方法就快完成了,只是您需要更进一步,将其设为 "Statement Expression":

#define MOVE_AND_CLEAN(p) ( \
  { \
    __typeof__(p) p_tmp = p; \
    p = NULL; \
    p_tmp; \
  } \
)

这样使用:

#include <stdio.h>

int main(void)
{
  const char * ps = "string";
  const char * pd = MOVE_AND_CLEAN(ps); 

  printf("ps = %p\npd = %p\n", (void*)ps, (void*)pd);
}

并得到:

ps = 0x0
pd = 0x123456789

:-)