calling a function indirectly from main with an particular format output - c++

Here is my program below.
void fun1(void);
int main(int argc, char *argv[])
{
cout<<"In main"<<endl;
atexit(fun1); //atexit calls the function at the end of main
cout<<"Exit main"<<endl;
return 0;
}
void fun1(void)
{
cout<<"fun1 executed"<<endl;
}
The output is
In main
Exit main
fun1 executed
But I intend the output like this:
In main
fun1 executed
Exit main
I don't want to call "fun1" function directly or use any other functions which would call my function "fun1".
Is there any way I can acheive this this output? Any help is most welcome.

No. †
Only atexit and static object destruction happen "on their own", and both these things occur after returning from main.
And this makes sense, when you think about it: something that should occur during main should be written in main. If you need a function to be invoked at a given time, write it into your program. This is what you write the program for. main is for your program.
† Probably, with a "trick" or "hack" that'll get you fired from my team.

Here is a hack using a scope:
#include <iostream>
class call_on_destructed {
private:
void (*m_callee)();
public:
call_on_destructed(void (*callee)()): m_callee(callee) {}
~call_on_destructed() {
m_callee();
}
};
void fun() {
std::cout << "fun\n";
}
int main() {
{
call_on_destructed c(&fun);
std::cout << "In main" << std::endl;
}
std::cout<<"Exit main"<<std::endl;
}
Outputs:
In main
fun
Exit main
The scope end causes the class destructor to be invoked, which in turn calls the fun function, registered within the class.

Do you want something like:
void fun1(void)
{
std::cout << "fun1 executed" << std::endl;
}
void call(void f())
{
f();
}
int main(int argc, char *argv[])
{
std::cout << "In main" << std::endl;
call(fun1); //call calls the given function directly
std::cout << "Exit main" << std::endl;
return 0;
}

Clearly, if you want to have your function executed, something is going to call it! That is, calling your function without calling your function won't work. atexit() is also just calling your function: you register what's being called eventually.
From the sounds of it, your assignment asks to pass off a function object off and have that facility call your function. For example, you could use a function caller:
template <typename F>
void caller(F f) {
f();
}
int main() {
std::cout << "entering main\n";
caller(fun1);
std::cout << "exiting main()\n";
}
Clearly, caller() does call fun1 although without mentioning that name.

Related

What does '&' mean in this statement?

class CTest
{
public:
CTest(){}
~CTest(){}
public:
int Output(const char * szBuf)
{
std::cout << szBuf << std::endl;
return 0;
}
void AsyncMethod()
{
std::thread t(&CTest::Output, this, "hello, world");
t.join();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
CTest obj;
obj.AsyncMethod();
}
In AsyncMethod(), there is a statement std::thread t(&CTest::Output, this, "hello, world");. What does & mean in this statement?
Firstly, this is not a lambda, right?
Secondly, here we need a pointer to a function. For a variable, & is used to acquire the address of the variable, but for a function, the name of the function itself is already the pointer to this function, right?
Thirdly, since AsyncMethod() and Output() are in the same class, why we need namespace CTest:: before Output?
So, why can't we write std::thread t(Output, this, "hello, world");?
Thank you for your help :)

Detecting if I am in an exit handler in C++

I would like to know if I am in an atexit() handler. I'm looking for the moral equivalent of std::uncaught_exceptions() for exit() calls.
I want to do this so I can have the destructors in my static objects behave one way when my main() function returns, and another way when exit() is called.
I could add a call to atexit() that sets a bool I inspect, but that runs into ordering issues. For example, this:
#include <iostream>
#include <stdlib.h>
struct Setter {
static void set_in_at_exit() { in_at_exit = true; std::cout << "setting\n";}
Setter() { std::cout << "constructor\n"; atexit(set_in_at_exit); }
static bool in_at_exit;
};
bool Setter::in_at_exit = false;
struct A {
A() { static Setter s; }
~A() { if (Setter::in_at_exit) {
std::cout << "in at exit\n";
}
std::cout << "My destructor\n"; }
};
A a;
int main()
{
return 0;
}
produces:
constructor
My destructor
setting
Which is not what I want. The destructor doesn't know it is in an exit handler.
[basic.start.main]
A return statement (8.6.3) in main has the effect of leaving the main function (destroying any objects with
automatic storage duration) and calling std::exit with the return value as the argument. If control flows off the end of the compound-statement of main, the effect is equivalent to a return with operand 0
So no, you cannot distinguish between the two situations unless you somehow instrument all explicit calls to exit or all return statements and the last line before the closing brace in main.

