logo
down
shadow

Designing the instantiation and destruction of a class using the pimpl idiom


Designing the instantiation and destruction of a class using the pimpl idiom

By : user2950116
Date : November 17 2020, 11:52 AM
I hope this helps you . This is almost a Code Review question now, so you might want to consider posting this on CodeReview.SE. Also, it might not fit well to StackOverflow's philosophy of specific questions with specific answers, no discussion. I'll try to present an alternative nevertheless.
Analysis and critique of (details of) the OP's approach
code :
Entry(EntryImpl* impl) : m_Impl(impl) { }
// 2. Public destructor
~Entry() { delete m_Impl; }
Entry e(0);
class Entry final
{
private:
    EntryImpl* const m_Impl;
// interface headers:

class IEntry // replacement for `Entry`
{
public:
    // public API as virtual functions
};

class Tree
{
    // [implementation]
public:
    IEntry* AddEntry();
    void DoSomething();
};


// implementation headers:

class EntryImpl : public IEntry
{
    // implementation
};

// implementation of `Tree::AddEntry` returns an `EntryImpl*`
Tree myTree;
auto myEntry = myTree.AddEntry();
myEntry->SomeFunction();
class Tree
{
    // [implementation]
public:
    non_owning_pointer<IEntry> AddEntry();
    void DoSomething();
};
class Tree
{
    // [implementation]
public:
    non_owning_pointer<IEntry> AddEntry();
    void RemoveEntry(non_owning_pointer<IEntry>);

    void DoSomething();
};
namespace detail
{
    class UnqiueEntryPtr_deleter {
        non_owning_pointer<Tree> owner;
    public:
        UnqiueEntryPtr_deleter(Tree* t) : owner{t} ()
        void operator()(IEntry* p) { owner->RemoveEntry(p); }
    };
}

using unique_entry_ptr = std::unique_ptr<IEntry, UniqueEntryPtr_deleter>;

auto AddEntry(Tree& t) // convenience function
{ return unique_entry_ptr{ t.AddEntry(), &t }; }
class EntryImpl;
class Entry
{
    EntryImpl* pimpl;
public:
    EntryImpl const* get_pimpl() const;
    EntryImpl* get_pimpl();
};


Share : facebook icon twitter icon
Pimpl idiom used with a class member variable

Pimpl idiom used with a class member variable


By : user1788897
Date : March 29 2020, 07:55 AM
it helps some times MyClass is a singleton -- some call it a glorified global. An oft-abused pattern. Use private ctors and a public static accessor:
code :
 MyClass {
       public:
            static MyClass& Instance() {
                 static MyClass obj;
                 return obj;
            }
       // ...
       private:
            MyClass() : m_handle(pimpl()), initialized(true) {}
       // ...
 };
Using C++ class in Objective-C - Why use PImpl idiom?

Using C++ class in Objective-C - Why use PImpl idiom?


By : Israel Lucena
Date : March 29 2020, 07:55 AM
like below fixes the issue The downside is this C++ type MyCPPClass is now in the header file MyObjCClass.h, which other Objective-C classes that use MyObjCClass will have to import. Importing a header is like putting it into the code, so these other Objective-C classes now have C++ in their code, and so will now have to be changed to Objective-C++ files or they won't compile. This is often not desirable, as these other files shouldn't need C++. Although this problem can be solved by declaring your instance variable not in the main class declaration in the header, but in the "extension" (declared like a category but with no name in the parentheses) or in the @implementation, which are in the implementation file, so other classes don't have to import it.
Another problem with C++ classes as instance variables of Objective-C classes is that your C++ object can only be constructed using the default constructor (i.e. no constructor arguments), as there is no way to provide an initializer for an instance variable of an Objective-C class. So if you want to construct it with constructor arguments, you must use pimpl.
Pimpl idiom as template base class

Pimpl idiom as template base class


By : Rajashekar Reddy
Date : March 29 2020, 07:55 AM
will be helpful for those in need I'm currently researching the pimpl idiom and there are very nice tutorials how it could be implement (e.g. here). But i have never seen it implemented as a base template class like this: , Yes, there are several problems, as I see it.
code :
template <class Handle, class Impl>
class Pimpl
{
private:
    Impl* _make() const
    { return ((Handle const*)this)->make(); }

    void _unmake(Impl *p) const
    { ((Handle const*)this)->unmake(p); }

    Impl* _clone(Impl *p) const
    { return ((Handle const*)this)->clone(p); }

    void swap(Pimpl &other) {
        Impl *temp = d_ptr;
        d_ptr = other.d_ptr;
        other.d_ptr = temp;
    }

public:
    explicit Pimpl();
            ~Pimpl();

    Pimpl(const Pimpl &other);
    Pimpl &operator=(const Pimpl &other);

    // fall-backs
    static Impl* make()          { return new Impl; }
    static void  unmake(Impl* p) { delete p; }
    static Impl* clone(Impl* p)  { return new Impl(*p); }

protected:

