O que C ++ pode fazer isso muito difícil ou confuso em qualquer outro idioma?

StackOverflow https://stackoverflow.com/questions/423335

  •  05-07-2019
  •  | 
  •  

Pergunta

Ainda sinto que o C ++ oferece algumas coisas que não podem ser espancadas. Não é minha intenção iniciar uma guerra de chamas aqui, por favor, se você tiver opiniões fortes sobre não gostar de C ++, não as desaceite aqui. Estou interessado em ouvir os gurus C ++ sobre por que eles continuam com isso.

Estou particularmente interessado em aspectos do C ++ que são pouco conhecidos ou subutilizados.

Editar: Pessoas, por favor, tenha pelo menos uma leitura superficial de outras respostas para garantir que você não esteja duplicando o que já foi dito, se você concorda com o que alguém disse, vote!

Foi útil?

Solução

Eu fiquei com o C ++, pois ainda é a linguagem de uso geral de maior desempenho para aplicações que precisam combinar eficiência e complexidade. Como exemplo, escrevo software de modelagem de superfície em tempo real para dispositivos portáteis para a indústria de pesquisa. Dados os recursos limitados, Java, C#, etc ... simplesmente não fornecem as características de desempenho necessárias, enquanto idiomas de nível inferior como C são muito mais lentos para se desenvolver, dadas as características de abstração mais fracas. A gama de níveis de abstração disponível para um desenvolvedor de C ++ é enorme, em um extremo, posso estar sobrecarregando operadores aritméticos para que eu possa dizer algo como MaterialVolume = DesignSurface - SoundSurface Ao mesmo tempo, executando vários montes diferentes para gerenciar a memória com mais eficiência para o meu aplicativo em um dispositivo específico. Combine isso com uma riqueza de fonte disponível gratuitamente para resolver praticamente qualquer problema comum, e você tem uma linguagem de desenvolvimento poderosa.

O C ++ ainda é a solução ideal de desenvolvimento para a maioria dos problemas na maioria dos domínios? Provavelmente não, embora em uma pitada ainda possa ser usada para a maioria deles. Ainda é a melhor solução para o desenvolvimento eficiente de aplicações de alto desempenho? IMHO sem dúvida.

Outras dicas

RAII / deterministic finalization. No, garbage collection is not just as good when you're dealing with a scarce, shared resource.

Unfettered access to OS APIs.

Shooting oneself in the foot.

No other language offers such a creative array of tools. Pointers, multiple inheritance, templates, operator overloading and a preprocessor.

A wonderfully powerful language that also provides abundant opportunities for foot shooting.

Edit: I apologize if my lame attempt at humor has offended some. I consider C++ to be the most powerful language that I have ever used -- with abilities to code at the assembly language level when desired, and at a high level of abstraction when desired. C++ has been my primary language since the early '90s.

My answer was based on years of experience of shooting myself in the foot. At least C++ allows me to do so elegantly.

Deterministic object destruction leads to some magnificent design patterns. For instance, while RAII is not as general a technique as garbage collection, it leads to some impressive capabilities which you cannot get with GC.

C++ is also unique in that it has a Turing-complete preprocessor. This allows you to prefer (as in the opposite of defer) a lot of code tasks to compile time instead of run time. For instance, in real code you might have an assert() statement to test for a never-happen. The reality is that it will sooner or later happen... and happen at 3:00am when you're on vacation. The C++ preprocessor assert does the same test at compile time. Compile-time asserts fail between 8:00am and 5:00pm while you're sitting in front of the computer watching the code build; run-time asserts fail at 3:00am when you're asleep in Hawai'i. It's pretty easy to see the win there.

In most languages, strategy patterns are done at run-time and throw exceptions in the event of a type mismatch. In C++, strategies can be done at compile-time through the preprocessor facility and can be guaranteed typesafe.

Write inline assembly (MMX, SSE, etc.).

Deterministic object destruction. I.e. real destructors. Makes managing scarce resources easier. Allows for RAII.

Easier access to structured binary data. It's easier to cast a memory region as a struct than to parse it and copy each value into a struct.

Multiple inheritance. Not everything can be done with interfaces. Sometimes you want to inherit actual functionality too.

I think i'm just going to praise C++ for its ability to use templates to catch expressions and execute it lazily when it's needed. For those not knowing what this is about, here is an example.

Template mixins provide reuse that I haven't seen elsewhere. With them you can build up a large object with lots of behaviour as though you had written the whole thing by hand. But all these small aspects of its functionality can be reused, it's particularly great for implementing parts of an interface (or the whole thing), where you are implementing a number of interfaces. The resulting object is lightning-fast because it's all inlined.

Speed may not matter in many cases, but when you're writing component software, and users may combine components in unthought-of complicated ways to do things, the speed of inlining and C++ seems to allow much more complex structures to be created.

