次のコード例では、B
のオブジェクトが存在する限り、構造体B
内に構造体A
のインスタンスが1つ存在する必要があります。例は期待通りに機能します。unique_ptrのrefcountの代わり
#include <memory>
#include <iostream>
#include <mutex>
struct A
{
A() { std::cout << "A() called" << std::endl; }
~A() { std::cout << "~A() called" << std::endl; }
};
struct B
{
B()
{
std::cout << "B() called" << std::endl;
std::lock_guard<std::mutex> guard(mtx);
if(!refCount)
{
a.reset(new A);
}
++refCount;
}
~B()
{
std::cout << "~B() called" << std::endl;
std::lock_guard<std::mutex> guard(mtx);
--refCount;
if(!refCount)
{
a.reset();
}
}
static std::unique_ptr<A> a;
static std::mutex mtx;
static int refCount;
};
std::unique_ptr<A> B::a;
int B::refCount(0);
std::mutex B::mtx;
int main()
{
{
B b1; //B::a should be created here
B b2;
} //B::a should be destroyed here
B b3; // B::a should be recreated here
} //B::a should be destroyed again here
はhttp://coliru.stacked-crooked.com/a/fea428254933ee5c
私の質問も参照してください:代替(!スレッドセーフ)実装は参照カウントせずにありますか?これはおそらくstd::shared_ptr
とstd::weak_ptr
の構成で解決することが可能でしょうか?
を、それが、トラブルを要求します'struct B'のコピーコンストラクタとコピー代入(refcountが常に正しく維持されるように) – Leon
'A'のインスタンスは、' B'のようなことが起こっていないときに実際には死ぬ必要がありますか?あなたが今、物事を持っている方法では、 '静的なA a; 'を単に持つことができ、それは' B'オブジェクトにしかアクセスできません。あなたの現在のコードでは、 'std :: unique_ptr'はref-countが0になったときにその内容を手動で削除しなければならないので、冗長です。 – Galik
@レーオン:はい、それは最小限の例にちょうど短縮されました – meddle0106