I have searched the web and read through the Boost documentation about shared_ptr
. There is a response on SO that says that shared_ptr
for Copy-On-Write (COW) sucks and that TR!
has removed it from the string libraries. Most advice on SO says to use shared_ptr
rather than regular pointers.
The documentation also talks about using std::unique()
to make a COW pointer, but I haven't found any examples.
Is the talk about having a smart pointer that performs COW for you or about having your object use a new shared_ptr
to a cloned object then modifying the cloned object?
Example: Recipes & Ingredients
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;
}
The confusion is how to replace the 'Milk' in the oatmeal
recipe with Cream and not affect the mashed_potatoes
recipe.
My algorithm is:
locate pointer to `Milk` ingredient in the vector.
erase it.
append `Cream` ingredient to vector.
How would a COW pointer come into play here?
Note: I am using MS Visual Studio 2010 on Windows NT, Vista and 7.
fork()
in Unix. Whenever a shared_ptr reference count is bumped its memory page becomes unshared, adding to the system's real memory usage. – Circumscription