c++ - 此代码是否违反一个定义规则?

标签 c++ one-definition-rule

AOSP10中的某些代码似乎违反了ODR:

来源1:

struct ExtentsParam
{
  void init (const OT::cff1::accelerator_t *_cff)
  {
    path_open = false;
    cff = _cff;
    bounds.init ();
  }
  void start_path ()         { path_open = true; }
  void end_path ()           { path_open = false; }
  bool is_path_open () const { return path_open; }
  bool    path_open;
  Bounds  bounds;
  const OT::cff1::accelerator_t *cff;
};

从:
https://android.googlesource.com/platform/external/harfbuzz_ng/+/refs/heads/android10-gsi/src/hb-ot-cff1-table.cc

来源2:
struct ExtentsParam
{
  void init ()
  {
    path_open = false;
    min_x.set_int (0x7FFFFFFF);
    min_y.set_int (0x7FFFFFFF);
    max_x.set_int (-0x80000000);
    max_y.set_int (-0x80000000);
  }
  void start_path ()         { path_open = true; }
  void end_path ()           { path_open = false; }
  bool is_path_open () const { return path_open; }
  void update_bounds (const Point &pt)
  {
    if (pt.x < min_x) min_x = pt.x;
    if (pt.x > max_x) max_x = pt.x;
    if (pt.y < min_y) min_y = pt.y;
    if (pt.y > max_y) max_y = pt.y;
  }
  bool  path_open;
  Number min_x;
  Number min_y;
  Number max_x;
  Number max_y;
};

从:
https://android.googlesource.com/platform/external/harfbuzz_ng/+/refs/heads/android10-gsi/src/hb-ot-cff2-table.cc

构建脚本:
...
srcs: [
    ...
    "src/hb-ot-cff1-table.cc",
    "src/hb-ot-cff2-table.cc",
],
...

https://android.googlesource.com/platform/external/harfbuzz_ng/+/refs/heads/android10-gsi/Android.bp

这些资源也内置在同一共享库中。两种来源都有“struct ExtentsParam”的定义,内容绝对不同。这两个结构似乎仅在本地使用。

这两个来源具有相似的名称,因此,非故意的名称重复的机会很小。而且Google违反ODR的机会可能很小。

可以?

最佳答案

:因为它们都在全局 namespace 中,所以这绝对违反了ODR。

只有在定义它们的翻译单元内使用的类类型才有豁免。一个程序只能包含一个具有任何给定名称的类类型。

它是满足免除此规则的标准的第一个要求:

There can be more than one definition of a [..] class type [..] in a program provided that each definition appears in a different translation unit, and provided the definitions satisfy the following requirements. [..] Given such an entity named D defined in more than one translation unit, all of the following requirements shall be satisfied. [..] Each definition of D shall consist of the same sequence of tokens [..] (ref)



开发人员只是“很幸运”,链接器没有尝试做任何导致这种违规症状的滑稽 Action 。

这就是 namespace 的用途。例如,如果类类型仅在定义它的转换单元中使用,则它可能已经在匿名 namespace 中定义了。

关于c++ - 此代码是否违反一个定义规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60376420/

相关文章:

c++ - Qt ActiveX 动态调用 : bad parameter count

java - 不同语言的内存管理是否足够相似以转移我的知识?

c++ - 如果变量和函数在头文件中声明为内联,那么包含保护是否多余?

c++ - 访问 GL_DEPTH_COMPONENT 纹理

c++ - 两个源文件之间的变量(类和全局)

c++ - C++ 模块是否不存在 ODR 违规?

c++ - MSVC 中的 ODR 错误?

c++ - 为什么将 set::iterator 而不是 const_iterator 传递给函数会违反单一定义规则?

c++ - 不纯就用虚成员函数?

c++ - 命令提示符 "runas user:<admin-user> <command>"未正确执行