logoalt Hacker News

PhilipRoman • today at 6:24 PM • 2 replies • view on HN

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

Replies

plorkyeran • today at 8:07 PM

C in C++20, A, B and C in C++23. This does sort of fall under a backwards compatibility issue, albeit not with C, as making D valid was considered too much of a breaking change.

trealira • today at 6:36 PM

Why not simply write the following?

   const Config config { loadConfig() };
   for (auto &name : config.names) {
       use(name);
   }
Or else you could have "loadConfig()" be a method that returns a reference, which is in turn the member of a class, so that there isn't any dangling reference issue.