2. AGENDA
1. How to avoid object copy in C/C++ program?
2. An example: DataBuffer/Employee
3. Summary: How to implement COW?
4. Overhead: COW is worthy to big object, and lots of copying
but few writing
5. TypeFactory<T> in GOAM
3. How to avoid object copy in C/C++ program?
• Passing/return reference(&):
void foo(const std::vector<int>& data);
const std::string& XsdDNDescription::toString();
• Passing/return pointer(*):
void bar(std::vector<int>* pData);
DmAttribute* DmTable::getDmAttribute(const DmAttributeId& aid) const;
• Passing/return smart pointer:
void hoo(const boost::shared_ptr<std::list<int> > pData);
DmObject_SmartPtr DmTable::_CreateCachedObject(const DmObjectId& objId_);
• COW: 既想占引用 / 智能指针的好处 ( 延迟 / 避免不必要的拷贝操作,提高
性能 ) ,又想保持对象之间的独立性 ( 写时 ) 。
R4.3, /vob/oam_generic_srv/src/xsdFunction/Src/XsdDNDescription.cc, line 158:
const string& XsdDNDescription::toString()
{
string buffer ="";
for (DnSyntaxMap::const_iterator
iter = _dnSyntaxMap.begin();
iter != _dnSyntaxMap.end();
iter++)
{
buffer = buffer + iter->second->toString() + " / ";
}
return buffer; // !!! 错误 : 返回本地变量的引用 !!!
}
Widely used in Singleton Pattern & STL!
About Smart pointer,
Do you have any
question?
11. How to implement COW in your class?
• Smart Pointer is necessary;
• Keep sharing with others when there is only copy operation;
• Stop sharing and make new copy from original data, then change it (add,
modify, remove);
• COW: From outside, each DataBuffer/Employee object is completely
independent; but in it’s underlying implementation, the real data is shared
or exclusive;
12. COW overhead
• Smart Pointer give us an additional indirectness;
• Always allocate memory dynamically(new/delete, because of Smart
pointer);
• Additional “if…else…” branches;
• Compare all above overheads with the benefits to us: COW is worthy
to big object, and with lots of copying operations but few
writing(few amount and few opportunity);
13. TypeFactor<T> in GOAM
* All of TypeInt, TypeString, TypeFloat, TypeBool, TypeDn are TypeFactory<>
with special data type as template parameter.