缓存一个const char *作为返回类型

编程入门 行业动态 更新时间:2024-10-23 17:34:05
本文介绍了缓存一个const char *作为返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

Was reading up a bit on my C++, and found this article about RTTI (Runtime Type Identification): msdn.microsoft/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 *作为返回类型

本文发布于:2023-10-28 23:25:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1538071.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:缓存   类型   const   char

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!