C++11 rvalue calls destructior twice

I'm trying to make a class runner (run a class at a fixed time freq), which runs a class in another thread, and can be controlled (like pause, resume, stop) from main thread.
So I want to take advantage of C++11's Functor and other features. But I have a strange problem, the Functor's destructor passed into Runner has been called twice.
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
class Runner {
public:
typedef function<bool()> fn_t;
Runner(fn_t &&fn) : fn_(move(fn)), thread_(Thread, ref(*this)) {
cout << "Runner" << endl;
}
~Runner() {
cout << "~Runner" << endl;
thread_.join();
}
private:
fn_t fn_;
thread thread_;
static void Thread(Runner &runner) {
while (runner.fn_()) {
cout << "Running" << endl;
this_thread::sleep_for(chrono::milliumseconds(1));
}
}
};
class Fn {
public:
Fn() : count(0) {
cout << "Fn" << endl;
}
~Fn() {
cout << "~Fn" << endl;
}
bool operator()() {
return (++count < 5);
}
private:
int count;
};
int main (int argc, char const* argv[])
{
Fn fn;
Runner runner(move(fn));
return 0;
}
outpus:
Fn
Runner
~Fn
~Runner
Running
Running
Running
Running
Running
~Fn
~Fn
and if I change
Fn fn;
Runner runner(move(fn));
to
Runner runner(Fn());
the program outpus nothing and stalls. I have tried to disable compiling optimization, nothing changes. Any explanation?
How can I fix this or do the samething in other method? Should I implement this class like std::async / std::thread?
Update to Runner runner(Fn())
This statement was interrupted as a function declaration.
Runner runner((Fn())) solved problem.
Thanks for all comments and answers. After look into rvalue, seems I have misunderstand the meaning of rvalue reference from ground 0. I will try some other ways.
Final Solution for this problem
#include <iostream>
#include <chrono>
#include <thread>
#include <vector>
using namespace std;
template<typename T, typename... Args>
class Runner {
public:
Runner(Args&&... args) :
t(forward<Args>(args)...),
thread_(Thread, ref(*this)) {
cout << "Runner" << endl;
}
~Runner() {
cout << "~Runner" << endl;
thread_.join();
}
private:
T t;
thread thread_;
static void Thread(Runner &runner) {
while (runner.t()) {
cout << "Running" << endl;
this_thread::sleep_for(chrono::milliseconds(100));
}
}
};
class Fn {
public:
Fn() : count(0) {
cout << "Fn" << endl;
}
~Fn() {
cout << "~Fn" << endl;
}
bool operator()() {
return (count++ < 5);
}
private:
int count;
};
int main (int argc, char const* argv[])
{
//vector<Fn> fns;
//fns.emplace_back(Fn());
Runner<Fn> runner;
return 0;
}
outpus:
Fn
Runner
~Runner
Running
Running
Running
Running
Running
~Fn
Use std::move:
Runner(fn_t &&fn) : fn_(std::move(fn)), thread_(Thread, ref(*this)) {
/*....*/
}
You need to explicitly use std::move, otherwise it will be treated as a const reference. You could also use std::forward:
Runner(fn_t &&fn) : fn_(std::forward<fn_t>(fn)), thread_(Thread, ref(*this)) {
/*....*/
}
First of all, you shouldn't be taking r-value reference arguments for the most part, except in your own move constructors. As you have it, there is no way to pass l-values of std::function<bool()> into the constructor of Runner.
int main()
{
Fn fn;
std::function<bool()> func(fn);
Runner runner(func); // this is illegal
}
Maybe I'm just not creative enough, but I can't imagine any valid reason which you would want to prevent such a thing.
You should let std::function take care of its own copying/moving. When you need a copy of an object, take your parameter by value. If the function is passed an r-value, then it will be move constructed. If it is passed an l-value, then it will be copy constructed. Then, in your Runner constructor, you can move the value into the member object, as fontanini showed.
None of this is guaranteed to reduce destructor calls though, because when you move an object, you're still creating a second object, and will have to destroy a second object. In order to see fewer destructions, copy elision would have to happen, which actually does avoid the creation of multiple objects. But unlike moving, that's an implementation issue that's not guaranteed to come into effect in all the situations where you would hope.

