Я поискал в сети и прочитал документацию по Boost о shared_ptr
. На SO есть ответ, в котором говорится, что shared_ptr
для Copy-On-Write (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;
}
Проблема заключается в том, как заменить «Молоко» в рецепте овсянки
на Сливки и не повлиять на рецепт пюре из картофеля
.
Мой алгоритм:
locate pointer to `Milk` ingredient in the vector.
erase it.
append `Cream` ingredient to vector.
Как бы Здесь играет роль указатель COW?
Примечание: я использую MS Visual Studio 2010 в Windows NT, Vista и 7.