向量清除能力 [英] clearing capacity af a vector
问题描述
我们有一个线索关于如何清除std :: vector的容量......
怎么样:
std ::矢量<诠释> v;
v .~vector< int>(); //破坏它(不知道我是否需要
< int>这里?)
new(& v)vector< int>(); //再次构建它
-
Lasse
" ; Lasse Skyum < no spam>写了...我们有一个关于如何清除
std :: vector的容量的线程......怎么样:
std: :矢量<诠释> v;
v。~vector< int>(); //破坏它(不知道我是否需要
< int>这里?)
new(& v)vector< int>(); //再次构建它
虽然它_might_工作(甚至根据一些扭曲的阅读
标准的
,它被允许工作) ,我建议
v.swap(std :: vector< int>());
Victor
" Lasse Skyum" < no spam>在消息中写道
news:3f *********************** @ dread16.news.tele.d k ... < blockquote class =post_quotes>我们有一个关于如何清除
std :: vector的容量的线程......怎么样:
std :: vector< int> v;
v。~vector< int>(); //破坏它(不知道我是否需要
< int>这里?)
new(& v)vector< int>(); //再次构建
-
正如Victor已经说过 - 这可能会奏效。但恕我直言,使用新的
任何真正的需要并不是一个好主意。 BTW使用
的问题是什么?具有交换功能的解决方案?
Chris
>虽然它_might_工作(甚至根据标准的一些扭曲的读取,它被允许工作),我建议
v.swap(std :: vector< int> ());
这项技术几乎可行,但并不完全。问题是
std :: vector< int>()是一个rvalue,这意味着它不能用作交换的
参数,需要一个左值。
你可以使用一个稍微偷偷摸摸的技巧来使用该技术:
std :: vector< int>()。 swap(v);
此代码依赖于允许调用成员
函数来改变rvalue内容的事实。 />
We had a thread earlies about how to clear the capacity af a std::vector...
how about this:
std::vector<int> v;
v.~vector<int>(); // destruct it (don''t know if I need
the <int> here?)
new (&v)vector<int>(); // construct it again
--
Lasse
"Lasse Skyum" <no spam> wrote...We had a thread earlies about how to clear the capacity af a std::vector... how about this:
std::vector<int> v;
v.~vector<int>(); // destruct it (don''t know if I need
the <int> here?)
new (&v)vector<int>(); // construct it again
While it _might_ work (and even according some twisted reading
of the Standard, it is allowed to work), I''d suggest
v.swap(std::vector<int>());
Victor
"Lasse Skyum" <no spam> wrote in message
news:3f***********************@dread16.news.tele.d k...We had a thread earlies about how to clear the capacity af a std::vector... how about this:
std::vector<int> v;
v.~vector<int>(); // destruct it (don''t know if I need
the <int> here?)
new (&v)vector<int>(); // construct it again
--
As Victor already said - this might work. But IMHO using placement new with
any real need to is not such a hot idea. BTW what''s the problem with using
the "normal" solution with the swap function?
Chris
> While it _might_ work (and even according some twisted readingof the Standard, it is allowed to work), I''d suggest v.swap(std::vector<int>());
This technique almost works, but not quite. The trouble is that
std::vector<int>() is an rvalue, which means that it can''t be used as the
argument to swap, which requires an lvalue.
You can make the technique work with a slightly sneaky trick:
std::vector<int>().swap(v);
This code relies on the fact that it is permissible to call a member
function that changes the contents of an rvalue.
这篇关于向量清除能力的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!