Re: BeginInvoke on a delegate
- From: Jeroen Mostert <jmostert@xxxxxxxxx>
- Date: Fri, 27 Jun 2008 21:15:07 +0200
Bob Altman wrote:
"Jeroen Mostert" <jmostert@xxxxxxxxx> wrote in message news:48653159$0$14347$e4fe514c@xxxxxxxxxxxxxxxxxIt hurts when you move your arm that way, doesn't it? :-)Bob Altman wrote:I looked at the article you referenced in your reply (http://msdn.microsoft.com/en-us/library/aa730837(VS.80).aspx) and that author provides a more complete implementation of your managed wrapper class (shown below). I have a couple of questions about his code:Those are the semantics of the class -- passing it a pointer means it'll take ownership of the allocated memory. The STL's auto_ptr works the same way.
1. Why does the destructor call "delete m_ptr"? This wrapper didn't allocate that memory.
Aha! That also explains why the copy constructor modifies the "right" object by clearing its pointer to the native data. That's what the author meant by "transfer of ownership semantics".
But that still leaves the question of whether or not it's even correct to call delete on the pointer. What if the native object was allocated on the stack, e.g.
void MySub() {
MyNativeClass c;
MyOtherSub(c);
}
void MyOtherSub(MyNativeClass& c) {
// At this point we have no idea whether
// c was allocated on the stack or the heap
AutoPtr<MyNativeClass> p(&c);
}
Assuming I got the syntax at least kind of correct, what will happen when the AutoPtr goes out of scope and its destructor tries to delete c?I'm pretty sure demons will fly out of your nose, since that invokes undefined behavior.
The reason the class is named AutoPtr is to evoke images of the STL's auto_ptr, which *also* isn't used this way. Indeed, there's no point at all to using auto_ptr on objects you didn't construct yourself (as MyOtherSub is doing here).
You can still write MyOtherSub this way, with some care:
void MyOtherSub(MyNativeClass& c) {
AutoPtr<MyNativeClass> p(new MyNativeClass(c));
}
But of course copying the object isn't always desirable or even possible.
If you want to pass a stack-allocated objects, don't use smart pointers. On the other hand, smart pointers are a pretty good approach to avoiding memory leaks for objects you *can't* stack-allocate.
--
J.
.
- Follow-Ups:
- Re: BeginInvoke on a delegate
- From: Bob Altman
- Re: BeginInvoke on a delegate
- References:
- BeginInvoke on a delegate
- From: Bob Altman
- Re: BeginInvoke on a delegate
- From: Bob Altman
- Re: BeginInvoke on a delegate
- From: Bob Altman
- Re: BeginInvoke on a delegate
- From: Jeroen Mostert
- Re: BeginInvoke on a delegate
- From: Bob Altman
- BeginInvoke on a delegate
- Prev by Date: Re: BeginInvoke on a delegate
- Next by Date: Re: BeginInvoke on a delegate
- Previous by thread: Re: BeginInvoke on a delegate
- Next by thread: Re: BeginInvoke on a delegate
- Index(es):
Relevant Pages
|