Override bad_alloc Exception - exception

I am trying to change the message for bad_alloc.
#include <iostream>
#include <iomanip>
#include <stdexcept>
using std::logic_error;
using std::bad_alloc;
class OutOfRange : public logic_error {
public:
OutOfRange(): logic_error("Bad pointer") {}
};
class OutOfMem : public bad_alloc {
public:
OutOfMem(): bad_alloc("not enough memory") {}
};
OutOfRange() works fine, but OutOfMem sends me an error:
No matching function for call to std::bad_alloc::bad_alloc(const char[21])

The compile error is telling you that that bad_alloc constructor does not take a char *.
e.g. See here
Instead, note that exception what method is vritual and use that instead.
class OutOfMem : public bad_alloc {
public:
OutOfMem() {}
const char *what() const {
return "not enough memory";
}
};
Edit: note you might have to state it doesn't throw as follows:
//... as before
virtual const char * what() const throw () {
return "not enough memory";
}
// as before ...

Related

how to do template class constructors as forward declaration

I am migrating my code from c++17 to c++20 and need to use require instead of std::enable_if...
How to define class constructors as forward declaration with c++20 that uses require keyword on following sample ?
#include <type_traits>
class CChMyBaseClass {
};
template <
typename _ChClass,
typename _ChFunction>
class CChMyClass : public CChMyBaseClass {
private:
_ChFunction m_ChFunction;
public:
// how to do forward declaration ?
CChMyClass()
requires (std::is_member_function_pointer<_ChFunction>::value)
: CChMyBaseClass() {
}
// how to do forward declaration ?
CChMyClass()
requires (!std::is_member_function_pointer<_ChFunction>::value)
: CChMyBaseClass()
, m_ChFunction(
nullptr) {
}
};
class CChTestClass {
public:
void ChTest() {
}
};
void ChTest() {
}
int main() {
CChMyClass<CChTestClass, decltype(&CChTestClass::ChTest)> CChMyClass1();
CChMyClass<CChTestClass, decltype(&ChTest)> CChMyClass2();
return 0;
}
It's really not different from any other type of forward declaration. Just write:
template <typename _ChClass, typename _ChFunction>
class CChMyClass: public CChMyBaseClass {
...
CChMyClass() requires (std::is_member_function_pointer<_ChFunction>::value);
CChMyClass() requires (!std::is_member_function_pointer<_ChFunction>::value);
...
};
I think the difficulty is rather in the actual function definitions. But even that is not too difficult if you think about it. You just need to include the template parameters and the requires clause again:
template <typename _ChClass, typename _ChFunction>
CChMyClass<_ChClass, _ChFunction>::CChMyClass()
requires (std::is_member_function_pointer<_ChFunction>::value)
: CChMyBaseClass(), m_ChFunction(...) {
...
};
Note that in your example, you did not declare two instances of CChMyClass in main(), but rather forward declared two functions that had a CChMyClass as a return type (this is known as the most vexing parse). Just omit the () at the end, or use braces instead.

How to get the underlying vector of an IVector<IInspectable>

