Skip to main content

C++ of the Day #14 - Overload resolution before access checking

오늘 내용은 뉴스 그룹에서 가져왔습니다.((c.l.c.m:overload resolution before access checking))

Question

struct S
{
public:
  void foo(long);
private:
  void foo(int);
};

....
S s;
s.foo(1);       // error, S::foo(int) is private
위의 코드와 같이 s.foo(1) 문은 컴파일 에러가 발생합니다. 이유는 C++ 컴파일러가 access checking을 하기 전에 overload resolution을 먼저 수행하기 때문입니다. 즉, 접근 권한에 관계 없이 두개의 foo 함수중 어떤 것이 인자 '1'에 더 적합한가를 확인하는데 이때 literal 1은 int이기 때문에 foo(int) 를 수행하도록 결정됩니다. 하지만 함수를 결정한 후 접근 권한을 검사해보면 이 foo(int)는 private이기 때문에 컴파일 에러가 발생하는 것이죠.

만약 overload resolution이 접근 가능한 멤버에 대해서만 동작한다면 위의 코드는 컴파일 에러 없이 foo(long)을 호출할 수 있었겠죠?
오늘의 질문은 이것입니다.
  1. C++에서 컴파일을 이렇게 하는 타당한 이유는 무엇인가?
  2. 다른 말로 하자면, private 멤버는 왜 보이지 않는 것(invisible)이 아니라 접근 불가능(inaccessible)인가?

Answer

먼저 첫번째 질문에 대한 답은 애석하게도 "뭐 특별한 이유가 있었던 것은 아니다"입니다. :-(

그래도 가장 그럴듯한 답은 아래 내용이 아닐까 합니다. ((D&E 책에 보면 Bjarne Stroustrup씨가 왜 이렇게 설계했는지 기억을 못한다고 하네요. ;-) ))
The design goal was that, as long as the code remains well-formed, changing a member's access level shall not change the semantics of the program.
즉, 코드가 계속 유효하면서 멤버의 접근 권한만 바뀌는 경우, 프로그램의 의미가 바뀌지 않도록 하기 위해서라는군요. 예를 들어 볼까요?
class Hello
{
public:
  void greet(long) {
    cout << "welcome";
  }
private:
  void greet(int){
    cout << "unwelcome";
  }
};
....
S s;
s.foo(1);       // call greet(long) if private: means not inaccessible but invisible.
위의 코드에서 만약 private이 invisible을 의미하였다면 overload resolution의 후보에서 greet(int)는 빠지게 되므로 greet(long)이 호출됩니다. int 에서 long 변환은 자동으로 가능하기 때문이죠.

그런데 이 코드에서 나머지 부분은 가만히 두고 private만 public으로 바꾸게 되면 literal 1은 int이므로 greet(int)가 호출됩니다. 즉, 코드는 계속 컴파일 및 실행이 되는데 전혀 다른 의미로 수행되는거죠. 단지 함수의 접근 권한만 바꾸었을 뿐인데 말이죠.

따라서 먼저 overload resolution을 처리하고 접근 권한을 확인하는 방법으로 이런 의도적이지 않은 실수를 방지할 수 있습니다. 프로그램의 의미가 모르는 사이에 바뀌는 것보다는 컴파일 에러가 발생하는게 좋겠죠?

이런 기능을 위해 C++ 언어가 위와 같은 규칙을 가지게 된것은 아니지만 이 규칙때문에 이런 기능이 생겼다고 할 수 있을 것 같습니다. 에공 뭔 말인지~ ;-)

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...

C++ of the Day #43 - SQLite3 C++ wrapper #1

The Definitive Guide to SQLite 를 읽다가 공부 겸 해서 C++ wrapper를 만들어 보았습니다. 최대한 C++ 냄새(?)가 나도록 만들어 보았습니다. :-) ((SQLite는 복잡한 관리가 필요없이 사용가능한, 파일이나 메모리 기반의, 라이브러리로 제공되는, 약 250kb 용량의, 대부분의 SQL92문을 지원하는, open source RDB입니다.)) 이 wrapper를 사용하기 위해서는 (당연하게도!) sqlite3 와 (당연하게도?) boost 라이브러리가 필요합니다. 사용 예들을 살펴보는 것으로 설명을 대신합니다. 이번 글에서는 다음과 같은 contacts 테이블이 test.db에 존재한다고 가정합니다. CREATE TABLE contacts ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, phone TEXT NOT NULL, UNIQUE(name, phone) ); Command 먼저 test.db 파일을 사용하기 위해 다음과 같이 파일 이름을 주어 connection 객체를 생성합니다. 생성과 동시에 test.db와 연결이 이루어집니다. ((생성자외에 open() 함수를 사용할 수도 있습니다.)) sqlite3pp::connection conn("test.db"); 다음은 contacts 테이블에 정보를 추가하는 가장 간단한 방법입니다. connection 클래스에서 제공하는 execute 함수를 사용합니다. ((executef 함수를 사용하면 printf와 같은 문법을 사용하여 query문을 작성할 수 있습니다.)) conn.execute("INSERT INTO contacts (name, phone) VALUES ('user', '1234')"); 위와 동일한 작업을 parameterized query를 사용하여 할 수도 있습니다. ((step()함수가 실제 query문을 수행하는 함수입니다. ...

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...