Safety в С++ та що про це думає АІ

Колеги, якщо хто забув, плюси живі, розвиваються і судячи з усього, будуть жити ще дуже довго, принаймні я вірю, що джаву переживуть %).

Прямо зараз комітет і особисто Б’ярн Страуструп працюють над покищо ідеями стосовно того, як має виглядати безпека в С++.
P2759R1: DG Opinion on Safety for ISO C++
Документ цікавий, всього на 10 сторінок, але показує, що розробники цікавляться темою і хочуть покращити технологію.

Якщо у вас дійсно є ідеї/коментарі стосовно викладеного матеріалу за посиланням, пишіть Страуструпу(за посиланням є його мило) або можемо зібрати коментарі від спільноти тут в темі і я оформлю все одним листом.

Ну і ще аби додати трохи вже спадаючого хайпу, я запитав у ChatGPT два запитання:

1. Tell me about best practices Safety in C++

There are several best practices that C++ developers can follow to help ensure safety in their code. Some of these best practices include:

  1. Use modern C++ features: Modern C++ features like smart pointers can help to minimize the risk of memory leaks and other related issues that can compromise the safety of your code. By using these features, you can reduce the likelihood of errors caused by incorrect memory management.
  2. Avoid dangerous constructs: Constructs like raw pointers and null references can be difficult to use safely and can cause errors in your code. To minimize the risk of these errors, it’s best to avoid using these constructs whenever possible.
  3. Manage memory carefully: Memory allocation and deallocation can be a major source of bugs and other issues in C++ code. To minimize these risks, it’s important to carefully manage memory allocation and deallocation, using tools like smart pointers and other memory management features to help automate these processes.
  4. Avoid undefined behavior: Undefined behavior can be a major source of bugs and other issues in C++ code. To minimize these risks, it’s important to avoid undefined behavior wherever possible, following best practices like using range-based loops and avoiding undefined conversions.
  5. Use testing and analysis tools: Static and dynamic analysis tools can help to identify potential issues in your code before it is deployed. By using these tools, you can catch bugs and other issues before they become major problems, improving the overall safety and reliability of your code.

By following these and other best practices, C++ developers can help to ensure that their code is as safe as possible, reducing the risk of bugs, vulnerabilities, and other potential issues.

2. А також про те, що можна імпрувнути. Мій промт(запит до чату) був досить довгим із цитуванням документу за посиланням, тому наводжу лише відповідь:

In the context of safety in modern C++, there are several areas where improvements can be made. Some possible solutions that meet the basic tenets listed in the prompt could include:

  1. Improved standardization: Standardization of safety features in C++ can help to improve safety without breaking backwards compatibility or impeding the ability to express abstractions. For example, standardizing on smart pointers or other memory management techniques could help to reduce the likelihood of memory-related bugs.
  2. Better tooling support: Improved tooling support can help to catch potential safety issues early on without imposing undue performance overhead. This could include the development of static analysis and testing tools specifically tailored to modern C++ features and best practices.
  3. More emphasis on safety in education: Increasing the emphasis on safety in C++ education can help to reduce the risk of errors caused by novice or inexperienced developers. This could include the development of safety-focused training materials and courses, as well as the integration of safety best practices into existing education programs.
  4. Enhanced safety features: Enhanced safety features, such as support for secure coding practices and improved memory safety, can help to reduce the risk of bugs, vulnerabilities, and other related issues. These features should be developed with an eye toward maintaining compatibility and preserving C++’s productivity advantages.
  5. Improved integration with existing codebases: Improved integration with existing C++ codebases can help to facilitate gradual and partial adoption of new safety features without imposing undue constraints or requiring wholesale rewrites. This could include the development of tools and techniques for identifying and addressing potential issues in legacy code.

By addressing these and other areas, it may be possible to improve the overall safety of modern C++ programming without sacrificing compatibility, performance, or productivity.

Як бачимо, чат не надає конкретних технічних рекомендацій, але вказує на важливість «інфраструктури», тулів, навчання девелоперів.

Особисто я хз чи вийде зробити щось дійсно робоче не плодячи «діалекти» мови під різні доменні області, типу розвитку AUTOSAR із своїм, в перспективі, діалектом С++ для додаткової безпеки в автомотіві, але спостерігти за розвитком технології цікаво.

Підписуйтеся на Telegram-канал «DOU #tech», щоб не пропустити нові технічні статті

👍ПодобаєтьсяСподобалось0
До обраногоВ обраному0
LinkedIn
Дозволені теги: blockquote, a, pre, code, ul, ol, li, b, i, del.
Ctrl + Enter
Дозволені теги: blockquote, a, pre, code, ul, ol, li, b, i, del.
Ctrl + Enter

На загал, судячи з усього увесь комітет вважає,що треба бігом копіювати ідею з слідкуванням за часом життя об’єкту на момент компіляції з Rust, щоб взагалі бути конкурентними з Rust. Зараз розробників компіляторів, принаймні GCC та LLVM/Clang активно пилять доробки. Як я розумію приціл на стандарт 25. 23 стандарт вже на етапі фіксування, скоро має вийти.

опитування 2022 Annual C++ Developer Survey «Lite»
каже що
«Memory safety: Bounds safety issues (read/write beyond the bounds of an object or array)»
цікавиться «аж» 14% учасників опитування
то, отже «такі проблеми» всі решта або «вже порішали» або ж «думають що порішати» (що, насправді сумно)

а как джава может пережить плюсы, когда она на них и написана? Ну может на С

Ну чисто технически, за два человеко-столетия можно переписать все теперь уже модули виртуальной машины и т.д. скажем на Rust, D или Go Lang. Чисто практически — оно никому нахрен не надо, это огромные расходы на голом месте, работа ради работы. Намного лучше эволюционно улучшить сами С/С++, поросто добавив фитчи которые себя хорошо показали в других языках: корутины уже перенесли, разные монады типа std::optional и т.д. и т.п. У С++ как минимум три активно разрабатываемых и широко используемых компилятора, масса компаний и программистов работающих с языком, миллиарды строк кода написанные на этом языке, огромная експертиза, международные стандарты как на С так и на С++ и т.д.

Підписатись на коментарі