缓存一个const char *作为返回类型 [英] Caching a const char * as a return type

查看:114
本文介绍了缓存一个const char *作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的C ++上读了一下,发现这篇关于RTTI(运行时类型标识)的文章:
http://msdn.microsoft.com/en-us/library/70ky2y6k(VS.80).aspx 。好吧,这是另一个主题:) - 但是,我偶然发现了一个奇怪的说法在 type_info -class,即关于 :: name -method。它说: type_info :: name 成员函数返回一个 const char *

Was reading up a bit on my C++, and found this article about RTTI (Runtime Type Identification): http://msdn.microsoft.com/en-us/library/70ky2y6k(VS.80).aspx . Well, that's another subject :) - However, I stumbled upon a weird saying in the type_info-class, namely about the ::name-method. It says: "The type_info::name member function returns a const char* to a null-terminated string representing the human-readable name of the type. The memory pointed to is cached and should never be directly deallocated."

如何自己实现这样的类型?我之前经常遇到这个确切的问题,因为我不想为调用者删除一个新的 char -array,

How can you implement something like this yourself!? I've been struggling quite a bit with this exact problem often before, as I don't want to make a new char-array for the caller to delete, so I've stuck to std::string thus far.

所以,为了简单起见,让我们说,我想要的是: std :: string 创建一个返回Hello World!的方法,我们称之为

So, for the sake of simplicity, let's say I want to make a method that returns "Hello World!", let's call it

const char *getHelloString() const;

就我个人而言,我会像这样(Pseudo):

Personally, I would make it somehow like this (Pseudo):

const char *getHelloString() const
{
  char *returnVal = new char[13];
  strcpy("HelloWorld!", returnVal);

  return returnVal
}

调用者应该在我的返回指针上执行 delete []

.. But this would mean that the caller should do a delete[] on my return pointer :(


推荐答案

如何:

const char *getHelloString() const
{
    return "HelloWorld!";
}

直接返回文字意味着字符串的空间由编译器在静态存储中分配,并且在整个程序期间都可用。

Returning a literal directly means the space for the string is allocated in static storage by the compiler and will be available throughout the duration of the program.

这篇关于缓存一个const char *作为返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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