【发布时间】:2013-07-30 11:26:10
【问题描述】:
我有一堂课Keywords:
#include <boost/lambda/lambda.hpp>
class Keywords
{
public:
///Constructor
Keywords(const char*,vector<shared_ptr<RegularExpression>>,vector<string>);
Keywords(const Keywords& other);
private:
const char * xmlFile;
vector<shared_ptr<RegularExpression>> vreg;
vector<string> sw;
}
我想为const char*和vector<shared_ptr<RegularExpression>>构造一个拷贝构造函数
我的编码是否正确?
Keywords::Keywords(const Keywords& other):xmlFile(new char[100]),vreg(other.vreg.size())
{
strcpy((char*)xmlFile, (char*)other.xmlFile);
for (std::size_t i = 0; i < other.vreg.size(); ++i)
vreg[i] = shared_ptr<RegularExpression>(new RegularExpression(*other.vreg[i]));
}
据我了解,我复制了 Const char* 和 shared_ptr 的向量。
谢谢。
*所以在去掉 const char * 后我就有了*
class Keywords
{
public:
///Constructor
Keywords(string,vector<shared_ptr<RegularExpression>>,vector<string>);
Keywords(const Keywords& other);
private:
string xmlFile;
vector<shared_ptr<RegularExpression>> vreg;
vector<string> sw;
}
复制构造函数是:
Keywords::Keywords(const Keywords& other):vreg(other.vreg.size()),sw(other.sw)
{
for (std::size_t i = 0; i < other.vreg.size(); ++i)
vreg[i] = shared_ptr<RegularExpression>(new RegularExpression(*other.vreg[i]));
}
解说员:
Keywords::~Keywords()
{
sw.clear();
vreg.erase(vreg.begin());
}
【问题讨论】:
-
为什么不用
std::string而不是char*?编译器生成的副本成员是正确的。 -
是的,我正在考虑。是的,这是真的。而不是这个
-
还有
char const *到std::string的隐式转换,所以你可以用同样的方式调用你的构造函数 -
智能指针矢量做得好!
-
使用
shared_ptr将允许多个对象共享同一个RegularExpression的所有权,但您不会共享所有权,因为您的复制构造函数为新的RegularExpression对象创建了新的RegularExpression对象。如果这是你想要的,那你就写对了。
标签: c++ constructor shared-ptr