strncpy在代码中强调等同性

时间:2016-01-21 12:43:24

标签: c++ string strcpy code-cleanup strncpy

我有这个丑陋的功能,我觉得整个strncpy应该只是strcpy

void PackData(char*& cursor, const std::string& data) {
    *(reinterpret_cast<int*>(cursor)) = static_cast<short>(data.length() + 1);
    cursor += sizeof(int);
    // copy the text to the buffer
    ::strncpy(cursor, data.c_str(), data.size());
    cursor += (data.length() * sizeof(char));
    *(reinterpret_cast<char*>(cursor)) = 0;
    cursor += sizeof(char);
}

cursor保证有足够的空间来包含所有复制的数据。 data在终止时只包含'\0'字符。

我想更新此函数以使用strcpy,并删除一些丑陋的内容。这就是我所拥有的:

void PackData(char*& cursor, const std::string& data) {
    const int size = data.size() + 1;

    std::copy_n(cursor, sizeof(int), reinterpret_cast<char*>(&size));
    cursor += sizeof(int);
    strcpy(cursor, data.c_str());
    cursor += size;
}

我的代码工作正常,但我想问一下是否有人发现我可能错过的任何不当行为?

1 个答案:

答案 0 :(得分:2)

编写该代码的人不知道他们在做什么。使用strncpy毫无意义,因为在调用中传递给它的长度是源的长度,而不是目标。最后reinterpret_cast只会将cursor投射到其原始类型。摆脱这种废话。您的代码是一个很好的替代品。