问题描述
有没有办法在c ++中获得callstack级别?例如,取以下代码:
void call3(){
// callstack level将是3
}
void call2(){
// callstack level为2
call3() ;
}
int main(){
// callstack级别为1
call2();
返回0;
}
我并不是说使用调试器来获取它看着
的callstack。我的意思是以编程方式获取它。
Is there a way to get the callstack level in c++? for example, take
the following code:
void call3() {
//callstack level would be 3
}
void call2() {
//callstack level would be 2
call3();
}
int main() {
//callstack level would be 1
call2();
return 0;
}
And I don''t mean obtaining it from using a debugger and looking at the
callstack. I''m mean obtaining it programmatically.
推荐答案
不,不是标准的C ++。
-
Ian Collins。
No, not in standard C++.
--
Ian Collins.
检测函数,即添加维护调用堆栈的代码
级别计数。
这可以通过构建和销毁每个函数中的本地
对象轻松完成。
例如,关闭袖口,
级CallTracer
{
私人:
静态标准::为size_t和放大器; theLevel()
{
static std :: size_t theLevelVariable = 0;
返回theLevelVariable;
}
CallTracer(){++ theLevel(); }
~CallTracer(){ - theLevel(); }
static std :: size_t level(){return theLevel(); }
};
你将使用的
void foo3()
{
CallTracer示踪剂;
std :: cout
<< foo3,在通话级别 << CallTracer :: level()
<< std :: endl;
}
这计算以这种方式检测的函数的调用;如果那不是足够的话,请使用一个体面的调试器。
-
答:因为它搞砸了人们通常阅读文字的顺序。
问:为什么这么糟糕?
A:热门发布。
问: usenet和电子邮件中最烦人的事情是什么?
Instrument the functions, that is, add code that maintains a call stack
level count.
That can easily be done via the construction and destruction of a local
object in each function.
For example, off the cuff,
class CallTracer
{
private:
static std::size_t& theLevel()
{
static std::size_t theLevelVariable = 0;
return theLevelVariable;
}
public:
CallTracer(){ ++theLevel(); }
~CallTracer(){ --theLevel(); }
static std::size_t level() { return theLevel(); }
};
which you''d use like
void foo3()
{
CallTracer tracer;
std::cout
<< "foo3, at call level " << CallTracer::level()
<< std::endl;
}
This counts the calls of functions instrumented this way; if that''s not
enough, use a decent debugger.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
如果你对一个确切的数字不感兴趣,但可以接受一个措施
这将指示堆栈深度(以字节为单位),您可以通过&获取函数的一个普通局部变量的地址
。运算符
并将其转换为char *指针。我已经使用这种技术来跟踪程序运行期间堆栈空间的使用情况;请参阅
< http://www.spinellis.gr/codequality/stack.gif?clcpp>的快照。这种技术
不可移植,但适用于大多数计算机体系结构。
If you''re not interested in a precise number, but can accept a measure
that would indicate the stack depth in bytes you can obtain the address
of one of the function''s plain local variables through the & operator
and cast it to a char * pointer. I''ve used this technique to track the
use of stack space during the runtime of a program; see the snapshots at
<http://www.spinellis.gr/codequality/stack.gif?clcpp>. This technique
is not portable, but will work on most computer architectures.
这篇关于获得callstack级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!