Suppose you have a type T
, and a pointer T* ptr;
Assuming ptr
is currently a valid pointer, then T* ptr2 = new T(*ptr);
should invoke the copy constructor on T to create a new pointer on the heap. Now, this requires that your type T
has a correctly written copy constructor and destructor and the like.
Create a new object from existing pointer C++
-
29-07-2021 - |
Domanda
I've looked for the answer but still can't figure this out.
Sorry, but my work is too complex to copy here sample code.
I have a function, which gets a pointer as parameter; I use it, but later, I need a kind of callback, where I want to use my old pointed object.
The problem is, when this callback is invoked, the pointer has already been deleted or freed. My idea was to make a copy of the pointed object on the heap, and free it when callback is finished. But I got lost between pointers, copy constructors and other stuff. The solution is probably quite simple, but I'm stuck.
Soluzione
Altri suggerimenti
If you have a T * p
, then you can make a new object like so:
T x(*p);
Or, if you must (but seriously, don't!), a dynamically allocated object:
T * q = new T(*p);
Don't use the second form. There's no end to the headache you're inviting with that.
I just found this: C++ Idioms/Virtual Constructor
Another way to do it:
MyObject* pointerFromOld;
...
MyObject newObject = *pointerFromOld;
Asterisk before a pointer returns the object it points to (interprets the contents of the address as the object), while assigning that object to newObject makes its copy.