c++ - 安全转换为 const char * - 临时生命周期问题

标签 c++ casting temporary

我定义了以下模板,以便我可以执行显式但安全的转换:

/// cast using implicit conversions only
template <class To,class From>
inline To safe_cast( const From &from ) {return from;}

经常(例如,将参数传递给 sprintf 和类似函数时)我想使用此模板执行从字符串类到 C 风格字符串的转换。然而,当临时通过时,它表明这是不可能的,因为临时不会活得足够长。

考虑以下示例:

class Object
{
  public:
  MyStringClass GetDebugName() const;
};

Object obj;
printf("%s",safe_cast<const char *>(obj.GetDebugName()));

来自 obj.GetDebugName() 的临时文件仅在 safe_cast 期间存在,并且指针在 printf 内部时无效(指向已被销毁的字符串临时文件的数据)。

作为一种变通方法,我目前使用不带模板调用的直接转换:const char *c = (const char *)(obj.GetDebugName(),但这有降低类型安全性的缺点,因为转换不必要地强大(例如,即使 obj.GetDebugName() 将返回 int 而不是字符串值,它也会默默地成功)。static_cast 可能稍微好一点,但即使这样也太强大了,我想在不确定转换是否安全的任何情况下得到一个错误。

1) 如果我没记错的话,标准说临时生命周期是一个声明(除非通过绑定(bind)到 const 引用来扩展,在这种情况下它是引用的生命周期)。在查看上面的 printf 示例时,我不太确定“语句”是什么,以及我所看到的行为是否符合要求。如果语句是整个 printf,则 const From &from 的生命周期更短——我应该从临时变量中期望多长的生命周期?有人可以澄清一下吗?

2) 有没有其他方法可以进行安全的转换,但结果会存在足够长的时间以供使用?

编辑:

请考虑这是一个更普遍的问题,我正在寻找一种机制如何在临时生命周期内完成这样的转换,我对任何特定字符串的特殊情况不太感兴趣类。

澄清为什么我不想使用 .c_str 或类似的成员函数:我希望转换代码是类型不可知的,我不希望代码依赖于我知道这个特定字符串类型具有 c_str实现后,即使 ObjectDebugName 返回不同的字符串类,或者即使 ObjectDebugName 已经返回 const char *(这排除了调用 .operator const char *() 的可能性),我也希望它能够工作。

最佳答案

I can perform an explicit, but safe cast

我将其称为显式完成的隐式转换,或者只是显式隐式转换。

1) If I am not mistaken, the standard says the temporary life time is a statement (unless extended by being bound to a const reference, in which case it is the life time of the reference). When looking at the printf example above, I am not quite sure what a "statement" is, and if the behaviour I have seen is conformant or not. If the statement is the whole printf, the lifetime of the const From &from is shorter - what lifetime should I expect from the temporary? Can someone clarify?

你是对的,临时文件在 printf 返回后被销毁。 您提供的代码应该可以工作。如果没有,则表示您提供了一些重要信息。

关于c++ - 安全转换为 const char * - 临时生命周期问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4254907/

相关文章:

c++ - 为什么在返回临时(右值)时在 move 构造函数之前调用析构函数

python - 在 boost.python 中使用它时不能在我的抽象类中使用纯虚函数

c++ - 一个类可以有将当前类作为参数的成员吗

C 和类型转换 - 为什么这个程序在 6 处停止?

Oracle 临时表有 "data block corrupted"吗?

python - python表达式中的临时变量

c++ - 如何使用 CSpinButtonCtrl 类在 MFC 中动态创建旋转按钮控件?

c++ - 使用 boost :qi 解析两个字符串 vector

c++ - 从 'const QVector<QVector<qreal>>' 转换为 'QVector<QVector<qreal>>'

c# - 将枚举底层整数值转换为字符串