2013-02-21 17 views
1

例如走出的函数的,与参考,一个类型的对象没有默认的构造

bool read(Input &input); 

Input input; //error 
bool success = read(input); 

将是一个错误,因为输入没有默认构造函数。

在这种情况下,我可以用什么技巧将输入对象从函数中取出?我想象一下,我可以得到一些unique_ptr技巧,但我不确定如何。随意建议其他方法。

请用示例说明读取函数的外观。

我宁愿不为输入创建一个(无意义的)默认构造函数,只是为了这个目的,并且注意这只是一个愚蠢的例子,所以不要给“输入”,“读取”等:)

+0

有'阅读( )'返回一个'Input'和'throw'异常失败? – hmjd 2013-02-21 14:11:52

+0

为什么不能'输入read();'? – PlasmaHH 2013-02-21 14:12:03

+0

因为在我的情况下,返回类型将是重要的,甚至“假”不足以成为一个例外。 – user2015453 2013-02-21 14:12:30

回答

1
bool read(unique_ptr<Input> &input) // read asume input is disposable/empty 
{ .... 
    input.reset(new Input(a,d,c)); 
    .... 
} 

.... 
unique_ptr<Input> input;  //error ? 
bool success = read(input); 
if (input) 
    if (succes) 
    input->X(); 
    else 
    input->Y(); 
+0

是的,我想像这样的事情,但问题是,你不能重新分配在读取功能的输入指针。我想我可以做“input.reset(new whatever)”,但这听起来是对的吗? – user2015453 2013-02-21 14:20:25

+0

'unique_ptr'本身就足以表示“没有对象”,所以我没有看到通过引用“bool”函数结果来传递它的目的。而且,与普通的C++堆栈分配相比,动态分配的效率非常低。那么,对于那种冗长,模糊和无效率,有什么引人注目的论点? – 2013-02-21 14:28:57

+0

@干杯和hth。 - Alf:这只是一个愚蠢的例子,所以不要给“输入”,“阅读”等词添加任何特殊的含义。因为在我的情况下,返回类型很重要,甚至“假”也不是无效的 – qPCR4vir 2013-02-21 14:36:13

0

从评论,似乎你的问题是设计一个功能

  • 可能失败(如果有的话应该用信号通知到主叫方),

  • 但如果没有,产生一个类型的值没有默认cconstructor

第一点是容易的:使用异常。

第二点也很简单:使用函数返回值功能。

即,

Object foo() 
{ 
    if("didna wrok") 
    { 
     throw std::runtime_error("foo: I failed, miserably"); 
    } 

    return Object(arg1, arg2, arg3); 
} 

现在也有许多其他方法可以做到这一点,但上面是最自然的,直接使用的目的是支持和全面解决这些方面的语言特点。

0
unique_ptr<Input> input_ptr = read(); 

其中read()被定义为:

unique_ptr<Input> read() 
{ 
    . 
    . 
    . 
    return unique_ptr<Input>(new Input(x,y,z)); 
} 
+0

更高效和安全的变体是使用Barton和Nackman的'Fallible'类的实现,例如'boost :: optional'。实现POD内部类型也很简单(几分钟内)。我没有建议在我的回答中 - 我只是说有更多的可能性 - 因为显然OP是学习C++的基础知识。 – 2013-02-21 14:25:22

0

如果你是前C + 11的世界里,有一种变通方法通过使用malloc

bool read(Input &input); // keep the function read intact 

Input* input = static_cast<Input*>(malloc(sizeof(Input))); // bypass constructor 
bool success = read(*input); 
... 
free(input); // don't forget to free input later 
相关问题