Suddenly in this article ("problem 2") I see a statement that C++ Standard prohibits using STL containers for storing elemants of class if that class has an overloaded operator&()
.
Having overloaded operator&()
can indeed be problematic, but looks like a default "address-of" operator can be used easily through a set of dirty-looking casts tha开发者_JAVA百科t are used in boost::addressof()
and are believed to be portable and standard-compilant.
Why is having an overloaded operator&()
prohibited for classes stored in STL containers while the boost::addressof()
workaround exists?
Without having looked at the links, I suppose the tricks in boost::addressof()
were invented well after the requirement to not to overload unary prefix &
for objects to be held in containers of the std lib.
I vaguely remember Pete Becker (then working for Dinkumware on their standard library implementation) once stating that everyone who overloads the address-of operator and expects their standard library implementation still to work should be punished by having to implement a standard library which does this.
Probably because it's less hassle to just prohibit the use of overloaded operator&() classes than to create a std::addressof() function and replace every use of & in container code with it.
The standard was finalized in 1998 with fixes in 2003, whereas boost::addressof
dates to early 2002.
Moreover, it's not clear that addressof
is the answer. Overloads of operator&()
indicate that raw pointers are supposed to be avoided. The Allocator::address
member provides the best interface to get from Allocator::reference
to Allocator::pointer
, so in general theory, you should be able to effectively introduce an operator&
override to an otherwise well-behaved class with a custom allocator.
Considering that references do almost everything that pointers do, and the Allocator interface abstracts everything else, there should be no need for raw pointers.
Convenience to the library implementers should not be an issue. The ill-defined semantics of Allocator::pointer
are a problem, and what I've read so far in C++0x doesn't clear that up.
C++0x removes any mention of operator&
from CopyConstructible, and furthermore doesn't require anything-Constructible for container arguments at all — the user can stick to emplace
. Even vector
only requires Destructible, although I suppose actually using insert
or erase
would require more.
(Note that, in the strictest reading, overloads are not forbidden in C++03. You are just not allowed to change the value or type of the builtin.)
精彩评论