vector push_back class

Oct 23, 2014 at 6:21pm
how bad/good is this code? I mean, how do you push back class to a vector in other way? is this somehow bad or not at all?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class cls
{
public:
    int a, b, c;
    cls() { a=1; b=2; c=3; }
    int rtrn() { return a; }
};

int main()
{
    vector<cls> mycls;
    mycls.push_back(*new cls);
    cout << mycls[0].rtrn();
}
Oct 23, 2014 at 6:25pm
Yeah this is bad. If you create an object using new you should also clean it up using delete, but in your code you have no way of doing that because the vector is storing a copy of the object that was creates using new.

There is no point using new here at all. Just create a temporary object that you pass to push_back, like this:
 
mycls.push_back(cls());
Oct 23, 2014 at 6:26pm
how bad/good is this code?
mycls.push_back(*new cls); — absymal. You have a memory leak here. *new is beyound good and evil in itself.
how do you push back class to a vector in other way?
1
2
3
mycls.push_back(cls());
//or
mycls.emplace_back();
Last edited on Oct 23, 2014 at 7:59pm
Oct 24, 2014 at 7:23am
I see, not sure why I didn't think about using constructor >.<

thanks
Oct 24, 2014 at 3:31pm
@Mekkatorqu,

Just a point about terminology.

Calling new also calls the constructor. What @Peter87 and @MiiNiPaa were showing you was a statically allocated temporary object (located on the stack) which is destroyed when going out of scope rather than a dynamically allocated object (located on the heap) which is never destroyed because it is never deleted.

Line 12 (new cls) in your original post and line 1 in @MiiNiPaa's post ( cls() ) both call the same constructor.
Oct 25, 2014 at 11:41am
well obviously, as constructor is called whenever the class is created, I just didn't think about putting it in the push_back function

that is also the reason why I created this thread to find a better way, as I was 99% sure that this isn't the right one
Last edited on Oct 25, 2014 at 11:41am
Topic archived. No new replies allowed.