-2

コンストラクター内の特定の条件が満たされた場合にのみ、構造体のインスタンスを作成したいと考えています。これらの条件が満たされない場合、インスタンスを作成したくありません。これが可能かどうかわからない場合、そうでない場合は、それを行う別の方法は何ですか?

Class Consumer
{




struct SampleStruct
            {
                MyClass     *   m_object;

                RoutingItem()
                {
                    m_object            = NULL;
                }
                MyClass(std::string name)
                {
                        if (! ObjSetting()->GetObj(name, m_object))//this function is supposed to populate m_object, but if it fails, I dont want to create this instance
                            return; //I dont want to create this object if GetObj() returns a false             

                }
            };



std::vector<SampleStruct> m_arrSample;

void LoadSettings(std::string name)
{

SampleStruct * ptrS;

SampleStruct s(name);


//I tried following two lines but it did'nt work. SO looks like returning from struct constructor still creates the instance
ptrS = &s;
if (!ptrS)
return;

m_arrSample.push_back(s);//only insert in vector if sampleStruct was successfully created


}




}
4

4 に答える 4

1

やらないでください。

別のデザインを見つけます。コンストラクターは、オブジェクトを構築するためのものであり、構築するかどうかを決定するためのものではありません。

言語の規則に反してプログラミングしようとしないでください。

于 2013-07-25T15:42:22.990 に答える
1

インスタンスを構築する create 関数を定義できると思いますが、

test* createInstance(string name)
    {
        if(conditon )
            return new test();
        else
            return nullptr;
    }
于 2013-07-25T14:40:55.020 に答える
0

例外を使用するか (Stefano が言うように)、またはファクトリ関数を使用します (minicaptain が言うように)。

2 つのバージョンは次のようになります。

#include <stdexcept>
#include <memory>

struct ExceptionStyle {
    std::unique_ptr<int> m_object;

    ExceptionStyle(std::string const &name) {
        if (name == "good")
            m_object.reset( new int(42) );
        else
            throw std::runtime_error(name);
    }
};
void save(ExceptionStyle*) {} // stick it in a vector or something

class FactoryStyle {
    std::unique_ptr<int> m_object;

    FactoryStyle() : m_object(new int(42)) {}

public:
    static std::unique_ptr<FactoryStyle> create(std::string const &name) {
        std::unique_ptr<FactoryStyle> obj;
        if (name == "good")
            obj.reset( new FactoryStyle );
        return obj;
    }
};
void save(std::unique_ptr<FactoryStyle>) {} // stick it in a vector or something

次のように使用できます。

void LoadSettings(std::string const &name) {

    // use the exception style
    try {
        ExceptionStyle *es = new ExceptionStyle(name);
        // if we reach here, it was created ok
        save(es);
    } catch (std::runtime_exception) {}

    // use the factory style
    std::unique_ptr<FactoryStyle> fs = FactoryStyle::create(name);
    if (fs) {
        // if we reach here, it was created ok
        save(fs);
    }
}

例外は、インスタンスを構築せずにコンストラクターから制御を移す唯一の方法です。したがって、代替手段は、最初に自分の状態を確認することです。

于 2013-07-25T15:36:18.193 に答える