Re: setter for deleter in boost::shared_ptr (and alike)
Alf P. Steinbach ha scritto:
* Alberto Ganesh Barbati:
Alf P. Steinbach ha scritto:
* Abhishek Padmanabh:
Why doesn't boost::shared_ptr<> provide a setter for the deleter when
it provides a getter?
What's provided is a pointer to the deleter function pointer or functor
object,
template<class D, class T>
D * get_deleter(shared_ptr<T> const & p);
Since there's no 'const' that pointer can used to change the deleter
function.
It's true that with the pointer returned by get_deleter() you can call
non-const functions on the deleter, however you still can't replace it
with another (possibly unrelated) deleter
I see no wording to that effect, neither in TR1 nor the draft standard.
If you would care to cite chapter & verse, please?
The onus of the prove is on you.
And technically, nothing prevents the replacement of the deleter.
<code>
#include <iostream>
#include <ostream>
#include <boost/shared_ptr.hpp>
typedef void(*MyDeleteFunc)(int*);
void destroy( int* p ) { delete p; }
void bah( int* ) { std::cout << "Bah!" << std::endl; }
int main()
{
boost::shared_ptr<int> p( new int(123), destroy );
MyDeleteFunc* d = boost::get_deleter<MyDeleteFunc>( p );
*d = bah;
}
</code>
I agree that this kind of code is embarrassing and that having
get_deleter return a const pointer might be better. However, your
example only proves that you can perform an *assignment*, which is not
the same as *replacing* the deleter, as I were objecting. Notice that,
in order for your code to work you need that:
1) the type of the new deleter must match the type of the old deleter.
As there is no way to determine such type from the interface, you must
know it in advance.
2) the type of the deleter must be Assignable, but it's only required to
be CopyConstructible. Just provide the deleter a private (deleted?)
assignment operator and you would need to rely onto explicit destruction
and placement new... not the code one can write by mistake and expect it
to work properly.
So, you see, the case you present is a very special one, which does not
actually disprove my original statement.
Ganesh
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]