    Impl *d_ptr;
};

template<class Handle, class Impl>
Pimpl<Handle, Impl>::Pimpl() :
  d_ptr(_make())
{

}

template<class Handle, class Impl>
Pimpl<Handle, Impl>::~Pimpl()
{
    _unmake(d_ptr);
    d_ptr = 0;
}

template<class Handle, class Impl>
Pimpl<Handle, Impl>::Pimpl(const Pimpl &other) :
  d_ptr(_clone(other.d_ptr))
{

}

template<class Handle, class Impl>
Pimpl<Handle, Impl> &Pimpl<Handle, Impl>::operator=(const Pimpl &other)
{
    Pimpl copy(other);
    swap(copy);

    return *this;
}
PIMPL idiom for a pointer to a class in C++

PIMPL idiom for a pointer to a class in C++


By : user2064854
Date : March 29 2020, 07:55 AM
will help you Your implementation should use an interface (or in fact a class with only abstract methods) as a base class. You cannot assign types in C++. You can only create typedefs and aliases, like that:
code :
using PIMPLType = Compute_Prop;
class IImplementation
{
public:
    virtual void saySomething() = 0;
};

class ImplementationA : public IImplementation
{
public:
    virtual void saySomething() override {
        std::cout << "A";
    }
};
class ImplementationB : public IImplementation
{
public:
    virtual void saySomething() override {
        std::cout << "B";
    }
};

class Foo {
    IImplementation *pimpl;
public:
    Foo()
        : pimpl(new ImplementationA)
    {}

    ~Foo() { delete pimpl; }

    void saySomething() {
         pimpl->saySomething();
    }
};
C++ Pimpl Idiom using a pre-existing class

C++ Pimpl Idiom using a pre-existing class


By : Ranjith Kumar
Date : March 29 2020, 07:55 AM
I wish did fix the issue. You can just forward-declare Foo in FooWrapper.h. This will allow you to declare a std::unique_ptr for it:
code :
#ifndef FOO_WRAPPER_HEADER
#define FOO_WRAPPER_HEADER

#include <memory>

// Forward declaration
template <typename T>
class Foo;

struct FooWrapper {
  FooWrapper();
  ~FooWrapper();

  void bar(double t);

 private:
  std::unique_ptr<Foo<double>> impl;
};

#endif /* FOO_WRAPPER_HEADER */
#include "foo_wrapper.h"
#include "foo.h"

void FooWrapper::bar(double t) {
  impl->bar(t);
}

FooWrapper::FooWrapper() : impl(std::make_unique<Foo<double>>()) {}

FooWrapper::~FooWrapper() = default;
Related Posts Related Posts :
  • C++ Doubly Linked List with Pointers: Object of class isn't constructed properly
  • Using a random string generator in c++ constructor
  • What should I use instead of void as one of the alternative types in an variant?
  • C++ return value from multithreads using reference
  • How to connect multiple TCP IP clients to same server port using c++
  • Defaul compiler generates the reference operator (In C++)?
  • Unable to change directory time stamp after using FILE_FLAG_BACKUP_SEMANTICS
  • vector handling displaying output
  • WSAGetLastError returns WSAENOTSOCK - Cause?
  • C++: How to overload pow for user type?
  • C++ using arrays as multidimensional despite initalising it as 1D with pointer
  • How negate std::is_integral for use in tag dispatch?
  • Retrieve serial number from USB memory (Windows environment c++)
  • g++ error: invalid preprocessing directive #INCLUDE
  • C++ What is the std::for_each() function parameter type?
  • C++: Read individual lines from text file, sort words alphabetically
  • Saving 'this' address into a variable
  • c++ command line arguments in ubuntu terminal
  • Convert "Cartesian coordinates" to "polar coordinates with respect to user specified origin"
  • In what order are local scoped objects destructed?
  • How to use SDL_MapRGB with SDL 2.0
  • how compiler and interpreter work in case of array declaration
  • GSL integration behaves strange
  • Cropping an image with OpenCV and C
  • Find the last line in text file and select the first 10 char and print to a new file?
  • Created many CCSprits but when triggering ccTouchBegan gives the last one allways
  • seekp and seekg don't work with fstream
  • Taking input in Sublime Text 3
  • ld: -bind_at_load and -bitcode_bundle (Xcode setting ENABLE_BITCODE=YES) cannot be used together
  • C++ storing #define as std::string would give size as zero compile time
  • How to use static linking with OpenSSL in C/C++
  • What is the difference between a trap, an error, a failure and program abortion?
  • Dynamic members allocation in qt
  • How to reduce object file size when compiling for VxWorks 5.5.1?
  • Printing char by integer qualifier
  • How to write code to be executed before main() gets control?
  • Blocking socket - waitForReadyRead()
  • std::string related errors and handling them, c++
  • VM interpreter - weighting performance benefits and drawbacks of larger instruction set / dispatch loop
  • C / C++ SHIFT / OFFSET / MOVE a Bitmap to the LEFT or RIGHT?
  • Printing numbers column by column
  • How do you change your app icon in visual studio 2013?
  • Fast Screen Transfer
  • c++ Read text file and input the numbers into a 2D array
  • Why are my C++ pointers suddenly diverging?
  • Is there a macro-based adapter to make a functor from a class?
  • CRTP and multilevel inheritance
  • How to implement timer for each object in c++?
  • Stuck when testing custom list class in c++
  • Using each member of class within one function to calculate average
  • check whether if two squares are intersecting with each other
  • Glm Quaternion lookat function
  • Is there guarantee heap allocated block address will not change(implicitly)?
  • Cosine Calculation without cmath library
  • Manually deleting a pointer returned by function
  • Avoid output interleaving
  • C++ error : Expected an identifier
  • Segmentation fault when I call operator new in linux mint
  • Recursively Solving A Sudoku Puzzle Using Backtracking Theoretically
  • lambda closure type and default argument in function template
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org