给定一个指向char数组的指针,是否可以从中构建std::vector或boost::array,并避免内存复制?
谢谢!
谢谢!
std::vector<char>&
,即使使用自定义分配器¹,也永远不会成功。
boost::string_ref
(在utility/string_ref.hpp
中)。multi_array_ref
(来自Boost Multi Array)#include <boost/utility/string_ref.hpp>
#include <iostream>
using boost::string_ref;
int main() {
char some_arr[] = "hello world";
string_ref no_copy(some_arr);
std::cout << no_copy;
}
multi_array_ref
这种方式更加灵活,如果你不需要使用字符串接口,那么它会“更好”地工作。
#include <boost/multi_array/multi_array_ref.hpp>
#include <iostream>
using ref = boost::multi_array_ref<char, 1>;
using boost::extents;
int main() {
char some_arr[] = "hello world";
ref no_copy(some_arr, extents[sizeof(some_arr)]);
std::cout.write(no_copy.data(), no_copy.num_elements());
}
这两个例子都会打印出来
hello world
¹专门使用std::allocator<char>
太过危险,不被标准允许
std::vector<T>
:))。 - sehevoid api2::foo(std::vector<char> const&);
- 这就是我说“在那里使用 std::vector 没有真正价值”的原因。我认为这种情况是 OP 面临的情况。实际上,他应该要求库开发人员修复 API,使其不那么侵入性 :) - sehe如果不使用boost,另一种选择是std::reference_wrapper。
#include <vector>
#include <iostream>
#include <functional>
using namespace std;
struct S
{
S() : val(0) {}
S(int val_) : val(val_) {}
S(const S& other) : val(other.val) {
cout << "copy" << endl;
}
int val;
};
int main()
{
char a[] = "Hello";
vector<reference_wrapper<char>> v(a, a+5);
S vS[] = {S(1), S(2), S(3)};
vector<S> v_copy(vS, vS + 3);
vector<reference_wrapper<S>> v_nocopy(vS, vS+3);
}
S
,你可以看到对象并没有被复制到向量中。因此,这对于char
也应该很好用。char*
向量,这可能会对性能产生非常严重的影响。这就是我不在这里点赞的原因,因为我认为上下文都是关于通过消除分配/复制来最大化性能的。 - sehe
std::array_view
或者string_view
,因为这是关于char
的。 - chris