Search Unity

C++ < C#

Discussion in 'General Discussion' started by kingcharizard, Aug 27, 2012.

  1. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    Sorry - not a student - been doing this professionally for 25 years, every day on a team of professional developers that I now manage. You always catch exceptions in "real life". It is a rookie mistake to let them propagate up to where you cannot handle them or don't have the information you need to record what went wrong.

    C++ is a good language, don't get me wrong. But it's way easier to make mistakes, and mistakes cost lots of money.
     
  2. fano_linux

    fano_linux

    Joined:
    Jan 1, 2012
    Posts:
    909

    Well then like i hate from the bottom of my heart the fu*** objective C, i would prefer to use C# not cause i love it, but it's cause i have allot of code in C# to use at a IOS project with mono. So yes i can use my familiar language in this case hahahaha... S*** endless conversation someone love F# other like Objective C (btw again, i hate it) but i've never said in my life C# or C++ or other language is better than Objective C... Pointless discussion (i mean the discussion about witch programming language is better, it's the same as the witch S.O. is better)

    Regards
     
  3. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    How can you use it in 'this case' given that you don't know what this case is?
     
  4. fano_linux

    fano_linux

    Joined:
    Jan 1, 2012
    Posts:
    909
    In a IOS case, i've said that:

    "cause i have allot of code in C# to use at a IOS project with mono.".....

    Was talking about IOS project particular case.
     
  5. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    Don't need one, the destructor ~ClassName (similar to C#) is called as soon as the variable goes out of scope. Or if created on the heap using a standard smart pointer, as soon as the smart pointer container goes out of scope and calls delete.

    The using statement is for the Danger class that is only required within lifetime of the constructor blocks.
    The manual cleaning up is because C# doesnt do this for me in a deterministic manner (or ever if the Something class contains a unit of execution (thread) running in it.

    That is the thing... I didn't need to. The Danger class was instantiated on the stack and the Something class instance (on the heap) was protected within a smart pointer (on the stack)

    I am not handling the exception.. I am just cleaning up the memory. I expect somewhere further up to actually do the handling as the exception propagates. In this case, lets imagine that Danger threw an exception because a file was not found... What should I do? Create a file and just guess at the data it should contain within this context? No... Let it propagate further up so perhaps I can then create a msgbox within the GUI to alert the user of the exception (using the Message property or the exception type).

    Does this perhaps give a good example of all the effort I have to go through to simply clean up memory rather than focusing on actually handling the issue?

    I prefered C# to objective C, but now Apple has deprecated the garbage collector in favour of reference counting It is actually very usable for the software I develop. Perhaps one day C# will follow suit.

    No you don't, in the local context you rarely have a way to fix the problem. And if you can't fix the problem, you will just have to throw another exception anyway. And this is where you would start to lose information about the exception.

    If dealing with the same high level problems as C# (i.e using premade libraries and integrating code rather than very low level development) then I simply have never come across where I or any other developer I know has made a mistake specifically from using C++ as opposed to any other language. Even from the very beginning of my career. It was also a very easy transition to C++ from Ada which was renowned for preventing mistakes.
     
    Last edited: Sep 11, 2012
  6. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    Not true. You can rethrow if it's not possible, or pass the existing exception up as an inner exception. Perhaps "always" is too strong. But it's true in the vast majority of cases - can't connect to a DB? Catch it, record it, try again, change timeouts - you can do whatever is needed right there at the source. letting it throw all the way up the call chain usually leaves you without options.

    Our c++ code (yes, we have both) would error more often (most of it has since been rewritten), and when it did, was significantly harder to debug. And it was all written by people who think like you - that their code does not have problems.
     
    Last edited: Sep 11, 2012
  7. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    Code has problems, but because of a specific language is dubious at best. I have seen a lot of bugs caused by garbage collectors and non deterministic destruction however. Like constantly trying to open a file that has been locked by a previous instance and the GC hasn't finalized and released it yet. (i.e because of the issue my code snippets demonstrate above)

    In particular can you think of a specific C++ language construct that was causing extra errors? And suggesting a feature in C++ that doesn't exist in C# does not constitute an answer (such as pointers) because you can just as easily use references in C++.

    C++ also has better tools for when you do need to debug such as "memory checkers" like valgrind that C# lacks even though they would be very useful for finding resource leaks (like open files, socket descriptors and threads).

    This sounds like a software house that is unprepared for C++ development. Kinda like blaming SVN for being harder because you have only used the Unity Asset server. Or blaming the Unity Asset server for being harder because you have only been using SVN.

    Language jumping does create these sort of issues so in the perfect world we would all be using C++ all the time.
    Luckily we have C++.NET (and auto_handle<T>) as a compromise for when C# can't do the job well. ;)


    Edit: Reading through my post, it may sound like I am attacking developers or companies that get value from C# but I am not! Really I am attacking these recurring excuses which are the main reasons why Unity (or many indie development tools) are not supporting native C++.
     
    Last edited: Sep 11, 2012
  8. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    I think we're just going to need to disagree. You obviously don't like C#, and you're incorrect about some of it (C# does have pointers), but it really is easier to debug and easier to develop in - I still like C++, but once you "drink the koolaid" and go to C#, you'd probably like it too. Because it's easier, and you can do nearly everything. But my job isn't to convince you - I'm just trying to tell you my experience - take it or leave it. I can't tell you how much C++ code i've written, but it's A LOT. Same with C#. But if I needed to program something, I would choose C# if possible, and C++ if not. The 2,000 developers where I work are not "unprepared for working in c++". Many of us started in C a long time ago, and came up the ranks.

    http://msdn.microsoft.com/en-us/library/y31yhkeb(v=vs.80).aspx

    Of course it has memory profilers. Ants, and Memprofiler come to mind. And yes, I've used C++ tools like this as well. But you're missing the big picture.

    I'm going to assume you just don't know how cool it is to debug in C#. Here's what you do:


    Customer: My Program is locked up!
    You:
    Take a minidump of the process on their machine, copy it to yours.
    Load the minidump into Visual Studio. Load your project.

    At this point, it's like you're in the debugger - look at the values of all the variables, as if you were in the debugger.
    Look at the exact code.
    Step backward through the program, see what everything passed - as if you were in the debugger.
    Find the exact thing that didn't work, the exact data that was wrong.

    Total time - 20 minutes. Almost all of which is transferring the minidump.

    So, this is my final post on this. But please don't give out misinformation to make your point.
     
    Last edited: Sep 11, 2012
  9. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    C# supporting pointers? Hah! I can only assume you mean when using the /unsafe flag?
    Perhaps read that URL you linked to and you will realize that it only supports a certain few types and is in no way C# actually supporting "pointers". Again, it is as similar to pointers as C# is to actual C. Just a big Microsoft marketing ploy, barely part of the standard and is not how people use C#. Wouldn't like to see the code of any Unity game using this. Obviously the web player won't even allow this so removes it's usefulness for a large number of indie / hobby developers. Very weak argument to me being "incorrect about some of it".

    As for C#, I don't have a dislike for it. I just recognize some of it's failures. These aren't weaknesses... they are outright failures. I have a fine grasp on the language, afterall it is the current "in thing". Just as Visual Basic was back in the day before it completely died once Microsoft dropped it and decided to emulate it in .NET instead. I remember arguing the exact same things back then too but obviously the devs jumped straight onto the next gimmick language rather than tried and tested ones such as C and C++.

    So with the .NET performance profiler and memory profiler you suggested, why is it still harder to debug / analyze C++ with VTune and Valgrind? You are effectively doing the exact same thing as C#. Makes no sense.

    For your 20 minute minidump... As a past C/C++ developer, surely you must have come across the "coredump"? It does the exact same thing and can be used in the exact same way. Not only this but if you are using native code with C# your tool will stop where .NET ends... Not if you are using native code throughout. So long as your library has debugging symbols you get much more flexibility with debugging. This is more a platform thing than language though. C++.NET would have the same restrictions. Just so happens no-one has bothered to make a native C# compiler.

    We can disagree for now, but I guess this discussion will surface again once C# is a distant memory and C++ is still "uncool".
     
    Last edited: Sep 11, 2012
  10. Jaimi

    Jaimi

    Joined:
    Jan 10, 2009
    Posts:
    6,208
    Ok, I lied. this is my last post in this thread. :) The minidump (and intellitrace) is lightyears ahead of a core dump. Seriously, read up on it. You're missing out.
     
    Last edited: Sep 11, 2012
  11. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    Great... except that that was already considered and was deemed insufficient reason to stick with C#. Just knowing/guessing which platform your code is going to be deployed on is but one small consideration.


    Same for C#.


    Could you provide an example of what you're trying to demonstrate?

    Again, how does this differ from C#?

    You should either let it die... or you should handle it and return an error value [not an exception].

    Nope, because as far as I can tell, your C# code doesn't make any sense. AFAIK this is the appropriate C# version:

    Code (csharp):
    1.  
    2. struct Test
    3. {
    4.   // Something contains a thread or socket descriptor so must be cleaned up.
    5.   Something something;
    6.  
    7.   Test()
    8.   {
    9.        something = new Something()
    10.         using (var danger = something.GetDangerous());) {} // throws exception
    11.   }
    12. };
    13.  
    If I've missed some key point, please elaborate further.
     
    Last edited: Sep 12, 2012
  12. keithsoulasa

    keithsoulasa

    Joined:
    Feb 15, 2012
    Posts:
    2,126
    Too bad I lack the skill to get anything done in C++ ...
     
  13. Dabeh

    Dabeh

    Joined:
    Oct 26, 2011
    Posts:
    1,614
    This seems to become rather personal, although it seems now that it's more about not wanting to be wrong, rather than proving which is right.

    Obviously C# and C++ are both good in their own way, why can't we agree on this and stop arguing?

    Why you like C# and not C+=
    Why you like C++ and not C#
    Not why C# is bad or C++ is bad. Obviously neither of them are bad.
     
  14. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    Err what?

    k.pedersen has made some very specific claims, claims that can be tested. I'm trying to gain an understanding of what the claim actually is so I can evaluate its validity and value.


    Because argument [and discussion] is a good thing?

    I've never understood the argument that just because there's a possibility for disagreement one shouldn't bother to try to discuss, argue and learn about crucial topics in their profession? What, is programming anti-science?
     
  15. holyjewsus

    holyjewsus

    Joined:
    Mar 7, 2011
    Posts:
    624
    well I'm learning a bunch, please continue discussing! :)
     
  16. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    npsf3000,

    In C#, the finalizer ~ClassName is not called as soon as the variable goes out of scope. It gets called only when the garbage collector runs a pass. So unless you run GC.Collect() every game loop, this data will not be cleaned up in a determinate manner.

    Now, if a constructor fails, the finalizer is never run either so you can't rely on being able to call Dispose() at any other time than just before the exception propagates.

    It gets worse! If the Something class is running a thread or another critical resource such as a socket, then the GC will *never* call it's finalizer and the developer will have a memory/resource leak. You need to dispose it some other way. Once you get to the point where the finalizer is meant to do this job, it is too late to clear it manually (unless a very messy system of static instances is used as a typical hack to get round this limitation).

    Your implementation of the code has demonstrated the issue well, for example you create a new instance of something

    Code (csharp):
    1.  
    2. something = new Something()
    3.  
    But then an exception is thrown immediately after during
    Code (csharp):
    1.  
    2. using (var danger = something.GetDangerous());) {} // throws exception
    3.  
    Which means that nothing has called Dispose on the something instance and you have a memory leak..

    This is a well documented issue (i.e described in a blog like this: http://swiftcoder.wordpress.com/2009/02/18/raii-why-is-it-unique-to-c/)

    I have attempted to get round this in my solution in this bit by cleaning up and rethrowing the exception:

    Code (csharp):
    1.  
    2. ...
    3. catch(Exception)
    4. {
    5.   Cleanup();
    6.   throw;
    7. }
    8. ...
    9.  
    But this is going to need to be adopted for *every* class in the application which might contain a class which might contain (after N number of aggregate or composite children) the critical thread or any other limited memory containing class.

    Basically, in games where memory does matter, C# simply is the wrong tool for the job.
    It's suggested ease does not outweigh its failure to dispose memory in a correct manner.

    This isnt an argument it is a discussion (The internet is not a good media for arguments anyway). I feel it really should be a discussion only for people who have experience in both C# and C++, otherwise no value is being brought to the table.

    npsf3000 and I have experience with both languages and that is why this discussion is useful. What I am trying to get out of it is perhaps a solution where I can be guarenteed to have a cleanup call on every class if an exception is thrown at *any* point within my software. (Because in C++ this is possible). This is seriously where a language fails to be suitable for anything other than hobby/indie games development if it is lacking in this area.
     
    Last edited: Sep 12, 2012
  17. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    @k.pedersen

    If the C++ version works as you've advertised, then I can see how it uses less code to be safer.

    That said, as someone currently working to develop a socket server, so what?

    The tools are available in C# to build a safe sockets - we have try/catch/finally, IDisposable, and using. The code required is fairly simple:

    Code (csharp):
    1.  
    2. class Test : IDisposable
    3. {
    4.   Something something;
    5.  
    6.   Test()
    7.   {
    8.        something = new Something();
    9.        
    10.        try
    11.        {
    12.             something.Get(); // throws exception
    13.        }
    14.        catch
    15.        {
    16.              Dispose();
    17.              throw;
    18.        }
    19.   }
    20.  
    21.   public void Dispose()
    22.   {
    23.        if (something != null) something.Dispose();
    24.   }
    25. };
    26.  
    How is that showbreakingly complicated? This isn't code that one uses on a regular basis - you write it, test it and forget it. Particularly in a game engine - you've got a namespace for file IO, and a namespace for networking - pretty basic stuff

    Lastly, you can reduce this even further with a little thought, here's a 5 min framework:

    Code (csharp):
    1.  
    2.  class Test : SafetyFramework
    3.  {
    4.       FileStream fs;
    5.      public Test()
    6.      {
    7.          Safe(() => fs = new FileStream("ErrorOut", FileMode.Open));
    8.      }
    9.  
    10.      public override void Dispose()
    11.      {
    12.          Console.WriteLine("Disposing FS");
    13.          if (fs != null) fs.Dispose();
    14.      }
    15.  };
    http://pastebin.com/pKyymPzp

    In fact, I'm starting to wonder if this a language issue at all - or a slightly simpler API that you happen to use. There's nothing preventing our 'dangerous' objects to clean up after themselves - and writing a library that does this for commonly used classes is fairly trivial, if boring. Alternatively someone could be a little bold and use reflection to do this at run-time.

    I should clarify that I've got next to no experience in C++, but am willing to learn and have plenty of experience in C#. I've also dabbled in ~dozen other languages.
     
    Last edited: Sep 12, 2012
  18. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    This sums up exactly what I expect from the language. And exactly the reason I am willing to try to explain why C++ is superior for games development.

    Your safety framework isn't a bad solution. Heck it is the first one I have ever seen that attempts to adress the issue elegantly. However, this will only work if every class (in every C# library you use) adopts the same pattern. Whereas in C++, this is not an API but a core language construct that will flag up errors in lint or other analysis tools if not done.

    The following link demonstrates how Microsoft suggests tackling the issue (and how it is commonly done in C# projects and games where most things are disposable resources (like images or handles to vertices on graphics card). You can however ignore the lines specifically to unmanaged resource.
    http://msdn.microsoft.com/en-us/library/fs2xkftw.aspx

    This is not good. And in C++ can be done in less lines than the Main() function itself.

    For that one single "something" variable, it is considerably more complex than the C++ version. And with many variables (as commonly required) it will only get worse. It doesn't feel entirely scalable, especially for large teams of developers who don't have an easy way of finding out what needs explicit disposal.
    This code is used on a regular basis, because not only will you need to propagate the Dispose() down to any contained classes that need to be disposed correctly, but things like Images or certainly meshes need to be disposed as soon as possible if your game is of sufficient size and/or on a mobile device as Unity advertises.

    This may sound condescending but it isnt meant to be. If possible, for a future project or research tech demo, give C++ a shot. (I know this is not always possible (afterall Unity forces .NET down our throats)). Especially if you are willing to learn, already having C# (and more) knowledge obviously puts you in a very good position because C++ isn't any harder.
    Or perhaps have a quick play with the C++.NET msclr::auto_handle<T> class if you do want to stick with .NET.
    http://msdn.microsoft.com/en-us/library/ms177066.aspx

    Out of interest, have your other languages all used a garbage collector? If not, perhaps we can find a better comparison.
    Ada and CPython both handle memory in the same way as C++. (Which is why Ada can be used for nuclear bombs and CPython (stackless modifications) can be used in Eve online.
     
    Last edited: Sep 12, 2012
  19. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    I guess I still don't see the issue. Sure, it's a nice feature of C++ and having a C# version would be nice... but what's the impact? At the end of the day all it can do is make your code safer, develop faster etc... but if your code is by and large safe regardless, and developed fast... where's the benefit?

    I can see how it's beautiful in theory, but I don't see the practical benefits over what already exists.

    Futhermore, most of your arguments for it are, from a C# POV, very poor. For example you claim:

    "things like Images or certainly meshes need to be disposed as soon as possible if your game is of sufficient size and/or on a mobile device as Unity advertises."

    Err what? Come again?

    Things need to be disposed of... when they need disposing of. The idea that they must be deleted as fast as humanly possible is flawed - sometimes it's smarter to *not* delete the data this very second!

    I think the issue here is how you're approaching the code, not a language problem. Don't worry too much about when data is deleted - just make sure the you call Dispose at the appropriate times. Don't have huge complicated hierarchies of classes linking to each other's dispose - encapsulate it in nice wrappers. The class that gets data from a IO stream doesn't need to know or care about the implementation details of that IO stream.


    As I said earlier, C++ is, and has been for a while now on my 'like to know list'... problem is its never made it very high up. Even now, when I'm here discussing the various merit's there's nothing that jumps out at me as particularly useful to me, or something worth investigating. When I do have a spare moment I find studying functional programming much more stimulating.

    That said, I may be picking up Objective C in the next month - which'll be somewhat closer even if a bit odd.

    Technically brainfuck doesn't... other than that no.
     
    Last edited: Sep 12, 2012
  20. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    "Garbage collection [in Objective-C] is deprecated in OS X Mountain Lion v10.8, and will be removed in a future version of OS X. Automatic Reference Counting is the recommended replacement technology."

    http://developer.apple.com/library/...sitioningToARC/Introduction/Introduction.html

    Yes, objective-c will be quite a cool one to use as a comparison. A few of the C++ smart pointers (such as std::tr1::shared_ptr<T> work by reference counting).

    Good luck learning it, it certainly looks weird but it seems very powerful on Apple platforms.

    Heh, Objective-C doesn't look quite this weird ;)
     
  21. jedy

    jedy

    Joined:
    Aug 1, 2010
    Posts:
    579
    C++ is HUGE - you can do anything you could think of with it ( yes unicorns ). There is a massive amount of code available online for it. You can inline assembler code in the files. You have the ultimate freedom to mess everything or make it extremely fast. Generally - if you want speed - this is one of the best tools to achieve it.

    C# has remarkable capabilities - you could do most of the stuff you could/would in C++, you can even use references and skip the GC entirely. But yet, there is this thing to it - it's efficient ( multiplied by a hundred in combination with Unity ). You can write a lot less code and complete the tasks of the same complexity. It's slower - yes, there is not possible way it goes any faster than well written C++ code, but yet you write 3 times less code.

    My final choice is C# - C++ has great capabilities ( which you can use via native code libraries in unity ) but C# gives me the faster development cycle ( which means more work done, more money, more games, more fun etc ).
     
  22. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    Huh? In C# we use references anyway. However the memory they "reference" needs to be freed by the GC.

    Would it be possible to get a quick C# code example of what you mean?

    As for the speed, I may appear to be a C++ obsessive but this is not an area that bothers me about C# because at the end of the day, with Unity, the native engine code does the intensive stuff anyway. I also assume it is heavily optimized and much faster than any C# or C++ we could produce in our projects timeframe.

    For code size... as demonstrated in the code examples previously in the thread, C++ is actually *much* less verbose than the C# alternative. (yes probably because C# is not appropriate for manual memory management.)

    If C# is faster for your projects, then that is cool. However this isn't the case for everyone (Contrary to popular belief or Microsoft's previous marketing)
     
    Last edited: Sep 13, 2012
  23. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    This conversation reminds me of when C++ began replacing C, and everyone said that C++ was way too slow for serious developers, and that C would still be used for everything important, and C++ was mostly only ok for hobbyists where performance didn't matter. It sort of also reminds me of when C started becoming popular, and everyone said that C was way too slow for serious developers, and that assembly would still be used for everything important, and C was mostly only ok for hobbyists where performance didn't matter.

    Twenty years from now, when C%#^ is replacing C*, people will be talking about how C%#^ is way too slow for serious developers, asserting that C* will still be used for everything important, and claiming that C%#^ is mostly just for hobbyists where performance doesn't matter.
     
  24. jedy

    jedy

    Joined:
    Aug 1, 2010
    Posts:
    579
    Yeah - C# has managed references, C++ has references. Yet thanks for the clarification.
     
  25. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    If you're going for "short" you could do this:
    Code (csharp):
    1.  
    2. public class Test
    3. {
    4.   // Something contains a thread or socket descriptor so must be cleaned up.
    5.   Something something;
    6.      
    7.   public Test()
    8.   {
    9.      something = new Something();
    10.      using(Danger danger = new Danger(something)) {}  // throws exception    
    11.   }
    12.  
    13.   private void Dispose()
    14.   {
    15.     if(something != null){something.Dispose();}
    16.   }
    17.  
    18.   ~Test()
    19.   {
    20.     Dispose();
    21.   }
    22. }
    23.  
    I also think it's a little cheesy to cheer on C++'s memory management by using auto_ptr, something that was invented by C++ programmers who got sick of how annoying memory management was in C++ and wanted to make something a little closer to garbage collection. ;) I think your C++ example is the one place where auto_ptr shines, but using auto_ptr's everywhere will become a nightmare if people start referencing the same objects. That's what reference-counted garbage collection was created to solve. I would much rather have a language that makes it easier to manage hundreds of objects with circular references all pointing to each other than one that makes it a few lines shorter to write exception-safe constructors for unmanaged resource wrappers.
     
    Last edited: Sep 14, 2012
  26. keithsoulasa

    keithsoulasa

    Joined:
    Feb 15, 2012
    Posts:
    2,126
    Belive it or not the CEO at my last game company was saying C++ is too slow , as in he stuck with C .
     
  27. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    At least in my experience this is a *bad* assumption to make with Unity - a lot of things are implemented in a 'poor' fashion. So while it is faster than writing your own engine, always remember that various key elements can be rewritten to increase performance if needed. Classic example is GUI.
     
  28. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Yeah I've met a few people like that too! And one particularly old dev who was still convinced that he had to write half his code in assembly in order to make sure it was performant. And then there are all the people who use C++ but not the std library because they're convinced that they need to write all their memory management manually to stop it from being too slow. I knew a game dev team that spent a year trying to write their own version of the STL and Boost because some ancient graybearded programmer had convinced them that the real ones were too slow. Needless to say, they went out of business and never finished their game. ;)
     
  29. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    eventually i'll go back n read this entire thread but i haven't felt like it... i cant believe this thread is still going on...
     
  30. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    makeshiftwings,

    The shorter code listing is still larger and more complex than the C++ alternative.

    It also isn't exception safe because nothing is going to be cleaning up the
    Code (csharp):
    1.  
    2. something = new Something()
    3.  
    once the exception is thrown from the line below. (The GC will after an unspecified time, but for a few patterns and memory intensive processes (i.e Games) this is unacceptable.)

    Also... C++ can use a garbage collector http://www.hpl.hp.com/personal/Hans_Boehm/gc/ (This is the same one that Mono (C#) can use internally.). C++ projects generally dont though because garbage collection is not only slow and impractical but also restricts certain code design. Luckily C++ developers have the choice. This is also the reason why Apple is removing garbage collection from ObjectiveC in future versions.

    But no, the C++ spec did not develop smart pointers to be closer to garbage collection. It was developed because the try / catch system is not scalable and exception safe code is important.
    We also have shared_ptr<T> for when the object needs to be shared between multiple things.

    It isn't just the CEO that stuck with C. Look at the mono source code... This isn't C++. It is C. OpenGL is C and DirectX is C (with C++ extensions). C is still around and has outlived a lot of C#/Java type languages which have been marketed in the past and it will continue to do so because it provides awesome functionality.
    What actual fundamental library / technology that is used in the majority of games has been written in C#?

    C++ does offer a true object orientated structure to C. Whereas C# offers... nothing new to C++. But it does take away a *lot* of flexibility.

    Fair enough, although with the GUI I assume the slowdown was because it was doing things in immediate mode rather than storing vertices etc.. in a vertex buffer on the graphics card. I don't know if rewriting the code could be any faster if it still blocks the pipeline between CPU and GPU.
     
    Last edited: Sep 14, 2012
  31. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    You just said exception-safe, not that it needed to dispose itself immediately and avoid GC; if so, then you can call GC.Collect(), or put the extra catch{} in there, but in my experience, most C++ programmers who whine about wanting to put GC.Collect() all over the place because they're convinced that "games have to delete everything NOW NOW NOW" are just paranoid.

    In real life, most of the things you're worried about leaking (file handles, database connections, etc) have corresponding .NET implementations, and you would be using those instead of custom leakable resource wrappers. If you were doing interop you could use SafeHandles. I just think that basing your whole opinion of a language on one corner case (needing to write a few extra lines to handle non-framework, non-interop, resource-leaking exception-throwing constructors that can't wait a few milliseconds for GC) is silly.

    And C# can use unsafe, interop, and suppress GC, so they have that choice too. Also... citing apple as a an example of a good developtment platform? No.

    I've used auto_ptr and shared_ptr, and IMO they are a nightmare compared to a language with built in GC.

    Trick question... there's no library or technology that's used in the majority of games, period. There's no C++ library used in the majority of games either. Games use all kinds of different libraries and technologies.

    I almost spit coffee out. I've gotten WAY more use out of things like LINQ, the .NET library, Entity Framework, Unity (the dependency injector not the game engine), Parallel Tasks, etc than I got out of the StdLib. As far as core language I've found implicit types, dynamic types, garbage collection, etc to be godsends. Also I'm assuming you're talking about actual C++ and not C++/CLI, since otherwise usage of auto_ptr would be even more catastrophic.

    I mean, if you're going to praise the StdLib for letting you write a few less lines of code to make an exception-safe resource leaking constructor, then we should compare lines of code in C++ to do something like:

    Code (csharp):
    1.  
    2. var names = from n in myList.Where(a => a.Foo(1) < a.Bar(2)).OrderBy(a.LastName).Skip(5) select new { First = n.FirstName, Last = n.LastName };
    3. danger(); //throws exception
    4. return names.ToDictionary(n => n.Last);
    5.  
     
    Last edited: Sep 14, 2012
  32. makeshiftwings

    makeshiftwings

    Joined:
    May 28, 2011
    Posts:
    3,350
    Let me also just say I'm not really a religious warfare kind of dev; I don't think C# or any other language is the one language to rule them all. The best language is whatever gets the particular job done as quickly and correctly as possible. Writing a low level graphics driver? You'll probably use C and even some assembly. Writing an n-tiered business enterprise web suite? You're probably better off using C#. Writing an app that's entirely composed of classes with constructors that open custom file handle resource wrappers and immediately throw exceptions afterwards? You may have just found a place where auto_ptr is useful. I just think that people who shortchange C# because "My own memory management code is always better than the garbage collector" are often wrong and haven't really had enough experience with it. Keep in mind that the reason so many modern languages use managed objects is because the best programmers in the industry thought managing their own memory constantly was too error-prone. If the pros can admit that doing things the hard way isn't necessarily always the best way, then we can all admit it.
     
  33. CaptainExtra300

    CaptainExtra300

    Joined:
    Jul 14, 2012
    Posts:
    130
    This comparison is very unfair
    does not make any sense

    is like comparing a ford focus vs a ford f250 diesel pickup truck,

    C# barely been out for a decade, higher level, while C++ has been out for more than 30 years.

    C++ is a very low level programming language, pretty much can do anything you want with it.
    C++ is going nowhere, at least not in our lifetime and probably not even in our kids lifetime aswell.
     
  34. _Petroz

    _Petroz

    Joined:
    May 13, 2010
    Posts:
    730
    Code (csharp):
    1.     var names = from n in myList.Where(a => a.Foo(1) < a.Bar(2)).OrderBy(a.LastName).Skip(5) select new { First = n.FirstName, Last = n.LastName };
    2.     danger(); //throws exception
    3.     return names.ToDictionary(n => n.Last);
    I think the bigger question about this code snippet is what scenario would require that type of operation inside a game client. With this discussion being centered around game development, I have yet to encounter a scenario where this kind of problem wouldn't have been solved better without using LINQ. Often the solution in either C# or C++ would be to have a separate data structure and save yourself the run-time computation altogether. That said I have less experience with C# than C++ and would be interested to know what sort of problems people are solving using LINQ in game development.
     
    Last edited: Sep 15, 2012
  35. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    I use it LINQ, Lambda's and similar all the time.

    Here's a quick example of some code about to be put into production:

    Code (csharp):
    1.  
    2. var point = (from p in SpherePoints(radius)
    3.              where p.y < heightTop  p.y > heightBottom
    4.              where isSphere ? true : p.z > width
    5.              select p).First() + origin.position;
    6.  
    7. GameObject go = (GameObject)Instantiate(prefab, point, Quaternion.identity);
    8.  
    9. ....
    10.  
    11. IEnumerable<Vector3> SpherePoints(float radius)
    12. {
    13.     while (true)
    14.         yield return Random.onUnitSphere * radius;
    15. }
    16.  
    While there are at least half a dozen different ways I could have written this - this version is quick to write, clean easy to read [even relatively weak programmers will quickly understand what's happening even though they don't quite know how], easy to modify so on and so forth.

    Another possible example is:

    Code (csharp):
    1.  
    2. var config = urls.Select(url => new{url, data = DownloadConfig(url)}).First(x => x.data != null);
    3.  
    Goes through a list of url's and returns the first one that works.

    You don't have to use LINQ to make any of these work, but LINQ helps put you in the right mindset - and in my experience results in less buggy code.

    I'm sorry for quoting you twice but...

    'Inside a game client'.

    1. How about external tools?
    2. How about external services?

    I've been speccing out the costs of various projects, both real and imagined, both game and 'non-game'... often the external services make up the bulk of the code cost. Sure I'm biased towards said projects, but there is a misunderstanding on the relative importance of the game client.

    Outside of unity LINQ becomes even more powerful as you now have access to:

    • Newer .NET
    • 64bit
    • Multi-Cores.
    • Other resources - e.g. DB drivers
    • Less GC considerations
     
    Last edited: Sep 15, 2012
  36. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    LINQ is "THE" reason i love C#, i develop LOB apps for a living and at first a few years back i thought "this will be very good for this and this scenario" , well no, actually it's good for everything and really grows on you, "over" (literally) half the code i type each year is LINQ, and most of my methods now start with "return" followed by some LINQ.
    I expect it to be the same within unity as i dig deeper in it (for now just prototyping and fooling around), with game state being so data centric i actually expect to have more than half my code in LINQ in unity.
     
  37. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    Linq++ or clinq.
    Not to mention Microsoft/Mono Linq can be used in C++.NET.

    Linq came from Microsoft's .NET framework rather than the C# language itself.

    With Microsoft's new focus on C++/CX and Javascript, I dont think the same can be said for C#.
     
  38. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    I was just answering your question about use cases for LINQ, not comparing with other languages.
    However only the methods for LINQ are part of the API , the query syntax is language specific and does not map 1:1 to the method syntax. Also language support is a key feature for LINQ as the operators aren't naive iterations and are heavily dependent on auto generated enumerable state machines (LINQ effiency comes from it working as a composable pipeline, streaming elements one at a time throught the pipeline without creating copies / temp collections and never processing more than is required)
    I'm pretty clueless anout c++'s latest new version . I know it added supprt for lambdas but unless it also supports automatic enumerable class generation it must be hell to create, unless it also supports anonymous types it's also goong to be pretty useless for anything non trivial in linq

    So while specific LINQ variants ( to object / sql / whatever) are APIs and LINQ operators are the standard operator sets expected on each LINQ API, LINQ is really only usefull thanks to the actual language features that support it ( pretty much every feature added in C#3 is there to support LINQ)

    Sorry for the typos. Answering from iphone, will edit in 10min
    edit : fixed the typos
     
    Last edited: Sep 16, 2012
  39. _Petroz

    _Petroz

    Joined:
    May 13, 2010
    Posts:
    730
    Well C# is quite common in tools, and external services could be written in anything really. I'm not going to debate those points because it is a proven technology in those applications. What makes game development different is the performance requirements. I'm sure LINQ is a useful feature, but it seems to always be trade-off, sacrificing performance for simplicity. Normally I would favor simple code but for the situations LINQ is applicable it seems to be likely performance hot spots, traversing data structures.
     
  40. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    But that's a huge common missconception, LINQ is not a performance tradeoff really. In most real cases your code will be (much) faster when s itched to linq unless you carefully hand tuned it into something barely maintainable because as i said it's streaming . And only streaming the required amount
     
  41. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    So now we have C# as a proven tool for game dev. That gives it a pretty big headstart because if you can use it in the client you have one nice big unified experience.

    I like to use it like this:

    1) Use it anywhere it keeps my code simpler.
    2) If there's a problem, rewrite it [generally easy].

    Even when I do discover than LINQ is hideously expensive - it's so cheap to use that all I've done is prototype the functionality I want before spending substantially longer building an optimized version.

    Game's aren't as different as people think - only a subset of games actually even have to worry about performance, and only a subset of their code actually has any issues. Not all games are Crysis [which, btw, wasn't exactly stellar code] :p

    Seriously, so what?

    If I have to drop C# in favor of something better in 3-5 years... I'm fine with that. The idea that one would stick with C++ just because its 'been around' and will continue to 'be around' isn't particularly enlightening - particularly in the Tech Field.
     
    Last edited: Sep 16, 2012
  42. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    But LINQ ISN'T expensive at all, quite the reverse if used properly, it's slower than the best you can do for sure, but you're not doing the best everywhere, only on very very few tiny loops where unmaintainability for perf tradeoff might be good.
    LINQ is simpler AND faster (no tradeoff) than common things you can do with linq are actually usually done without it, and a LOT more maintainable / concise too.
     
  43. _Petroz

    _Petroz

    Joined:
    May 13, 2010
    Posts:
    730
    The point I was making regarding perfomance and LINQ was not that those loops should be hand coded. I am in complete agreement that I would favor the simplicity of LINQ if I was going to do any pseudo-database query type task. It's just those kinds of tasks themselves should be optimized out at a higher level in a high performance application. If you are going to need a subset of data every frame, it is faster to just cache that subset in it's own data structure rather than do any loops full data set.

    The language does not really impact the experience from the user's point of view. There is often a variety of technologies used for tools, asset pipeline, servers, etc. By this definition PHP is also a proven technology in 'game development', it would be a long bow to draw to say it would be a viable language for full scale game development.

    I couldn't agree more. The high level scripting component of games can be done in a number of languages such as LUA, UScript, C#, JavaScript. The crux of this debate has been whether C# is viable for the core systems and I haven't seen anything yet to convince me of that.
     
  44. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    Wether you query it with LINQ or not has nothing to do with the ability to cache it, query it with LINQ and cache the materialized result if it's cacheable (static) data, it'll still perform better and with a lower memory footprint than most code people write, and to beat that you'd have to write some hard to maintain code as the code that is generated when using linq to objects is very very very far from what people usually expect when they see a LINQ query

    edit : i'm not sure where the quote went wrong so removing it due to high uglyness, just immagine i quoted the first paragraph from you in the previous post
     
  45. npsf3000

    npsf3000

    Joined:
    Sep 19, 2010
    Posts:
    3,830
    Actually, as much as I hate to say it I'm pretty sure PHP is a proven technology in game development.

    You misunderstand - if you're web-server is in C#, your game-server is in C#, your tools are in C#, and your client is in C# - you gain huge efficiencies in dev-time.

    Ahh, the core systems.

    Core systems have been written in C#, and they work. Generally core system's are done in C++ because a well implemented C++ version should be faster... but U3D do appear to be working very hard to demonstrate the exact opposite :( At the end of the day C++ is a good Lowest Common Denominator language for 'core' systems. Most people can't be bothered writing their own physics engine, they'd rather buy Physx or similar off the shelf. Physx's customers tend to use C++... so writing it's implementation in C# wouldn't be very useful.

    For example, with some C# physics engines I've mucked around in you can have multi-threading, implement your own primitive shapes, put in callbacks to control collision behavior etc. Oh and you can use the exact same engine in Unity, or your .Net server [e.g. photon]. Not bad considering the amount of man-hours in the engine is probably orders of magnitude less than Physx.

    Example game: http://christophermpark.blogspot.com.au/2009/06/optimizing-30000-ships-in-realtime-in-c.html
     
    Last edited: Sep 16, 2012
  46. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    ok This is kinda on topic where can I go to look at others source code n study C++? I want to see how other people accomplish some things n study n figure out if there is other ways to accomplish what they did.. basically i need C++ code to look at is there such a site for this?
     
  47. ronan-thibaudau

    ronan-thibaudau

    Joined:
    Jun 29, 2012
    Posts:
    1,722
    I don't see how this would be on topic at all, but if you're curious about C++ code in the gaming department you could have a look at the ogre engine which is open source and in C++ (real time rendering engine)
     
  48. _Petroz

    _Petroz

    Joined:
    May 13, 2010
    Posts:
    730
    This guy is the OP, he decides what is on topic. :p

    You could take a look at the source code for Quake. https://github.com/id-Software/Quake-III-Arena

    They include cool tricks like this: http://blog.quenta.org/2012/09/0x5f3759df.html

    Jumping into source code for an entire project like that can be pretty difficult even if for someone familiar with the language. I have done feature integration with foreign engines and it can be a daunting task. I would consider it a baptism by fire, but you can learn a lot.
     
  49. kingcharizard

    kingcharizard

    Joined:
    Jun 30, 2011
    Posts:
    1,137
    Thanks..

    @ronan.thibaudau
    I'm looking at Irrlicht source right now just want more variety
     
  50. k-pedersen

    k-pedersen

    Joined:
    Sep 11, 2012
    Posts:
    30
    Yes, looking at Irrlicht is a good idea. This is an excellent engine and is very much suited to games out of the box (whereas Ogre3D does require a lot more initial boilerplate code to get started)

    Just because C++ can interface directly with low level stuff like native OpenGL. I wouldn't recommend it for a beginner (afterall, not many people would use an OpenGL C# binding directly so why would you just because using C++?).
    As for looking at the Quake source code... Just don't. Even Carmack has admitted it is less than ideal code to learn from. The code predates proper object orientation and was also written before C#/Java was but a twinkle in Microsoft / Sun marketing's eye. It would also be about as useful as reading through the implementation of XNA etc...

    For 2D stuff, there is an excellent SDL tutorial at (http://lazyfoo.net/SDL_tutorials/index.php). Which is about on par as if you were writing a game using C# and System.Windows.Forms.

    (Don't forget, you can also use C++.NET for Unity games if you want to take advantage of an easy to use engine)

    Don't know if this would help, but Quake II has been ported to C++.NET (http://www.vertigosoftware.com/quake2.htm). This might suggest that the code has been modernized.
     
    Last edited: Sep 16, 2012