跟踪C++变量值的来源

Track the origin of a C++ variable's value

本文关键字:变量值 C++ 跟踪      更新时间:2023-10-16

经过一些更改后,应用程序的输出在某些情况下不再有效。某些输出值错误。用于计算这些输出的值是正确的,并且在复杂的处理过程中,某些情况下会出现错误。

是否有跟踪C++变量值来源的工具?我以前使用过valgrind来跟踪NULL值,但我想要的是更通用的。是否有更通用的工具可以显示导致变量在某个时间点具有其值的赋值链(或树)?

PS:该代码几乎是所有遗留代码,很难遵循,没有单元测试等。

EDIT:变量上的数据断点只会显示链中的端点。再多一点就好了。

您可以用一系列通用包装器包装感兴趣的变量,这些包装器将记录堆栈和每次调用的值。类似(省略了一些细节):

template <typename T>
class TracingValue
{
private:
 T m_Val;
 ...    
 void LogStackTrace() {...}
public:
 // write
 TracingValue& operator= (const T& val) {
    LogStackTrace();
    m_Val=val;
    return *this;
 }
 // read     
 operator T () const { return m_Val; }
 // "connect" to other values
 TracingValue& operator=(const TracingValue &other) {
   LogStackTrace();
   m_Val = other.m_Val;
   std::cout << "id: " << this->Id() << " new value: " << m_Val
             << " from id: " << other.Id() << std::endl;
   return *this;
 }
};

记录堆栈跟踪会很慢,可能会生成太多数据,但如果你少用它,你可能会更好地了解软件中发生的事情。然后,您可以在包装器中放置断点,以便在修改发生时捕获这些修改。

这应该适用于琐碎的案件。如果涉及序列化和其他操作,则可能需要对其进行进一步细化。

可以从其他封装的值跟踪值更改和构造。请参阅&rar;举个例子:

TracingValue<double> d;
d = 3.;
d = 42.;
double x = d - 2.;
std::cout << x << std::endl;
TracingValue<double> other_d(d);
TracingValue<double> another_d;
another_d = other_d;  

输出

id: 1 constructed with value: 0
id: 1 new value: 3
id: 1 new value: 42
40
id: 2 constructed with value: 42
id: 2 constructed from id: 1
id: 3 constructed with value: 0
id: 3 new value: 42 from id: 2