Assume I'm writing a shared library and trying to make sure that the interface functions never throw. I have my own exception type that I throw, but since I'm using STL a lot I need to avoid any exceptions from there too. So, if I am lazy and don't want to have an additional catch(const std::exception&) {} block in each interface function, is it possible to derive my exception type from std::exception so that when an std::exception is thrown a constructor of my exception type is invoked with the original exception and then I could have a single catch handler with my exception type.
Ideally I would like something similar to this snippet (which obviously doesn't work), but maybe there are other techniques which I'm not seeing:
#include <iostream>
#include <stdexcept>
class derived_exception : public std::exception
{
public:
derived_exception(const std::exception& exception)
{
}
};
int main(int argc, char** argv)
{
try
{
throw std::exception("test");
}
catch (const derived_exception& exception)
{
std::cout << exception.what();
}
return 0;
}
Related
__event T e(args);
On line 9, VS gives me green squigglies under 'e' with the warning: Function definition for 'e' not found.
On compile/build, it throws the C1001 internal error occurred in the compiler (line 9 again).
I've tried renaming the variable, tried removing the template and just working with normal types, tried making it public.
If anyone can help it would be greatly appreciated, thank you.
(Whole code probably not necessary but just to give an idea what I'm going for)
#include <cstdarg>
#include <functional>
#include <iostream>
template <typename T, typename ... args>
[event_source(native)]
class Action {
private:
__event T e(args);
public:
~Action() {
__unhook(this);
};
void operator +=(std::function<T(args...)> f) {
__hook(e, this, &f);
}
void operator -=(std::function<T(args...)> f) {
__unhook(e, this, &f);
}
void operator()(args...) {
__raise e(args);
}
};
void print(const char* s) {
std::cout << s << std::endl;
}
int main() {
Action<void, const char*> printAction;
printAction += print;
printAction("Print a string.");
printAction -= print;
}
I was reading the following post:
What changes introduced in C++14 can potentially break a program written in C++11?
and also the isocpp page:
https://isocpp.org/files/papers/p0636r0.html
So I became curious, according to the Standard: What changes introduced in C++11 can potentially break a program written in C++98?
Big one that stands out -- throwing exceptions from destructors.
In C++98 you can have programs that do this and work fine if you are careful.
In C++11 you will often have to explicitly declare the dtor noexcept(false).
Nice blog post here, on Andrzej's C++ blog.
In short, the following program used to run successfully in C++03 (under some definition of “success”):
struct S
{
~S() { throw runtime_error(""); } // bad, but acceptable
};
int main()
{
try { S s; }
catch (...) {
cerr << "exception occurred";
}
cout << "success";
}
In C++11, the same program will trigger the call to std::terminate.
Here is another case related to destructors are noexcept(true) in C++11:
// A simple program that demonstrates how C++11 and pthread_cancel don't play
// nicely together.
//
// If you build without C++11 support (g++ threadkill.cpp -lpthread), the
// application will work as expected. After 5 seconds, main() will cancel the
// thread it created and the program will successfully exit.
//
// If you build with C++11 support(g++ -std=c++11 threadkill.cpp -lpthread),
// the program will crash because the abi::__forced_unwind exception will
// escape the destructor, which is implicitly marked as noexcept(true) in
// C++11. If you mark the destructor as noexcept(false), the program does
// not crash.
#include <iostream>
#include <unistd.h>
#include <string.h>
class sleepyDestructorObject
{
public:
~sleepyDestructorObject() //noexcept(false)
{
std::cout << "sleepy destructor invoked" << std::endl;
while(true)
{
std::cout << "." << std::flush;
sleep(1);
}
}
};
void* threadFunc( void* lpParam )
{
sleepyDestructorObject sleepy;
return NULL;
}
int main(int argc, char** argv)
{
pthread_t tThreadID;
pthread_create(&tThreadID, NULL, threadFunc, NULL);
sleep(5);
pthread_cancel(tThreadID);
pthread_join(tThreadID, NULL);
return 0;
}
Original reference:
https://gcc.gnu.org/ml/gcc-help/2015-08/msg00036.html
I'm coming from C# and trying to implement a simple Events/EventHandler pattern in c++11 which i believe the common name is Observers and signals, i know there are boost library and others but i dont want to use any external libs.
While searching online I found a simple implementation for what I need, so I took and modified the code and it works ok.
My problem is that the parameters are passed when registering events/observers, and not when raising/signaling/notifying which I find a bit awkward.
class EventManager
{
private:
static std::map<EventType, std::vector<std::function<void()>>> _eventHandlers;
public:
EventManager() = default;
template <typename EventHandler>
static void RegisterEventHandler(EventType&& eventType, EventHandler&& eventHandler)
{
EventManager::_eventHandlers[std::move(eventType)].push_back(std::forward<EventHandler>(eventHandler));
}
static void Raise(const EventType& event)
{
for (const auto& eventHandler : EventManager::_eventHandlers.at(event))
{
eventHandler();
}
}
// disallow copying and assigning
EventManager(const EventManager&) = delete;
EventManager& operator=(const EventManager&) = delete;
};
Can anyone help me to extend the following code by adding the functionality to accept parameters when raising the event as well ?
I believe this solves your question:
// g++ -std=c++11 -o /tmp/events /tmp/events.cpp && /tmp/events
// handler=1 arg=1
// handler=2 arg=1
// handler=1 arg=2
// handler=2 arg=2
#include <functional>
#include <map>
#include <vector>
template<class EventType, class... HandlerArgs>
class EventManager
{
public:
using EventHandler = std::function< void(HandlerArgs...) >;
void register_event(EventType&& event, EventHandler&& handler)
{
_handlers[std::move(event)].push_back(std::forward<EventHandler>(handler));
}
void raise_event(const EventType& event, HandlerArgs&&... args)
{
for (const auto& handler: EventManager::_handlers.at(event)) {
handler(std::forward<HandlerArgs>(args)...);
}
}
private:
std::map<EventType, std::vector<EventHandler>> _handlers;
};
int main(int argc, char **argv)
{
EventManager<int, int> m;
m.register_event(1, [](int arg) { printf("handler=%d arg=%d\n", 1, arg); });
m.register_event(1, [](int arg) { printf("handler=%d arg=%d\n", 2, arg); });
m.raise_event(1, 1);
m.raise_event(1, 2);
}
PS: I removed all the code regarding non-copiability and such, since it is not relevant to this question.
Since i havent got any answers on this, i figured a way to do so but i dont like it since i wanted a better way but well creating a static class that has static variables for each event, before raising the event , the caller will set those variables and the handler will read then reset them . this is dangerous approach especially with multi-threading since one or more threads might change the values while raising same event by mutli threads, so i had to implement some locking features to ensure thread safety.
Yes i know its not the best approach but as i'm not an expert in C++ and this question didnt get any comments nor answers, so this is the approach im following.
For message passing in between threads, I'm looking for a concurrent queue with following properties:
bounded size
pop method that blocks/waits until an element is available.
abort method to cancel the wait
Optional: priority
Multiple producers, one consumer.
The concurrent_bounded_queue of TBB would provide that, but I'm looking for alternatives to avoid the additional dependency of TBB.
The application uses C++11 and boost. I couldn't find anything suitable in boost. What are the options?
Naive implementation using Boost library(circular_buffer) and C++11 standard library.
#include <mutex>
#include <condition_variable>
#include <boost/circular_buffer.hpp>
struct operation_aborted {};
template <class T, std::size_t N>
class bound_queue {
public:
typedef T value_type;
bound_queue() : q_(N), aborted_(false) {}
void push(value_type data)
{
std::unique_lock<std::mutex> lk(mtx_);
cv_pop_.wait(lk, [=]{ return !q_.full() || aborted_; });
if (aborted_) throw operation_aborted();
q_.push_back(data);
cv_push_.notify_one();
}
value_type pop()
{
std::unique_lock<std::mutex> lk(mtx_);
cv_push_.wait(lk, [=]{ return !q_.empty() || aborted_; });
if (aborted_) throw operation_aborted();
value_type result = q_.front();
q_.pop_front();
cv_pop_.notify_one();
return result;
}
void abort()
{
std::lock_guard<std::mutex> lk(mtx_);
aborted_ = true;
cv_pop_.notify_all();
cv_push_.notify_all();
}
private:
boost::circular_buffer<value_type> q_;
bool aborted_;
std::mutex mtx_;
std::condition_variable cv_push_;
std::condition_variable cv_pop_;
};
My assumption is that packaged_task has a promise underneath. If my task throws an exception, how do I route that to the associated future? With just a promise I could call set_exception
– how do I do the same for packaged_task?
An std::packaged_task has an associated std::future object that will hold the exception (or the result of the task). You can retrieve that future by calling the get_future() member function of std::packaged_task.
This means that it is enough to throw an exception inside the function associated with the packaged task in order for that exception to be caught by the task's future (and re-thrown when get() is called on the future object).
For instance:
#include <thread>
#include <future>
#include <iostream>
int main()
{
std::packaged_task<void()> pt([] () {
std::cout << "Hello, ";
throw 42; // <== Just throw an exception...
});
// Retrieve the associated future...
auto f = pt.get_future();
// Start the task (here, in a separate thread)
std::thread t(std::move(pt));
try
{
// This will throw the exception originally thrown inside the
// packaged task's function...
f.get();
}
catch (int e)
{
// ...and here we have that exception
std::cout << e;
}
t.join();
}