Re: auto_ptr in exception safety design
"George" <George@discussions.microsoft.com> wrote in message
news:58080EE2-57AC-4D07-9EC2-C128F3BDDEB7@microsoft.com
http://www.gotw.ca/gotw/059.htm
--------------------
Indeed, often the best way to implement the Pimpl idiom is exactly as
shown in Example 4 above, by using a pointer (in order to take
advantage of nonthrowing operations) while still wrapping the dynamic
resource safely in an auto_ptr manager object. Just remember that now
your object must provide its own copy construction and assignment
with the right semantics for the auto_ptr member, or disable them if
copy construction and assignment don't make sense for the class.
--------------------
1. What means "the right semantics for the auto_ptr member"?
What I believe Heb is trying to say is this: if you don't write any copy
constructor for your class, the compiler will provide its own, which
will use auto_ptr's copy constructor. This way, if you make a copy of
your object, you would transfer ownership of the Pimpl class to the new
instance - which is highly unlikely to be what you want:
Widget w1; // w1 creates and holds a Pimpl pointer
w1.SomeMethod(); // calls pimpl->SomeMethod();
Widget w2 = w1;
// Now w2 holds Pimpl that used to belong to w1, and w1 has a NULL
pointer
w1.SomeMethod(); // Oops: no Pimpl
So, if you want to make your object copyable, you will have to write a
copy constructor that explicitly handles the pimpl pointer (e.g. by
making a deep copy of the Pimpl class). Or, you can disable the copy
constructor altogether. The compiler-generated constructor is
unsuitable, so you have to suppress it one way or another.
2. "disable" means for the class, copy construction and assignment
are not needed? Curious. Never thought of a class which does not need
that two basic functions. :-)
Suppose you have a car. If you want another car, you can't just copy the
one you have - you need to get a factory to build (create) you a new
one.
Suppose you have a class Car in your program that models a car. Real
life cars can't be copied, so your modelling class usually shouldn't,
either. When you need a new car, you have the "factory" create a new
instance of the class.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925