【问题标题】:Better expression than using s.str().c_str()?比使用 s.str().c_str() 更好的表达?
【发布时间】:2018-09-19 18:33:10
【问题描述】:
if ( hFileConnection == INVALID_HANDLE_VALUE ) {
    std::stringstream s;
    s << __func__ << " had GetLastError = " << GetLastError() << endl;
    OutputDebugStringA( s.str().c_str() );
    OutputDebugStringA( "\n" );
}

我喜欢

我的 Visual Studio“单元测试”在调试窗口中显示“Init had GetLastError = 2”,因此代码确实有效。

【问题讨论】:

  • 宏是合理的罕见情况
  • 你能有另一个版本的OutputDebugStringA 接受std::string吗?
  • @Colin 我怀疑这是可能的,因为OutputDebugString 是一个 WIN32 API 函数并且可能是 extern "C",它可以防止过载。
  • 请注意,您需要注意GetLastError 和评估顺序。在执行任何其他操作之前将其存储在变量中是最安全的。
  • 您还可以创建一个具有一组合适的operator&lt;&lt;() 重载的类,所有这些都根据需要调用OutputDebugStringA()。然后,给定该类的一个实例,您在示例中需要做的就是if (hFileConnection == INVALID_HANDLE_VALUE ) {instance &lt;&lt; __func__ &lt;&lt; " had GetLastError = " &lt;&lt; GetLastError() &lt;&lt; endl &lt;&lt; "\n";}。如果/根据需要,让该类的成员函数管理 stringstream 对象,而不是将其强制到调用代码上。可以选择将类设为单例。

标签: c++


【解决方案1】:

通过编写一点代码来制作您自己的界面。

void OutputDebug(const char* s)
{
    OutputDebugStringA(s);
}

void OutputDebug(const std::string& s)
{
    OutputDebug(s.c_str());
}

void OutputDebug(const std::stringstream& s)
{
    OutputDebug(s.str());
}


if ( hFileConnection == INVALID_HANDLE_VALUE ) {
    std::stringstream s;
    s << __func__ << " had GetLastError = " << GetLastError() << endl;
    OutputDebug(s);
    OutputDebug("\n");
}

如果你想变得花哨,你可以添加一点类型并重载operator&lt;&lt;

即使是像这样简单和不完整的东西也可以证明是有用的,有时是你需要的所有花哨:

// Empty types are surprisingly useful.
// This one is only a "hook" that we can attach 'operator<<' to
// in order to use stream insertion syntax.
struct DebugOutput {};  

template<typename T>
DebugOutput& operator<<(DebugOutput& lhs, const T& rhs)
{
    std::stringstream ss;
    ss << rhs;
    OutputDebugStringA(ss.str().c_str());
    return lhs;
}

int main()
{
    DebugOutput debug;
    debug << "hello" << 23 << "\n";
}

【讨论】:

  • 根据this answers.str().c_str() 将不起作用。
  • @PraneethPeiris 那是另一种情况。 OutputDebugStringA 不会为以后存储指针,因此它不会变得无效。 (在整个“全表达式”中有效。)
  • @PraneethPeiris 另一个答案是关于const char* str = s.str().c_str(); OutputDebugStringA(str); 的情况,它确实存在终身问题。
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 2017-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-12
  • 2019-02-08
相关资源
最近更新 更多