I want to use a function that requires me to pass to it as a parameter a void pointer to beginning of a block of memory. The data has to be contiguous in memory for this function to work correctly.
Right now my data is stored in a IVector<IInspectable>. Looking at the memory layout of this IVector in the debugger I see that there is 28 bytes between my data. Which I think are the 7 function pointers from IUnknown and IInspectable. How can I get the underlying contiguous memory allocation of my data?
UPDATE:
Here is the solution I came up with.
Instead of using the IVector<IInspectable> I created a custom vector using the winrt::vector_base as recommended here: https://learn.microsoft.com/en-us/windows/uwp/cpp-and-winrt-apis/collections
and I wrapped it in a windows runtime component so that I can use this custom vector from C#.
It looks like this:
MyVector.idl
namespace RuntimeComponent1
{
[default_interface]
runtimeclass MyVector
{
MyVector();
void Append(IInspectable in_val);
}
}
MyVector.h
// MyVector.h
#pragma once
#include "MyVector.g.h"
namespace winrt::RuntimeComponent1::implementation
{
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Foundation::Collections;
struct _MyVector :
implements<_MyVector, IVector<int>, IVectorView<int>, IIterable<int>>,
winrt::vector_base<_MyVector, int>
{
auto& get_container() const noexcept
{
return m_values;
}
auto& get_container() noexcept
{
return m_values;
}
private:
std::vector<int> m_values{};
};
struct MyVector : MyVectorT<MyVector, _MyVector>
{
MyVector() = default;
void Append(Windows::Foundation::IInspectable const& in_val);
};
}
namespace winrt::RuntimeComponent1::factory_implementation
{
struct MyVector : MyVectorT<MyVector, implementation::MyVector>
{
};
}
MyVector.cpp
#include "pch.h"
#include "MyVector.h"
using namespace winrt;
namespace winrt::RuntimeComponent1::implementation
{
void MyVector::Append(Windows::Foundation::IInspectable const& in_val)
{
base_type::Append(winrt::unbox_value<int>(in_val));
}
}
Example usage:
C#
MyRuntimeComponent.MyVector my_vec = new RuntimeComponent1.MyVector();
my_vec.Append(2);
my_vec.Append(4);
MyRuntimeComponent.MyControl my_control = new RuntimeComponent0.MyControl();
my_control.do_stuff_with_contiguous_memory(my_vec);
C++
void MyControl::do_stuff_with_contiguous_memory(RuntimeComponent1::MyVector const& in_data)
{
// Yay data is contiguous
auto contiguous_data = in_data.as<MyVector>()->get_container().data();
}
The end result is that I can pass data from C# to C++/WinRT and the data will be contiguous in C++, which fixes my original problem. It works but I wonder if there might be a simpler / better way?

Refering within the class to constructor with the this pointer

#include "stdafx.h"
ref class station{
public:
station(){
};
void wrapper_1()
{
this->somefunct(); /*happy*/
};
void wrapper_2()
{
this->station(); /*not happy*/
};
void somefunct(){
System::Console::WriteLine(L"abcde");
};
};
int main(array<System::String^>^ args)
{
station^ temp_1 = gcnew station();
temp_1->wrapper_1();
System::Console::ReadLine();
};
I want to use the this pointer to call my constructor within my station class, it doesn't like this and throws the following error:
error C2273: 'function-style cast' : illegal as right side of '->'
operator.
Can someone explain to me how the constructor differs to other functions when using the pointer this to point to the function. I don't want to take the easy way out using station::station();
example of what I meant to #hans-passant
#include "stdafx.h"
ref class station{
public:
station(int par_1,int par_2)
{
int sum = par_1 + par_2;
System::Console::WriteLine(System::Convert::ToString(sum));
//default value output 13
};
station(){
int pass_1 = 5;
int pass_2 = 8;
station(pass_1,pass_2); /* But why couldn't I use this->station(pass_1,pass_2);*/
};
};
int main(array<System::String^>^ args)
{
station^ obj = gcnew station();
System::Console::ReadLine();
};

How should memory be freed after an exception is thrown in C++?

