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

9

158

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

I am familiar with run-time assert(...). When should I prefer static_assert(...) over regular assert(...)?

Also, in boost there is something called BOOST_STATIC_ASSERT, is it the same as static_assert(...)?

Woolsey answered 30/10, 2009 at 3:35 Comment(0)
C
177

Static assert is used to make assertions at compile time. When the static assertion fails, the program simply doesn't compile. This is useful in different situations, like, for example, if you implement some functionality by code that critically depends on unsigned int object having exactly 32 bits. You can put a static assert like this

static_assert(sizeof(unsigned int) * CHAR_BIT == 32);

in your code. On another platform, with differently sized unsigned int type the compilation will fail, thus drawing attention of the developer to the problematic portion of the code and advising them to re-implement or re-inspect it.

For another example, you might want to pass some integral value as a void * pointer to a function (a hack, but useful at times) and you want to make sure that the integral value will fit into the pointer

int i;

static_assert(sizeof(void *) >= sizeof i);
foo((void *) i);

You might want to asset that char type is signed

static_assert(CHAR_MIN < 0);

or that integral division with negative values rounds towards zero

static_assert(-5 / 2 == -2);

And so on.

Run-time assertions in many cases can be used instead of static assertions, but run-time assertions only work at run-time and only when control passes over the assertion. For this reason a failing run-time assertion may lay dormant, undetected for extended periods of time.

Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert.

Conspecific answered 30/10, 2009 at 3:47 Comment(4)
Isn't static_assert REQUIRED to have a string literal as a second parameter?Huckaback
@Trevor Hickey: Yes, it is. But I wasn't trying to refer to static_assert from C++11 specifically. My static_assert above is just some abstract implementation of static assertion. (I personally use something like that in C code). My answer is intended to be about general purpose of static assertions and their difference from run-time assertions.Conspecific
In the first example, you are assuming there is no padding bits in a variable of type unsigned int. This is not guaranteed by the standard. A variable of type unsigned int could legally occupy 32 bits of memory, leaving 16 of them unused (and thus the macro UINT_MAX would be equal to 65535). So the way you describe the first static assertion ("unsigned int object having exactly 32 bits") is misleading. To match your description, this assertion should be included as well : static_assert(UINT_MAX >= 0xFFFFFFFFu).Nonprofit
@TrevorHickey not anymore (C++17)Prendergast
V
89

Off the top of my head...

#include "SomeLibrary.h"

static_assert(SomeLibrary::Version > 2, 
         "Old versions of SomeLibrary are missing the foo functionality.  Cannot proceed!");

class UsingSomeLibrary {
   // ...
};

Assuming that SomeLibrary::Version is declared as a static const, rather than being #defined (as one would expect in a C++ library).

Contrast with having to actually compile SomeLibrary and your code, link everything, and run the executable only then to find out that you spent 30 minutes compiling an incompatible version of SomeLibrary.

@Arak, in response to your comment: yes, you can have static_assert just sitting out wherever, from the look of it:

class Foo
{
    public: 
        static const int bar = 3;
};

static_assert(Foo::bar > 4, "Foo::bar is too small :(");

int main()
{ 
    return Foo::bar;
}
$ g++ --std=c++0x a.cpp
a.cpp:7: error: static assertion failed: "Foo::bar is too small :("
Vicinage answered 30/10, 2009 at 3:43 Comment(6)
I am little confused, can you put static_assert in a non-execution context? It seems a very nice example :)Woolsey
Yeah, static asserts as they stand are usually implemented as creating an object that's only defined if the predicate is true. This would just make a global.Millinery
i'm not sure this qualifies as answering the original question in it's entirety, but nice demonstrationMarmara
This answer doesn't provide any details on what's the difference between assert from <cassert> and static_assertRosalindarosalinde
@monocoder: See the paragraph starting with "Contrast with...". In short: assert checks its condition at runtime, and static_assert checks its condition at compilation. So if the condition you're asserting is known at compile time, use static_assert. If the condition won't be known until the program runs, use assert.Easting
Not upvoting because I just hate Foo and Bar examples so much, but good example otherwise.Foreordination
M
14

I use it to ensure my assumptions about compiler behaviour, headers, libs and even my own code are correct. For example here I verify that the struct has been correctly packed to the expected size.

struct LogicalBlockAddress
{
#pragma pack(push, 1)
    Uint32 logicalBlockNumber;
    Uint16 partitionReferenceNumber;
#pragma pack(pop)
};
BOOST_STATIC_ASSERT(sizeof(LogicalBlockAddress) == 6);

In a class wrapping stdio.h's fseek(), I have taken some shortcuts with enum Origin and check that those shortcuts align with the constants defined by stdio.h

