Topic: STL allocation of objects that own other objects
Author: dekai@cs.ust.hk (Dr. Dekai Wu)
Date: 1997/02/23 Raw View
I'd be grateful for
- any existing solution I've overlooked, within the current Draft,
- comments on the possible solution.
PROBLEM
The allocation behavior of the standard containers seems to overlook
something if you've defined a class X that owns class Y objects (via
pointer, a la auto_ptr). Let's say you've defined your own custom
allocator A for some efficiency reason, and you've got a vector<X, A>.
Then you'd want *both* the X and Y objects to get allocated by A,
whenever the vector constructs new X objects.
But from my reading of the the Draft (and in all Standard C++ Library
implementations I've seen so far, including KCC/Modena), the vector<>
would in effect do this:
1 A::pointer p = A.allocate( 1, 0 );
2 A.construct( p, X() ); // basically "new ((void*)p) X"
Because of line 2, there's no way for X's constructor to know it
should use A to allocate the Y it owns.
This can be a serious practical problem, since Y in practice can be
far larger than X (eg, Y may itself be a set of sets).
POSSIBLE SOLUTION (BUT REQUIRING CHANGE TO THE ALLOCATOR INTERFACE)
The problem could be solved if the vector<> container had also passed
the allocator:
2 A.construct( p, X(), A ); // basically "new (A, (void*)p) X"
You could then define your own
void* operator new(size_t n, A<X>& al, void* p)
that uses A to allocate a Y object.
Note that the following template would allow all default cases to be
handled invisibly:
3 template <class T>
4 void* operator new (size_t n, allocator<T>& al, void* p)
5 {
6 return new (p) T;
7 }
(This just generalizes P.J. Plauger's Dinkumware specification of
void* operator new(size_t n, allocator<T>&al)
to handle a placement address.)
--
Dekai Wu Assistant Professor HKUST
Dept of Computer Science tel. +852 2358-6989 dekai@cs.ust.hk
Univ of Science & Technology sec. +852 2358-7000 www.cs.ust.hk/~dekai
Clear Water Bay, Hong Kong fax. +852 2358-1477 ftp.cs.ust.hk/pub/dekai
---
[ comp.std.c++ is moderated. To submit articles: try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ FAQ: http://reality.sgi.com/employees/austern_mti/std-c++/faq.html ]
[ Policy: http://reality.sgi.com/employees/austern_mti/std-c++/policy.html ]
[ Comments? mailto:std-c++-request@ncar.ucar.edu ]