Search code examples
c++memorysolid-principlessingle-responsibility-principlepointers

Does memory handling violate the Single Responsibility Principle?


SRP : There should never be more than one reason for a class to change

If I have a class A whose responsibility is performing taskA. Does the memory handling inside class A violate the SRP? If so, Is it acceptable? What solutions do we have?

Note: Using delete or a std smart_ptr is the same, it is still a sort of memory handling (e.g. : We might want to change unique_ptr auto_ptr, etc...).

Here is how I thought one could deal with it. I don't find it good enough because MemoryHandler has to change for two reasons: if A needs more attributes or if we want another way of handling memory.

Note about the examples: Normally you would have a lot of methods (member functions) and multiple attributes (member variables). We may suppose owned_ptr is a functor (an algorithm / pattern strategy) or anything else needed by class A and task A.

Example 1 (cpp):

class A {
   Object* owned_ptr;

public:
   taskA() { ... }
   ~A() { delete owned_ptr; }
};

Example 2 (cpp):

class MemoryHandler {
   Object* owned_ptr;
public :
   Object* object() { return owned_ptr; }
   ~MemoryHandler() { delete owned_ptr; }
};

class A {
   MemoryHandler data;

public:
   taskA() { ... }
   ~A() { }
};

Solution

  • Pragmatically, the memory handling in your example does not violate the SRP. You're following a standard approach to memory handling in your environment, which is not really adding a separate responsibility. You wouldn't say, for example, that instantiating objects was a separate responsibility, and your case isn't all that different.

    (If you'd written your own allocator and your class was full of both low-level memory-management code and higher-level domain code, that would be a different story.)