如何通过函数赋值std::string

How assign std::string through a function?

本文关键字:string std 赋值 何通过 函数      更新时间:2023-10-16

那么,我如何通过函数分配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()); 

It print nothing

当我将ret string更改为"a"时,它会打印"a"我希望它打印none(在WP_Hash中散列,但忽略它,假设"none"是WP_Hash的结果)

我该怎么办?

c++不是Java:它的对象有值语义。所以,你传递了一个copy到那个函数。

如果您希望原始参数保留函数内部的更改,则传递引用。(同样值得将(const)引用传递给src,以节省不必要的复制。)
   void WP_Hash(std::string& dest, const std::string& src);
//                         ^       ^^^^^^           ^

或者,return从函数的结果字符串代替:

   std::string WP_Hash(const std::string& src);
// ^^^^^^^^^^^         ^^^^^^           ^

然后这样使用:

const std::string ret = WP_Hash("none");
sampgdk::logprintf("%s", ret.c_str());

与其他c++类型相同-除非另有指定,否则按值传递。添加&以使其成为引用。或者直接返回