我已经阅读了几个地方,c_str()和data()(在STL和其他实现中)之间的区别c_str()是总是空终止而data()不是.据我在实际实现中看到的,他们要么做同样的事情,要么做data()电话c_str().
我在这里错过了什么?在哪种情况下使用哪一个更正确?
标准C库中的许多函数,尤其是用于字符串操作的函数,最显着的是strcpy(),共享以下原型:
char *the_function (char *destination, ...)
Run Code Online (Sandbox Code Playgroud)
这些函数的返回值实际上与提供的相同destination.你为什么要浪费多余的回报价值呢?这样的函数无效或返回有用的东西更有意义.
我唯一的猜测是,为什么将函数调用嵌套在另一个表达式中更容易,更方便,例如:
printf("%s\n", strcpy(dst, src));
Run Code Online (Sandbox Code Playgroud)
还有其他合理的理由来证明这个成语吗?
我正在学习C++,当我尝试创建自己的异常并将它们放在Linux上时,我遇到了这种情况.
我已经创建了一个小测试项目来测试我的实现,下面是我的异常类头文件.
class TestClass : public std::runtime_error
{
public:
TestClass(char const* const message) throw();
virtual char const* what() const throw();
};
Run Code Online (Sandbox Code Playgroud)
异常类的源文件是
using namespace std;
TestClass::TestClass(char const* const message) throw()
: std::runtime_error(message)
{
}
char const * TestClass::what() const throw()
{
return exception::what();
}
Run Code Online (Sandbox Code Playgroud)
在我的主应用程序中,我正在调用一个抛出异常并在try/catch中捕获它的函数,如下所示:
void runAFunctionAndthrow();
/*
*
*/
int main(int argc, char** argv) {
try
{
cout << "About to call function" << endl;
runAFunctionAndthrow();
}
catch (TestClass ex)
{
cout << "Exception Caught: " << ex.what() << …Run Code Online (Sandbox Code Playgroud) 如何在不复制和保留源std :: string对象的情况下获取std :: string char数据的所有权?(我想使用移动语义但在不同类型之间.)
基本上我想做一些与此相当的事情:
{
std::string s(“Possibly very long user string”);
const char* mine = s.c_str();
// 'mine' will be passed along,
pass(mine);
//Made-up call
s.release_data();
// 's' should not release data, but it should properly destroy itself otherwise.
}
Run Code Online (Sandbox Code Playgroud)
为了澄清,我确实需要摆脱std :: string:继续前进.该代码处理字符串和二进制数据,并应以相同的格式处理它.我确实想要来自std :: string的数据,因为它来自另一个与std :: string一起使用的代码层.
为了给出更多透视图,我想要这样做:例如,我有一个异步套接字包装器,它应该能够从用户那里获取std :: string和二进制数据进行写入.两个"API"写入版本(将std :: string或行二进制数据)内部解析为相同(二进制)写入.我需要避免任何复制,因为字符串可能很长.
WriteId write( std::unique_ptr< std::string > strToWrite )
{
// Convert std::string data to contiguous byte storage
// that will …Run Code Online (Sandbox Code Playgroud) 我使用std :: string类型进行字符串操作.
但是,有时我需要保留原始的char*指针,即使在原始的std :: string对象被销毁之后(是的,我知道char*指针引用了HEAP并且最终必须被处理掉).
但是,看起来没有办法从字符串中分离原始指针或者是吗?
也许我应该使用另一个字符串实现?
谢谢.
编辑
伙计们,请不要将分离与复制混淆.分离的本质是字符串对象放弃其对底层缓冲区的所有权.所以,如果字符串有detach方法,它的语义将是这样的:
char *ptr = NULL;
{
std::string s = "Hello world!";
ptr = s.detach(); // May actually allocate memory, if the string is small enough to have been held inside the static buffer found in std::string.
assert(s == NULL);
}
// at this point s is destroyed
// ptr continues to point to a valid HEAP memory with the "Hello world!" string in it.
...
delete ptr; // …Run Code Online (Sandbox Code Playgroud)