Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. New code in C? Where and why, versus C++?

New code in C? Where and why, versus C++?

Scheduled Pinned Locked Moved The Lounge
c++questiondata-structuresooptutorial
58 Posts 24 Posters 2 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • H honey the codewitch

    How did I forget about "final"? I would have guessed it was newer than C++11 anyway - more like 17 or something. My hero! I guess I've got some code to refactor. Win!

    Real programmers use butterflies

    pkfoxP Offline
    pkfoxP Offline
    pkfox
    wrote on last edited by
    #31

    I think Java has this ( final not this )

    "I didn't mention the bats - he'd see them soon enough" - Hunter S Thompson - RIP

    1 Reply Last reply
    0
    • R Rick York

      It is very easy to delete unwanted aspects of classes like copy constructors and copy operators. If you can reduce the amount of dynamic objects used, performance can really improve and deleting those things can help. I have seen this many times.

      "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

      S Offline
      S Offline
      steveb
      wrote on last edited by
      #32

      They autogenerated by compiler automatically even if the code does not declare them

      R 1 Reply Last reply
      0
      • S steveb

        They autogenerated by compiler automatically even if the code does not declare them

        R Offline
        R Offline
        Rick York
        wrote on last edited by
        #33

        Yes, I know and as I wrote they can be deleted or, in other words, effectively removed from usage. I do this to make a class uncopyable :

        #define MakeUncopyable( className ) \
        className( const className & ) = delete; \
        className & operator=( const className & ) = delete;

        and any attempts to copy the object will fail to compile. This is useful for singleton objects and others where there can be only one.

        "They have a consciousness, they have a life, they have a soul! Damn you! Let the rabbits wear glasses! Save our brothers! Can I get an amen?"

        1 Reply Last reply
        0
        • H honey the codewitch

          This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

          Real programmers use butterflies

          G Offline
          G Offline
          giulicard
          wrote on last edited by
          #34

          Yes. I agree. To not mention that with the "placement new" operator is possible to create objects on existing memory blocks. Turning off the exception mechanism C++ is very good for the development of real-time embedded applications. Recreating the polymorfism in C, at best, has the same speed as in C++. But most of the time, C++ beats C in many areas, as the latter does not have templates. It's only possible to emulate them with macros, but macros, most of the time, are ugly and dangerous. Templates help with performances: for example, qsort has to do a callback to compare items; so, it spends CPU cycles, fools the CPU branch predictor, and possibly invalidates the level-1 instruction cache. With std::sort (or std::stable_sort) it's possible "to inject" the comparison into the algorithm. Yes, templates could make code bloating, but judicious use of non-template base classes could mitigate it.

          1 Reply Last reply
          0
          • R Rage

            honey the codewitch wrote:

            What is the purpose of writing new code in C for targeting, well ... anything?

            For products that you want to put on market, you have to comply to a lot of standards (like MISRA) that are much easier to implement in C, which is the state-of-the-art language. Given the amount of legacy code, this will probably not change in the next decade, so C remains the language if choice because, well, it was the language of choice. Of course, footprint & co also play a role, but not that much with modern compilers. Honestly, I am working in the automotive industry, and when I see what people are able to do with C, I am glad they are not given more powerful tools to work with ; I have my personal blacklist of vehicles I will never put a foot in, unless their code gets rewritten and their hardware redesigned.

            Do not escape reality : improve reality !

            G Offline
            G Offline
            giulicard
            wrote on last edited by
            #35

            I remember badly or in 2008 they issued the specifications for Misra C ++?

            1 Reply Last reply
            0
            • H honey the codewitch

              A recurring misconception I see about C++ appears to be the notion that it will write code that you didn't tell it to write, or use memory you didn't tell it to use. It's simply not the case. More the issue is, knowing what you're telling the C++ compiler to generate in terms of code. To wit, there is no code that can be written in C that I cannot write in C++ and generate the equivalent machine instructions - even if doing so means giving up certain niceties like virtual inheritance, exceptions or run time type information. RAII is reason alone to consider minimalistic C++ as an alternative to straight C. It generates no extra code, and it reduces lots of bugs.

              Real programmers use butterflies

              G Offline
              G Offline
              giulicard
              wrote on last edited by
              #36

              honey the codewitch wrote:

              RAII is reason alone to consider minimalistic C++ as an alternative to straight C. It generates no extra code, and it reduces lots of bugs.

              Exactly

              1 Reply Last reply
              0
              • Mike HankeyM Mike Hankey

                I ran into this problem with the small footprint Arduinos, folks where asking mw why I wanted to use C++ when C was so efficient, faster and used less memory. But I found there really wasn't much difference in size or speed...no response from the peanut gallery. Now with devices with more memory I think that people still use C because that is what they are comfortable with. In the late 80s early 90s I worked for the railroad in the cyber division and I tried to get people to cross over to C++ but not one person could I get to change. I taught classes in using the development tools, debuggers and worked with them one on one...nope!

                The less you need, the more you have. JaxCoder.com

                M Offline
                M Offline
                Martin ISDN
                wrote on last edited by
                #37

                i like this - "The less you need, the more you have"

                1 Reply Last reply
                0
                • H honey the codewitch

                  This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

                  Real programmers use butterflies

                  M Offline
                  M Offline
                  Martin ISDN
                  wrote on last edited by
                  #38

                  i would use C as a personal preference. it's subjective. also i rather be in company of C programmers than C++, that is also one reason you would use a particular language. but, i assume you posted a question to get some objective info as why C is a better choice than C++ in your use case scenario. maybe it is not. C++ was designed by Bjarne with zero cost abstractions in mind - "What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better." lots of people in the game making business use C style code with the C++ compiler or as little as possible classes, shallow hierarchies and such. the C++ compiler is a powerful beast and we (the programmers) are in the business of automation. so in that sense it's a better choice. C++ does not force you to use it in any way, that's good. i think Bjarne was hot on the OOP subject, if you read early editions of the book, but not so any more. he merely says C++ gives you complete support for OOP if you want it, among other things. here is a statement from Bjarne's book that you may consider when programming embedded - "Except for the new, delete, typeid, dynamic_cast, throw operators and the try block, individual C++ expressions and statements need no run-time support." for myself, i don't dislike OOP as a technical solution and capability. i dislike object orientation in people. that philosophy, look everything is an "object" and everything is related in hierarchies, took a wrong turn. instead of a solution for a problem it became a problem of it's own and a philosophy of life. solving the problem of say input data > processing > output data with classes and objects (if you like) became looking at classes as something that has a life of it's own. carried away by work on the class rather then on the whole... you know what i mean, that thing: this is a car and a car is a vehicle. then in the boom of OOP it became, either you do it our way or the highway.

                  H 1 Reply Last reply
                  0
                  • H honey the codewitch

                    Maybe I just vastly misunderstand C++, but AFAIK you don't have to use ctors, which are basically "operator overloads" in a sense for object "creation/instantiation/initatialization". If they don't do anything the compiler doesn't generate code for them. And addressof & does the same thing in C as it does in C++, unless you overload it. The theme here is, if you don't use the feature, it doesn't produce the code to run the feature. So if anything it seems a matter of education? Knowing what C++ will generate and what it won't. I write code for real time devices in C++ all the time. There's no more latency than C. Consider the following:

                    class A {
                    public:
                    int x;
                    };

                    This generates the same exact code as

                    struct A {
                    int x;
                    };

                    There are no constructors there. x will not get initialized on instantiation because I didn't write code for it. They are also both sizeof(int) in size. If i needed initialization

                    class A {
                    public:
                    int x;
                    A() : x(0) {}
                    // i'm omitting the big-5 here
                    };

                    this is no different than if i needed initialization in C except it's cleaner:

                    struct A {
                    int x;
                    };
                    void initializeA(struct A *a) {
                    // can't remember if -> is strictly C++ or not
                    (*a).x=0;
                    }

                    The former doesn't pollute the namespace, and also prevents the case of forgetting to call the initialization function.

                    Real programmers use butterflies

                    D Offline
                    D Offline
                    Dave B 68
                    wrote on last edited by
                    #39

                    honey the codewitch wrote:

                    So if anything it seems a matter of education? Knowing what C++ will generate and what it won't.

                    Perhaps this is the biggest issue. The level of knowledge one has to earn to know how to make the compiler generate what they want and even more importantly, know what the compiler will generate when reading someone else's code. This knowledge has a cost (potentially a high cost) that needs to be maintained by the organization through the expense of time and paid experience of every developer reading or maintaining the code. That expense must be offset by the reduction in cost of using C++ features that eliminate writing boilerplate code and organizing code. I suspect with the far simpler rules/capabilities of C code, you have to look at a lot less code you didn't write to understand exactly what it is doing without resorting to using a debugger or looking at assembly. My current opinion is that the decision of C versus C++ would come down to the project size and the pool and expense of developers you want maintaining the code. Imagine a "C++ developer" jumping into a project that required diagnosing a set of code that used partial and full template specialization a few levels deep and being asked to refactor it. Could they do it? The statements "I know C++" and "I know C" carry two different levels of trust. I would trust most people who claim to know C and I can easily test their knowledge. With C++, the question for me becomes, what parts of C++ do you know and how well do you know each?

                    Dave B

                    T 1 Reply Last reply
                    0
                    • H honey the codewitch

                      This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

                      Real programmers use butterflies

                      B Offline
                      B Offline
                      Behzad Sedighzadeh
                      wrote on last edited by
                      #40

                      Who needs inheritance in embedded world?

                      Behzad

                      H 1 Reply Last reply
                      0
                      • H honey the codewitch

                        This is something I'm really curious about, and maybe it's just because I'm newish to coding small gadgets, though most of it is comfortable to me since I cut my teeth on 6502 CPUs back in the day. What is the purpose of writing new code in C for targeting, well ... anything? I've put away my C compiler and simply relied on limited use of C++ features to keep the footprint the same as it is in C: 1. no vtables. slightly complicates inheritance, as you can no longer do virtual ~foo() {} 2. extremely limited use of the STL, if at all. I typically use std::atomic if available, but not std::string, for example 3. judicious use of extern "C" when exporting my main, or importing "C" headers 4. no exceptions/SEH/etc, RTTI or other C++ frills that bloat code or stack Why do I do it? Primarily for that sweet sweet RAII, but also general source management. Classes can keep everything together. HPP based libraries are useful for simplifying distribution. public and private members replace the need for hiding in C files in many cases. and many other reasons. Should I not be doing it? Is there a reason this is bad form? Is there a reason you wouldn't?

                        Real programmers use butterflies

                        S Offline
                        S Offline
                        Stuart Dootson
                        wrote on last edited by
                        #41

                        This is absolutely what I do. And I agree with you that so long as you understand and are happy with the 'hidden' code that C++ abstractions introduce, there's nothing wrong with using them. The only time I'll use C rather than C++ is if I'm targeting a platform that doesn't have a C++ compiler. And yes, I have one of those - it's a proprietary processor, has a port of GCC, Gnat (the GCC Ada compiler) but not G++. Yes, it's for a safety critical application. No, I can't talk any more about it. C++17 and 20 have introduced some nice new little abstractions, like `std::string_view` and `std::span` that would be useful in a C-ish world - basically, they're just pointer and length in a struct... Also - things like lambdas, once you realise they're just a function pointer (if you have no captures) or a function object, are equally usable in a resource constrained environment. The main thing I'd be wary of would be over many templates, in case they introduce too much code with multiple instantiations of functions for different template parameters.

                        Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                        H 1 Reply Last reply
                        0
                        • S Stuart Dootson

                          This is absolutely what I do. And I agree with you that so long as you understand and are happy with the 'hidden' code that C++ abstractions introduce, there's nothing wrong with using them. The only time I'll use C rather than C++ is if I'm targeting a platform that doesn't have a C++ compiler. And yes, I have one of those - it's a proprietary processor, has a port of GCC, Gnat (the GCC Ada compiler) but not G++. Yes, it's for a safety critical application. No, I can't talk any more about it. C++17 and 20 have introduced some nice new little abstractions, like `std::string_view` and `std::span` that would be useful in a C-ish world - basically, they're just pointer and length in a struct... Also - things like lambdas, once you realise they're just a function pointer (if you have no captures) or a function object, are equally usable in a resource constrained environment. The main thing I'd be wary of would be over many templates, in case they introduce too much code with multiple instantiations of functions for different template parameters.

                          Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                          H Offline
                          H Offline
                          honey the codewitch
                          wrote on last edited by
                          #42

                          I didn't know lambdas reduce to a function pointer without captures. I thought they were always functors. Cool. On that subject, how would you go about accepting a lambda as a parameter to a function without accepting std::function? (i'm pretty sure you'd need to make the accepting function a template but it would be cool if you didn't) For the most part, in embedded code I limit my templates to things that basically replace preprocessor macros, like

                          #define BAR_STATIC_ALLOCATION_SIZE 256

                          struct bar {
                          char foo[BAR_STATIC_ALLOCATION_SIZE];
                          };

                          instead i might make a declaration that allows for the following

                          bar<256> b;
                          

                          Real programmers use butterflies

                          S 1 Reply Last reply
                          0
                          • B Behzad Sedighzadeh

                            Who needs inheritance in embedded world?

                            Behzad

                            H Offline
                            H Offline
                            honey the codewitch
                            wrote on last edited by
                            #43

                            Why wouldn't you use inheritance? Do design patterns really change that significantly in embedded code?

                            Real programmers use butterflies

                            1 Reply Last reply
                            0
                            • M Martin ISDN

                              i would use C as a personal preference. it's subjective. also i rather be in company of C programmers than C++, that is also one reason you would use a particular language. but, i assume you posted a question to get some objective info as why C is a better choice than C++ in your use case scenario. maybe it is not. C++ was designed by Bjarne with zero cost abstractions in mind - "What you don’t use, you don’t pay for. And further: What you do use, you couldn’t hand code any better." lots of people in the game making business use C style code with the C++ compiler or as little as possible classes, shallow hierarchies and such. the C++ compiler is a powerful beast and we (the programmers) are in the business of automation. so in that sense it's a better choice. C++ does not force you to use it in any way, that's good. i think Bjarne was hot on the OOP subject, if you read early editions of the book, but not so any more. he merely says C++ gives you complete support for OOP if you want it, among other things. here is a statement from Bjarne's book that you may consider when programming embedded - "Except for the new, delete, typeid, dynamic_cast, throw operators and the try block, individual C++ expressions and statements need no run-time support." for myself, i don't dislike OOP as a technical solution and capability. i dislike object orientation in people. that philosophy, look everything is an "object" and everything is related in hierarchies, took a wrong turn. instead of a solution for a problem it became a problem of it's own and a philosophy of life. solving the problem of say input data > processing > output data with classes and objects (if you like) became looking at classes as something that has a life of it's own. carried away by work on the class rather then on the whole... you know what i mean, that thing: this is a car and a car is a vehicle. then in the boom of OOP it became, either you do it our way or the highway.

                              H Offline
                              H Offline
                              honey the codewitch
                              wrote on last edited by
                              #44

                              I don't look at C++ as C with objects. If anything I look at it as C with templates. Classes are just fancy structs anyway, and overuse of OO is for the birds, although admittedly I use more OOP than Generic Programming in C++ when I'm coding embedded, mostly because of code bloat issues with GP.

                              Martin ISDN wrote:

                              everything is an "object" and everything is related in hierarchies, took a wrong turn.

                              I have a problem with those people too - particularly if they're calling themselves C++ developers. If you want an object oriented language, learn C#. That's not what C++ is about. You *can* use it that way, but I can also use my C compiler as an assembler by wrapping everything with asm {}.. it doesn't mean it's a great idea.

                              Real programmers use butterflies

                              1 Reply Last reply
                              0
                              • H honey the codewitch

                                I didn't know lambdas reduce to a function pointer without captures. I thought they were always functors. Cool. On that subject, how would you go about accepting a lambda as a parameter to a function without accepting std::function? (i'm pretty sure you'd need to make the accepting function a template but it would be cool if you didn't) For the most part, in embedded code I limit my templates to things that basically replace preprocessor macros, like

                                #define BAR_STATIC_ALLOCATION_SIZE 256

                                struct bar {
                                char foo[BAR_STATIC_ALLOCATION_SIZE];
                                };

                                instead i might make a declaration that allows for the following

                                bar<256> b;
                                

                                Real programmers use butterflies

                                S Offline
                                S Offline
                                Stuart Dootson
                                wrote on last edited by
                                #45

                                honey the codewitch wrote:

                                On that subject, how would you go about accepting a lambda as a parameter to a function without accepting std::function? (i'm pretty sure you'd need to make the accepting function a template but it would be cool if you didn't)

                                The way I generally do it on a non-constrained platform is with a template: ```c++ template int do_something(F&& f, int value) { return f(value); } ``` However - there is a C++ standard proposal paper for something called a `function_view`, which is intended as a lightweight alternative to `std::function` purely for passing functions as parameters. This [blog article](https://vittorioromeo.info/index/blog/passing\_functions\_to\_functions.html) explains it more. I've seen other `std:function` alternatives as well - [this one, here on CodeProject](https://www.codeproject.com/articles/11015/the-impossibly-fast-c-delegates) was one of the first I saw, IIRC.

                                Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                                H 1 Reply Last reply
                                0
                                • S Stuart Dootson

                                  honey the codewitch wrote:

                                  On that subject, how would you go about accepting a lambda as a parameter to a function without accepting std::function? (i'm pretty sure you'd need to make the accepting function a template but it would be cool if you didn't)

                                  The way I generally do it on a non-constrained platform is with a template: ```c++ template int do_something(F&& f, int value) { return f(value); } ``` However - there is a C++ standard proposal paper for something called a `function_view`, which is intended as a lightweight alternative to `std::function` purely for passing functions as parameters. This [blog article](https://vittorioromeo.info/index/blog/passing\_functions\_to\_functions.html) explains it more. I've seen other `std:function` alternatives as well - [this one, here on CodeProject](https://www.codeproject.com/articles/11015/the-impossibly-fast-c-delegates) was one of the first I saw, IIRC.

                                  Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                                  H Offline
                                  H Offline
                                  honey the codewitch
                                  wrote on last edited by
                                  #46

                                  unfortunately I'll probably be at least well on my way to dead by the time function_view makes its way through the standards body to find itself in C++50 and then finally gets picked up by GCC and then the Espressif ESP32 toolchain. :((

                                  Real programmers use butterflies

                                  S 1 Reply Last reply
                                  0
                                  • P PIEBALDconsult

                                    I like that C/C++ is "multi-paradigm" and I wish C# were too.

                                    H Offline
                                    H Offline
                                    honey the codewitch
                                    wrote on last edited by
                                    #47

                                    C++ is anyway. I wouldn't say C is. It's got one mode - "the hard way" :laugh:

                                    Real programmers use butterflies

                                    1 Reply Last reply
                                    0
                                    • H honey the codewitch

                                      unfortunately I'll probably be at least well on my way to dead by the time function_view makes its way through the standards body to find itself in C++50 and then finally gets picked up by GCC and then the Espressif ESP32 toolchain. :((

                                      Real programmers use butterflies

                                      S Offline
                                      S Offline
                                      Stuart Dootson
                                      wrote on last edited by
                                      #48

                                      All the code for it is contained in [a single C++ header file](https://github.com/SuperV1234/vittorioromeo.info/blob/master/extra/passing\_functions\_to\_functions/function\_view.hpp) - you could just incorporate that into your build :-)

                                      Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                                      H 1 Reply Last reply
                                      0
                                      • S Stuart Dootson

                                        All the code for it is contained in [a single C++ header file](https://github.com/SuperV1234/vittorioromeo.info/blob/master/extra/passing\_functions\_to\_functions/function\_view.hpp) - you could just incorporate that into your build :-)

                                        Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                                        H Offline
                                        H Offline
                                        honey the codewitch
                                        wrote on last edited by
                                        #49

                                        decltype(auto) operator()(TArgs... xs) const

                                        Doesn't seem to matter how much time I spend looking at C++ code, I'm still always learning new things about it. Didn't know decltype(auto) was a thing. That's pure magic. Now I know how they do their elastic functors. :-D

                                        Real programmers use butterflies

                                        S 1 Reply Last reply
                                        0
                                        • H honey the codewitch

                                          decltype(auto) operator()(TArgs... xs) const

                                          Doesn't seem to matter how much time I spend looking at C++ code, I'm still always learning new things about it. Didn't know decltype(auto) was a thing. That's pure magic. Now I know how they do their elastic functors. :-D

                                          Real programmers use butterflies

                                          S Offline
                                          S Offline
                                          Stuart Dootson
                                          wrote on last edited by
                                          #50

                                          There's more than one way to skin that cat :-) `decltype(auto)` is used instead of `auto` here because `auto` strips references from the type of the thing it's inferring from (e.g. if your function returned a `std::string const&`, using `auto` would cause it to return by value, whereas `decltype(auto)` would cause it to return the reference). However, in this case, `auto&&` has the same semantics as `decltype(auto)`, and will return by reference if that's what's wanted. `auto` return types are useful for places where the return type is difficult (or impossible) to state statically - consider this code (which is valid c++17), which returns a string if it's instantiated for `std::string` and an integer otherwise... There are situations where something like this is useful. ```c++ template auto foo(T const& t) { if constexpr (std::is_same_v) { return "Hello"; } else { return 3; } } int main() { std::cout << foo(12) << std::endl; std::cout << foo(std::string("a")) << std::endl; } ``` outputs 3 Hello

                                          Java, Basic, who cares - it's all a bunch of tree-hugging hippy cr*p

                                          H 1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups