在构造函数C ++中初始化成员向量 [英] Initialize member vector in constructor C++
问题描述
我有一个类,该类的成员类型为 vector< CCPoint>
.我想在构造函数调用中初始化此成员,如何实现呢?
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?
我是这样的:
.h
class A{
public:
A(vector<CCPoint> *p);
private:
vector<CCPoint> *p;
}
.cpp
A:A(){
this->p = p;
}
致电
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?
将成员更改为向量:
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
}
然后这样呼叫:
Vector<CCPoint> p;
A a(p);
永远不要使用"new"创建对象,除非您确切地知道为什么这样做,即使这样,也要重新考虑.
Never, ever create an object with "new" unless you know exactly why you are doing so, and even then, reconsider.
性能注意:是的,此可能会导致矢量复制的发生,具体取决于编译器对复制的选择.另一种C ++ 11花哨的裤子解决方案是使用move:
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.
这篇关于在构造函数C ++中初始化成员向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!