C++ Logo

std-proposals

Advanced search

Re: [std-proposals] std::came_from_new [[must_new]]

From: Rainer Deyke <rainerd_at_[hidden]>
Date: Thu, 3 Sep 2026 19:12:07 +0200
On 9/3/26 17:54, Frederick Virchanza Gotham via Std-Proposals wrote:
> Some libraries have classes that you must create objects of with
> 'new', because later they're destroyed by an object management system
> which uses 'delete'.
>
> An example of this is wxWindow in the wxWidgets library. You can do this:
>
> auto *p = new wxButton();
> main_window.AddWidget( p );
>
> but you can't do this:
>
> wxButton b;
> main_window.AddWidget( &b );
>
> The problem with the latter is that it will later call 'delete' on a
> variable that wasn't new'd.

That sounds like a library design issue. If wxWidgets wants to take
ownership of a pointer, it should take a std::unique_ptr as argument.

> So I was thinking, would it be helpful if C++29 had the following?
>
> class wxWindow {
> public:
> wxWindow(void)
> {
> assert( std::came_from_new(this) );
> }
> };

If wxWidgets wants to track whether wxWindow instances are allocated
through operator new, it can do this by overloading operator new for the
wxWindow type. This would come at a cost, both in performance and in
memory usage. However, the cost would be limited to instances of the
wxWindow class, which is better than forcing the cost on every object
allocated through operator new.

You are probably thinking that the default operator new implementation
already tracks which memory it owns. This could be true, but:
   * It is not true for every default operator new implementation, nor
should it have to be.
   * It produces false positives: a wxWindow could be a member of an
object that is allocated by operator new.
   * It produces false negatives: a wxWindow could be allocated with a
non-default operator new implementation.


-- 
Rainer Deyke - rainerd_at_[hidden]

Received on 2026-09-03 17:12:21