/ home / Programming / Style /

Auto

auto should only be used for Lambdas, Templates, and Macros.

Why not in ordinary code? §
  1. auto costs time in the long run.
  2. auto can be potentially dangerous.

1. Why does auto cost time in the long run? §
  1. // Type is currently unknown
  2. auto sneed = feed.seed();
  3. // v Deduced from here:
  4. QString Feed::seed() { ... }
  5. // or possibly even here: v
  6. auto Feed::seed() { return 1; }
  1.   int sneed = 1;
  2. // ^ type known immediately
  3. auto sneed = 1;
  4. // ............^ type known @ EOL
  1. // char or int?
  2. auto seed = '1';
  3. // bool or string?
  4. auto feed = "false";

2. How can auto be potentially dangerous? §
  1. // Perfectly fine and acceptable
  2. auto sneed = []( int feed ){ return feed += 1024; };
  3. sneed("seed"); // Will not compile!
  4. // Dangerous and completely unacceptable
  5. auto sneed = []( auto feed ){ return feed += 1024; };
  6. sneed("seed"); // Buffer Overflow
  7. // Output: "ceFrom == displaceTo"

Why use auto for a lambda's type? §
  1. // Function Pointer - Works
  2. int (*sneed)() = [ ]() { return 1; };
  3. // with capture - WILL NOT COMPILE!
  4. int (*sneed)() = [&]() { return 1; };
  5. // Acceptable either way.
  6. auto sneed = [ ]() { return 1; };
  7. auto sneed = [&]() { return 1; };

Why in Templates or Macros? §
  1. union Seed;
  2. union Feed
  3. {
  4. int operator+( Feed & ) { return 0 ; };
  5. QString operator+( Seed & ) { return "feed"; };
  6. };
  7. union Seed
  8. {
  9. int operator+( Feed & ) { return 1 ; }
  10. QString operator+( Seed & ) { return "seed"; }
  11. };
  12. // This template can now return either an integer, or a string
  13. template<typename T0, typename T1> auto sneed()
  14. {
  15. T0 p;
  16. T1 q;
  17. return p + q;
  18. }
  19. qDebug() << sneed<Feed,Feed>(); // 0
  20. qDebug() << sneed<Feed,Seed>(); // "feed"
  21. qDebug() << sneed<Seed,Feed>(); // 1
  22. qDebug() << sneed<Seed,Seed>(); // "seed"