2014-06-22 57 views
0

我有一个类class1及其构造函数class1(int i)和复制构造函数class1(const class1& other)C++指针指向的类的副本的动态分配

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。 我该如何做到这一点?

+2

你可以做'internalC = new class1(* c)'。 – 0x499602D2

+0

这会导致错误:无法将'class1 **'转换为'作业中的'class1 *' –

+0

您是否可以发布已更新的'consumer :: set'实现,因为我认为0x49 ...建议看起来正确。 – ilent2

回答

6

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 
} 
+0

正如我所说的,'class1'的构造函数是'class1(int i)'。你写的东西无法工作。 –

+0

@ the_candyman,是的,它可以。容易。请再次阅读您书中的相关部分。 – chris

+1

@the_candyman出于什么原因?因为'consumer'会默认构造'internalC'?那么你有一些选择。第一个是给class1一个默认的构造函数,第二个是给'consumer'一个构造函数,它通过传递一个int来构造'internalC',第三个选项是使用boost :: optional内部函数。 '如果你想要的是'internalC'在设置之前不存在。 –