0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デバッグ用の小ネタを動作確認して車輪を再発明

0
Last updated at Posted at 2020-08-07

環境

Ubuntu20.04LTS on VMWare Player
Core i7 4770 / RAM4GB割り当て
g++/clang++
リポジトリ https://github.com/pff01632/EnterLeave

何をするものか?

関数の先頭で TRACE(); と一行書いておくだけで、その関数への突入と離脱のログが取れる。std::coutに出力しているが、任意のログ出力ライブラリに置き換えてもよい。これを使うメリットとしては、

  • いちいち離脱時のログ出力を書かなくて良い
  • 途中離脱でも正しくログ出力してくれる
  • 関数名を自分で書く必要がない
  • オーバーロードやC関数との名前の競合も正しく判断する

といったところ。関数先頭に TRACE() マクロを定義すると、EnterLeaveクラスの自動変数を暗黙的に定義する。変数は自動的に初期化され、Enterを出力する。関数の途中を含む任意のポイントで関数から離脱すると、自動変数であるEnterLeaveクラスのデストラクタが走り、Leaveを出力してくれる。

コード

EnterLeave.h
# ifndef     _ENTER_LEAVE_H_
# define     _ENTER_LEAVE_H_
# include    <bits/stdc++.h>

class EnterLeave {
    public:
        EnterLeave(std::string name)
        {
            nm = name;
            std::cout << nm << " Enter." << std::endl;
        };
        ~EnterLeave()
        {
            std::cout << nm << " Leave." << std::endl;
        };
    private:
        std::string nm;
};
# define     TRACE()     EnterLeave  trace_instance(__PRETTY_FUNCTION__)

# endif  //  _ENTER_LEAVE_H_
main.cpp
# include	"EnterLeave.h"

class testclass
{
public:
	testclass()
	{
		TRACE();
	};
	~testclass()
	{
		TRACE();
	};
	void testfunc()
	{
		TRACE();
	};
};

void testfunc()
{
	TRACE();
}

int main(int argc, char *argv[])
{
	TRACE();
	testfunc();
	testclass tst;
	tst.testfunc();
	return	0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?