Off Topic > Off Topic
Programming Megathread
Ipquarx:
Keep in mind that by using new, you're also making your class instance a heap variable instead of a stack variable. This is slow because it takes extra time to allocate the memory on the heap. Always use stack variables when you can.
Meldaril:
--- Quote from: Ipquarx on February 17, 2017, 01:42:25 AM ---
--- End quote ---
Yep and it's also safer! Stack unwinding will happen when an exception occurs that has a handler. It's no good putting "delete" at the end of a function body when you're done with a heap-allocated object if the function can throw an exception.
Smart pointers can solve a lot of issues like this one.
Headcrab Zombie:
--- Quote from: SUSHI on February 16, 2017, 11:14:06 PM ---When creating a class using new, it will not be deleted when it goes out of scope. You must delete it some point when you're finished with it, or you will leak memory.
--- End quote ---
Ah, yes, I forgot this aspect of C++.
I'm used to C#, where new is the only way to create a class instance
SUSHI:
--- Quote from: Headcrab Zombie on February 17, 2017, 11:01:07 AM ---Ah, yes, I forgot this aspect of C++.
I'm used to C#, where new is the only way to create a class instance
--- End quote ---
I should also add that in c++ new will return a pointer, so the correct code would actually be:
--- Code: ---thingHandler* TH = new thingHandler(20);
--- End code ---
Additionally, If you want a more compact statement, you can use the auto keyword.
--- Code: ---auto TH = new thingHandler(20);
--- End code ---
The example code has a few more issues that need to be addressed. Firstly, access modifiers are not set by prepending them to each member, instead you section them off like so:
--- Code: ---class thingHandler
{
bool thingsAreHandled = false; // class members are private by default
public:
thingHandler(int start);
void handleThings(); // member function
int things;
};
--- End code ---
Secondly, there was no declaration for the constructor, which I've added to the code above. Finally, knowing new returns a pointer and memory allocated with it must be explicitly released, the main function should be adjusted as follows:
--- Code: ---int main()
{
auto TH = new thingHandler(20);
TH->handleThings(); // use -> to access members of a pointer
TH->things += 10;
delete TH;
}
--- End code ---
Pecon: