那么,我如何通过函数分配 std::string 呢?
我有这个代码
void WP_Hash(std::string dest, std::string src)
{
// Set up all the locals
struct NESSIEstruct
whirlpool_ctx;
char
digest[64],
buffer[4100];
unsigned char
*tmp = (unsigned char *)digest;
// Start the hashing
NESSIEinit(&whirlpool_ctx);
NESSIEadd((const unsigned char *)src.c_str(), src.length() * 8, &whirlpool_ctx);
// Finish the hashing
NESSIEfinalize(&whirlpool_ctx, tmp);
// Convert to a real string
unsigned int len = 0;
while (len< 128)
{
buffer[len++] = gch[*tmp >> 4];
buffer[len++] = gch[*tmp & 0x0F];
tmp++;
}
buffer[128] = 0;
dest.assign(buffer);
}
以及初始化它的代码:
std::string ret;
WP_Hash(ret, "none");
sampgdk::logprintf("%s", ret.c_str());
什么都不打印
当我将 ret 字符串更改为“a”时,它会打印“a” 我希望它打印无(在 WP_Hash 中散列但忽略它,假设“无”是 WP_Hash 的结果)
我能做什么?
最佳答案
C++ 不是 Java:它的对象具有值语义。所以,您正在将一个拷贝传递给该函数。
如果您希望原始参数保留函数内的更改,请改为传递引用。 (也值得将 (const
) 引用传递给 src
以节省不必要的复制。)
void WP_Hash(std::string& dest, const std::string& src);
// ^ ^^^^^^ ^
或者,返回
函数的结果字符串:
std::string WP_Hash(const std::string& src);
// ^^^^^^^^^^^ ^^^^^^ ^
然后这样使用:
const std::string ret = WP_Hash("none");
sampgdk::logprintf("%s", ret.c_str());
关于c++ - 如何通过函数分配 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30689127/