Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing `this` to a function as a shared_ptr

Tags:

c++

c++11

I am writing some example code that hopefully captures my current struggle. Let's assume I have a class for some general shapes Shape and a nice Function that doubles the perimeter of any shape

float DoublePerimeter (shared_ptr<Shape> shape)
  return 2*shape->GetPerimeter();
};

Is it possible to use such a function in a class itself?

class Square : Shape {
  float side = 1;
  public:
  void Square(float aside) : side(aside) {;}
  float GetPerimeter(){return 4*side;}
  void Computation() { DoublePerimeter (??????);}
};

What can I pass in the ?????? to make this work? I tried using something like

shared_ptr<Shape> share_this(this);

and also tried enable_shared_from_this<> for my class, however the pointer that I pass to the function always returns null on lock. Is this even possible, or is this bad design? Am I forced to make this function a member function?

like image 866
the.polo Avatar asked Jul 31 '26 08:07

the.polo


1 Answers

If you don't want to use enable_shared_from_this, perhaps because your objects are not always owned by a shared pointer, you can always work around it by using a no-op deleter:

void nodelete(void*) {}

void Square::Computation() { DoublePerimeter({this, nodelete}); }

but it's a hack (and a fairly expensive one at that, since you're allocating and deallocating a control block just to con the function you're calling).

A cleaner solution, albeit one that might require more typing, is to separate your free function implementation from the ownership scheme:

float DoublePerimeter(Shape const& shape)
  return 2*shape.GetPerimeter();
};

float DoublePerimeter(std::shared_ptr<Shape> shape)
  return DoublePerimeter(*shape);
};

void Square::Computation() const { DoublePerimeter(*this); }
like image 191
Useless Avatar answered Aug 01 '26 23:08

Useless