static๊ณผ const

static const in C++

terminology

  • Translation Unit
    • ์ปดํŒŒ์ผ๋Ÿฌ๋Š” ๋ฒˆ์—ญ์„ ๋‹จ์œ„๋ณ„๋กœ ์‹คํ–‰ํ•˜๋Š”๋ฐ, ์ด๋•Œ ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ๋ฌธ์žฅ์„ ๋ฒˆ์—ญํ•˜๋Š” ๋‹จ์œ„๋ฅผ Translation Unit๋ผ ํ•œ๋‹ค
    • ๋ชจ๋“ˆ์ด๋ผ๊ณ  ์ƒ๊ฐํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™๋‹ค
  • Static linkage
    • ์ด๋Š” ํ•ด๋‹น ๋ชจ๋“ˆ ์•ˆ์—์„œ๋งŒ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค
  • Extenal linkage
    • ๋‹ค๋ฅธ ๋ชจ๋“ˆ์—์„œ๋„ ์ ‘๊ทผ์ด ๊ฐ€๋Šฅํ•˜๋‹ค

namespace์—์„œ์˜ static

static const int sci = 0; // sci is explicitly static
const int ci = 1;         // ci is implicitly static
extern const int eci = 2; // eci is explicitly extern
extern int ei = 3;        // ei is explicitly extern
int i = 4;                // i is implicitly extern
static int si = 5;        // si is explicitly static
  • ์œ„์˜ ์ „์—ญ๋ณ€์ˆ˜๋“ค์˜ ํƒ€์ž…์€ ์ฃผ์„๊ณผ ๊ฐ™๋‹ค
  • C++ namespace์—์„œ const์˜ default๋Š” static์ด๋‹ค
    • ๋‘˜ ๋‹ค ์ปดํŒŒ์ผ ํƒ€์ž„์— ์ดˆ๊ธฐํ™”๋˜๋ฉฐ, const-initilaize ํ˜น์€ zero-initialize๋ฅผ ์‹œํ–‰ํ•œ๋‹ค
    • ๊ฐ๊ฐ Data segment์™€ BSS๋กœ ๋‚˜๋‰œ๋‹ค

static const in C#

public static const string CONST_NAME = "blah";
  • ์œ„์˜ ์ฝ”๋“œ๋Š” ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค
  • C#์—์„œ์˜ const๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ static์ด๋‹ค
    • ๊ทธ๋Ÿผ์—๋„ ๋ถˆ๊ตฌํ•˜๊ณ , const์— static ํ‚ค์›Œ๋“œ๋ฅผ ์ถ”๊ฐ€ํ•  ์ˆ˜๋Š” ์—†๋‹ค

C++๊ณผ์˜ ์ฐจ์ด์ ?

  • static์€ read/write ๊ฐ€๋Šฅํ•˜๋ฉฐ ๋ฉ”๋ชจ๋ฆฌ์— ํ• ๋‹นํ•  ์ €์žฅ ๊ณต๊ฐ„์ด ํ•„์š”ํ•˜๊ณ  ๋Ÿฐํƒ€์ž„์— ์ดˆ๊ธฐํ™”๋˜์–ด์•ผ ํ•œ๋‹ค
    • ํ•ด๋‹น static ๋ณ€์ˆ˜์— ์ ‘๊ทผํ•˜๊ธฐ ์ „๊นŒ์ง€ ์ •์  ์ƒ์„ฑ์ž๋Š” ํ˜ธ์ถœํ•˜์ง€ ์•Š๋Š”๋‹ค
    • static ๋ณ€์ˆ˜๊ฐ€ ์ €์žฅ๋˜๋Š” ๊ณต๊ฐ„์€ Heap์ด๋‹ค
  • const๋Š” ๊ฐ’ ๋ณ€๊ฒฝ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๊ณ  (๋Œ€๊ฐœ) ์ปดํŒŒ์ผ ํƒ€์ž„์— ์ดˆ๊ธฐํ™”๋œ๋‹ค

๊ทธ๋ž˜์„œ const ๋ณ€์ˆ˜๊ฐ€ Heap์— ์ƒ์„ฑ๋˜๋‚˜?

  • ์ปดํŒŒ์ผ ํƒ€์ž„์— ๊ณง์žฅ ์ƒ์„ฑ ์ฝ”๋“œ์— ์ž„๋ฒ ๋“œ ๋˜๋ฉฐ, ๋Ÿฐํƒ€์ž„์— ์ด๋ฅผ ์œ„ํ•œ ๋ณ€์ˆ˜๊ฐ€ ํ•„์š”ํ•˜์ง€ ์•Š๋‹ค
    • https://stackoverflow.com/questions/54105028/where-does-the-memory-is-allocated-for-static-constant-and-readonly-fields
    • static ์œผ๋กœ ๋ถ„๋ฅ˜๋˜๋‚˜, Heap์— ์ €์žฅ๋˜์ง€๋Š” ์•Š๋Š” ๊ฒƒ ๊ฐ™๋‹ค

์ถœ์ฒ˜