1

I would like to use a boost::shared_ptr in order for WSACleanup() to be called when my function goes out of scope, like this:

void DoSomething() {
    WSAStartup(...);
    boost::shared_ptr<void> WSACleaner(static_cast<void*>(0), WSACleanup);
}

This does not compile,

Error 1 error C2197: 'int (__stdcall *)(void)' : too many arguments for call C:\projects\svn-5.3\ESA\Common\include\boost\detail\shared_count.hpp 116

any thoughts?

MD XF
  • 7,860
  • 7
  • 40
  • 71
tsotso
  • 322
  • 1
  • 2
  • 9

2 Answers2

1

From the docs: "The expression d(p) must be well-formed" (i.e. WSACleanup(static_cast<void*>(0) must be well-formed.)

One possible solution:

boost::shared_ptr<void> WSACleaner(static_cast<void*>(0),
                                   [](void* dummy){WSACleanup();});
MSalters
  • 173,980
  • 10
  • 155
  • 350
1

You can create a class Awhich destructor invoques WSACleanup and instance of shared_ptr with it:

class A
{
    public:
        ~A() { WSACleanup(...); }
}

....

void DoSomething() {
    WSAStartup(...);
    boost::shared_ptr<A> x(new A);
}
Tio Pepe
  • 3,071
  • 1
  • 17
  • 22
  • 4
    But then, you can just create a local variable of that type. And now that you are on it, you can call `WSAStartup` from the constructor. – rodrigo Oct 11 '11 at 12:27
  • @rodrigo yes you are right, but can use it wherever you want in other scope of program. – Tio Pepe Oct 11 '11 at 12:30
  • 1
    Using a class with ctor and dtor is the far cleaner solution. It's also easily extended to situations where you might have multiple sections of code that require network connections, potentially overlapping in time. Just use a private static counter to keep track of the ctor-dtor balance. – MSalters Oct 11 '11 at 12:34