Skip to main content

C++ of the Day #41 - Maintaining const in Impl classes

이번 내용은 c.l.c.m.에 올라온 Maintaining const in Impl classes라는 글에서 가지고 왔습니다. Pimpl Idiom과 const correctness에 관한 글입니다.


struct Foo {
struct Impl {
void A() const { }; // unreachable code!
void A() { };
};

Foo() : pimpl_(new Impl) { };

void A() const { pimpl_->A(); };
void A() { pimpl_->A(); };

Impl* pimpl_;
};

// ...
Foo const foo;
foo.A(); // will always call non-const Foo::Impl::A()


위의 코드에서 문제라고 얘기되고 있는 것은 foo가 Foo 클래스의 const instance인데 Impl의 A() const가 호출되지 않고 A()가 호출된다는 점입니다.

원인은 간단합니다. foo가 const instance라서 const가 되는 것은 Impl*이지 Impl이 아니기 때문입니다. Impl* const냐 Impl const*냐의 차이죠. ((const 관련 내용이 얼마전 시즈하님의 C 포인터, 확실히 알자(6) - 상수와 포인터에도 올라왔었습니다.))

무엇의 const인지 쉽게 알기 위해서는 const 키워드의 바로 앞에 무엇이 있는지 보면 됩니다. 예를 들어보죠.


  • T const* -> T가 const

  • T* const -> T*가 const

  • std::auto_ptr<T const> -> T가 const

  • std::auto_ptr<T> const -> std::auto_ptr<T>가 const

  • boost::shared_ptr<T const> -> T가 const

  • boost::shared_ptr<T> const -> boost::shared_ptr<T>가 const



위 공식(?)에 맞추기 위해 const T* 대신 T const* 라고 썼습니다. 게다가 몇 년전부터 T const* 형식이 유행인 듯... 왠지 멋져 보입니다. :-)

따라서 위의 문제에서 Impl::A() const 함수가 불리게 하기 위한 가장 간단한 방법은 Foo::A() const를 다음과 같이 수정하는 것입니다.


void Foo::A() const {
const_cast(pimpl_)->A();
}


만약 다뤄야 할 멤버 함수가 많다면 다음과 같이 get_impl()같은 helper 함수를 만들어 사용하는 것이 좋겠죠?


struct Foo {
struct Impl {
void A() const { };
void A() { };
};

Impl* get_pimpl() { return pimpl_; }
Impl const* get_pimpl() const { return pimpl_; }

Foo() : pimpl_(new Impl) { };

void A() const { get_pimpl()->A(); };
void A() { get_pimpl()->A(); };

Impl* pimpl_;
};


원본 링크의 김승범님 답변을 보면 이 용도의 PimplPtr라는 smart pointer 클래스도 볼 수 있습니다. 이 PimplPtr는 일반 smart pointer와는 다르게 T* 대신 T const*를 리턴하도록 구현되어 있죠.

개인적으론 Impl 클래스는 말 그대로 원래 클래스의 private에 해당하는 코드로 그 클래스에서만 사용하는 코드들인데 굳이 const correctness까지 필요할까라는 생각이 드네요. :-)

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