I'm actually very new to c++. I tried to write a function template, passing a parameter as reference.
While doing so I got a std::bad_alloc. So I also tried to pass it as value and even by pointer. I always got a std::bad_alloc, but I'm very sure, the object exists and the adress is correct (checked it with debugger).
My last try was to create the object right in the function. It works, if I use hard-coded data, but not if I pass the data, needed to create the object, as function parameter.
I'm using a specific framework for numeric simulation (http://www.dune-project.org/), so I'm not sure, if example code is helpfull. I just contacted the framework support and they had no idea, where this problem comes from.
I hope anyone could help me or has an idea, how to fix this/work arround!
code example:
template<const int dim, const int k>
int solvePoissonPDE2(int maxlevel, Dune::YaspGrid<dim>& grid)
{
/*
* Debugging Notes:
* function works, if grid, fieldvector, array AND bitset are created inside the function
* BUT NOT if grid OR the components used to create a grid are passed as reference, value or pointer parameters (SEGMENTATION FAULT)
*/
try {
/*// make grid
Dune::FieldVector<double, dim> L(1.0);
Dune::array<int, dim> N(Dune::fill_array<int, dim>(1));
std::bitset<dim> B(false);
Dune::YaspGrid<dim> grid(L, N, B, 0);*/
grid.globalRefine(maxlevel - 1);
// get view
using GV = typename Dune::YaspGrid<dim>::LeafGridView;
const GV &gv = grid.leafGridView();
const int q = 2 * k;
// make finite element map
using DF = typename GV::Grid::ctype;
using FEM = Dune::PDELab::QkLocalFiniteElementMap<GV, DF, double, k>;
FEM fem(gv);
BCTypeParam bctype;
// solve problem
using Constraints = Dune::PDELab::ConformingDirichletConstraints;
poisson_driver<GV, FEM, BCTypeParam, Constraints>(gv, fem, "poisson_yasp", bctype, false, q);
return 0;
}
catch (Dune::Exception &e){
std::cerr << "Dune reported error: " << e << std::endl;
return false;
}
catch (std::string &e){
std::cerr << "An error has been detected: " << e << std::endl;
return false;
}
catch (std::exception &e){
std::cerr << "STL reported error: " << e.what() << std::endl;
}
catch (...){
std::cerr << "Unknown exception thrown!" << std::endl;
return false;
}
}
all used functions are working and are tested.
Related
My following code runs into error if I comment out the first line in the constructor. The return error is:
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
However, it is weird that if I output something (e.g., uncomment the first line) in the constructor, then my program works fine.
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);
}
You are storing an address of a temporary that goes out of scope. Using *kernel after what it points to goes out of scope is undefined behavior.
kernel should be of type std::unique_ptr<X> instead of type X*.
Replace assignment with:
kernel = std::make_unique<Kernel_Matern>(param, param.size());
or:
kernel = std::make_unique<Kernel_SE>(param, param.size());
at the two lines in question.
If you have code where you pass kernel to a function, instead pass kernel.get().
Note that is blocks copying instances of GP but not moving them, as unique ptr is move-only. If you have a type that stores both values and pointers into its own values, copying it is probably a bug anyhow.
In C++, I'm trying to write a function with function pointers. I want to be able to throw an exception if a function pointer is passed for a function that does not exist. I tried to handle the function pointer like a normal pointer and check if it is null
#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (funcPtr != NULL) {
return funcPtr(x);
} else {
throw "not a valid function pointer";
}
}
int main(int argc, char** argv) {
try {
int x = 5;
cout << "add_1 result is " << add_1(x) << endl;
cout << "foo add_1 result is " << foo(x, add_1) << endl;
cout << "foo add_2 result is " << foo(x, add_2) << endl; //should produce an error
}
catch (const char* strException) {
cerr << "Error: " << strException << endl;
}
catch (...) {
cerr << "We caught an exception of an undetermined type" << endl;
}
return 0;
}
but that doesn't seem to work. What is the best way to do this?
Checking for NULL is ok. But it is not possible to pass a pointer to a function that does not exist in the first place. So you don't have to worry about this. Although it is possible to just declare a function without defining it and pass the address of it. In that case you will get linker error.
It will automatically throw an error if you are passing pointer which does not exist, if you are declaring a pointer then you have to initialize it with null to avoid garbage value, so comparing with null will not serve any purpose.
you still you want to check then try to assign some function(like add, sub etc.), if it takes then ok , if not then it will show again error as previously mentioned.
#include<cstddef>
#include <iostream>
using namespace std;
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (*funcPtr != NULL) {
return funcPtr(x);
}
else
{
cout << "not a valid function pointer";
}
}
If you want to 'throw' exception then you need to 'catch' it as well.
Your code is failing because of two reasons in short,
1) You are not checking value of function pointer.
2) You are not properly catching the thrown exception.
I'd like to simulate a std::vector that has mixed const and non-const elements. More specifically, I want to have functions that operate on a vector and are allowed to see the entire vector but may only write to specific elements. The elements that can and cannot be written will be determined at runtime and may change during runtime.
One solution is to create a container that holds an array of elements and an equal sized array of booleans. All non-const access would be through a function that checks against the boolean array if the write is valid and throws an exception otherwise. This has the downside of adding a conditional to every write.
A second solution might be to have the same container but this time write access is done by passing an array editing function to a member function of the container. The container member function would let the array editing function go at the array and then check that it didn't write to the non-writable elements. This has the downside that the array editing function could be sneaky and pass around non-const pointers to the array elements, let the container function check that all is well, and then write to non-writable elements.
The last issue seems difficult to solve. It seems like offering direct writable access ever means we have to assume direct writable access always.
Are there better solutions?
EDIT: Ben's comment has a good point I should have addressed in the question: why not a vector of const and a vector of non-const?
The issue is that the scenario I have in mind is that we have elements that are conceptually part of one single array. Their placement in that array is meaningful. To use vectors of const and non-const requires mapping the single array that exist in concept to the two vectors that would implement it. Also, if the list of writable elements changes then the elements or pointers in the two vectors would need to be moved about.
I think you can accomplish what you wish with the following class, which is very simplified to illustrate the main concept.
template <typename T>
struct Container
{
void push_back(bool isconst, T const& item)
{
data.push_back(std::make_pair(isconst, item));
}
T& at(size_t index)
{
// Check whether the object at the index is const.
if ( data[index].first )
{
throw std::runtime_error("Trying to access a const-member");
}
return data[index].second;
}
T const& at(size_t index) const
{
return data[index].second;
}
T const& at(size_t index, int dummy) // Without dummy, can't differentiate
// between the two functions.
{
return data[index].second;
}
T const& at(size_t index, int dummy) const // Without dummy, can't differentiate
// between the two functions.
{
return data[index].second;
}
std::vector<std::pair<bool, T> > data;
};
Here's a test program and its output.
#include <stdio.h>
#include <iostream>
#include <utility>
#include <stdexcept>
#include <vector>
//--------------------------------
// Put the class definition here.
//--------------------------------
int main()
{
Container<int> c;
c.push_back(true, 10);
c.push_back(false, 20);
try
{
int value = c.at(0); // Show throw exception.
}
catch (...)
{
std::cout << "Expected to see this.\n";
}
int value = c.at(0, 1); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = c.at(1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
value = c.at(1, 1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
// Accessing the data through a const object.
// All functions should work since they are returning
// const&.
Container<int> const& cref = c;
value = cref.at(0); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = cref.at(0, 1); // Should work.
std::cout << "Got c[0]: " << value << "\n";
value = cref.at(1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
value = cref.at(1, 1); // Should work.
std::cout << "Got c[1]: " << value << "\n";
// Changing values ... should only work for '1'
try
{
c.at(0) = 100; // Show throw exception.
}
catch (...)
{
std::cout << "Expected to see this.\n";
}
c.at(1) = 200; // Should work.
std::cout << "Got c[1]: " << c.at(1) << "\n";
}
Output from running the program:
Expected to see this.
Got c[0]: 10
Got c[1]: 20
Got c[1]: 20
Got c[0]: 10
Got c[0]: 10
Got c[1]: 20
Got c[1]: 20
Expected to see this.
Got c[1]: 200
So I have an upcoming assignment dealing with exceptions and using them in my current address book program that most of the homework is centered around. I decided to play around with exceptions and the whole try catch thing, and using a class design, which is what I will eventually have to do for my assignment in a couple of weeks. I have working code that check the exception just fine, but what I want to know, is if there is a way to standardize my error message function, (i.e my what() call):
Here s my code:
#include <iostream>
#include <exception>
using namespace std;
class testException: public exception
{
public:
virtual const char* what() const throw() // my call to the std exception class function (doesn't nessasarily have to be virtual).
{
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
void noZero();
}myex; //<-this is just a lazy way to create an object
int main()
{
void noZero();
int a, b;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
myex.noZero(b); // trys my exception from my class to see if there is an issue
}
catch(testException &te) // if the error is true, then this calls up the eror message and restarts the progrm from the start.
{
cout << te.what() << endl;
return main();
}
cout <<endl;
cout << "The two numbers divided are " << (a / b) << endl; // if no errors are found, then the calculation is performed and the program exits.
return 0;
}
void testException::noZero(int &b) //my function that tests what I want to check
{
if(b == 0 ) throw myex; // only need to see if the problem exists, if it does, I throw my exception object, if it doesn't I just move onto the regular code.
}
What I would like to be able to do is make it so my what() function can return a value dependent on what type of error is being called on. So for instance, if I were calling up an error that looked a the top number,(a), to see if it was a zero, and if it was, it would then set the message to say that "you can't have a numerator of zero", but still be inside the what() function. Here's an example:
virtual const char* what() const throw()
if(myex == 1)
{
return "You can't have a 0 for the numerator! Error code # 1 "
}
else
return "You can't divide by zero! Error code number 0, restarting the calculator..."; // my error message
}
This obviously wouldn't work, but is there a way to make it so I'm not writing a different function for each error message?
Your code contains a lot of misconceptions. The short answer is yes, you can change what() in order to return whatever you want. But let's go step by step.
#include <iostream>
#include <exception>
#include <stdexcept>
#include <sstream>
using namespace std;
class DivideByZeroException: public runtime_error {
public:
DivideByZeroException(int x, int y)
: runtime_error( "division by zero" ), numerator( x ), denominator( y )
{}
virtual const char* what() const throw()
{
cnvt.str( "" );
cnvt << runtime_error::what() << ": " << getNumerator()
<< " / " << getDenominator();
return cnvt.str().c_str();
}
int getNumerator() const
{ return numerator; }
int getDenominator() const
{ return denominator; }
template<typename T>
static T divide(const T& n1, const T& n2)
{
if ( n2 == T( 0 ) ) {
throw DivideByZeroException( n1, n2 );
}
return ( n1 / n2 );
}
private:
int numerator;
int denominator;
static ostringstream cnvt;
};
ostringstream DivideByZeroException::cnvt;
In the first place, runtime_error, derived from exception, is the adviced exception class to derive from. This is declared in the stdexcept header. You only have to initialize its constructor with the message you are going to return in the what() method.
Secondly, you should appropriately name your classes. I understand this is just a test, but a descriptive name will always help to read and understand your code.
As you can see, I've changed the constructor in order to accept the numbers to divide that provoked the exception. You did the test in the exception... well, I've respected this, but as a static function which can be invoked from the outside.
And finally, the what() method. Since we are dividing two numbers, it would be nice to show that two numbers that provoked the exception. The only way to achieve that is the use of ostringstream. Here we make it static so there is no problem of returning a pointer to a stack object (i.e., having cnvt a local variable would introduce undefined behaviour).
The rest of the program is more or less as you listed it in your question:
int main()
{
int a, b, result;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
result = DivideByZeroException::divide( a, b );
cout << "\nThe two numbers divided are " << result << endl;
}
catch(const DivideByZeroException &e)
{
cout << e.what() << endl;
}
return 0;
}
As you can see, I've removed your return main() instruction. It does not make sense, since you cannot call main() recursively. Also, the objective of that is a mistake: you'd expect to retry the operation that provoked the exception, but this is not possible, since exceptions are not reentrant. You can, however, change the source code a little bit, to achieve the same effect:
int main()
{
int a, b, result;
bool error;
do {
error = false;
cout << endl;
cout << "Enter a number to be divided " << endl;
cout << endl;
cin >> a;
cout << endl;
cout << "You entered " << a << " , Now give me a number to divide by " << endl;
cin >> b;
try
{
result = DivideByZeroException::divide( a, b ); // trys my exception from my class to see if there is an issue
cout << "\nThe two numbers divided are " << result << endl;
}
catch(const DivideByZeroException &e) // if the error is true, then this calls up the eror message and restarts the progrm from the start.
{
cout << e.what() << endl;
error = true;
}
} while( error );
return 0;
}
As you can see, in case of an error the execution follows until a "proper" division is entered.
Hope this helps.
You can create your own exception class for length error like this
class MyException : public std::length_error{
public:
MyException(const int &n):std::length_error(to_string(n)){}
};
class zeroNumerator: public std::exception
{
const char* what() const throw() { return "Numerator can't be 0.\n"; }
};
//...
try
{
myex.noZero(b); // trys my exception from my class to see if there is an issue
if(myex==1)
{
throw zeroNumerator(); // This would be a class that you create saying that you can't have 0 on the numerator
}
}
catch(testException &te)
{
cout << te.what() << endl;
return main();
}
You should always use std::exception&e. so do
catch(std::exception & e)
{
cout<<e.what();
}
You should consider a hierarchy of classes.
The reason for it might not be obvious when trying to use exceptions just for transferring a string, but actual intent of using exceptions should be a mechanism for advanced handling of exceptional situations. A lot of things are being done under the hood of C++ runtime environment while call stack is unwound when traveling from 'throw' to corresponded 'catch'.
An example of the classes could be:
class CalculationError : public std::runtime_error {
public:
CalculationError(const char * message)
:runtime_error(message)
{
}
};
class ZeroDeviderError : public CalculationError {
public:
ZeroDeviderError(int numerator, const char * message)
: CalculationError(message)
, numerator (numerator)
{
}
int GetNumerator() const { return numerator; }
private:
const int numerator;
};
Providing different classes for the errors, you give developers a chance to handle different errors in particular ways (not just display an error message)
Providing a base class for the types of error, allows developers to be more flexible - be as specific as they need.
In some cases, they might want to be specific
} catch (const ZeroDividerError & ex) {
// ...
}
in others, not
} catch (const CalculationError & ex) {
// ...
}
Some additional details:
You should not create objects of your exceptions before throwing in the manner you did. Regardless your intention, it is just useless - anyway, you are working with a copy of the object in the catch section (don't be confused by access via reference - another instance of the exception object is created when throwing)
Using a const reference would be a good style catch (const testException &te) unless you really need a non-constant object.
Also, please note that the type (classes) used for exceptions are not permitted to throw exceptions out of their copy constructors since, if the initial exception is attempted to be caught by value, a call of copy constructor is possible (in case is not elided by the compiler) and this additional exception will interrupt the initial exception handling before the initial exception is caught, which causes calling std::terminate.
Since C++11 compilers are permitted to eliminate the copying in some cases when catching, but both the elision is not always sensible and, if sensible, it is only permission but not obligation (see https://en.cppreference.com/w/cpp/language/copy_elision for details; before C++11 the standards of the language didn’t regulate the matter).
Also, you should avoid exceptions (will call them the additional) to be thrown out of constructors and move constructors of your types (classes) used for exceptions (will call them initial) since the constructors and move constructors could be called when throwing objects of the types as initial exceptions, then throwing out an additional exception would prevent creation of an initial exception object, and the initial would just be lost. As well as an additional exception from a copy constructor, when throwing an initial one, would cause the same.
Suppose I have the following function:
void myFunc(P& first, P& last) {
std::cout << first.child.grandchild[2] << endl;
// ...
}
Now, let's assume that first.child.grandchild[2] is too long for my purposes. For example, suppose it will appear frequently in equations inside myFunc(P&,P&). So, I'd like to create some sort of symbolic reference inside the function so that my equations would be less messy. How could I do this?
In particular, consider the code below. I need to know what statement I could insert so that not only would the output from line_1a always be the same as the output from line_1b, but also so that the output from line_2a would always be the same as the output from line_2b. In other words, I don't want a copy of the value of first.child.grandchild, but a reference or symbolic link to the object first.child.grandchild.
void myFunc(P& first, P& last) {
// INSERT STATEMENT HERE TO DEFINE "g"
std::cout << first.child.grandchild[2] << endl; // line_1a
std::cout << g[2] << endl; // line_1b
g[4] = X; // where X is an in-scope object of matching type
std::cout << first.child.grandchild[4] << endl; // line_2a
std::cout << g[4] << endl; // line_2b
//...
}
Say that the type of grandchild is T and size is N; then below is the way to create a reference for an array.
void myFunc(P& first, P& last) {
T (&g)[N] = first.child.grandchild;
...
}
I would not prefer pointer here, though it's also a possible way. Because, the static size of array is helpful to a static analyzer for range checking.
If you are using C++11 compiler then auto is the best way (mentioned by #SethCarnegie already):
auto &g = first.child.grandchild;
Use a pointer - then you can change it in the function.
WhateverGrandchildIs *ptr=&first.child.grandchild[2];
std::cout << *ptr << std::endl;
ptr=&first.child.grandchild[4];
std::cout << *ptr << std::endl;