gpt4 book ai didi

c++ - 包含在许多翻译单元中时静态常量的开销?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:37:09 25 4
gpt4 key购买 nike

在头文件中,可以在一行中声明和(预)定义全局常量。

// constants.h
namespace Constant{
static const unsigned int framerate = 60;
static const char * const windowName = "Test";
static const unsigned char * const cursorBitmap = { lots of data };
}

我喜欢这种格式,因为它让我可以将我的常量保存在一个地方,并且避免需要在一个文件中声明常量并在另一个文件中定义它,有助于提高可读性。然而,当任何翻译单元包含 constants.h 时,它会在适当的位置扩展这些定义,每个单元

我的问题是,如果我将 constants.h 包含到许多翻译单元中,这是否会导致大量开销,例如,cursorBitmap 和其他数组常量非常大?如果我将每个字符串和数组文字包含到 100 个单元中,我的程序是否会包含 100 个拷贝?还是只复制指针和值?

如果有开销,有什么方法可以避免它而无需分离声明和定义?

(而且我猜'static'在这种用法中是多余的,但我还是喜欢把它放在那里)

最佳答案

字符串文字是否在各种翻译单元中重复是一个实现质量问题。

直接声明的对象将在包含此 header 的每个翻译单元中复制。虽然不多。并且在不直接或间接使用某些常量地址的翻译单元中,它可能会被优化掉。

如果你想保证每个常量只有一份,甚至没有拷贝,那么你可以使用类模板,像这样:

常量.h
#pragma once

template< class Dummy >
struct Constant_{
static const unsigned int framerate;
static const char * const windowName;
static const unsigned char * const cursorBitmap;
};

template< class Dummy >
const unsigned int Constant_<Dummy>::framerate = 60;

template< class Dummy >
const char * const Constant_<Dummy::windowName = "Test";

template< class Dummy >
const unsigned char * const Constant_<Dummy>::cursorBitmap = ...;

using Constant = Constant_<void>;

但恕我直言,工作量超出了它的值(value)。

一种类似的替代方法是使用内联 函数,每个常量一个。

关于c++ - 包含在许多翻译单元中时静态常量的开销?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34740335/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com