Re: Pimpl idiom without dynamic memory allocation
Daniel Lidström a écrit :
> Hello!
>
> 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"
>
> // Here we define the class with the member variables
[snip]
> // all methods need to be const here
[snip]
> mutable std::string m_s; // the trick! all members are mutable
Which mean you coerce the code into compilation. That's all.
> // create the pimpl instance without using new
> Line::Line(const std::string& s) : m_pimpl(LineImpl(s)) {}
Your local is destroyed when going out of scope. Doesn't it ?
> [snip]
> Ok experts, what do you all think? This method sacrifies
> const-correctness for some extra speed. Is it worth it?
Not really.
And certainly not worth a dangling reference.
Michael
|