2014-01-28 3 views
5

여기에 코드입니다 : 오류가있는 경우 R로를 소스로 사용한 후여기서 어설 션이 작동하지 않는 이유는 무엇입니까?

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

, 나는 다음과 같은 결과를 얻을, 분명히 그것은 중단하지 않습니다에 -g 사용 ++ g를 들어

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

어떻게 컴파일하나요? 'NDEBUG'를 정의하면'assert'가 전 처리기에 의해 제거됩니다; 아마 그 일이 일어날거야. –

+0

'throw()'로 전환하기위한 세 가지 환호와 upvote, –

+2

아, 그리고 stickler가되기 위해서 : R 's I/O 버퍼에 쓰려면'std :: cout' 대신'Rcpp :: Rcout'을 사용하십시오. –

답변

4

CRAN 업로드에는 assert() 등이 명시 적으로 금지되어 있습니다. 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() .

것은 그래서 디버그 모드에 대한 대답은 기술적으로 정확하지만, 또한 당신은 당신이 어떤 점에서 CRAN을 업로드하려면이를 사용하기로되지 않습니다.

0

디버그 옵션 사용 :

g++ -g code.cpp 

또는 Visual Studio의 디버그 모드.

3

assert 대신 throw을 사용하면 문제가 해결되며, 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); 
} 
관련 문제