Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Question regarding the creation of objects.  (Read 1018 times)

0 Members and 1 Guest are viewing this topic.

jonathansty

  • Newbie
  • *
  • Posts: 4
    • View Profile
    • Email
Question regarding the creation of objects.
« on: August 03, 2015, 03:16:05 pm »
Hello everyone,

Why do you use:
sf::Sprite sprite

and not
sf::Sprite* sprite

What's the different and why should you use one over the other?
I know the first variable is created on the stack and the second one is a pointer to an object on the heap?
Isn't the stack limited so won't it be a problem once you start using lots of variables?

eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11032
    • View Profile
    • development blog
    • Email
Re: Question regarding the creation of objects.
« Reply #1 on: August 03, 2015, 03:33:24 pm »
This is a basic C++ question and is not really related to SFML.
If you don't know when to use what, you might play around a bit longer with pure C++ and keep reading a good C++ book, before starting to work more with SFML.

The first is a local variable created on the stack. The second is by itself just a pointer. The pointer can point to a variable on the stack as well as one on the heap.
You should work on the stack as much as possible and only create objects on the heap if they need to be dynamically created.
However if you do create a dynamic object, you should make sure to use RAII and smart pointers and not work with new/delete, that's "old" C++ and is hard to use properly. See also "Why RAII rocks".
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

zsbzsb

  • Hero Member
  • *****
  • Posts: 1409
  • Active Maintainer of CSFML/SFML.NET
    • View Profile
    • My little corner...
    • Email
Re: Question regarding the creation of objects.
« Reply #2 on: August 03, 2015, 03:40:29 pm »
Another link that may help you out is this SO question: http://stackoverflow.com/questions/599308/proper-stack-and-heap-usage-in-c
Motion / MotionNET - Complete video / audio playback for SFML / SFML.NET

NetEXT - An SFML.NET Extension Library based on Thor