I apologize if this question is a duplicate - I searched for a while, but it's possible that my Google-fu just isn't up to snuff.
I am modifying a C++ program that calls into a C library. The C library allocates a bunch of memory (using malloc()), and the C++ program uses it and then frees it. The catch is that the C++ program can throw an exception midway through execution, causing the allocated memory to never be freed.
As a (rather contrived) example:
/* old_library.c */
char *allocate_lots() {
char *mem = (char *)malloc(1024);
return mem;
}
/* my_prog.cpp */
void my_class::my_func () {
char *mem = allocate_lots();
bool problem = use(mem);
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
free(mem); // Never gets called if problem is true
}
My question is: how ought I to deal with this? My first idea was to wrap the whole thing in a try/catch block, and in the catch just check and free the memory and re-throw the exception, but this seems graceless and clunky to me (and wouldn't work well if I want to actually catch an exception). Is there a better way to do it?
EDIT: I probably should have mentioned that we're using g++ 4.2.2, from back in 2007 before std::unique_ptr was introduced. Chalk it up to corporate inertia.
Use std::unique_ptr with a custom deleter that calls free:
class free_mem {
public:
void operator()(char *mem) { free(mem); }
};
void my_class::my_func() {
std::unique_ptr<char, free_mem> mem = allocate_lots();
You should make sure that you don't throw until after you have freed the memory - or that you use a suitable smart pointer structure to store the mem, such that when the throw happens, and the stack unwinds, the mem gets freed.
Wrap that rascal:
struct malloc_deleter {
template <typename T>
void operator () (T* p) const {
free(p);
}
};
void my_class::my_func () {
std::unique_ptr<char[],malloc_deleter> mem{allocate_lots()};
bool problem = use(mem.get());
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Since you're using an old compiler version that doesn't have unique_ptr, you can write your RAII wrapper yourself:
class ResourceWrapper {
public:
ResourceWrapper(char* ptr) : m_ptr(ptr) {}
~ResourceWrapper() { free(m_ptr); }
// whatever getters suit you, at the very least:
char* get() const { return m_ptr; }
private:
char* const m_ptr;
};
void my_class::my_func () {
ResourceWrapper mem(allocate_lots());
bool problem = use(mem.get());
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Just make sure not to allow copy/assignment even implicitly (which is why I made m_ptr const) or you'd risk ending up with double-freeing your memory ("move" semantics à la auto_ptr are best avoided unless you absolutely need it).
Since you can't use std::unique_ptr, you could create your own deleter class that would control the lifetime of the pointer in RAII fashion. To keep it simple this example doesn't wrap the actual pointer but exists alongside it; a safer approach would be to make a true smart pointer class.
class AutoFree
{
public:
AutoFree(void* p) : m_p(p)
{
}
~AutoFree()
{
free(m_p);
}
private:
void* m_p;
};
void my_class::my_func () {
char *mem = allocate_lots();
AutoFree mem_free(mem);
bool problem = use(mem);
if (problem)
throw my_exception("Oh noes! This will be caught higher up");
}
Is there any reason not to simply free the memory inside the if clause?
if (problem) {
free (mem);
throw my_exception ("Drat!");
}
Use unique_ptr: http://coliru.stacked-crooked.com/view?id=cd3f0fc64d99cc07a2350e2ff9686500-542192d2d8aca3c820c7acc656fa0c68
#include <stdexcept>
#include <iostream>
#include <memory>
/* old_library.c */
char *allocate_lots()
{
return static_cast<char*>(malloc(1024));
}
struct my_exception : virtual std::exception {
const char* const msg;
my_exception(const char* const msg) : msg(msg) {}
const char* what() const noexcept { return msg; }
};
struct my_class
{
struct Free { void operator() (char* p) const { free(p); } };
/* my_prog.cpp */
void my_func()
{
std::unique_ptr<char, Free> mem;
mem.reset(allocate_lots());
bool problem = use(mem.get());
if(problem)
{
throw my_exception("Oh noes! This will be caught higher up");
}
}
static bool use(char*) { return true; }
};
int main()
{
my_class prog;
prog.my_func();
}

Implementing a good C++0x error_condition?

I try to figure out how the new system_error together with error_code, error_category and not the least the (meant to implement portable error reporting) error_condition should be used.
I think by reading boost.system I understand how I should use error_codes and error_category. The description leaves out how this is used in conjunction when throwing an exception with ´system_error`, but from the interface from that class I can guess.
class system_error : public runtime_error {
public:
// [...]
system_error(error_code ec, const string& what_arg);
system_error(int ev, const error_category& ecat, const string& what_arg);
system_error(int ev, const error_category& ecat);
// [...]
So, I throw a system_error-exception with the right int+error_category or error_code with its error_category()-method.
But whats the way to provide the portable interface with error_condition?
Both error_code and error_category both have method default_error_condition:
class error_category {
public:
// [...]
virtual error_condition default_error_condition(int ev) const noexcept;
// [...]
class error_code {
public:
// [...]
error_condition default_error_condition(int ev) const noexcept;
// [...]
The error_category-Instances should be pre-created, for example (user-code):
struct AppCategory : public error_category {
const char *name() const noexcept override {
return "application"; }
string message(int ev) const override {
switch(ev) {
case 14: return "error message";
default: return "???";
}
}
error_condition default_error_condition(int ev) const noexcept override {
... ??? ...
}
};
My questions implementing this:
Should I implement default_error_condition in error_category, and how?
Or how do I connect error_codes to the proper error_conditions,
and should I pre-construct error_condition instances?
A class error_code is not supposed to be provided by the user (me), right?
Is there a good example where I can take a look at code how error_condition is supposed to be extended by the user, in conjunction with system_error-exceptions?
If the error codes for your error category can be mapped to one of the std::errc error codes then default_error_condition should do that mapping, and return a std::error_condition with a category of std::generic_category() and a value of the corresponding std::errc enum value. Otherwise it should return an error_condition referring to that category.