Is it safe to push_back 'dynamically allocated object' to vector?

前端 未结 4 742
长发绾君心
长发绾君心 2020-12-17 01:07

Whenever I need to add dynamically allocated object into a vector I\'ve been doing that the following way:

class Foo { ... };

vector v;

v.push_         


        
4条回答
  •  自闭症患者
    2020-12-17 01:36

    How resilient to memory shortage is your program? If you really care about this you have to be prepared for new to throw as well. If you aren't going to handle that, I would not worry about jumping through the push_back hoops.

    In the general case, if you run out of memory, the program already has likely insurmountable problems unless it's specifically designed to run forever in a constrained footprint (embedded systems) - in that case you do have to care about all of these cases.

    If that applies to you, you could have a lengthy code review and retest cycle ahead of you. My guess is that you are OK to follow your team's practice here, though.

    As others have pointed out, using vector to store raw pointers has its own problems, and there is a wealth of material on this site and in the other answers to direct you to a safer pattern.

提交回复
热议问题