C++ Weekly - Ep 155 - Misuse of pure Function Attribute

preview_player
Показать описание
☟☟ Awesome T-Shirts! Sponsors! Books! ☟☟

Upcoming Workshops:

T-SHIRTS AVAILABLE!

WANT MORE JASON?

SUPPORT THE CHANNEL

GET INVOLVED

JASON'S BOOKS

► C++23 Best Practices

► C++ Best Practices

JASON'S PUZZLE BOOKS

► Object Lifetime Puzzlers Book 1

► Object Lifetime Puzzlers Book 2

► Object Lifetime Puzzlers Book 3

► Copy and Reference Puzzlers Book 1

► Copy and Reference Puzzlers Book 2

► Copy and Reference Puzzlers Book 3

► OpCode Puzzlers Book 1


RECOMMENDED BOOKS

AWESOME PROJECTS

O'Reilly VIDEOS

Рекомендации по теме
Комментарии
Автор

Well, you are correct, but isn't this obviouse? I mean the attribute is called pure after all. That's like doing i += 1 and wondering why i was incremented by one

petermuller
Автор

Why doesn't the compiler throw an error when your code is violating such directives?

stephenjames
Автор

Well that demonstrates nicely the answer to my question from the previous episode on the topic. Thank you. I only wish you said: "expected behaviour" in the end :P

abbyssoul
Автор

If the compiler has access to the function body, it can deduct the const and pure attributes automatically. Depending on optimizer settings it will do it.
With *const*, it assumes and checks that nothing is modified (except mutable members). But the function may depend on anything. It will optimize the call away if the return value is unused. Example: std::time(nullptr);
With *pure* it assumes and doesn't check, that the function depends on the parameters only and doesn't modify anything. It additionally will optimize the call away if it knows the return value from another call. Example: double a =

Hauketal
Автор

Prepare for unforeseen consequences (Alyx)

frobeniusfg
Автор

how is a function without any body being called without any errors?

VishalSharma-yswt
Автор

in thie last example the compiler called the increment function only once and then added the result to itself, but how can the compiler know that the function isn't let's say time dependent and that it will return the same thing every time ?

orocimarosay
Автор

Thank you Jason Turner for this episod of C++ Weekly that I saw just now. #cplusplus

danielphd
Автор

What if you called another externally defined function between the two calls here? I'd expect that even with [[gnu::pure]] the compiler must assume that the second function could modify some global state on which S::increment_value() depends.

michal.gawron
visit shbcf.ru