Question

Why not choose this design :

// A.hpp
class A
{
public:
    void do_something();
};

// A.cpp
#include "A.hpp"
#include <vector>

std::vector<int> impl_database_for_do_something;

static void impl_helper_for_do_something(const std::vector<int>& database){}

void A::do_something(){ impl_helper_for_do_something(impl_database_for_do_something); }

Instead of this one :

// A.hpp
#include <vector>
class A
{
public:
    void do_something();

private:
    std::vector<int> database_for_do_something_;
    void helper_for_do_something(const std::vector<int>& database){}
};

Could I hide implementation details and speed-up compilation with variables and static functions defined in the source file ? If not, what's wrong with this design (besides inheritance) ?

Was it helpful?

Solution

If you use global vectors to store state as you propose, you will somehow have to make sure that different instances of class A use different parts of the vector (besides the obvious difficulties of doing so, consider how much harder this gets if different threads use different instances of A). This design only makes very much sense if A is a singleton.

OTHER TIPS

In the first case there is only one instance of impl_database_for_do_something for the entire program. You want one instance of it per instance of A. So the code is not in any sense equivalent.

Your first design has one vector for all instances of A; the latter has one per instance. Read up on instance variables vs. class variables.

This is not, at all, PIMPL: Pointer to IMPLementation.

You could do it this way:

// A.hpp
#include <boost/shared_ptr.hpp>

class A
{
public:
  A();
  void foo();

private:
  struct Impl;
  boost::shared_ptr<Impl> _impl;
};

// A.cpp
#include <vector>
#include "A.hpp"

struct A::Impl {
  std::vector<int> _data;
};

A::A(): _impl(new std::vector<int>()) {}

void A::foo() {
  _impl->_data.push_back(3);
}

Warning: this code does not deal with proper copying / assignment behavior, it is left as an exercise to the reader.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top