简体   繁体   中英

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);

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM