Ferenc Dajka
Ferenc Dajka

Reputation: 1051

Initialize member vector in constructor C++

I have a class that has a member with type vector<CCPoint>. I want to initialize this member in the constructor call, how can achieve it?

I made it like this:

.h

class A{
    public:
        A(vector<CCPoint> *p);
    private:
        vector<CCPoint> *p;
}

.cpp

A:A(){
    this->p = p;
}

call

Vector<CCPoint> *p = new Vector<CCPoint>;
A a = new A(p);

Upvotes: 0

Views: 263

Answers (2)

user2428400
user2428400

Reputation:

This will leak memory, because nobody is deleting the vector you "new"-ed.

Also, why have a pointer to a vector at all? Are you worried about copying it into the constructor being expensive?

Change the member to be a vector:

class A{
    public:
        A(vector<CCPoint> p);
    private:
        vector<CCPoint> p;
}

Change the constructor to use the initialiser list:

A:A(vector<CCPoint> newP) : p(newP){
    // Empty
}

And call like this:

Vector<CCPoint> p;
A a(p);

Never, ever create an object with "new" unless you know exactly why you are doing so, and even then, reconsider.

Performance Note: Yes this may cause a vector copy to occur, depending on copy elision by the compiler. An alternative C++11 fancy pants solution would be to use move:

class A{
    public:
        A(vector<CCPoint> p);
    private:
        vector<CCPoint> p;
}

A:A(vector<CCPoint> newP) : p(std::move(newP)){
    // Empty
}

Vector<CCPoint> p;
A a(std::move(p)); // After this completes, 'p' will no longer be valid.

Upvotes: 4

wrren
wrren

Reputation: 1311

There's an error in your cpp file, you're missing the second colon:

A::A() {

Also, you can directly initialize p using an initializer list like so:

A::A( vector<CCPoint>* _p ) :
p( _p )
{}

Not that there's any real advantage in using this for primitive types like pointers, but it's good convention. Does this answer your question? I'm not clear on what the problem is, exactly, based on your post.

Upvotes: 1

Related Questions