logoalt Hacker News

pjmlp • today at 5:17 PM • 1 reply • view on HN

C raw arrays and strings should only be used for "unsafe" C++ code, in the implementation of safer types, with bounded checked interfaces, or in interop code with C libraries, properly wrapped in safe accessors for example.

Use of references for any non nullable pointer.

RAII for heap allocated types, eventually new/delete, leave malloc()/free() family with sizeof type math for interop with existing C code.

Prefer standard library algorithms with proper bounds checking, instead of memsomething and strsomething function family.

Preprocessor magic, when templates and constexpr are type safe, and can even be single stepped on a modern IDE.

Just some examples out of my mind.


Replies

PhilipRoman • today at 6:24 PM

I wholeheartedly disagree with the idea that all C++'s problems come from backwards compatibility with C. Even "pure" C++ alone without C constructs brings enough footguns.

  struct Config {
    std::vector<std::string> names;
    const std::vector<std::string>& getNames() const { return names; }
  };
  Config loadConfig();
  
  // which of these are safe?
  for (const auto& n : loadConfig().names)      { use(n); }  // A
  for (const auto& n : loadConfig().getNames()) { use(n); }  // B
  
  const auto& v1 = loadConfig().names;          // C
  for (const auto& n : v1) { use(n); }
  
  const auto& v2 = loadConfig().getNames();     // D
  for (const auto& n : v2) { use(n); }
Trick question btw
➕ show 1 reply