c++ - 为什么断言在这里不起作用?

标签 c++ r rcpp

代码如下:

#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 Policy页:

The code and examples provided in a package should never do anything which might be regarded as malicious or anti-social. The following are illustrative examples from past experience.

  • Compiled code should never terminate the R process within which it is running. Thus C/C++ calls to assert/abort/exit, Fortran calls to STOP and so on must be avoided. Nor may R code call q().

所以关于 Debug模式的答案在技术上是正确的,但也请注意,如果您计划在某个时候上传 CRAN,则不应该使用它。

关于c++ - 为什么断言在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409237/

相关文章:

c++ - 从 C++ 中的基类继承复制/移动构造函数作为构造函数

r - Shiny -点击刷新后如何记住用户输入?

c++ - 在 Mac OS X 10.10 上安装 Ingres 数据库

r - ggplot 指数平滑,在 exp 内调整参数

r - 是否可以评估指数的分数与指数之和

c++ - 如何将 OpenBlas Lapacke 与 Rcpp 一起使用

r - 是否允许/可能在 Rcpp 中的 pragma openmp parallel for 循环中调用 R 函数或 fortran 代码?

Rcpp 检查列表是否有一个元素

c++ - 为什么 (1/2)*x 不同于 0.5*x?

c++ - 与 View 一起使用的自定义容器类型的要求