c++ - 退出一个函数,引用一个没有默认构造函数的类型的对象

标签 c++ pointers c++11 unique-ptr

例如

bool read(Input &input);

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

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

在这种情况下,我可以使用任何技巧从函数中获取 Input 对象吗?我想一定有一些 unique_ptr 技巧可供我使用,但我不确定具体如何。欢迎提出其他方法。

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

我宁愿不为此目的为 Input 创建一个(无意义的)默认构造函数,并注意这只是一个愚蠢的例子,所以不要给“Input”、“read”等词附加任何特殊含义,等:)

最佳答案

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();

关于c++ - 退出一个函数,引用一个没有默认构造函数的类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15004317/

相关文章:

java - 分析和检查由 Java 加载的 DLL 中的内存分配

c - 为结构分配内存

c++ - {} 构造语法有多通用?

c++ - 是否可以在模板化函数签名中使用 typedef?

c++ - MFCreateAggregateSource 是否对排序做出任何保证?

c++ - 使用 Sleep() 阻止我写入文件

c++ - native GUI 的解决方案是什么?

c - C中打印Trie的内容和数量

c++ - 通过其抽象基类的指针返回派生类对象

C++ View 类型 : pass by const& or by value?