# Correct use of boost::shared_ptr - More questions

This topic is 4866 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I have a class:
class Functor
{
public:
virtual void operator()() = 0;
};

template <class T, class R>
class SObjFunctor : public Functor
{
protected:
boost::shared_ptr<T> obj;
typedef R& (T::*funcType)();
funcType func;

public:
unsigned long size(){return sizeof(*this);}

SObjFunctor(T* o, funcType f) : func(f)
{
boost::shared_ptr<T> tmpPtr(o);
obj = tmpPtr;

/* tmpPtr destroyed when out of scope */
}

void operator()()
{
(obj->*func)();
}

};

My question is about the constructor. Can I just have the constructor use the passed in T* o as part of an initialiser list:
SObjFunctor(T* o, funcType f) : obj(o), func(f)
{}

Or would this be completely incorrect?

##### Share on other sites
Yeah, you should be able to that. You just have to be positive that 'o' was created with 'new' and its not just any pointer, because it will delete it when you class gets destructed.

##### Share on other sites
I'd go with:

SObjFunctor(const T& o, funcType f) :   obj(new T(o)), func(f){}

Making a copy of the T object that got passed in.

Or I would just use boost::function ;)

##### Share on other sites
Of course if you're making a copy, you might as well be storing it by value. Either way, you should watch out for slicing.

##### Share on other sites
Quote:
 Original post by SiCraneOf course if you're making a copy, you might as well be storing it by value. Either way, you should watch out for slicing.

Not really. A functor ought to be lightweight, since they are passed around a lot, and generally by value.

##### Share on other sites
This is a polymorphic functor class; the virtual operator() implies that the functor is meant to be passed by reference/pointer. Of course, in general I agree that functors should have value semantics, but in this case trying to use the functor with value semantics most likely will lead to slicing. It would probably be best if the base functor type was a value type and the functor type in the OP was instead used as the implementation portion of a pimpl. Or use a pre-existing functor like previously suggested.

1. 1
Rutin
42
2. 2
3. 3
4. 4
5. 5

• 9
• 27
• 20
• 14
• 14
• ### Forum Statistics

• Total Topics
633388
• Total Posts
3011614
• ### Who's Online (See full list)

There are no registered users currently online

×