我已经在网上搜索并阅读了有关shared_ptr
. SO上有一个回应说shared_ptr
写时复制(COW)很糟糕,并且TR!
已将其从字符串库中删除。大多数关于 SO 的建议都说使用shared_ptr
而不是常规指针。
该文档还讨论了std::unique()
用于制作 COW 指针,但我没有找到任何示例。
是谈论拥有一个为您执行 COW 的智能指针还是关于让您的对象使用shared_ptr
克隆对象的新指针然后修改克隆对象?
示例:食谱和配料
struct Nutrients;
struct Ingredient
{
Ingredient(const std::string& new_title = std::string(""))
: m_title(new_title)
{ ; }
std::string m_title;
Nutrients ing_nutrients;
};
struct Milk : public Ingredient
: Ingredient("milk")
{ ; }
struct Cream : public Ingredient
: Ingredient("cream")
{ ; }
struct Recipe
{
std::vector< boost::shared_ptr<Ingredient> > m_ingredients;
void append_ingredient(boost::shared_ptr<Ingredient> new_ingredient)
{
m_ingredients.push_back(new_ingredient);
return;
}
void replace_ingredient(const std::string& original_ingredient_title,
boost::shared_ptr<Ingredient> new_ingredient)
{
// Confusion here
}
};
int main(void)
{
// Create an oatmeal recipe that contains milk.
Recipe oatmeal;
boost::shared_ptr<Ingredient> p_milk(new Milk);
oatmeal.add_ingredient(p_milk);
// Create a mashed potatoes recipe that contains milk
Recipe mashed_potatoes;
mashed_potatoes.add_ingredient(p_milk);
// Now replace the Milk in the oatmeal with cream
// This must not affect the mashed_potatoes recipe.
boost::shared_ptr<Ingredient> p_cream(new Cream);
oatmeal.replace(p_milk->m_title, p_cream);
return 0;
}
困惑是如何用奶油代替oatmeal
配方中的“牛奶”而不影响mashed_potatoes
配方。
我的算法是:
locate pointer to `Milk` ingredient in the vector.
erase it.
append `Cream` ingredient to vector.
牛指针如何在这里发挥作用?
注意:我在 Windows NT、Vista 和 7 上使用 MS Visual Studio 2010。