我有一个类 class1
,它有一个构造函数 class1(int i)
和一个复制构造函数 class1(const class1& other)
。
class1
的实例是动态创建的,因为 int
参数在编译时是未知的。
我的问题是我必须在生产者对象和消费者对象之间传递这个指针:
void producer::produceAndSend(...) {
class1 *c1 = generate(...);
consumerObj.set(c1);
}
class consumer {
class1 *internalC;
void set(class1 *c);
}
void consumer::set(class1 *c) {
this->internalC = c; //This only copies the pointer, not the content
}
我想存储 c1
指向的对象的拷贝,并且此拷贝必须由 internalC
指向。
我怎样才能做到这一点?
最佳答案
Instances of class1 are created dynamically, since the int argument is not known at compile time.
这不是动态分配的目的。您可以使用运行时参数创建具有自动存储持续时间的对象。事实上,通过不使用动态分配,您的问题会自动解决,不会涉及内存泄漏。
void producer::produceAndSend(...) {
class1 c1 = generate(...);
consumerObj.set(c1);
}
class consumer {
class1 internalC;
void set(class1 c);
}
void consumer::set(class1 c) {
this->internalC = c; //This only copies the pointer, not the content
}
关于c++动态分配指针指向的类的拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24353555/