Web を検索し、Boost に関するドキュメントを読みましたshared_ptr
。SO には、shared_ptr
Copy-On-Write (COW) が最悪でTR!
、文字列ライブラリから削除されたという応答があります。SOに関するほとんどのアドバイスshared_ptr
は、通常のポインターではなく使用するように言っています。
ドキュメントには、COW ポインターを作成するための使用についても記載std::unique()
されていますが、例は見つかりませんでした。
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.
ここで、COW ポインターはどのように機能しますか?
注: Windows NT、Vista、および 7 で MS Visual Studio 2010 を使用しています。