C++
पिंपल मुहावरा
खोज…
टिप्पणियों
Pimpl मुहावरा (पी ointer को impl ementation, कभी कभी अपारदर्शी सूचक या चेशायर कैट तकनीक के रूप में जाना जाता है), एक struct .cpp फ़ाइल में परिभाषित में सभी अपनी निजी डेटा के सदस्यों को ले जाकर एक वर्ग के संकलन बार कम कर देता है।
वर्ग कार्यान्वयन के लिए एक संकेतक का मालिक है। इस तरह, इसे आगे घोषित किया जा सकता है, ताकि हेडर फ़ाइल को निजी सदस्य चर में उपयोग किए जाने वाले #include वर्गों की आवश्यकता न हो।
पिंपल मुहावरे का उपयोग करते समय, एक निजी डेटा सदस्य को बदलने के लिए उस पर निर्भर वर्गों को फिर से जमा करने की आवश्यकता नहीं होती है।
मूल पिंपल मुहावरा
हेडर फ़ाइल में:
// widget.h
#include <memory> // std::unique_ptr
#include <experimental/propagate_const>
class Widget
{
public:
Widget();
~Widget();
void DoSomething();
private:
// the pImpl idiom is named after the typical variable name used
// ie, pImpl:
struct Impl; // forward declaration
std::experimental::propagate_const<std::unique_ptr< Impl >> pImpl; // ptr to actual implementation
};
कार्यान्वयन फ़ाइल में:
// widget.cpp
#include "widget.h"
#include "reallycomplextype.h" // no need to include this header inside widget.h
struct Widget::Impl
{
// the attributes needed from Widget go here
ReallyComplexType rct;
};
Widget::Widget() :
pImpl(std::make_unique<Impl>())
{}
Widget::~Widget() = default;
void Widget::DoSomething()
{
// do the stuff here with pImpl
}
pImpl में Widget स्थिति (या कुछ / अधिकांश) होती है। हेडर फ़ाइल में राज्य के Widget विवरण के उजागर होने के बजाय, इसे केवल कार्यान्वयन के भीतर ही उजागर किया जा सकता है।
pImpl "पॉइंटर टू pImpl " के लिए खड़ा है। Widget का "वास्तविक" कार्यान्वयन pImpl ।
खतरे: ध्यान दें कि इसके लिए unique_ptr साथ काम करने के लिए, ~Widget() को एक फ़ाइल में उस बिंदु पर लागू किया जाना चाहिए जहां Impl पूरी तरह से दिखाई देता है। आप इसे वहां =default कर सकते हैं, लेकिन अगर =default जहां Impl अपरिभाषित है, तो प्रोग्राम आसानी से बीमार हो सकता है, निदान की आवश्यकता नहीं है।