Search code examples
c++pimpl-idiom

About the pimpl syntax


I have a question about the C++ usage used in the pimpl syntax.

First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl )

Second, why is the lifetime of new impl extended even though it is a temporary object?

//my_class.h
class my_class {
   //  ... all public and protected stuff goes here ...
private:
   class impl; unique_ptr<impl> pimpl; // opaque type here
}
// my_class.cpp
class my_class::impl {  // defined privately here
  // ... all private data and functions: all of these
  //     can now change without recompiling callers ...
};
my_class::my_class(): pimpl( new impl )
{
  // ... set impl values ...
}

Solution

  • First, why is it not necessary to write pimpl( new impl ) as pimpl( new my_class::impl )

    Scope. When constructor is defined you are inside a cope of a class, so name lookup is able to find it without problems.

    Second, why is the lifetime of new impl extended even though it is a temporary object?

    You are passing temporary pointer to as constructor argument of std::unique_ptr<impl> so value is consumed by a field pimpl. impl value s not temporary since it is created on a heap, control of its lifetime was passed to smart pointer.

    Extra:
    You did using namespace std; in header (the only case when you can skip std:: before unique_ptr)! This is BIG mistake do not do it. This will impact dangerously all sources which will include this header. You can have symbol ambiguity error because of that.

    Even having using namespace std; in cpp file is considered a bad practice.