将std::string传递给函数f(**char)

Pass std::string to a function f(**char)

本文关键字:char 函数 std string      更新时间:2023-10-16

是否有可能将std::string的指针传递给期望**char的函数?该函数需要一个**字符,以便向其写入值。

当前我正在做以下操作:

char *s1;
f(&s1);
std::string s2 = s1;

没有更近的路吗?很明显,s2.c_str()不起作用,因为它返回const *char .

这是处理这类函数的合适方法。您不能直接传入std::string,因为虽然您可以转换为C字符串,但它在内存中的布局不同,因此被调用的函数不知道将其结果放在哪里。

但是,如果可能的话,您应该重写该函数,使其接受std::string&std::string *作为参数。

(另外,如果合适的话,请确保free()delete[]为C字符串。请参阅f()的文档,以确定您是否需要这样做。

不,那不可能。函数覆盖指针(s1)本身。您可以从字符串(&s2[0])传入数据数组,但这只允许您覆盖当前保留的内容空间,而不是指针。

函数还以某种方式为字符串分配内存。你可能也需要清理一下。如果它起作用了,它将如何被清理?

你不能——字符串的字符缓冲区是不可写的,你不应该这样做。您总是可以使用中间缓冲区:

const size_t n = s2.size();
char buf[n + 1];
buf[n] = 0;
std::copy(s2.begin(), s2.end(), buf);
f(&buf);
s2.assign(buf, n);

是的,写一个包装器函数/宏,然后使用它

将字符串传递给函数的一种方法是让字符串

std::string name;

作为对象的数据成员。然后,在f()函数中创建一个字符串,并像前面所示的那样通过引用传递它

void f( const std::string & parameter_name ) {
    name = parameter_name;
}

现在,要将字符串复制到char *,以便将其作为char引用传递给函数:

从这个链接:

如果你想获得一个可写的副本,比如str.c_str(),比如char *,你可以这样做:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = ''; // don't forget the terminating 0
// don't forget to free the string after finished using it
delete[] writable;
上面的

不是异常安全的!

您可以通过引用将char * writable传递给f()函数。