为什么断言在这里不起作用

Why does assert not work here?

本文关键字:不起作用 在这里 断言 为什么      更新时间:2023-10-16

这是代码:

#include <Rcpp.h>
#include <iostream>
#include <assert.h>
#include <stdio.h>
using namespace Rcpp;

// [[Rcpp::export]]
double eudist(NumericVector x, NumericVector y) {
    int nx = x.size();
    int ny = y.size();
    std::cout << nx << 'n' << ny << std::endl;
    assert(nx == ny);
    double dist=0;
    for(int i = 0; i < nx; i++) {
        dist += pow(x[i] - y[i], 2);
    }
    return sqrt(dist);
}

将其采购到R中后,我得到以下结果,显然它在出现错误时不会流产:

#////////////////////////////////////////////////////
sourceCpp('x.cpp')
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1))
2
2
[1] 1.4142
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1, 1))
2
3
[1] 1.4142

请注意,assert()等明确禁止用于cran上传。引用Cran Repo政策页面:

包装中提供的代码和示例永远不要做任何事情 可能被视为恶意或反社会。以下是 过去经验的说明性示例。

  • 编译的代码绝不应终止其运行的R过程。因此,C/C 调用assert/abort/exit,fortran调用 必须避免使用STOP等。R代码也可以致电q()

因此,关于调试模式的答案在技术上是正确的,但也请注意,如果您打算在某个时候上传cran,则不应使用此功能。

通过使用throw而不是assert解决了问题,RCPP实际上将把东西放在适当的try-catch块中,这非常好。

#include <Rcpp.h>
#include <iostream>
#include <assert.h>
#include <stdio.h>
using namespace Rcpp;

// [[Rcpp::export]]
double eudist(NumericVector x, NumericVector y) {
    int nx = x.size();
    int ny = y.size();
    Rcout << nx << 'n' << ny << std::endl;
    if(nx != ny) {
        throw std::invalid_argument("Two vectors are not of the same length!");
    }
    double dist=0;
    for(int i = 0; i < nx; i++) {
        dist += pow(x[i] - y[i], 2);
    }
    return sqrt(dist);
}

用于G 使用-g启用调试选项:

g++ -g code.cpp

或视觉工作室中的调试模式。