What does static_assert do, and what would you use it for?

前端 未结 8 726
生来不讨喜
生来不讨喜 2020-12-04 06:21

Could you give an example where static_assert(...) (\'C++11\') would solve the problem in hand elegantly?

I am familiar with run-time assert(...)<

相关标签:
8条回答
  • 2020-12-04 07:04

    BOOST_STATIC_ASSERT is a cross platform wrapper for static_assert functionality.

    Currently I am using static_assert in order to enforce "Concepts" on a class.

    example:

    template <typename T, typename U>
    struct Type
    {
      BOOST_STATIC_ASSERT(boost::is_base_of<T, Interface>::value);
      BOOST_STATIC_ASSERT(std::numeric_limits<U>::is_integer);
      /* ... more code ... */
    };
    

    This will cause a compile time error if any of the above conditions are not met.

    0 讨论(0)
  • 2020-12-04 07:04

    The static_assert can be used to forbid the use of the delete keyword this way:

    #define delete static_assert(0, "The keyword \"delete\" is forbidden.");

    Every modern C++ developer may want to do that if he or she wants to use a conservative garbage collector by using only classes and structs that overload the operator new to invoke a function that allocates memory on the conservative heap of the conservative garbage collector that can be initialized and instantiated by invoking some function that does this in the beginning of the main function.

    For example every modern C++ developer that wants to use the Boehm-Demers-Weiser conservative garbage collector will in the beginning of the main function write:

    GC_init();

    And in every class and struct overload the operator new this way:

    void* operator new(size_t size)
    {
         return GC_malloc(size);
    }
    

    And now that the operator delete is not needed anymore, because the Boehm-Demers-Weiser conservative garbage collector is responsible to both free and deallocate every block of memory when it is not needed anymore, the developer wants to forbid the delete keyword.

    One way is overloading the delete operator this way:

    void operator delete(void* ptr)
    {
        assert(0);
    }
    

    But this is not recommended, because the modern C++ developer will know that he/she mistakenly invoked the delete operator on run time, but this is better to know this soon on compile time.

    So the best solution to this scenario in my opinion is to use the static_assert as shown in the beginning of this answer.

    Of course that this can also be done with BOOST_STATIC_ASSERT, but I think that static_assert is better and should be preferred more always.

    0 讨论(0)
提交回复
热议问题