Dark Bit Factory & Gravity
PROGRAMMING => C / C++ /C# => Topic started by: James_wright_1990 on February 17, 2010
-
hi
i am currently writing a program in c++ and i am using classes. in c# classes are always on the heap and created like:
class blah = new blah()
but in c++ i know i can use:
class blah;
or
class *blah = new blah();
delete blah;
although our lecturers have given an overview of how each works we have not been given many examples situations where each is approptriet and i was wondering if anyone could clear this up for me.
james
-
Not much. The C++ compiler is allowed to put these objects wherever it likes, the standard says nothing about stack and heap. An OS doesn't need to provide either and C++ can still be implemented on that OS.
For the sake of argument on a modern OS like Windows you have unlimited heap and stack. On an embedded system, like a PSP for instance, you might only have 4Kb of stack, but 20Mb of heap to play with. In this case you want to use the heap for everything.
Jim
-
ah ok fair enough so it comes down to choice unless resorces are scarce in which case heep is better cheers for clearing that up.
james
-
Given that the C++ standard doesn't mention stack or heap, I'm surprised your lecturers mention them. They are wrong if they are saying C++ compilers, in general, behave in that way. Also, for instance the C++ standard doesn't mention a screen, a keyboard, or even the necessity for a persistent file system.
The C and C++ standards aren't free, they cost about USD20 each. But the drafts are online, e.g.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n3000.pdf (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n3000.pdf)
It's seriously worth reading the ISO C99 standard and the ISO C++ standard, they are incredibly turgid but once you have read them you will understand a lot of the motivations and reasonings behind the language. C99 is pretty short and good 'on the bog' reading that should only take a month-worth of visits.
Jim
-
Ah fair enough so the difference is whether the object is stored automatically or dynamicaly and not where it is stored so if i use:
class blah;the destructor will be called when the block of code i delcared my istance of the class ends but if i use:
class *blah = new blah();the destructor is called when i use the line:
delete blah;
is that right?
-
20 bucks for C, cheaper than beer :) but what about beer-spilled c-specs? 8$ maybe?, well they'll be all over beer after 10 yaers anyway, so u could aim for that directly and save money
Yes James_wright_1990 you are correct
if u malloc space, just hold the ptr and you'll be fine
in demos u might like to write 2 versions of the effect-system one with the statically allocated memory and one with dynamic, I usually use #ifdefs to change which one I want to use