Why were the non-placement new
expression and the delete
expression implemented as language built-in instead of regular functions?
If we have...
a way of requesting/giving back memory to the OS
a way of explicitly invoking a constructor (placement
new
)a way of explicitly invoking a destructor (
~T()
)
...why couldn't non-placement new
and delete
just be regular functions in the Standard Library? Example:
template <typename T, typename... Ts>
T* library_new(Ts&&... xs)
{
auto* ptr = /* request enough memory for `T` from OS */;
new (ptr) T(std::forward<Ts>(xs)...);
return ptr;
}
template <typename T>
void library_delete(T* ptr)
{
ptr->~T();
/* reclaim memory for `T` from OS */
}
new
anddelete
are in the language since the beginning and the placement versions were added later? – Selfpossessednew
anddelete
put into the language instead of the standard library in the first place. – Doorsillnew
is not provided as a function implemented using placementnew
. – Selfpossessedlibrary_delete
find the correctoperator delete
to return the memory to? – Emblementsnew
into 2 lines and do the same thing manually – Sweenynew
/delete
or if it could have been implemented as a library feature. – Laurentianmalloc
andfree
where you had comments. – Sweenynew
/delete
operators were created, there was absolutely no way to write what you have written here! You needed the "magic" to be provided by the compiler. – Bendyoperator delete
be called according to the dynamic type of the object being deleted. I don't see how yourlibrary_delete
function can accomplish that. If you try to dooperator delete(ptr);
, you'll just end up calling theoperator delete
that is in scope, which isn't necessarily the correct one. – Bendydelete
. – Laurentiannew
dates back to C with Classes, circa 1980. Templates aren't accepted until ten years later, in 1990. Placementnew
dates to Cfront 2.0, in 1989. – Damiendamiettamove
andintptr_t
,size_t
...). Great plan. On the contrary, I'd ask why is the standards committee to darn concerned about breaking compatibility with versions that are utterly incompatible anyway, and why are they so darn reluctant to adding keywords for things that make sense as keywords. Note howwchar_t
is a keyword which is total bollocks, butsize_t
is not. – Selfexamination