uint64_t BasicFile::seek(int64_t offset, enum Origin origin)
{
    BOOST_STATIC_ASSERT(SEEK_SET == Origin::SET);

You should prefer static_assert over assert when the behaviour is defined at compile time, and not at runtime, such as the examples I've given above. An example where this is not the case would include parameter and return code checking.

BOOST_STATIC_ASSERT is a pre-C++0x macro that generates illegal code if the condition is not satisfied. The intentions are the same, albeit static_assert is standardised and may provide better compiler diagnostics.

Marmara answered 30/10, 2009 at 3:46 Comment(0)
M
10

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.

Metalliferous answered 12/1, 2010 at 12:18 Comment(1)
Now that C++11 is out (and has been out for a while), static_assert should be supported by the more recent versions of all the major compilers. For those of us who can't wait for C++14 (which hopefully will contain template constraints), this is a very useful application of static_assert.Biome
E
9

One use of static_assert might be to ensure that a structure (that is an interface with the outside world, such as a network or file) is exactly the size that you expect. This would catch cases where somebody adds or modifies a member from the structure without realising the consequences. The static_assert would pick it up and alert the user.

Enchant answered 30/10, 2009 at 3:43 Comment(0)
A
5

In absence of concepts one can use static_assert for simple and readable compile-time type checking, for example, in templates:

template <class T>
void MyFunc(T value)
{
static_assert(std::is_base_of<MyBase, T>::value, 
              "T must be derived from MyBase");

// ...
}
Amadavat answered 14/9, 2015 at 20:54 Comment(0)
B
2

This doesn't directly answers the original question, but makes an interesting study into how to enforce these compile time checks prior to C++11.

Chapter 2 (Section 2.1) of Modern C++ Design by Andrei Alexanderscu implements this idea of Compile-time assertions like this

template<int> struct CompileTimeError;
template<> struct CompileTimeError<true> {};

#define STATIC_CHECK(expr, msg) \
{ CompileTimeError<((expr) != 0)> ERROR_##msg; (void)ERROR_##msg; } 

Compare the macro STATIC_CHECK() and static_assert()

STATIC_CHECK(0, COMPILATION_FAILED);
static_assert(0, "compilation failed");
Bamberg answered 2/6, 2014 at 3:47 Comment(0)
N
0

To add on to all the other answers, it can also be useful when using non-type template parameters.

Consider the following example.

Let's say you want to define some kind of function whose particular functionality can be somewhat determined at compile time, such as a trivial function below, which returns a random integer in the range determined at compile time. You want to check, however, that the minimum value in the range is less than the maximum value.

Without static_assert, you could do something like this:

#include <iostream>
#include <random>

template <int min, int max>
int get_number() {
    if constexpr (min >= max) {
        throw std::invalid_argument("Min. val. must be less than max. val.\n");
    }
    srand(time(nullptr));
    static std::uniform_int_distribution<int> dist{min, max};
    std::mt19937 mt{(unsigned int) rand()};
    return dist(mt);
}

If min < max, all is fine and the if constexpr branch gets rejected at compile time. However, if min >= max, the program still compiles, but now you have a function that, when called, will throw an exception with 100% certainty. Thus, in the latter case, even though the "error" (of min being greater than or equal to max) was present at compile-time, it will only be discovered at run-time.

This is where static_assert comes in.

Since static_assert is evaluated at compile-time, if the boolean constant expression it is testing is evaluated to be false, a compile-time error will be generated, and the program will not compile.

Thus, the above function can be improved as so:

#include <iostream>
#include <random>

template <int min, int max>
int get_number() {
    static_assert(min < max, "Min. value must be less than max. value.\n");
    srand(time(nullptr));
    static std::uniform_int_distribution<int> dist{min, max};
    std::mt19937 mt{(unsigned int) rand()};
    return dist(mt);
}

Now, if the function template is instantiated with a value for min that is equal to or greater than max, then static_assert will evaluate its boolean constant expression to be false, and will throw a compile-time error, thus alerting you to the error immediately, without giving the opportunity for an exception at runtime.

(Note: the above method is just an example and should not be used for generating random numbers, as repeated calls in quick succession to the function will generate the same numbers due to the seed value passed to the std::mt19937 constructor through rand() being the same (due to time(nullptr) returning the same value) - also, the range of values generated by std::uniform_int_distribution is actually a closed interval, so the same value can be passed to its constructor for upper and lower bounds (though there wouldn't be any point))

Nureyev answered 11/12, 2022 at 16:40 Comment(0)
C
-2

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.

Colossian answered 23/8, 2019 at 22:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.