Get autograd name fails

In C++, I want to get name of autograd function for tensor. I use this code:

void TensorPrintData(const torch::Tensor& t){
	std::cout << t << std::endl;

	if (const auto& g = t.grad_fn()){
		//crash on gName at the end ob block - assertion failure
		std::string gName = g->name();
		std::cout << "Grad: " << gName << std::endl;
	else if (t.requires_grad()){
		std::cout << " > requires_grad" << std::endl;

but gName causes crash when block ends with assertion failure in Visual Studio 2019 C++. I have Torch 1.9.0 cpu, x64, C++17.