pword() 值被另一个流修改

pword() value modified by another stream

os.pword(index) 方法应该 return 自定义操纵器指定的当前日期格式。然而,pword() 的结果被另一个流通过它的 str(string) 方法修改。

ostringstream os;
istringstream is;
CDate f ( 2000, 5, 12 );

os << date_format ( "%Y-%m-%d" ) << f;
is.clear ();
is.str ( "05.06.2003" ); // causes pword() to return "05.06.2003" instead of "%Y-%m-%d"
os.str ("");
os << f;

Class 方法:

struct date_format
{
    static const int index;
    string format;

    explicit date_format(const char * fmt)
    {
        format = string(fmt);
    }

    friend ostream & operator<<(ostream & s, const date_format & df)
    {
        s.pword(index) = (void*)df.format.c_str();
        return s;
    }

};

const int date_format::index = ios_base::xalloc();

class CDate
{
    ...
    friend ostream & operator<<(ostream & os, const CDate & cdate)
    {
        /* should point to the current date format of os */ 
        const char * ptr = (const char*)os.pword(date_format::index);
        ...
        return os;
    }
}

是什么导致了这种行为,如何避免这种行为?

您遇到了未定义的行为。在您的 operator<<(ostream & s, const date_format& df) 中,您将 s.pword(index) 设置为指向临时 date_format 实例的数据成员的指针。由于 date_format( "%Y-%m-%d" ) 在表达式末尾析构,因此您的流会留下一个悬空指针。

在设置指向它的指针之前尝试对字符串进行深度复制。