将变量地址重新解释为联合地址是否安全?

问题描述

以下是否定义明确(即不回复未定义或实现定义的行为)?

header.hpp:

#pragma once

union union_type { 
  char   c; 
  // many member types...
  double d[4]; 
}; 

static_assert(alignof(union_type) != alignof(char));

int func1(char & arg1);
int func2(union_type & arg2);
int func3(void * arg3,bool arg3_is_char);

func1.cpp

int func1(char & arg1) {
  // perform some operation with arg1,might modify it
}

func2.cpp

#include “header.hpp”
int func2(union_type & arg2) {
  return func1(arg2.c);
} 

func3.cpp

#include “header.hpp”
int func3(void * arg3,bool arg3_is_a_char) {
  if (arg3_is_a_char && arg3) {

    // does the following cast rely on undefined 
    // or implementation defined behavIoUr?
    auto * ptr = reinterpret_cast<union_type *>(arg3);

    return func2(*ptr);
  }
  return 0;
}

根据经验,上面的代码似乎按预期工作(不管 arg3 指向的内存的底层对齐如何)。也就是说,即使 arg3 指向的地址没有合适的对齐方式。

我担心这依赖于带下划线的行为,未来的一些优化可能会假设 arg2 的有效地址可以是什么,然后使用 union_type:: 的不同地址: c

编辑: 对于那些对此问题的背景感兴趣的人,union_typevoid* 表示来自不公开任何 STL 类型的公共 API 的输出参数。然后有两种类型的访问器,它们继续增长和分化。能够将 void** 转换为 union_type 将允许移除一半的包装器。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)