C++ 是否有任何理由对联合使用最终说明符?
最后一个说明符可以与类或结构一起使用,以禁止从它们继承。在这种情况下,我们只需要将类/结构标记为C++ 是否有任何理由对联合使用最终说明符?,c++,c++11,C++,C++11,最后一个说明符可以与类或结构一起使用,以禁止从它们继承。在这种情况下,我们只需要将类/结构标记为final: class Foo final { // ... }; 更有趣的是,相同的语法对联合有效: union Foo final { // ... }; 从: final还可以与联合定义一起使用,在这种情况下,它具有 没有影响(除了对std::is_最终结果的影响),因为 无法从中派生) 看起来将final说明符与并集一起使用是毫无意义的。如果是这样的话,为什么甚至有可能将
final
:
class Foo final {
// ...
};
更有趣的是,相同的语法对联合有效:
union Foo final {
// ...
};
从:
final还可以与联合定义一起使用,在这种情况下,它具有
没有影响(除了对std::is_最终结果的影响),因为
无法从中派生)
看起来将final说明符与并集一起使用是毫无意义的。如果是这样的话,为什么甚至有可能将联盟标记为最终联盟?只是为了一致性?或者是关于你的性格特征?我是否遗漏了什么,是否存在需要在联合中使用final的情况?正如您所说,
联合
无法派生,因此final
说明符对它们绝对没有影响其他的结果,可以使用下面的代码测试哪些行为,其中所有断言都通过:
struct P final { };
union U1 { };
union U2 final { }; // 'union' with 'final' specifier
template <class T>
void test_is_final()
{
static_assert( std::is_final<T>::value, "");
static_assert( std::is_final<const T>::value, "");
static_assert( std::is_final<volatile T>::value, "");
static_assert( std::is_final<const volatile T>::value, "");
}
template <class T>
void test_is_not_final()
{
static_assert(!std::is_final<T>::value, "");
static_assert(!std::is_final<const T>::value, "");
static_assert(!std::is_final<volatile T>::value, "");
static_assert(!std::is_final<const volatile T>::value, "");
}
int main()
{
test_is_final <P>();
test_is_not_final<P*>();
test_is_not_final<U1>();
test_is_not_final<U1*>();
test_is_final <U2>(); // 'std::is_final' on a 'union' with 'final' specifier
test_is_not_final<U2*>();
}
structpfinal{};
联盟U1{};
联合U2最终{};/'带有“最终”说明符的“并集”
模板
无效测试是最终测试()
{
静态断言(std::is_final::value,“”);
静态断言(std::is_final::value,“”);
静态断言(std::is_final::value,“”);
静态断言(std::is_final::value,“”);
}
模板
无效测试不是最终测试()
{
静态断言(!std::is_final::value,“”);
静态断言(!std::is_final::value,“”);
静态断言(!std::is_final::value,“”);
静态断言(!std::is_final::value,“”);
}
int main()
{
测试是最终的();
测试不是最终测试();
测试不是最终测试();
测试不是最终测试();
带有“final”说明符的“union”上的test_is_final();/“std::is_final”
测试不是最终测试();
}
您可能正在使用依赖于std::is_final
的第三方库(即使来自同一家公司,但没有写访问权限)。一个常见的例子是半正确编写的singleton模式:您肯定不希望BaseSingleton和DerivedSingleton并行实例化。防止这种情况的一种(众所周知的糟糕)方法是启用std::if
forstd::is_final
。因此,您需要能够以某种方式指定它。问题是,为什么工会不是自动确定的。如果你对“无效”有一种崇拜。这一点都不“荒谬”。@ddriver抱歉,我没听清楚。你说的“恋物癖”是什么意思?我的意思正是它的意思。这可能是因为一个联合
被认为是一个类,所以final
关键字适用于它。@yg它基本上意味着,唯一的原因是一致性。。。