Re: Pimpl idiom without dynamic memory allocation

Tech-Archive recommends: Fix windows errors by optimizing your registry



Daniel Lidstrm <somebody@xxxxxxxxxxxxx> wrote:
I have just discovered a way to use the private implementation idiom
(pimpl), without the overhead of dynamic memory allocation. For those
of you who don't know what this is, Wikipedia has a nice article you
can read. Anyway, I discovered that if you make all members in the
implementation class mutable, you can in fact use this idiom without
any "unnecessary" memory allocation. Here's a minimal example of the
method:

// In the header of your class called Line

#include <string>

class Line
{
public:

Line(const std::string& name);
const std::string& GetName() const;
void SetName(const std::string& s);

private:

// Private implementation idiom:
// all member variables are hidden in this class
class LineImpl;
const LineImpl& m_pimpl; // normally a non-const pointer
};

// and in your implementation file:

#include "Line.h"

// create the pimpl instance without using new
Line::Line(const std::string& s) : m_pimpl(LineImpl(s)) {}

That's not going to work. LineImpl temporary will be destroyed at the
end of constructor, and you'll end up with a dangling reference. Just
write ~LineImpl destructor, put a breakpoint there and see for yourself.
From the C++ standard:

12.2/5 ... A temporary bound to a reference member in a constructor's
ctor-initializer (12.6.2) persists until the constructor exits...

Where did you think the memory for LineImpl instance came from in your
code? Fifth dimension?
--
With best wishes,
Igor Tandetnik

With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925


.



Relevant Pages

  • Re: Wouldnt it be nice to have a [binary set] command ?
    ... (it's actually exactly 6 machine words). ... object due to memory allocation is very low (sub-byte after ... allocation overhead of the Tcl_Obj's for that exact reason. ... I may have been a little overzealous in my estimation, ...
    (comp.lang.tcl)
  • Re: Passing multiple arguments to a thread
    ... > synchronize both threads... ... > There are so many way to go along like mutex, semaphores, critical ... The overhead of memory allocation is infinitesimal compared with the ...
    (microsoft.public.win32.programmer.kernel)