我正在阅读boost::empty_value
源代码,不了解boost::empty_init_t
的用法。在empty_value
专用模板代码中(我删除了一些不活动的#ifdefine
块):
template<class T, unsigned N> class empty_value<T, N, true> : T { public: typedef T type; empty_value() = default; empty_value(boost::empty_init_t) : T() { } template<class... Args> explicit empty_value(boost::empty_init_t, Args&&... args) : T(std::forward<Args>(args)...) { } const T& get() const BOOST_NOEXCEPT { return *this; } T& get() BOOST_NOEXCEPT { return *this; } };
像下面的一个构造函数就不够了吗?
template<class... Args>
explicit empty_value(Args&&... args)
: T(std::forward<Args>(args)...) { }
为什么empty_value
实现需要另外两个构造函数?:
empty_value() = default;
empty_value(boost::empty_init_t)
: T() { }
另一个问题是:什么是< code>typedef T类型;用于?
我还写了一封电子邮件给作者Glen Fernandes,这是他的回复。希望它能帮助其他人:
现在只记录了2个构造函数:https://www.boost.org/doc/libs/master/libs/core/doc/html/core/empty_value.html
empty_value()=默认值代码>
模板
最后一个是不够的,因为第一个做了一些不同的事情。它执行默认初始化,而最后一个执行值初始化。
即它是以下两者之间的区别:
新(存储)T代码>
新(存储)T()代码>
例如,基本类型的默认初始化意味着什么都不做。基元类型的值初始化意味着初始化为零。
例如,考虑<代码>空值
这里构造函数 1 不起作用。但是构造函数 2 会将所有 10,000 个整数初始化为零(这很昂贵,因此用户可能希望选择退出)。
“type”typedef是我几次发现有用的东西,当时我有:<code>typedefempty_value
即容易得到'复杂类型表达式'
作为base::类型
而不是重复它。
希望这有帮助。
标记< code>boost::empty_init_t允许您区分
T value; // default initialization
和
T value(); // value initialization (warn: most vexing parse)
这两种类型的初始化通常使用单个构造函数执行不同的事情
template<class... Args>
explicit empty_value(Args&&... args)
: T(std::forward<Args>(args)...) {}
没有办法默认初始化基类T
。
例如,如果T
是
struct T {
int i;
}
则 empty_value(
) 将使 T.i 保持未初始化状态,而 empty_value(boost::empty_init_t)
会将 T.i
初始化为零。请参阅此简单演示。
typedef T 类型是什么?
简化从empty_value中提取基础类型
template<class Empty_value_type>
void foo(Empty_value_type) {
using my_type = typename Empty_value_type::type;
}