如何确保constexpr函数从未在运行时调用? [英] How to ensure constexpr function never called at runtime?

查看:184
本文介绍了如何确保constexpr函数从未在运行时调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您有一个函数为您的应用程序生成一些安全令牌,例如一些哈希盐,或者一个对称或不对称的键。

Lets say that you have a function which generates some security token for your application, such as some hash salt, or maybe a symetric or asymetric key.

现在让说你在你的C ++中有这个函数作为一个constexpr,并根据一些信息(例如,内部版本号,时间戳,别的东西)生成你的构建的密钥。

Now lets say that you have this function in your C++ as a constexpr and that you generate keys for your build based on some information (like, the build number, a timestamp, something else).

你是一个勤奋的程序员,确保并以适当的方式调用它,以确保它只在编译时被调用,因此死去除器从最终可执行文件中删除代码。

You being a diligent programmer make sure and call this in the appropriate ways to ensure it's only called at compile time, and thus the dead stripper removes the code from the final executable.

但是,你永远不能确定别人不会以不安全的方式调用它,或者编译器不会删除该函数,然后你的安全令牌算法将被公开知识,使得攻击者更容易猜出未来的令牌。

However, you can't ever be sure that someone else isn't going to call it in an unsafe way, or that maybe the compiler won't strip the function out, and then your security token algorithm will become public knowledge, making it more easy for would be attackers to guess future tokens.

或者说,安全放在一边,让我们说这个函数需要很长时间才能执行,确保它在运行时不会发生,并为最终用户带来不良的用户体验。

Or, security aside, let's say the function takes a long time to execute and you want to make sure it never happens during runtime and causes a bad user experience for your end users.

有什么方法可以确保constexpr函数永远不会在运行时被调用?或者,在运行时抛出一个断言或类似的东西将是确定的,但不是那么理想,显然是一个编译错误。

Are there any ways to ensure that a constexpr function can never be called at runtime? Or alternately, throwing an assert or similar at runtime would be ok, but not as ideal obviously as a compile error would be.

我听说有一些方法涉及抛出一个不存在的异常类型,所以如果constexpr函数没有死机,你会得到一个链接器错误,但听说这只适用于一些编译器。

I've heard that there is some way involving throwing an exception type that doesn't exist, so that if the constexpr function is not deadstripped out, you'll get a linker error, but have heard that this only works on some compilers.

与之相关的问题:强制constexpre在编译时间

推荐答案

您可以强制在常量表达式中使用它:

You can force the use of it in a constant expression:

#include<utility>

template<typename T, T V>
constexpr auto ct() { return V; }

template<typename T>
constexpr auto func() {
    return ct<decltype(std::declval<T>().value()), T{}.value()>();
}

template<typename T>
struct S {
    constexpr S() {}
    constexpr T value() { return T{}; }
};

template<typename T>
struct U {
    U() {}
    T value() { return T{}; }
};

int main() {
    func<S<int>>();
    // won't work
    //func<U<int>>();
}

通过使用函数的结果作为模板参数,如果它不能在编译时解决。

By using the result of the function as a template argument, you got an error if it can't be solved at compile-time.

这篇关于如何确保constexpr函数从未在运行时调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