gpt4 book ai didi

c++ - 延期成员(member) build

转载 作者:太空狗 更新时间:2023-10-29 19:58:32 24 4
gpt4 key购买 nike

我有以下结构:

struct Logger::LoggerImpl {
std::wofstream loggerStream;
}

当我创建一个 LoggerImpl 时,显然会隐式创建一个 std::wofstream(通过编译器的默认构造函数)。

我的问题是,有没有一种方法可以在不使用指针的情况下阻止(或推迟)构建 wofstream?因为稍后我将使用给定的文件名创建它。

我知道在这种情况下这没什么区别,但我是在理论上问的。

最佳答案

为什么不使用默认构造函数创建 std::wofstream ,然后只使用 open() 文件?绑定(bind)包含对象的生命周期似乎是正确的方法。

在 C++11 中,您还可以将带有构造函数的对象放入 union 中。当然,结果是您需要接管 union 成员的生命周期管理。但是,通过这种方式,您可以将特定成员的构造推迟到以后。请注意,下面代码中 new 的使用实际上只是 placement new,将对象构造到合适的位置。这是一个例子:

#include <iostream>
#include <fstream>
#include <new>

class foo
{
bool constructed;
union helper {
helper() {}
~helper() {}
std::ifstream stream;
} member;
public:
foo(): constructed() {}
~foo() {
if (constructed) {
using std::ifstream;
this->member.stream.~ifstream();
}
}
void open(std::string const& name) {
new (&this->member.stream) std::ifstream(name);
constructed = true;
}
std::streambuf* rdbuf() {
return this->member.stream.rdbuf();
}
};

int main()
{
foo f;
f.open("foo.cpp");
std::cout << f.rdbuf();
}

关于c++ - 延期成员(member) build ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20646658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com