accessing the caller data type in a member function

I want to do something like this code:
myType a;
a->foo();
void foo()
{
cout << a->bar();
}
void bar()
{
cout << a->bar2();
}
void bar2()
{
cout << a->bar3();
}
In another word, when a member function is called, can we use the original caller?
You want:
cout << this->bar();
Or, more simply
cout << bar();
This IBM C++ documentation explains it pretty well. Have a look.
What you're probably trying to do is something like this:
#include <iostream>
class myType {
void foo()
{
std::cout << bar();
}
void bar()
{
std::cout << bar2();
}
void bar2()
{
std::cout << bar3();
}
};
... and in e.g. main method:
int main(int argc, char** argv)
{
myType a;
a->foo();
}
Inside a class, you can refer to methods of the same class just by their name, and they will be called on the same object as the original method! If you want to highlight that you're referring to methods of the same object, use e.g. this->bar() instead of bar(); it is only necessary in cases where there are other names (e.g. method parameters) which would conceal the class members, but it can be used all the time.

How to get Windows thread pool to call class member function?

I want the Windows thread pool (QueueUserWorkItem()) to call my class' member functions.
Unfortunately this cannot be done directly by passing a member function pointer as an argument to QueueUserWorkItem().
What makes it difficult is that more than one member function must be callable and they have different signatures (all return void though).
One probably need to add a few layers of abstraction to get this to work, but I'm not sure how to approach this. Any ideas?
This might help.
You can use tr1::function () and tr1::bind to "coalesce" various calls:
#include <iostream>
#include <tr1/functional>
using namespace std;
using namespace tr1;
class A
{
public:
void function(int i) { cout << "Called A::function with i=" << i << endl; }
};
void different_function(double c) {
cout << "Called different_function with c=" << c << endl;
}
int main(int argc, char* argv[])
{
function<void()> f = bind(different_function, 3.14165);
f();
A a;
f = bind(&A::function, a, 10);
f();
return 0;
}
The address of the function object can be passed as a single callable object (needing only one address).
Example:
In your class add:
char m_FuncToCall;
static DWORD __stdcall myclass::ThreadStartRoutine(LPVOID myclassref)
{
myclass* _val = (myclass*)myclassref;
switch(m_FuncToCall)
{
case 0:
_val->StartMyOperation();
break;
}
return 0;
}
Make a member for adding to queue then
void myclass::AddToQueue(char funcId)
{
m_FuncToCall=funcId;
QueueUserWorkItem(ThreadStartRoutine,this,WT_EXECUTEDEFAULT);
}
or create
typedef void (*MY_FUNC)(void);
typedef struct _ARGUMENT_TO_PASS
{
myclass* classref;
MY_FUNC func;
}ARGUMENT_TO_PASS;
and then
void myclass::AddToQueue(MY_FUNC func)
{
ARGUMENT_TO_PASS _arg;
_arg.func = func;
_arg.classref = this;
QueueUserWorkItem(ThreadStartRoutine,&_arg,WT_EXECUTEDEFAULT);
}
If you need further explanation feel free to ask :)
EDIT: You'll need to change the ThreadStartRoutine for the second example
and you can also change the struct to hold the passing argument