[英]Is there a mechanism in C++ to make a full copy of a derived class from a base class pointer without dynamic memory allocation?
[英]c++ dynamic allocation for a copy of a class pointed by a pointer
我有一個類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
指向。 我該如何實現?
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.