为什么你可以初始化静态const变量inline而不是一个纯静态(C ++) [英] Why can you initialize a static const variable inline but not a plain static (C++)

查看:169
本文介绍了为什么你可以初始化静态const变量inline而不是一个纯静态(C ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样做

class Gone
{
    public:
    static const int a = 3;
}

它可以工作,但如果

class Gone
{
    public:
    static int a = 3;
}

它会产生编译错误。现在我知道为什么第二个不工作,我只是不知道为什么第一个做。

it gives a compile error. Now I know why the second one doesn't work, I just don't know why the first one does.

提前感谢。

推荐答案

此技巧仅适用于常量编译时表达式。考虑以下简单示例:

This trick works only for constant compile-time expressions. Consider the following simple example:

#include <iostream>

class Foo {
public:
    static const int bar = 0;
};

int main()
{
    std::cout << Foo::bar << endl;
}

它工作正常,因为编译器知道 Foo :: bar 为0,从不更改。

It works just fine, because compiler knows that Foo::bar is 0 and never changes. Thus, it optimizes the whole thing away.

但是,如果你取这个变量的地址,整个事情就会中断:

However, the whole thing breaks once you take the address of that variable like this:

int main()
{
    std::cout << Foo::bar << " (" << &Foo::bar << ")" << std::endl;
}

Linker发送修复程序,因为编译时常数地址。

Linker sends you to fix the program because compile-time constants don't have addresses.

现在,示例中的第二种情况不起作用,因为非常量变量不能是常量编译时表达式。因此,你必须在某个地方定义它,并且不能在初始化中赋值任何值。

Now, the second case in your example doesn't work simply because a non-constant variable cannot be a constant compile-time expression. Thus, you have to define it somewhere and cannot assign any values in initialization.

顺便说一下,C ++ 11有 constexpr 。您可以检查广义常数表达式 wiki(或C ++ 11标准: - ))了解更多信息。

C++11, by the way, has constexpr. You can check Generalized constant expressions wiki (or C++11 standard :-)) for more info.

此外,注意 - 使用某些工具链,您将永远无法链接程序,如第一个示例中所述,如果你从来没有采取这些变量的地址。我认为在Boost中有一个 BOOST_STATIC_CONSTANT 宏来解决这个问题(不知道如果它工作,因为我估计看到链接失败与一些旧的gcc甚至与该宏)。

Also, be careful - with some toolchains you will never be able to link program as listed in your first example when optimizations are turned off, even if you never take an address of those variables. I think there is a BOOST_STATIC_CONSTANT macro in Boost to work around this problem (not sure if it works though because I reckon seeing linkage failures with some old gcc even with that macro).

这篇关于为什么你可以初始化静态const变量inline而不是一个纯静态(C ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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