[英]pImpl idiom methods
I have implemented a basic pImpl set-up that is basically this example: Is the pImpl idiom really used in practice? 我已经实现了一个基本的pImpl设置,基本上就是这个示例: pImpl习惯用法是否真的在实践中使用? . 。
Most pImple implementations I find online never show any method examples. 我在网上找到的大多数pImple实现都从不显示任何方法示例。 The rule of thumb seems to be to hide all private members/methods in the pImple. 经验法则似乎是将所有私有成员/方法隐藏在该示例中。 The problem I am running into is I have a public method that looks sort of like this: 我遇到的问题是我有一个看起来像这样的公共方法:
bool Foo::Bar(const void* data, size_t size)
{
if( size > 0 )
{
if(data == nullptr)
return false;
size_t newSize = m_size + size;
if ( newSize > m_capacity )
{
m_capacity = GROW_FACTOR*newSize;
void* newMem = Malloc(m_capacity);
if ( m_size > 0 )
::memcpy(newMem, m_data, m_size);
if ( m_data )
Free(m_data);
m_data = (char*)newMem;
}
::memcpy(m_data + m_size, data, size);
m_size += size;
}
return true;
}
Should this be in the pImpl? 这应该在pImpl中吗? If not it seems a bit ugly to put pImpl->member every few words. 如果不是的话,每隔几句话就把pImpl-> member看起来有点难看。 How do you go about this? 您如何处理?
Assuming I am interpreting your question correctly, ie that Foo
is the public class and Bar
is a public method. 假设我正确地解释了您的问题,即Foo
是公共类,而Bar
是公共方法。 You have two options. 您有两个选择。 Option A is: 选项A为:
void Foo::Bar() // Foo is the public class
{
pImpl->baz = 5;
}
and Option B is: 选项B为:
void Foo::Bar() { pImpl->Bar(); }
where the Impl class contains: Impl类包含以下内容:
void Impl::Bar() { baz = 5; }
I'm not sure if there are any published guidelines on choosing between the two. 我不确定在这两者之间进行选择是否有任何已发布的指南。 In my own code I use Option A for simple methods and Option B once it starts getting to the stage that it seems like there are pimples everywhere. 在我自己的代码中,我将选项A用于简单的方法,将选项B用于开始似乎到处都是丘疹的阶段。 It is a balance between redundant code and extra argument copying, and pimple abundance. 它在冗余代码和额外的参数复制以及粉刺数量之间取得了平衡。
However, as suggested in comments, perhaps it would be cleaner to use Option B for everything, or at least every non-trivial function. 但是,正如评论中所建议的那样,对于所有内容,或者至少对每个非平凡的函数使用选项B,可能会更清洁。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.