如果我注释掉构造函数中的第一行,我的以下代码就会出错。返回错误为:
libc++abi.dylib: terminating with uncaught exception of type boost::exception_detail::clone_impl<boost::exception_detail::error_info_injector<std::overflow_error> >: Error in function boost::math::cyl_bessel_k<double>(double,double): numeric overflow
Abort trap: 6
然而,奇怪的是,如果我在构造函数中输出一些东西(例如,取消注释第一行),那么我的程序就可以正常工作。
GP::GP(const Training_set& _sample, Eigen::VectorXd& param,
const std::string& which_kernel) : sample(_sample)
{
// std::cout << "WORKS" << std::endl;
if (which_kernel == "Matern") {
std::cout << "Matern kernel is used!" << std::endl;
Kernel_Matern matern(param, param.size());
kernel = &matern;
} else if (which_kernel == "Square_Exponential") {
std::cout << "Square Exponential kernel is used!" << std::endl;
Kernel_SE se(param, param.size());
kernel = &se;
} else {
std::cout << "Cannot identify the kernel" << std::endl;
exit(1);
}
input_dim = sample.dim;
input_size = sample.size;
L_chol.resize(sample.size, sample.size);
Eigen::MatrixXd cov_matrix = Eigen::MatrixXd::Zero(sample.size, sample.size);
get_cov_matrix(sample.X, input_size, sample.X, input_size, cov_matrix);
get_chol(cov_matrix);
}
最佳答案
您正在存储超出范围的临时地址。使用 *kernel
在它指向的超出范围之后是未定义的行为。
kernel
应该是 std::unique_ptr<X>
类型而不是输入 X*
.
将赋值替换为:
kernel = std::make_unique<Kernel_Matern>(param, param.size());
或:
kernel = std::make_unique<Kernel_SE>(param, param.size());
在有问题的两行。
如果您有传递 kernel
的代码给一个函数,而不是传递 kernel.get()
.
请注意,它会阻止复制 GP
的实例但不移动它们,因为 unique ptr 只能移动。如果您有一个类型将值和指针都存储到它自己的值中,那么无论如何复制它都可能是一个错误。
关于c++ - boost 功能的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51161481/