简体   繁体   English

在构造函数C ++中初始化成员向量

[英]Initialize member vector in constructor C++

I have a class that has a member with type vector<CCPoint> . 我有一个类,其成员的类型为vector<CCPoint> I want to initialize this member in the constructor call, how can achieve it? 我想在构造函数调用中初始化此成员,如何实现呢?

I made it like this: 我是这样的:

.h 。H

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

.cpp 的.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. 永远不要使用“ new”创建对象,除非您确切地知道为什么这样做,甚至重新考虑。

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: 另一种C ++ 11花式裤子解决方案是使用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: 您的cpp文件中有一个错误,您缺少第二个冒号:

A::A() {

Also, you can directly initialize p using an initializer list like so: 同样,您可以使用初始化器列表直接初始化p,如下所示:

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. 根据您的帖子,我不清楚是什么问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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