为什么编译器不对同一翻译单元中的 ODR 违规发出警告

2024-05-27

在同一个翻译单元中,ODR 问题很容易诊断。那么为什么编译器不会针对同一翻译单元中的 ODR 违规发出警告呢?

例如在下面的代码中https://wandbox.org/permlink/I0iyGdyw9ynRgny6 https://wandbox.org/permlink/I0iyGdyw9ynRgny6(转载如下),检测是否存在 ODR 违规std::tuple_size已被定义。此外,当您取消注释定义时,未定义的行为是显而易见的three and four。程序的输出发生变化。

只是想了解为什么 ODR 违规行为如此难以发现/诊断/可怕。


#include <cstdint>
#include <cstddef>
#include <tuple>
#include <iostream>

class Something {
public:
    int a;
};

namespace {
template <typename IncompleteType, typename = std::enable_if_t<true>>
struct DetermineComplete {
    static constexpr const bool value = false;
};

template <typename IncompleteType>
struct DetermineComplete<
        IncompleteType,
        std::enable_if_t<sizeof(IncompleteType) == sizeof(IncompleteType)>> {
    static constexpr const bool value = true;
};

template <std::size_t X, typename T>
class IsTupleSizeDefined {
public:
    static constexpr std::size_t value =
        DetermineComplete<std::tuple_size<T>>::value;
};
} // namespace <anonymous>

namespace std {
template <>
class tuple_size<Something>;
} // namespace std

constexpr auto one = IsTupleSizeDefined<1, Something>{};
// constexpr auto three = IsTupleSizeDefined<1, Something>::value;

namespace std {
template <>
class tuple_size<Something> : std::integral_constant<int, 1> {};
} // namespace std

constexpr auto two = IsTupleSizeDefined<1, Something>{};
// constexpr auto four = IsTupleSizeDefined<1, Something>::value;

int main() {
    std::cout << decltype(one)::value << std::endl;
    std::cout << decltype(two)::value << std::endl;
}

为了使模板编译速度更快,编译器会记住它们。

因为 ODR 保证模板的全名及其参数完全定义了它的含义,所以一旦实例化模板并生成“它是什么”,您就可以将表从其名称(包含所有命名的参数)存储到“它是什么”是”。

下次您向模板传递其参数时,它不会尝试再次实例化它,而是在记忆表中查找它。如果找到,它会跳过所有这些工作。

为了执行您想要的操作,编译器必须放弃此优化并重新实例化模板每次你传递了它的参数。这可能会导致构建时间大幅减慢。

在你的玩具代码中,也许不是,但在真实的项目中,你可能拥有数千个独特的模板和数十亿个模板实例化,记忆化可以将模板实例化时间减少一百万倍。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么编译器不对同一翻译单元中的 ODR 违规发出警告 的相关文章

随机推荐