C++ 仅当构造函数中满足条件时才创建结构实例

C++ 仅当构造函数中满足条件时才创建结构实例,c++,constructor,C++,Constructor,我只想在满足构造函数中的某些条件时创建结构的实例。如果不满足这些条件,我不想创建实例。 不确定这是否可行,如果不可行,那么有什么替代方法 Class Consumer { struct SampleStruct { MyClass * m_object; RoutingItem() { m_object

我只想在满足构造函数中的某些条件时创建结构的实例。如果不满足这些条件,我不想创建实例。 不确定这是否可行,如果不可行,那么有什么替代方法

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


}




}
类消费者
{
结构样本构造
{
MyClass*m_对象;
路由项()
{
m_object=NULL;
}
MyClass(标准::字符串名称)
{
if(!ObjSetting()->GetObj(name,m_object))//这个函数应该填充m_object,但是如果它失败了,我不想创建这个实例
return;//如果GetObj()返回false,我不想创建此对象
}
};
std::向量m_样本;
无效加载设置(标准::字符串名称)
{
样本结构*PTR;
样本结构s(名称);
//我尝试了以下两行,但都不起作用。所以看起来从struct构造函数返回仍然会创建实例
ptrS=&s;
如果(!ptrS)
返回;
m_arrSample.push_back;//仅在成功创建sampleStruct时插入向量
}
}

<代码> > p>你会考虑从构造函数内部抛出一个解决方案吗?如果不是这样,那是不可能的。另一种方法是使用工厂方法,该方法检查条件并决定是否需要创建对象

下面是第二个解决方案的简单示例:

struct A{
};

A* factoryPtr(bool build){
    if(build)
        return new A;
    return nullptr;
}

A factoryRef(bool build){
    if(not build)
        throw 0;
    return A();
}

我想你可以定义一个create函数来构造这个实例

test* createInstance(string name)
    {
        if(conditon )
            return new test();
        else
            return nullptr;
    }
要么使用异常(如Stefano所说),要么使用工厂函数(如minicaptain所说)

这两个版本看起来像这样:

#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
#包括
#包括
结构例外样式{
std::唯一的\u ptr m_对象;
异常样式(标准::字符串常量和名称){
如果(名称=“良好”)
m_对象重置(新int(42));
其他的
抛出std::运行时错误(名称);
}
};
void save(ExceptionStyle*){}//将其粘贴到向量或其他内容中
类工厂样式{
std::唯一的\u ptr m_对象;
FactoryStyle():m_对象(新int(42)){}
公众:
静态std::unique_ptr create(std::string const&name){
std::唯一对象;
如果(名称=“良好”)
对象重置(新FactoryStyle);
返回obj;
}
};
void save(std::unique_ptr){}//将其粘贴到向量或其他内容中
可按如下方式使用:

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);
    }
}
void加载设置(std::string const&name){
//使用异常样式
试一试{
ExceptionStyle*es=新的ExceptionStyle(名称);
//如果我们到了这里,它就被创造出来了,好吗
保存(es);
}catch(std::runtime_异常){}
//使用工厂风格
std::unique_ptr fs=FactoryStyle::create(名称);
if(fs){
//如果我们到了这里,它就被创造出来了,好吗
保存(fs);
}
}

异常是在不构造实例的情况下将控制权从构造函数中转移出去的唯一方法。因此,另一种选择是先检查你的病情。

不要这样做。

找到另一种设计。构造函数是用来构造对象的,而不是决定是否构造它


不要试图违反语言规则进行编程。

您随时可以抛出异常,但如果可能,最好在构造函数之外检查您的条件。可能的副本您可以尝试发布类似于真实代码的内容吗?在“提问”页面上有一个预览。请在发布之前检查它,如果格式看起来不好,请更正它。-1表示格式不好。是否可以添加更多详细信息,例如结构的access modified、构造函数的access修饰符。它是静态的吗?怎么打电话?