Absolute control over the memory layout, alignment, and access when you need it. If you're careful enough you can write some very cache-friendly programs. For multi-processor programs, you can also eliminate a lot of slow downs from cache coherence mechanisms.

(Okay, you can do this in C, assembly, and probably Fortran too. But C++ lets you write the rest of your program at a higher level.)

This will probably not be a popular answer, but I think what sets C++ apart are its compile-time capabilities, e.g. templates and #define. You can do all sorts of text manipulation on your program using these features, much of which has been abandoned in later languages in the name of simplicity. To me that's way more important than any low-level bit fiddling that's supposedly easier or faster in C++.

C#, for instance, doesn't have a real macro facility. You can't #include another file directly into the source, or use #define to manipulate the program as text. Think about any time you had to mechanically type repetitive code and you knew there was a better way. You may even have written a program to generate code for you. Well, the C++ preprocessor automates all of these things.

The "generics" facility in C# is similarly limited compared to C++ templates. C++ lets you apply the dot operator to a template type T blindly, calling (for example) methods that may not exist, and checks-for-correctness are only applied once the template is actually applied to a specific class. When that happens, if all the assumptions you made about T actually hold, then your code will compile. C# doesn't allow this... type "T" basically has to be dealt with as an Object, i.e. using only the lowest common denominator of operations available to everything (assignment, GetHashCode(), Equals()).

C# has done away with the preprocessor, and real generics, in the name of simplicity. Unfortunately, when I use C#, I find myself reaching for substitutes for these C++ constructs, which are inevitably more bloated and layered than the C++ approach. For example, I have seen programmers work around the absence of #include in several bloated ways: dynamically linking to external assemblies, re-defining constants in several locations (one file per project) or selecting constants from a database, etc.

As Ms. Crabapple from The Simpson's once said, this is "pretty lame, Milhouse."

In terms of Computer Science, these compile-time features of C++ enable things like call-by-name parameter passing, which is known to be more powerful than call-by-value and call-by-reference.

Again, this is perhaps not the popular answer- any introductory C++ text will warn you off of #define, for example. But having worked with a wide variety of languages over many years, and having given consideration to the theory behind all of this, I think that many people are giving bad advice. This seems especially to be the case in the diluted sub-field known as "IT."

Technically, I think there's none, really!

I honestly don't think that there's anything that C++ can do which The D Language can't. No matter what ability C++ has, it's always harder and messier than D or any other language. Even a simple thing like a class declaration is so much harder and messier in C++ than any other language.

The only thing C++ can do is be compatible with millions of lines of codes already written in C++.
This is the only thing that no language other than C++ can do :)

Passing POD structures across processes with minimum overhead. In other words, it allows us to easily handle blobs of binary data.

C# and Java force you to put your 'main()' function in a class. I find that weird, because it dilutes the meaning of a class.

To me, a class is a category of objects in your problem domain. A program is not such an object. So there should never be a class called 'Program' in your program. This would be equivalent to a mathematical proof using a symbol to notate itself -- the proof -- alongside symbols representing mathematical objects. It'll be just weird and inconsistent.

Fortunately, unlike C# and Java, C++ allows global functions. That lets your main() function to exist outside. Therefore C++ offers a simpler, more consistent and perhaps truer implementation of the the object-oriented idiom. Hence, this is one thing C++ can do, but C# and Java cannot.

I think that operator overloading is a quite nice feature. Of course it can be very much abused (like in Boost lambda).

Tight control over system resources (esp. memory) while offering powerful abstraction mechanisms optionally. The only language I know of that can come close to C++ in this regard is Ada.

C++ provides complete control over memory and as result a makes the the flow of program execution much more predictable. Not only can you say precisely at what time allocations and deallocations of memory occurs, you can define you own heaps, have multiple heaps for different purposes and say precisely where in memory data is allocated to. This is frequently useful when programming on embedded/real time systems, such as games consoles, cell phones, mp3 players, etc..., which:

  1. have strict upper limits on memory that is easy to reach (constrast with a PC which just gets slower as you run out of physical memory)
  2. frequently have non homogeneous memory layout. You may want to allocate objects of one type in one piece of physical memory, and objects of another type in another piece.
  3. have real time programming constraints. Unexpectedly calling the garbage collector at the wrong time can be disastrous.

AFAIK, C and C++ are the only sensible option for doing this kind of thing.

Well to be quite honest, you can do just about anything if your willing to write enough code.

So to answer your question, no, there is nothing you can't do in another language that C++ can't do. It's just how much patience do you have and are you willing to devote the long sleepless nights to get it to work?

There are things that C++ wrappers make it easy to do (because they can read the header files), like Office development. But again, it's because someone wrote lots of code to "wrap" it for you in an RCW or "Runtime Callable Wrapper"

EDIT: You also realize this is a loaded question.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top