开发者

Should the objects initialized and stored in another class be dynamically/statically allocated?

开发者 https://www.devze.com 2023-03-31 04:15 出处:网络
I am 开发者_StackOverflow社区new to C++ but I have some basic memory allocation knowledge in C. I am writing a class Card, which stores the card number and a list of class Activity object.

I am 开发者_StackOverflow社区new to C++ but I have some basic memory allocation knowledge in C. I am writing a class Card, which stores the card number and a list of class Activity object.

class Card {
    public:
    Card();
    ~Card();
    vector<Activity> activities;
    int cardNo;
}

Currently, I initialize the Activity object using code like:

Activity a = Activity("a"); 

and push them to the vector defined in the Card object.

But I found people tend to initialize using Activity *a = new Activity("a") instead (dynamically allocation?), and the objects declared in the former way (statically allocated?) will be freed when the function declares them terminated.

Then, if I initialize Activity objects the same way I did before, but initialize Card using the "new Card()" way, is it possible that the Activity objects may have been de-allocated before Card object freed? Should I switch to use "new Activity()" to initialize objects stored in Card?


No, what you're doing is fine. When you push an object onto a vector, a copy is made. So when your function returns, your a is destroyed, but the vector you added it to still has its own seperate copy.

One reason someone might allocate an instance of a class dynamically and push it onto a vector would be that copying objects of that particular class around is expensive (and vector does a lot of copying around internally) and they want to avoid that, so they store pointers instead of objects so that only copies of the pointers are made, not of the objects (which is would not be nearly so expensive). That all depends on the class though; generally you can use vectors of objects without any performance issues.

Note: a shortcut1 for Activity a = Activity("a"); is Activity a("a"), or better, do what Benjamin suggested and do activites.push_back(Activity("a")) if you're not performing some operations on the Activity before you push it.

1 It's not really a shortcut because it does something different, but for your intents and purposes, it is.


"But I found people tend to initialize using Activity *a = new Activity("a") instead (dynamically allocation?)"

What people? They're doing it wrong. You're doing it right, sort of. You could just do this instead:

activities.push_back(Activity("a"));


A few cases where you need pointers:

  • it might be NULL instead of some dummy state
  • it is polymorphic
  • shared, not exclusive to the class
  • there is a circular dependency or recursion that prevents a direct member variable

In this particular case, as with most STL containers, member variables are preferred over member pointers.

0

精彩评论

暂无评论...
验证码 换一张
取 消