C ++:返回C字符串最快速的方法 [英] C++: Fastest method to return a C string

查看:194
本文介绍了C ++:返回C字符串最快速的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的函数,它接受一个字符,并返回一个字符串,在C它看起来像;

 的char * get_string(焦三){
  开关(三){
    案例'A':回归一些字符串;
    案例'B':回归其他一些字符串;
...

和它工作正常,但后来我想我的code C ++中的工作,和C ++编译器抛出一个gazillions从字符串常量'字符*去precated转换。我理解的警告,但我不是100%肯定的是实现功能,所以它会工作,速度快,在两个C和C ++的最佳途径。此功能被称为很多,这是一个重要的瓶颈,所以它必须要快。我最好的尝试是;

 的char * get_string(焦三){
  字符*海峡=(字符*)malloc的(50);
  开关(三){
    案例'A':
      sprintf的(STR,一些字符串);
      返回海峡;
    案例'B':
      sprintf的(STR,其他一些字符串);
      返回海峡;
...


解决方案

返回一个为const char * 而不是的char * 。在常量在这种情况下意味着这个指针指向一个常量指针对象 - 换句话说,调用者不能修改返回的字符串。这使编译器将串在某些内存位置,在 get_string()函数可以只返回地址这些字符串。如果主叫方需要修改返回的字符串,就可以分配自己的缓冲区(通过的std ::字符串 pferably $ P $)。复制

 为const char * get_string(焦三){
  开关(三){
    案例'A':回归一些字符串;
    案例'B':回归其他一些字符串;
...

I have a simple function that takes a char and return a string, in C it looks like;

char* get_string(char c) {
  switch(c) {
    case 'A': return "some string";
    Case 'B': return "some other string";
...

And it works fine, but then I wanted my code to work in C++, and the C++ compilers throws a gazillions "deprecated conversion from string constant to ‘char*’". I understand the warning, but I'm not 100% sure what is the best way to implement the function so it will work, fast, on both C and C++. This function is being called a lot, it's an important bottleneck, so it has to be fast. My best try is;

char* get_string(char c) {
  char* str = (char*)malloc(50);
  switch(c) {
    case 'A':
      sprintf(str, "some string");
      return str;
    Case 'B':
      sprintf(str, "some other string");
      return str;
...

解决方案

Return a const char* instead of char*. The const in this context means "this pointer points to a constant pointee" - in other words, the caller cannot modify the returned string. This allows the compiler to place the strings in some memory location so the get_string() function can just return addresses to those strings. If the caller needs to modify the returned string, they can allocate their own buffer and copy it (preferably via std::string).

const char* get_string(char c) { 
  switch(c) { 
    case 'A': return "some string"; 
    case 'B': return "some other string"; 
...

这篇关于C ++:返回C字符串最快速的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