【发布时间】:2018-08-25 07:09:46
【问题描述】:
如何做到这一点,这样我就不必手动删除指针?
unique_ptr 在 vector<> 中?
这是我的代码:
class vec2 {
public:
double x;
double y;
vec2() {
x = 0.0;
y = 0.0;
}
vec2(double xx, double yy) {
x = xx;
y = yy;
cout << "constructor called" << endl;
}
~vec2() {
static int count = 0;
cout << "destructor " << count << endl;
count++;
}
virtual double Length() { return sqrt(x * x + y * y); }
bool operator==(vec2& v) { return x == v.x && y == v.y; }
virtual string toString() {
stringstream s("");
s << "[" << x << " " << y << "]";
return s.str();
}
};
int main() {
vector<vec2*> vecs;
vecs.push_back(new vec2(1.8, 1.7));
vecs.push_back(new vec2(1.99, 1.7));
for (vec2* v : vecs) {
cout << v->toString() << endl;
delete v;
}
}
【问题讨论】:
-
不使用指针并将其设为
std::vector<vec2>怎么样? -
如果我使用普通的 vec2 会更慢,并且构造函数和析构函数被调用的次数更多,效率更低。
-
@Thomas,可能
virtual方法的存在是有原因的。 -
还有一个 vec3 类,但我没有包含它。 vec3 继承自 vec2
-
使用vector
而不是使用指针实际上会更快。使您的指针变慢的原因是您为向量中的每个项目分配了一个新的。这对内存布局非常不利,您的指针最终会遍布各处,导致缓存未命中。直线布局,就像你使用 vector 得到的那样会更快,更容易维护。
标签: c++ c++11 unique-ptr