本文介绍了一个指针是否有可能被一个没有任何数据副本的向量所拥有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 C 类型的原始指针,是否可以从拥有指针数据的相同类型创建一个 std::vector 而无需任何数据副本(仅移动)?促使我提出这个问题的原因是 std::vectordata() 成员函数的存在,这意味着 vector 的元素连续驻留在内存中的某处.

If I have a C type raw pointer, is it possible to create a std::vector from the same type that owns the pointer's data without any data copy (only moving)? What motivates me for asking this question is the existence of data() member function for std::vector which means vector's elements are residing somewhere in the memory consecutively.

我必须补充一点,像 std::make_shared 这样的函数的存在也增强了我的希望.

I have to add that the hope I had was also intensified by the existence of functions like std::make_shared.

推荐答案

我不认为这是直接可行的,尽管您不是第一个错过此功能的人.使用没有非const data 成员的std::string 更加痛苦.希望这会在 C++17 中改变.

I don't think that this is directly possible, although you're not the first one to miss this feature. It is even more painful with std::string which doesn't have a non-const data member. Hopefully, this will change in C++17.

如果您自己分配缓冲区,则有一个解决方案.只需预先使用 std::vector .例如,假设您有以下 C 风格的函数,

If you are allocating the buffer yourself, there is a solution, though. Just use a std::vector up-front. For example, assume you have the following C-style function,

extern void
fill_in_the_numbers(double * buffer, std::size_t count);

然后您可以执行以下操作.

then you can do the following.

std::vector<double>
get_the_numbers_1st(const std::size_t n)
{
  auto numbers = std::vector<double> (n);
  fill_in_the_numbers(numbers.data(), numbers.size());
  return numbers;
}

或者,如果您不那么幸运,并且您的 C 风格函数坚持自己分配内存,

Alternatively, if you're not so lucky and your C-style function insists in allocating the memory itself,

extern double *
allocate_the_buffer_and_fill_in_the_numbers(std::size_t n);

你可以求助于 std::unique_ptr,它很糟糕.

you could resort to a std::unique_ptr, which is sadly inferior.

std::unique_ptr<double[], void (*)(void *)>
get_the_numbers_2nd(const std::size_t n)
{
  return {
    allocate_the_buffer_and_fill_in_the_numbers(n),
    &std::free
  };
}

这篇关于一个指针是否有可能被一个没有任何数据副本的向量所拥有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 16:42