less than 1 minute read

Categories:

Tags:

Nodiscard

struct Vector
{
  bool empty() const;
};

int main()
{
  Vector vec;
  vec.empty();
}

๋งŒ์•ฝ ์œ„์— ์ฝ”๋“œ์™€ ๊ฐ™์ด ๋ฆฌํ„ด๊ฐ’์— ๋Œ€ํ•ด ์•„๋ฌด๊ฒƒ๋„ ํ•˜์ง€ ์•Š์•˜์„๋•Œ ์ด๊ฒƒ์€ ๋ฒ„๊ทธ์ผ๊นŒ?

์•Œ๊ณ ๋ณด๋ฉด ์ด๊ฒƒ์€ c++ standard library ์‚ฌ์šฉ์ž๋“ค์ด ๊ฐ€์žฅ ํ”ํžˆ ๋งˆ์ฃผํ•˜๊ฒŒ๋˜๋Š” ๋ฒ„๊ทธ์ด๋‹ค. ์™œ๋ƒํ•˜๋ฉด ์‚ฌ์šฉ์ž๋“ค์€ Vector์•ˆ์— ์žˆ๋Š” empty ํ•จ์ˆ˜๊ฐ€ ๋น„์–ด์žˆ์„๋•Œ true๋ฅผ ๋ฐ˜ํ™˜ํ•˜๊ธธ ๊ธฐ๋Œ€ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ํ•˜์ง€๋งŒ ํ˜„์‹ค์€ vec.empty()๋Š” Vector๊ฐ€ ๋น„์–ด์žˆ๋“  ์•„๋‹ˆ๋“  true๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

struct Vector
{
  [[nodiscard("You probably meant to call clear()")]]bool empty() const;
  void clear();
};

int main()
{
  Vector vec;
  vec.empty();
}

๋”ฐ๋ผ์„œ ์–ด๋– ํ•œ ํ•จ์ˆ˜๊ฐ€ ๋ฆฌํ„ด๊ฐ’์„ ๋ฌด์‹œํ•˜๊ณ  ํ˜ธ์ถœํ–ˆ์„๋•Œ ๋ฒ„๊ทธ์ธ๊ฐ€๋ฅผ ์ƒ๊ฐํ•˜๊ณ  ์ ์ ˆํ•˜๊ฒŒ nodiscard๋ฅผ ์ถ”๊ฐ€ํ•ด์ฃผ๋Š”๊ฒƒ์ด ํ•„์š”ํ•˜๋‹ค.


ํƒ€์ž…๋˜ํ•œ nodiscard๋กœ ๋งˆํ‚น๋  ์ˆ˜ ์žˆ๋‹ค.

struct [[nodiscard("This is an error type!!")]] Error {};

Error do_thing();

int main()
{
	do_thing();
}

Leave a comment