问题描述
我在分配矢量的某些元素时遇到问题,然后删除
它们。
Basicaly我有这样的事情:
班级基础
{
私人:
std :: vector< object> V;
// std :: vector< * object> V;
public:
void addObject()
{
object * temp = new object;
V.push_back(* temp);
//V.push_back(new object);
}
void removeObject(index)
{
delete& V [index];
V .erase(V.begin()+ index);
//删除V [index];
//V.erase(V.begin( )+ index);
}
};
注释行是我使用指针版本的地方。在第一个
的情况下,对象的析构函数被调用两次(我想因为当我调用
addObject时,局部变量超出范围(任何方法来防止这种情况) )并且
在第二种情况下它根本没有被调用; /
我宁愿不使用指针向量。 ..我想也许我可以
将对象* temp声明为静态,但这似乎有点像黑客......我只需要一种方式来说b $ b
它超出范围或者其他东西时,不要为这个本地对象调用析构函数。
任何想法?
Jon
I''m having a problem allocating some elements of a vector then deleting
them.
Basicaly I have something like this:
class base
{
private:
std::vector<object> V;
//std::vector<*object> V;
public:
void addObject()
{
object *temp = new object;
V.push_back(*temp);
//V.push_back(new object);
}
void removeObject(index)
{
delete &V[index];
V.erase(V.begin() + index);
//delete V[index];
//V.erase(V.begin() + index);
}
};
the commented line is where I used the pointerized version. In the first
case the object''s destructor gets called twice(I suppose because when I call
addObject the local variable goes out of scope(any way to prevent this) and
in the second case it doesn''t get called at all ;/
I''d rather not use a vector of pointers though... I thought maybe I could
declare the object *temp as static but this seems to be kinda a hack... I
just need a way to say "don''t call the destructor for this local object when
it goes out of scope" or something.
Any ideas?
Jon
推荐答案
班级基础
{
私人:
std :: vector< object> V;
public:
void addObject()
{
V.push_back(object ());
}
void removeObject(index)
{
V.erase (V.begin()+ index);
}
};
-
Cy
不,不要试图规避语言的运作方式,更好的是
来理解它并在预期中使用它方式。
-Mike
No, don''t try to circumvent the way the language works, better
to understand it and use it in the intended ways.
-Mike
同意。似乎有太多人这样做了。 :-)
void removeObject(index)
{
if(!V.empty())
V.erase(V.begin()+ index);
}
};
Agreed. And too many people seem to be doing so. :-)
void removeObject(index)
{
if(!V.empty())
V.erase(V.begin() + index);
}
};
-Mike
-Mike
这篇关于新的,删除,STL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!