Skip to main content

C++ of the Day #1 - Be alert for C++'s most vexing parse.

Question

오늘 C++ 뉴스그룹에 올라온 질문 하나 ((comp.lang.c++.moderated: semantics???))
class X
{
  public:
  int i;
  private: //<<<<<(1)

  X():i(1) { printf ( "Ctor\n");}
  X(const X & ref ) { printf ( "CopyCtor\n" ); i = ref.i; }
  ~X() { printf ( "~Dtor\n" ); }
};

int main()
{
  X c(X());  //<<<<(2)
  //X& ref = c;  <<<<(3)
}
질문을 요약하면... - 위의 코드는 컴파일이 된다. - (1)에 있는 private을 public으로 변경해도 컴파일은 된다. 하지만 아무것도 출력되지 않는다. - (3)의 주석처리를 풀면 "c is not an lvalue"라는 컴파일 에러가 발생한다. - 도대체 왜 이런 결과가 나오는가?  답을 보기전에 한번 생각해 보세요.  


Answer

사실 정답은 Effective STL: Item 6 ((Effective STL: Item 6. Be alert for C++'s most vexing parse.)) 의 내용입니다. 위의 (2)번 라인은 실제 변수 선언이 아닌 함수 선언으로 파싱된 것입니다. 먼저 작성자의 의도는 아마 X() 로 temporary X 객체를 만든 후 이를 X의 복사 생성자에 넘겨 c라는 X 객체를 생성하려 했던 것일 겁니다. 하지만 실제로는 X를 리턴하고 인자로 X를 리턴하는 함수 포인터를 가지는 c라는 함수를 선언한 것이죠. (2)번 라인을 다르게 써보면 다음과 같습니다.
X c(X (*pf)());
X c(X pf());
X c(X ());
제일 위에 줄은 명확하게 함수 포인터를 인자로 가지는 함수 선언으로 보입니다. 두번째 줄은 포인터를 사용하지 않는 함수 포인터 문법으로 첫번째 줄과 동일합니다. 마지막으로 함수 선언중 인자 부분에서는 아래 예와 같이 인자의 이름을 생략할 수 있으므로 세번째 줄 역시 같은 내용이 됩니다.
int add(int x, int y);
int add(int, int );
언급한 책에 나와있듯이 아래와 같은 경우 흔히 범할 수 있는 실수입니다.
class Widget { ... };
Widget w(); // w라는 Widget 타입의 변수 선언이 아니라 Widget을 리턴하는 w라는 함수 선언
해결책은 다음과 같습니다.
X c( ( (X() ) ); // 괄호를 추가하여 함수 선언이 아님을 명시한다.
X tmp; X c(tmp); // 인자를 미리 변수로 선언한 후 이를 사용한다. (권장)

Comments

Popular posts from this blog

CodeHighlighter plugin test page.

This post is for testing CodeHighlighter plugin which uses GeSHi as a fontifier engine. ((Those code blocks are acquired from Google Code Search .)) ((For more supported languages, go CodeHighlighter plugin or GeSHi homepage.)) C++ (<pre lang="cpp" lineno="1">) class nsScannerBufferList { public: /** * Buffer objects are directly followed by a data segment. The start * of the data segment is determined by increment the |this| pointer * by 1 unit. */ class Buffer : public PRCList { public: Buffer() { ++index_; } PHP (<pre lang="php" lineno="4">) for ($i = 0; $i $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { // ASCII $unicode .= chr($value); } else { if ( count( $values ) == 0 ) { $num_octets = ( $value } $values[] = $value; Lisp (<pre lang="lisp">) ;;; Assignment (define-caller-pattern setq ((:star var fo...

Textiler plugin test page

This post is for testing Textiler plugin . This plugin uses Textile engine (version 2.0.0). The sample text is come from Textile test page. (Note that the result will be vary according to your CSS options.) Supported wiki syntax Rendering result h2{color:green}. This is a title h3. This is a subhead p{color:red}. This is some text of dubious character. Isn't the use of "quotes" just lazy writing -- and theft of 'intellectual property' besides? I think the time has come to see a block quote. bq[fr]. This is a block quote. I'll admit it's not the most exciting block quote ever devised. Simple list: #{color:blue} one # two # three Multi-level list: # one ## aye ## bee ## see # two ## x ## y # three Mixed list: * Point one * Point two ## Step 1 ## Step 2 ## Step 3 * Point three ** Sub point 1 ** Sub point 2 Well, that went well. How about we insert an <a href="/" title="watch out">old-fashioned hypertext link</a>? Will the quo...

BookCover plugin test page

This post is for testing BookCover plugin . (( The previous test page has some comments from users.)) The 'Books Reading' section in the sidebar is also using this plugin. [ bookcover:1932394613] [bookcover:1932394613] [ bookcover:1590598385(Smart and Gets Things Done)] [bookcover:1590598385(Smart and Gets Things Done)] [ bookcover:1591841380(Wikinomics : How Mass Collaboration Changes Everything)] [bookcover:1591841380(Wikinomics : How Mass Collaboration Changes Everything)] [ bookcover:8995856408] [bookcover:8995856408] [ bookcover:8831793721] [bookcover:8831793721] [ bookcover:9788831793728] [bookcover:9788831793728]