r/learnprogramming • • 23d ago

What language is most like a garbage collected version of c++?

I like c++ for its flexible multi paradigm support, wide applications, a decent amount of syntax sugar and a good type and metaprogramming system, but to be fair super precise manual memory management is overkill for most oft the programs i'm going to write.

43 Upvotes

65 comments sorted by

38

u/podule-games 23d ago

C# probably.

It's not that much like C++ in the grand scheme of things, but probably the closest you'll get with GC.

Rust doesn't have GC as such*, but it does mostly manage memory for you, just in a different way.

*It does have reference counting for some things, which some would call GC and some wouldn't, but basically, it's not GC in the Java or C# sense.

5

u/Active_Name5021 21d ago

I agree with C#, its also a kitchen sink, but with a GC!

(Love C#, but omg the features are all over the place)

4

u/MaeInMilwaukee 23d ago

You’ll love Rust’s “GC”—as long as you enjoy spicy debates!

1

u/ohkendruid 20d ago

Agree on both points.

Swift is worth adding. It derives from Objective C, which branched from C and added classes to C with a different design that C++.

Swift and Rust both offer reference-counted memory management. Similar to GC, you do not have to call free to release most of your allocated memory, so it feels to a programmer similar to a GCed language.

0

u/Kadabrium 23d ago

Thanks, do you maybe have any ideas about kotlin, dart, scala or swift?

5

u/podule-games 23d ago

Kotlin is nice, Swift is a good language, but no real traction outside of Apple platforms. Never used Dart or Scala.

Swift, even on Apple platforms isn't ubiquitous, loads of people make Mac apps with Electron or something like that, or the big players like Adobe use C++. Swift is nice, but it's just not that popular a language and I'm not sure it makes sense to use it, even on iPhone or Mac, depending on what you're making.

0

u/Kadabrium 23d ago

So il look into c# and kotlin and maybe typescript that is (never looked at a codebase in the latter two)

2

u/podule-games 23d ago

TypeScript is nice too, but I'm not wild about Node.js. I like TypeScript for web front end though.

0

u/spinwizard69 23d ago

The only way to expand Swift usage is to employ it on other platforms. As a programming language it is far better that C++, Go, Rust and a bunch of other players. On Linux there has been a lot of stupid resistance.

2

u/NomaTyx 23d ago

kotlin isn't super syntactically similar

0

u/amazing_rando 23d ago

You can write syntactically similar code in Kotlin but its strengths are in its functional language features and type comprehension, and its libraries use them extensively. If you want to write C++ style code you’ll be fighting against it.

7

u/Chad_Frost 23d ago

I'd guess something like golang is the most practical answer. Iirc C# allows for some more manual stuff like C++ compared to java but it runs on the CLR so it's not quite comparable.

If you want to be technical I guess D is the closest one on paper since its basically designed to be C but with GC, but D doesn't really have the same breadth of practical application as something like golang.

1

u/Kadabrium 23d ago

Thanks, D is defo interesting, what do you think of typescript?

1

u/Chad_Frost 22d ago

I haven't used it. Typescript from what I gather is for Web dev? I feel like for most desktop applications I would rather use something else like C#, but that's also because I am used to C# and it's my goto language

17

u/rupertavery64 23d ago edited 23d ago

I'm surprised that despite C# being the primary suggestion here, you don't seem interested in it at all, despite it being most like C++ in syntax, some delicious syntax sugar and yes, elegant type and metaprogramming.

Wait until you learn about switch expressions, try/catch expressions, property initializers, the Disposable pattern and the using statement, extension methods (recentlty expanded to extension members)

Let's not forget the versatility of IEnumerable and IQueryable and how it is powered by LINQ and how that lets you write typed queries against objects or build (SQL) expressions from them, or use however you like. You can even write code in code. And compile it.

A rich type and metaprogramming system, with reified generics, an attribute system and reflection.

And of course it is garbage collected, but you can do unsafe stuff with it as well. It exposes safe memory access with Span<T> and Memory<T> each with language embedded restrictions that guarantee safe usage.

C# also introduced async/await which really simplifies asynchronous programming and has been making its rounds with other programming languages since.

What kinds of programs are you planning on writing?

4

u/Ok-Interest9727 23d ago

C# is amazing. It’s a shame there’s not much of an ecosystem outside of dotnet compared to Java or TS/JS.

1

u/flatfinger 22d ago

The semantics of the language are coupled to the semantics of .NET features, and the parts of the language that try to deny such coupling end up as broken abstractions.

3

u/TSS_Firstbite 23d ago

A double credit course I have is basically building a web project with C# over the semester and one of the first things I noticed was how well I read and understood it, which as a student is not that common still, because I learned C++. And LINQ? Oh, it's so good, especially when I saw another group writing SQL queries by hand. I'm also confused why OP doesn't seem to consider C# an option

-5

u/Kadabrium 23d ago

PascalCase variable names strike me as somewhat odd. Wouldnt they look like types? I don't know if you do Object object = new Object in c# but if there is then with Object Object it just gets extra weird

6

u/insertAlias 22d ago

That's not a language feature, that's just the default style. Honestly: as a 20+ year professional developer, you're hung up on all the wrong things here. You'll get over that style difference in about a week.

And my best advice for you is to stop trying to find something perfect and just take the damn advice you're being given. It's good advice.

3

u/rupertavery64 23d ago edited 23d ago

There is no enforcement of case in variable or member names, but by convention properties are PascalCase and fields and local variables are camelCase.

object is a keyword in C#, which is an alias for the root type System.Object so it wouldn't compile anyway, but for illustrative purposes, yes, you can name a variable in the same case as a type, but that's on you.

Car Car = new Car();

Car.Drive();

Syntax highlighting will show you what is a type vs a variable.

You can't create a property or field with the same name as the class, because that's reserved for the constructor.

class Car
{
    // member names cannot be the same as their enclosing type
    public Car Car;
}

And if you try to be smart and confuse the compiler with a static method:

class Car
{
   public void Honk()
   {
   }

   public static void Drive()
   {
   }
}


Car Car = new Car();

// Car here is the variable, since Honk is an instance method
Car.Honk();

// Car here is resolved to the Type, since Drive is an static method
Car.Drive();

2

u/binarycow 23d ago

In C#, Members are PascalCase, variables are camelCase.

Yes, a member may be a property or field, which are like variables, but they're members.

It's fairly easy to tell the difference, with just a tad bit of experience. And decent IDEs give syntax highlighting to distinguish. L

All constructors would use parentheses.

Foo foo = new Foo();

2

u/ComasArentFun 21d ago

Such a shit reason to dispose of an entire language that literally ticks every box you want
I've worked with people like this that have firmly held opinions but on the weakest principals...
Also this is a "style" not "substance" issue. YOU dictate case.

You use what is best for the job. Languages are easy to learn and adapt to when you are a competent engineer. You don't nail your colours to a mast and refuse/insist on technology because of your beliefs

1

u/metaphorm 20d ago

syntax is superficial. style guidelines for code even more so. the most important things about a language are its set of programming language constructs and the ways these constructs model the language runtime.

-1

u/Ok_Entrepreneur_8509 23d ago

I agree that PascalCase is absolutely infuriating. It is the primary deficiency of C# to me. And I say this as someone who started my career writing Pascal, and maintain a fondness for it.

It is barely tolerable if you set your editor to use color syntax, but not otherwise.

1

u/Kadabrium 22d ago

Im taking TS and D, thank amen you

22

u/amazing_rando 23d ago edited 23d ago

Shared and smart pointers with reference counting and automatic freeing have been in the C++ standard library for 15 years now and should give you all the automatic memory management you need. Modern C++ does not require precise memory management, manual allocation and deallocation, or raw pointers. You need to be aware of your objects' lifecycles but this is also true in garbage collected languages, it mostly just changes the way it breaks if you 're wrong.

9

u/pareidoliaa1 23d ago

Was about to say isnt the answer to this question just Modern Cpp

31

u/burlingk 23d ago

Java is a contender. Go and Rust are not as syntactically similar.

21

u/GreenFox1505 23d ago

Rust isn't garbage collected.

4

u/FruitdealerF 23d ago

OP seems more interested in automatic and safe memory management in which case rust is the perfect answer.

1

u/Responsible-Bar7165 23d ago

Safe rust collects all the garbage it leaves.

14

u/11fdriver 23d ago

Here to go rogue as usual. Dlang for me, hands down.

https://dlang.org/

3

u/SomethingSomewhere14 23d ago

Isn’t this the obvious answer? I thought D’s whole design philosophy started with “C++ but with an optional GC”.

3

u/SnugglyCoderGuy 23d ago

Go. I imagine some would say Rust as well. I use Go professionally and it's easy to get shit done.

3

u/TheSkiGeek 23d ago

Java or C#.

Or C++ and only ever allocate via std::shared_ptr

2

u/gebbles1 23d ago

I maintain a static typed, object-oriented language that's easy to learn, but it's a stack VM based interpreter not a compiler. That said, it's a cool little project and a nice stepping-stone if you're getting into programming and supports a very wide range of features like generics, operator overloading, reflection, aspect-oriented programming, function overloading and much more. It's called Geblang.

2

u/Prestigious-Bet-6534 23d ago

Dlang! You get a modern module system for free too, no more headers or forward declarations.

2

u/gm310509 23d ago

For me I would suggest Java. I came back to C++ after learning Java (I didn't see the point of C++ until I choose to learn Java because prior to that I could do everything it offered C and I could not see the point of all the extra syntax at that time).

As for memory management generally, you typically don't even need to think about it in Java - Java uses a system of references which are pretty much implemented as double pointers (the pointer you have in your code is really just a pointer to a lookup table which has the pointer to the object). The GC can use this fact to move stuff around to close holes in the heap).

In the decades I've been using Java I've never had any problem with it's memory management - and I've loaded up some pretty massive structures into it. To be fair this is the only problem I have had, the Java runtime will allocate a default amount of memory for the heap - usually it is enough, but for the programs I am referring to here, I often had to specify my own maximums.

Some will argue performance - again, this was never an issue for me despite using large in-memory structures where there was quite a bit of allocation and freeing of dynamically created objects.

1

u/Jim-Jones 23d ago

Not C#??

1

u/goldscurvy 23d ago

This is pretty much what java was defined for. The metaprogramming is not nearly as robust or supported. But it is what you are asking for.

Java also has the benefit of being widely supported, having a huge ecosystem, and being incredibly mature.

1

u/NYU_VM 23d ago

Funny enough C++11 had introduced optional GC but no-one adopted and it just phased out

2

u/amazing_rando 23d ago

When people say they want garbage collection what they actually mean is that they want objects that get freed when they go out of scope and don’t leak, for which GC is neither necessary nor sufficient, since defining that scope for your objects ends up being the hard part, and it’s easy to hold references to data you don’t mean to. Java has garbage collection and no manual pointer dereferencing, but Out Of Memory errors and NPEs are still the cause of most of the crashes and bugs a beginner will experience.

1

u/flatfinger 22d ago

What Java adds is a guarantee that a reference to e.g. the 592nd object created during the execution of a program will never, as a consequence of memory reuse or any other reason, become anything other than a reference to the 592nd object created during the execution of that program.

That's a pretty big win.

1

u/amazing_rando 22d ago

That's kind of my point. You don't pick garbage collected languages because you don't care how your memory is managed, you pick them because you do. Their strength isn't that they let you avoid learning about pointers and object lifecycles, which is what a lot of beginners are lead to believe.

1

u/pixel293 23d ago

I would think with C++ and shared/unique pointers you wouldn't need to worry about freeing memory, it just happens. And unless you are doing new/delete in a tight loop the overhead isn't going to be noticeable. But if you want another language, Java would be the closest to C++ syntactically.

1

u/kevinossia 23d ago

Well it’s a good thing C++ doesn’t require super precise memory management, then.

C++ uses reference-counted garbage collection just like Swift or Rust. Try it out. It’s not hard, I promise.

1

u/Comprehensive_Mud803 23d ago

C++ in a trash bag?

1

u/Spleeeee 23d ago

You must be my coworker

1

u/LukaRozman27 23d ago

C is probably the closest, especially since.NET Core 3.1 or newer, but you lose C++ style templates for generics and get a runtime instead of native binaries. The syntax and multi-paradigm support are pretty similar though.

1

u/green_meklar 23d ago

Java is pretty close, isn't it?

1

u/vegan_antitheist 23d ago

You can just use a GC for C++. There's cpp-gc.

1

u/Ok-Pianist9692 23d ago

Honestly, I'd give C# a serious look.

Coming from C++, it feels familiar enough that you won't feel like you're learning programming all over again. You still get OOP, generics, operator overloading, LINQ, reflection and a pretty powerful type system, without worrying about manually managing memory.

The ecosystem is also mature enough to build almost anything.

I'd say C# is probably your best practical starting point. D is interesting if you specifically want something closer to C++ in philosophy.

1

u/ComasArentFun 21d ago

C# is the literal answer to this question

Every bit of the best syntactic sugar and library support you could want, with the backing of a comprehensive GC process

I've not though about low level memory optimisation in over a decade.. just potential runtime memory leaks
Let something dangle, the GC tidies it up

1

u/SpaceAviator1999 20d ago edited 15d ago

What language is most like a garbage collected version of c++?

It sounds like what you're looking for is provided in C++11.

Try to avoid using pointers -- by declaring as many variables as you can on the stack -- and that way you won't really need garbage collection.

But in those times that you need pointers, instead of using the old pointer declarations that will require manual deletion, like this:

MyClass *pointer1 = new MyClass(...);
MyClass *pointer2 = pointer1;
MyClass *pointer3 = pointer2;
MyClass *pointer4 = pointer1;
// Remember to delete pointer1/2/3/4, but ONLY ONCE!
//
// Forgetting to delete it will cause a memory leak,
// and deleting two or more of those pointers will
// cause a double-deletion error!

use std::shared_ptr instead (provided by the #include <memory> header):

std::shared_ptr<MyClass> pointer1 = std::make_shared<MyClass>(...);
// Or you can use:   auto pointer1 = std::make_shared<MyClass>(...);
auto pointer2 = pointer1;
auto pointer3 = pointer2;
auto pointer4 = pointer1;
// No need to delete anything!
//
// The memory gets reclaimed/deleted/collected as soon
// as the last std::shared_ptr goes out of scope!
//
// And you can still use these pointers just like traditional
// pointers with ->f(), as like:  pointer4->method()

So you see, replacing the old MyClass *ptr = new MyClass(...) declarations with the C++11 auto ptr = std::make_shared<MyClass>(...) declarations will automatically get your memory garbage-collected for you, even when you create another shared pointer and set it equal to an earlier shared pointer!

1

u/SpaceAviator1999 20d ago edited 20d ago

To summarize, the memory pointed to by old traditional MyClass *ptr variables are not garbage collected, but the memory pointed to by the new C++11 std::shared_ptr<MyClass> variables are garbage collected.

Not all memory should be deleted, so for that, use a traditional *ptr variable to point to it. Then it won't be garbage collected.

But most allocated memory (created by new) should eventually be deleted, so use a C++11 std::shared_ptr variable to hold it. Then it will be garbage collected.

EDIT: But if you don't need pointers to begin with, you can just use a normal object on the stack, and use references to that object. But references can't outlive their scope, so if you absolutely need memory to outlive its scope, consider using a std::shared_ptr to hold the memory, and the memory will eventually be automatically garbage-collected.

0

u/BranchLatter4294 23d ago

Rust, C#, etc.

4

u/ralphpotato 23d ago

Rust isn’t garbage collected. It uses RAII like C++.