Re: Pimpl idiom without dynamic memory allocation
- From: "Igor Tandetnik" <itandetnik@xxxxxxxx>
- Date: Wed, 17 Oct 2007 16:29:11 -0400
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
.
- Follow-Ups:
- Re: Pimpl idiom without dynamic memory allocation
- From: Daniel Lidström
- Re: Pimpl idiom without dynamic memory allocation
- Prev by Date: Re: A solution to warning C4251 - class needs to have dll-interface...?
- Next by Date: Re: recognize .Net controls properly and get infos/styles/properties
- Previous by thread: recognize .Net controls properly and get infos/styles/properties
- Next by thread: Re: Pimpl idiom without dynamic memory allocation
- Index(es):
Relevant Pages
|