【发布时间】:2011-09-06 21:10:40
【问题描述】:
我想填充 std::vector(或其他一些 STL 容器):
class Foo {
public:
Foo(int _n, const Bar &_m);
private:
std::vector<Foo> fooes_;
}
1.好看的ctor,性能昂贵
std::vector<Foo> get_vector(int _n, const Bar &_m) {
std::vector<Foo> ret;
... // filling ret depending from arguments
return ret;
}
Foo::Foo(int _n, const Bar &_m) : fooes_(get_vector(_n, _m) {}
2.更好的性能,更差的 ctor
void fill_vector(int _n, const Bar &_m, std::vector<Foo> &_ret) {
... // filling ret depending from arguments
}
Foo::Foo(int _n, const Bar &_m) { fill_vector(_n, _m, fooes_); }
是否可以使用 C++0x(移动语义功能等)重写第一个示例中的 get_vector 函数以避免冗余复制和构造函数调用?
【问题讨论】:
-
您能否澄清您的
_m参数是否会被这些函数修改?在这些函数中使用_m做了什么?是复制到get_vector吗? -
@Johannes - 感谢您删除的答案 (+1)。我添加了 2 个不同的论点只是为了说明。我对它们的性质不太感兴趣。没错,最好加个const,以免造成混乱。我不太了解右值引用。是
Bar必须在Foo::Foo(int _n, Bar _m) fooes_(get_vector(_n, move(_m)) {}中移动ctor 吗? -
这里没有描述 RVO、移动等的所有细节。这里是查看详细信息的文章的链接:cpp-next.com/archive/2009/08/want-speed-pass-by-value
标签: c++ stl c++11 move-semantics return-value-optimization