PIMPL Idiom in D

Steven Schveighoffer schveiguy at yahoo.com
Tue May 22 13:27:12 UTC 2018


On 5/21/18 11:44 PM, Walter Bright wrote:
> On 5/21/2018 2:41 PM, Steven Schveighoffer wrote:
>>
>> Will this really work?
>>
>> I mean, if the compiler can see the implementation of S, even though 
>> it's private, can't it inline things and screw with the binary 
>> compatibility?
> 
> That's right. To avoid that, you'll need to organize the code for 
> separate compilation. Of course, with Link Time Optimization, that goes 
> out the window (and for C and C++, too).

But link time optimization should be OK, because the idea is that you 
can link against different API-compatible objects, and then inlining is 
fine.

The problem with inlining is that if you change the actual underlying 
implementation, the inlined function may do something horribly wrong 
compared to the new implementation. With LTO, the correct implementation 
is used for inlining.

However, I'm not sure what the situation is with dynamic linking, but I 
would assume in order to keep everyone sane, LTO inlining is disabled 
for that situation.

>> I thought that was the main benefit of pimpl, to create a barrier 
>> which you know is going to separate the user from the implementation.
> 
> In this case, I was looking to hide it from the user.

Well, the fact that you have the private implementation right there for 
the user to see, you might as well just do:

public struct S
{
    private:
    // impl
}

// in separate moudule:

struct T
{
    S* pimpl;
}

There's no need for the private struct.

-Steve


More information about the Digitalmars-d mailing list