Widget wag = * new widget ()

I just came across a C ++ SDK that heavily uses this really weird pattern *new. I don’t understand why they do this.

What is the point of building objects using * new, for example. Widget wag = *new Widget();?

Update: I wonder what they are actually doing XPtr<T> p = *new T;- should be the semantics of some kind of smart pointer magic. Still doesn't make much sense. I am really sure that the SDK is of high quality.

+3
source share
5 answers

It creates a new object and then copies it. The pointer to the source object is discarded, so a memory leak may occur.

. , Widget . , .

. , , , . , , , . . , ?

+4

, ? , , , .

: . , SDK .

: , , , . XPtr, , , . SDK - - , , . , , : , .

+4

:

Widget wag = *(new Widget());

// or
Widget wag;

, . , .

, . , , .

+3

commom , ref, , IncRef:

SmartPtr<Type> ptr = new Type();

, IncRef:

SmartPtr<Type> ptr = *new Type();

, IncRef. ref, 2, , .

, , . XPtr, , , .

+2

. ,

int &a = *new int();
delete &a;

. ( ), , . ,

template<typename T>
struct XPtr {
    T *ptr;
    XPtr(T &t):ptr(&t) { }
    ~XPtr() { delete ptr; }
};

...
XPtr<T> p = *new T;

Or even more complex, with reference counting - so that p can be copied, and XPtr keeps track of all its copies, etc.

+1
source

Source: https://habr.com/ru/post/1702487/


All Articles