如何将std :: string分配回作为void *指针传递的std :: vector <char> .data()?

时间:2018-06-10 16:08:56

标签: c++ c++11

考虑以下代码,该代码将输入字符串作为源void*传递给函数filter(),并将vector<char>作为目标void*传递。

如何将已处理的字符串分配回目标void*,以便将其传回main()

size_t filter(void* destination, const void* source, size_t source_size)
{
    std::string source_string(static_cast<const char*>(source));

    std::string destination_string;

    // Do some processing on destination_string

    // HAS NO EFFECT ????????????????????
    destination = (&destination_string);

    return destination_string.size();
}

int main()
{
    std::vector<char> buffer;
    buffer.reserve(100);
    auto return_size = filter(buffer.data(), "Appollo", 7);

    std::string str(buffer.begin(), buffer.begin()+return_size);
    std::cout << str.c_str();
}

P.S。这是来自在线编码挑战的问题。

1 个答案:

答案 0 :(得分:1)

语句destination = (&destination_string)只是将本地std::string变量的内存地址分配给也是函数本地的指针。它根本不是将字符数据复制到调用者的缓冲区中。

尝试更像这样的东西:

size_t filter(void* destination, size_t destination_size, const void* source, size_t source_size)
{
    std::string source_string(static_cast<const char*>(source), source_size);

    std::string destination_string;
    // Do some processing on destination_string

    auto size = std::min(destination_string.size(), destination_size);
    std::copy_n(destination_string.begin(), size, static_cast<char*>(destination));

    return size;
}

int main()
{
    std::vector<char> buffer;
    buffer.resize(100);
    auto return_size = filter(buffer.data(), buffer.size(), "Appollo", 7);

    std::string str(buffer.data(), return_size);
    std::cout << str;

    return 0;
}