[英]Create a new object from existing pointer C++
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. 解决方案可能很简单,但我遇到了麻烦。
If you have a T * p
, then you can make a new object like so: 如果您有一个T * p
,那么您可以像这样创建一个新对象:
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. 令人头痛的是没有尽头。
Suppose you have a type T
, and a pointer T* ptr;
假设您有一个类型T
和一个指针T* ptr;
Assuming ptr
is currently a valid pointer, then T* ptr2 = new T(*ptr);
假设ptr
当前是一个有效的指针,则T* ptr2 = new T(*ptr);
should invoke the copy constructor on T to create a new pointer on the heap. 应该在T上调用复制构造函数以在堆上创建一个新的指针。 Now, this requires that your type T
has a correctly written copy constructor and destructor and the like. 现在,这要求您的类型T
具有正确编写的副本构造函数和析构函数等。
我刚刚发现了这一点: C ++习语/虚拟构造函数
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. 指针返回指向其的对象之前的星号(将地址的内容解释为对象),同时将该对象分配给newObject进行复制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.