上一篇文章中虽然暂时性解决了问题,但是由于缓冲区大小固定,很可能发生溢出。当然可以根据结果字符串的长度动态分配内存,但还是不够优雅。asString()方法是一个常量函数,所以不能修改成员变量,但是构造函数没有这个限制,于是修改后的结果如下:
#ifdef CXXTEST_RUNNING
#include <cxxtest/ValueTraits.h>
#include <typeinfo>
#include <sstream>
#include <string>

namespace CxxTest
{
template<class T>
class ValueTraits< TMyClass<T> >
{
private:
std::ostringstream _s;
std::string buf;
public:
ValueTraits( const TMyClass<T> &t )
{
_s << typeid(t).name() << "(" << t.value() << ")";
buf = _s.str();
}
const char *asString() const
{
return buf.c_str();
}
};
};
#endif // CXXTEST_RUNNING
运行结果也正确,看来和我猜测的结果完全吻合。
#ifdef CXXTEST_RUNNING
#include <cxxtest/ValueTraits.h>
#include <typeinfo>
#include <sstream>
#include <string>
namespace CxxTest
{
template<class T>
class ValueTraits< TMyClass<T> >
{
private:
std::ostringstream _s;
std::string buf;
public:
ValueTraits( const TMyClass<T> &t )
{
_s << typeid(t).name() << "(" << t.value() << ")";
buf = _s.str();
}
const char *asString() const
{
return buf.c_str();
}
};
};
#endif // CXXTEST_RUNNING
本文介绍了一种改进的方法来避免固定缓冲区大小导致的溢出现象。通过使用`std::ostringstream`动态调整内存,确保了字符串输出既安全又高效。

1169

被折叠的 条评论
为什么被折叠?



