c++ - 后期不可复制成员初始化

标签 c++ c++11 boost

我正在尝试初始化无法分配或复制的对象成员。我需要先执行一些其他任务,初始化依赖于它,所以我不得不延迟它。

#include <boost/process.hpp>

class A{
    std::unique_ptr<boost::process::child> child_;
    std::unique_ptr<boost::process::pistream> is;

    A(std::string exec, boost::process::context process_context){
        // Stuff that needs to be done first
        // ...

        child_ = std::make_unique<boost::process::child>(start_child(exec, process_context));
        is = std::make_unique<boost::process::pistream>(child_->get_stdout()); // <- error

    }

    boost::process::child start_child(std::string exec, boost::process::context process_context);
};

我得到的错误是:

error C2280: 'std::basic_ios>::basic_ios(const std::basic_ios> &)' : attempting to reference a deleted function

如果我理解正确,那行中的某处正在发生复制,这是不允许的。 不需要唯一指针。我只是使用它们来避免另一个错误(没有默认初始化),但我很乐意接受有或没有它们的建议。

最佳答案

您可以使用 boost::optional<>像这样延迟初始化。

Live On Coliru

#include <memory>
#include <boost/optional.hpp>

struct pistream { };
struct child    {
    pistream& get_stdout() { return is; }
    pistream is;
};
struct context  { };

class A {
    std::unique_ptr<child> child_;
    boost::optional<pistream&> is;

    A(std::string, context) {
        // Stuff that needs to be done first
        // ...

        child_ = std::make_unique<child>();
        is     = child_->get_stdout();
    }
};

关于c++ - 后期不可复制成员初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33181102/

相关文章:

c++ - 为什么没有 strand::wrap() 等同于 strand::post()?

c++ - 如何让 while 循环只运行特定次数?

c++ - Eclipse (CDT) 无法解析变量?

c++ - 智能指针与自动引用计数

c++ - auto & x = const int * 是什么类型?

c++ - C++ 中的类型删除: boost::shared_ptr 和 boost::function 如何工作?

c++ - 之间有什么区别。和 -> 在 C++ 中调用方法

c++ - 为什么有限递归行为会导致崩溃? (free():无效的指针)

c++ - 没有默认构造函数的重复元素模板化数组

c++ - Boost 文件系统非常慢?