toge's diary

コンピュータ関連の趣味をつらつらと。

const参照渡しで暗黙のinstance生成

http://d.hatena.ne.jp/ranha/20050727#1122442209 より。

うぐ知らなかったよ。C++適当に勉強し過ぎですね。勉強になりました。
高速化のためのconst参照なのに、暗黙にインスタンス生成しちゃうのか、危ないなぁ。

int foo = 0;
const long& bar1 = foo; // これはOK!
long& bar2 = foo;       // これはNG  

ちなみにアセンブラ出力するとこんな感じ。
見事に暗黙のインスタンス(dummy)が作られてますな。

main:
	pushl	%ebp
	movl	%esp, %ebp
	subl	$24, %esp
	andl	$-16, %esp
	movl	$0, %eax
	addl	$15, %eax
	addl	$15, %eax
	shrl	$4, %eax
	sall	$4, %eax
	subl	%eax, %esp
    ;; foo = 0 
	movl	$0, -12(%ebp)
    ;; eax = foo
	movl	-12(%ebp), %eax
    ;; dummy = foo
	movl	%eax, -16(%ebp)
    ;; eax = &dummy
	leal	-16(%ebp), %eax
    ;; bar1 = eax
	movl	%eax, -8(%ebp)
    ;; foo = 2
	movl	$2, -12(%ebp)
    ;; eax = bar1
	movl	-8(%ebp), %eax
    ;; eax = *bar1
	movl	(%eax), %eax
    ;; tmp = *bar1
	movl	%eax, -4(%ebp)
	movl	$0, %eax
	leave
	ret