在我的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 *作为返回类型
发布评论