4

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.

LSerni
  • 55,617
  • 10
  • 65
  • 107
Steve M. Bay
  • 313
  • 1
  • 3
  • 15

4 Answers4

6

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.

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
3

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.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • I was sure, that is should use copy constructor, but the how-to wasnt clear. Ill try it! – Steve M. Bay Nov 02 '12 at 18:11
  • Okay, I see whats the next problem: cannot allocate an object of abstract type# because the following virtual functions are pure within – Steve M. Bay Nov 02 '12 at 18:19
  • So you don't actually have an object of type T. You have an object of a subclass of type T. The only reasonable way to clone this object is if the T interface includes a clone() type method that does it for you. – Yakk - Adam Nevraumont Nov 02 '12 at 18:20
  • You say something... :D I'll try write this clone(), but not sure, what sould exactly write into.. – Steve M. Bay Nov 02 '12 at 18:49
  • 1
    `virtual T* clone() const` is the traditional `clone()` signature. Subtypes override it and return a pointer to the subtype, which lets you clone an instance of the object even if you don't know the type. – Yakk - Adam Nevraumont Nov 21 '12 at 19:22
1

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.

0

I just found this: C++ Idioms/Virtual Constructor

Steve M. Bay
  • 313
  • 1
  • 3
  • 15