c++ - 是否有任何理由将 final 说明符与 union 一起使用?

标签 c++ c++11

final 说明符 可以与类或结构一起使用以禁止从它们继承。在这种情况下,我们只需要将我们的类/结构标记为 final:

class Foo final {
    // ...
};

更有趣的是,相同的语法对 union 有效:

union Foo final {
    // ...
};

来自cpp.reference.com :

final can also be used with a union definition, in which case it has no effect (other than on the outcome of std::is_final), since unions cannot be derived from)

看起来 final 说明符 与 union 的用法是荒谬的。如果是这样,为什么甚至可以将 union 标记为最终的?只是为了一致性?或者关于 type_traits 的一些东西?我是否遗漏了什么,是否存在我们需要将 final 与 union 一起使用的情况?

最佳答案

正如您所说,union 无法派生,因此 final 说明符对它们绝对没有影响。 其他 std::is_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*>();   
}

关于c++ - 是否有任何理由将 final 说明符与 union 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40063717/

相关文章:

java - 将 java 字符串作为 c/c++ 字节发送

C++11 左值、右值和 std::move()

c++ - VS 2013 SFINAE 缺陷的解决方法

c++ - 泛化共享指针和 QSharedPointer::data() vs shared_ptr::get()?

java - 类、静态方法或实例方法 - 编译语言中的内存消耗和可执行文件大小?

c++ - 是否可以在不复制的情况下向下转换shared_ptr?

C++ 方法线程

c++ - throw 可移动物体

c++ - 从基类指针列表中获取特定派生类的对象的良好设计模式是什么?

c++ - 奇怪的程序挂起,这在调试中意味着什么?