c - 在 C 中 move 实现

标签 c macros initialization move

我正在尝试实现一个 move 函数,以便能够对 move 对象进行排序而不复制其内容。这就是我的意思:

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 扩展编写一个宏,但这似乎无法从中返回值:

#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

:-)

关于c - 在 C 中 move 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55429085/

相关文章:

c - 末尾显示随机字符的数组

c - 为什么这个程序的内存占用没有增加?

c++ - 在 C++ 中使用宏生成函数

c - 尝试通过 bash 脚本中的命令行传递预处理器指令

ios - 为什么在相似的代码片段中初始化的顺序不同。 swift 4

c++ - 分配数组与初始化指针

c - 确定基本算术计算最快的无符号整数类型

c - 按子字符串拆分字符串

macros - datum->syntax 和 define-syntax body 中的语法 #' 有什么区别?

c - 将整数数组初始化为成员