-2

次のコードがコンパイル時に「一時的な参照を返す」と失敗する理由がわかりません。私にとって、シングルトンは静的であるため、一時的なものにすることはできません!?

ありがとう

#include <memory>

class Parent {
public:
    static const std::shared_ptr<Parent>& get_default_value();
    static const std::shared_ptr<Parent>& get_some_other_value();
};

class Child: public Parent {
public:
    Child(){}
    static const std::shared_ptr<Child>& singleton;
};

const std::shared_ptr<Child>& singleton = std::make_shared<Child>();

const std::shared_ptr<Parent>& Parent::get_default_value() {
    return singleton;
}

const std::shared_ptr<Parent>& Parent::get_some_other_value() {
    //FILL ME
}

証拠

編集:親のデフォルト値は子のシングルトンです。(以前は他の名前もありましたが、これは混乱を招きました)。

編集2:また、デフォルトはLOTであり、とにかくシングルトンであるため、shared_pointersへの参照が必要でした。スペースを節約したほうがよいでしょう。

編集3:インターフェイスをデフォルトと他の値で一貫させたいので、タイプの結果としてstd :: shared_ptr&が必要です

編集4:そして、無関係な理由で、他の値はshared_ptr<>である必要があります。

4

3 に答える 3

4

あなたの問題はそれChild::singletonがタイプであるstd::shared_ptr<Child>&がをget_singleton返すことstd::shared_ptr<Parent>&です。std::shared_ptr<Child>に変換できますが、に変換できstd::shared_ptr<Parent>ないためstd::shared_ptr<Parent>&、型の一時オブジェクトを作成し、そのオブジェクトstd::shared_ptr<Parent>への参照を返す必要があります。

とにかく、通常、参照によってを返す理由はありませshared_ptrん。値で返すだけでコンパイルされます。

于 2013-03-12T17:55:39.797 に答える
2

シングルトンは、宣言する方法で一時的なものではありません。静的変数を宣言するには、次のようにします。

const std::shared_ptr<Child>& Child::singleton = std::make_shared<Child>();

Child::?に注意してください また、関数get_singletonで次を使用します。

const std::shared_ptr<Parent>& Parent::get_singleton() {
    return Child::singleton;
}
于 2013-03-12T17:48:52.813 に答える
0

変換が問題であるというDirkの分析に基づいて、これは良い解決策です。

class Parent {
public:
    static const std::shared_ptr<Parent>& get_singleton();
};

class Child: public Parent {
public:
    Child(){}
    static const std::shared_ptr<Parent>& singleton;
};

const std::shared_ptr<Parent>& singleton = std::make_shared<Child>();

const std::shared_ptr<Parent>& Parent::get_singleton() {
    return singleton;
}

証拠

于 2013-03-13T08:27:14.407 に答える