nekrolm / ubbook Goto Github PK
View Code? Open in Web Editor NEWПутеводитель C++ программиста по неопределенному поведению
Путеводитель C++ программиста по неопределенному поведению
Even in C++11!
// a.cpp
#include <iostream>
void print_hello() {
std::cout << "hello\n";
}
// b.cpp
void print_hello();
struct StaticObject {
StaticObject() {
print_hello();
}
} static_object;
int main() {
}
If I compile these two locally with g++ -std=c++17 a.cpp b.cpp
, the resulting a.exe
crashes. My compiler version is g++ (Rev2, Built by MSYS2 project) 10.3.0
on Windows.
I am also able to reproduce this behavior by compiling g++ -std=c++17 b.cpp a.cpp
with g++-10 (Ubuntu 10.3.0-1ubuntu1~20.04) 10.3.0
I believe it is because b.cpp
does not include <iostream>
and static_object
gets constructed before anything in a.cpp
, corresponding std::ios_base::Init
provided by <iostream>
in particular. Hence, when print_hello()
is called, std::cout
is not initialized yet, hence the crash.
Я не знаю деталей, но посмотрите какой кекс: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=68209#c3 Где-то, где упоминается wall/wextra, возможно стоит порекомендовать -pedantic, заодно может пояснить вариации.
Кажется, что UB от использования хитрых указателей возникает только если у реализации "strict pointer safety" — https://eel.is/c++draft/basic.stc.dynamic.safety#4
А так обычно у всех "relaxed pointer safety", это implementation-defined, никакого UB.
Можно даже в рантайме проверить: https://en.cppreference.com/w/cpp/memory/gc/get_pointer_safety
И даже под Valgrind, видимо, чисто теоретически подстроиться, если увидел preferred
В статье Неинициализированные переменные говорится, что в Go нельзя использовать неинициализированные переменные:
Новые современные языки программирования обычно запрещают использование неинициализированных переменных. И выдают ошибку компиляции, если такое происходит. Так сделано в Rust, Kotlin, Go. И еще в куче языков.
Однако Go такое не запрещает (выдержка из Go Specification, интерактивный пример - A Tour of Go):
When storage is allocated for a variable, either through a declaration or a call of
new
, or when a new value is created, either through a composite literal or a call ofmake
, and no explicit initialization is provided, the variable or value is given a default value. Each element of such a variable or value is set to the zero value for its type:false
for booleans,0
for numeric types,""
for strings, andnil
for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
Cкорее даже поощряет - What is the zero value, and why is it useful?
Apparently it's impossible to implement std::vector
:
https://stackoverflow.com/questions/60481204/dynamic-arrays-in-c-without-undefined-behavior
https://www.youtube.com/watch?v=IAdLwUXRUvg&t=1267s
In particular:
T*
without creating T[]
: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2019/p0593r5.html#dynamic-construction-of-arrays , so you should either placement-new an array in a chunk of memory (which will construct elements as well) or allocate char[]
/byte[]
and do char
-based arithmetics to address elements (not sure if it's legal), but you still cannot implement T* vector::data()
char[]
because it may need an unspecified number of extra bytes: https://stackoverflow.com/questions/15254/can-placement-new-for-arrays-be-used-in-a-portable-wayв главе про const
говорилось, что в цикле нельзя единожды вычислить size()
константного объекта в цикле и переиспользовать, так как существует const_cast
, который может изменять состояние объекта
for (size_t i = 0; i < v.size(); ++i) { // значение v.size() нельзя
// единожды сохранить в регистре
а в главе про race condition говорится, что компилятор таки может соптимизировать вычисление функции size()
// Race condition запрещен, от модификации v в
// параллельном потоке нас «защищает» UB.
// А значит можно соптимизировать вычисление size
// const size_t v_size = v.size();
// for (size_t i = 0; i < v_size; ++i) { ... }
return sum;
наверное, второй пример некорректен, и его следует заменить. или же тут всё не так однозначно?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.