0

I have something like this in pagePtr.h

typedef int (*FunPtrType)(char* sz, unsigned int max_bytes, char* arg1,
char* arg2, char* arg3, char* arg4);

and a static function which creates a object

static pagePtr* CreatePage( FunPtrType Ptr2Fun)
{
    return new pagePtr(ptr2Fun);
}

would boost::scoped_ptr help me not worry abt deleting those created abject later. if yes how should I implement in this case. And what could be the other possible better options, if available, to delete those objects created.

cybercop
  • 105
  • 1
  • 7

2 Answers2

5

boost:scoped_ptr is not copyable so cannot be returned from CreatePage(). If C++11 is available std::unique_ptr could be used:

static std::unique_ptr<pagePtr> CreatePage( FunPtrType Ptr2Fun)
{
    return std::unique_ptr<pagePtr>(new pagePtr(ptr2Fun));
}

Is there a reason pagePtr is not copyable? If not and it is inexpensive to copy then return by value.

If pagePtr is non-copyable and std::unique_ptr is not available then you could use boost::shared_ptr to remove the responsiblity from the caller for destructing the returned pagePtr. With the downside that using shared_ptr does not indicate sole ownership and pay the price for unrequired reference counting (see What C++ Smart Pointer Implementations are available? for more information and descriptions on the available smart pointers).

From the posted code, pagePtr appears to a wrapper around a function pointer so consider using boost::function instead, which is copyable, and remove pagePtr completely:

typedef boost::function<int(char* sz,
                            unsigned int max_bytes,
                            char* arg1,
                            char* arg2,
                            char* arg3,
                            char* arg4)> FunPtrType;
Community
  • 1
  • 1
hmjd
  • 120,187
  • 20
  • 207
  • 252
3

The idiom for having a function that dynamically allocates an object and safely returns ownership to the caller is to return a std::unique_ptr:

std::unique_ptr<foo> create_foo()
{
  return std::unique_ptr<foo>(new foo());
}

This tells the caller explicitly that they are getting ownership of the object and the object will be destroyed when their std::unique_ptr is destroyed (unless ownership is further passed elsewhere).

Applied to your example:

static std::unique_ptr<pagePtr> CreatePage( FunPtrType ptr2Fun)
{
    return std::unique_ptr<pagePtr>(new pagePtr(ptr2Fun));
}

As for why other pointers are not applicable:

  • boost::scoped_ptr cannot pass ownership at all - it is the most restrictive of the smart pointers (pretty much equivalent to a const std::unique_ptr)
  • std::auto_ptr is deprecated because it provides move semantics through copying
  • std::shared_ptr would work but doesn't make much sense - the function certainly isn't going to be sharing ownership with the caller because the function is ending
Joseph Mansfield
  • 108,238
  • 20
  • 242
  • 324