转换为const char * [英] converting to const char*
问题描述
我编写了一个函数将任何类型转换为字符串:
模板< typename T>
std :: string toStr(const T&事情){
std :: ostringstream outStr;
outStr<<东西;
返回outStr.str();
}
以上功能正常工作。我还写了另一个函数来
将任何类型转换为const char *但是它能够正常工作
模板< typename T>
const char * toCStr(const T& thing){
std :: ostringstream outStr;
outStr<<东西;
std :: string Str = outStr.str();
返回Str.c_str();
}
有没有人知道它的问题是什么?
谢谢
I wrote a function to convert any type to string:
template <typename T>
std::string toStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
return outStr.str();
}
the above function works properly. I also wrote another function to
convert any type to const char* but it doesent work properly
template <typename T>
const char* toCStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
std::string Str=outStr.str();
return Str.c_str();
}
Does any body know what is its problem?
Thanks
推荐答案
* sadegh:
* sadegh:
>
template< typename T>
const char * toCStr(const T& thing){
std :: ostringstream outStr;
outStr<<东西;
std :: string Str = outStr.str();
返回Str.c_str();
}
有没有人知道它的问题是什么?
>
template <typename T>
const char* toCStr(const T &thing) {
std::ostringstream outStr;
outStr << thing;
std::string Str=outStr.str();
return Str.c_str();
}
Does any body know what is its problem?
你返回指向
返回后不再存在的对象的指针;这被称为悬空。指针(或参考)。
-
答:因为它弄乱了人们通常阅读文本的顺序。
问:为什么这么糟糕?
A:热门发布。
问:usenet和电子邮件中最烦人的是什么?
You''re returning a pointer to a an object that no longer exists after
returning; this is known as a "dangling" pointer (or reference).
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
那么我要做什么来将任何类型转换为const char *?
So what shoud I do to convert any type to const char*?
sadegh写道:
sadegh wrote:
那么我要做什么来将任何类型转换为const char *?
So what shoud I do to convert any type to const char*?
调用者是否期望必须删除返回的字符串上的内存?
Does the caller expect to have to delete the memory on the returned string ?
这篇关于转换为const char *的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!