Re: Passing address of stack memory to placement new operator
* mlimber:
Alf P. Steinbach wrote:
* mlimber:
Alf P. Steinbach wrote:
* Frederick Gotham:
Alf P. Steinbach posted:
Fred* f = new(p) Fred();
Should be
Fred* f = ::new(p) Fred();
Could you please explain that?
Unqualified placement new might invoke a custom Fred allocation function
instead of the basic placement new.
But if there is a custom placement new operator defined for Fred,
presumably it is meant to be used.
Depends what you want. If you want to leave the decision of how to
allocate the memory to class Fred, use 'new'. If you want to take
charge, saying Here Should Be Placement Construction, use '::new'.
In either case, we're using placement new and allocation is done
outside the new operator itself.
Yes.
(If the custom placement new does
something different, it has changed the semantics of that operator
No (it's a circular argument: assuming that 'new' invokes some standard
semantics for the allocation function, then arguing that if it doesn't
the semantics have been changed, but the only standard semantics is for
'::new').
and
is no different than changing the semantics of other overloaded
operators, which is generally considered evil as in FAQ 13.9.)
Yes.
Leaving it unqualified seems fine to me.
If you want to leave the choice of allocation scheme to class Fred, yes,
but given that you've declared a buffer to put the object in, how likely
is that?
By the same logic I think we could justly say that if we've overridden
the placement new operator for this class,
No.
how likely is it that we want to use the global one?
Very. E.g., consider implementing something like a std::vector. Should
a std::vector<Fred> use Fred's placement allocation function if one is
defined? With MSVC 7.1 it does. With g++ 3.4.4 it doesn't. When that
function is inaccessible the code doesn't compile with MSVC 7.1, and I
don't see accessibility of that function as a requirement for standard
container elements (so I think that compiler is wrong). With g++ 3.4.4
the code compiles (which I think is correct, and anyway, it is IMO how a
properly designed & implemented class should work, no surprises).
Also, Sutter and Alexandrescu note, "If a
class defines any overload of operator new, it should provide overloads
of all three of plain, in-place, and non-throwing operator new. If you
don't, they'll be hidden and unavailable to users of your class." (_C++
Coding Standards_, Item 46).
Yes.
However, blaming the designer of class Fred is just that, assigning
blame: instead one should IMO make sure that there is no blame to
assign, by the simple expedient of using code that does what one wants
regardless of the class in question.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?