Why does assert not work here?

我怕爱的太早我们不能终老 提交于 2019-11-30 04:59:23

问题


Here is the code:

#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);
}

After sourcing it into R, I get the following result, apparently it does not abort when there is an error:

#////////////////////////////////////////////////////
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

回答1:


Note that assert() etc are explicitly prohibited for CRAN uploads. Quoting from the CRAN Repo Policy page:

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().

So the answer about debug mode is technically correct, but also note that you are not supposed to use this if you plan to upload CRAN at some point.




回答2:


The problem is solved by using throw instead of assert, Rcpp will actually put things in a proper try-catch block, which is super nice.

#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);
}



回答3:


For g++ use -g to enable debug options:

g++ -g code.cpp

Or debug mode in Visual Studio.



来源:https://stackoverflow.com/questions/21409237/why-does-assert-not-work-here

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!