83
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

「密」のときと「密でない」ときで挙動が変わる C++ プログラム

Posted at

実行

mitsu2.gif

解説

& の間の空白の有無によって異なる構文に解釈される。

    • a&&ba && ba.operator int() && b.operator int()1 && 1true
  • 密でない
    • a & & ba & (&b)a.operator int() & (b.operator&())1 & 0false

if (初期化; 条件) のように書けるのは C++17 からの文法。

ソースコード

# include <iostream>

struct X {
	int operator & () { return 0; }
	operator int () { return 1; }
};

int main()
{
	if (X a,b;a&&b)
		std::cout << "!!密!!\n";
	else
		std::cout << "密ではない\n";

	std::cout << "------------\n";

	if (X a, b; a & & b)
		std::cout << "!!密!!\n";
	else
		std::cout << "密ではない\n";
}
!!密!!
------------
密ではない

教訓

  • アドレス取得演算子を安易にオーバーロードしない
  • 型変換演算子に explicit を付け、暗黙の型変換を禁止する。
    • explicit operator int () { return 1; }
  • ソースコードに Social Distancing を導入しない
83
27
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
83
27

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?