If I have a function A(), I am interested in finding a convenient method to create a function B() that has the exact same functionality as A(), differing only in name. The new function would be for a one-time use. The intent is to differentiate between calls to the same function in a somewhat primitive sampling profiler, and the duplicated function would only be used in this context. That is, it would never touch production code and only be used for tinkering.
First guess would be a macro that declares a function named B and creates an inlined call to A() inside of it. The problem here is that I'm not aware of a method in GCC to force an arbitrary function call to inline; it seems all inlining options are for function declarations rather than calls.
There may be some esoteric way to do it with templates, or possibly by tricking the compiler into inlining. I'm not sure it's possible. Any thoughts? Unfortunately the new C++ standard is not available, if it would make a difference.
Using templates
template<int x>
void A()
{
// ..
}
int main()
{
A<0>();
A<1>();
return 0;
}
Update
The compiler can be too smart and create only one body for A<0> and A<1>. At least Visual C++ 2010 does it in Release mode. To prevent it, just use the template parameter inside the function template body in logs or asserts. For example,
#include <iostream>
template<int x>
void A()
{
::std::cout << x << std::endl;
// ..
}
int main()
{
A<0>();
A<1>();
auto v0 = A<0>;
auto v1 = A<1>;
::std::cout << v0 << std::endl;
::std::cout << v1 << std::endl;
::std::cout << (v0 == v1) << std::endl;
return 0;
}
This works using templates:
#include <iostream>
template<typename T>
void foo() {
static int x = 0;
std::cout << &x << std::endl;
}
int main(int argc, char **argv) {
foo<int>();
foo<float>();
return 0;
}
If you execute that, you'll see two different values printed, reflecting the compiler generated code for both calls, even though the template parameter is unused. nm on the object file confirms this.
If this is a one-time debug hack, then why not:
#define A_CONTENT \
... // whatever
void A()
{
A_CONTENT
}
void B()
{
A_CONTENT
}
...
A(); // Call to A
B(); // Call to B
Macros are generally grim, but we're not talking about production code here, so who cares?
Having been down this road myself, the short answer is that even if you get the compiler to emit two identical duplicates of a function, the optimizing linker will notice that they're identical and fold them back together into one implementation. (And if you've turned off optimization in the linker, then your profile isn't valid anwyay).
In the context of a sampling profiler, I've found the easier approach is to make two tiny wrappers for the function instead:
void Func() { .... }
_declspec(noinline)
void A_Func( return Func(); }
void B_Func( return Func(); }
void C_Func( return Func(); }
Then when your profiler samples the callstack, you'll be able to differentiate between the different callsites of this function in a very straightforward way..
You could always define a macro, for example in Chromium we do the following to reuse code:
#define CHROMEG_CALLBACK_1(CLASS, RETURN, METHOD, SENDER, ARG1) \
static RETURN METHOD ## Thunk(SENDER sender, ARG1 one, \
gpointer userdata) { \
return reinterpret_cast<CLASS*>(userdata)->METHOD(sender, one); \
} \
\
virtual RETURN METHOD(SENDER, ARG1);
And we call them like:
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnExposeEvent, GdkEventExpose*);
CHROMEGTK_CALLBACK_1(PageActionViewGtk, gboolean, OnButtonPressed, GdkEventButton*);
You can do something similar to do what you wanted. The above example shows us using two different implementations but with one common code base. For GTK callbacks.
It's a little unclear what you're really trying to do, but a really ugly solution would be to declare the body of A as a macro and then you can "inline" this macro within whatever functions you like.
Also, macros are evil. Never use them unless you really have to.
Why do you care so much about inlining it? If you create a wrapper function, there is a pretty good chance the compiler will inline it anyway. At the very least, you're unlikely to get a function frame constructed.
C++11 also lets you do this:
void A() {
...
}
...
auto B = [] () -> void { A(); };
You can now use B syntactically as though it was a function wrapping A.
Related
I must be misunderstanding something because I thought the two cases are the same:
#include <iostream>
void function() { std::cout << "Hi\n"; }
int main()
{
std::vector<void(*)()> funcPtrVec;
std::vector<void()> funcVec;
funcPtrVec.push_back(function); // Works
funcVec.push_back(function); // Works
auto lambdaFunc = []() { std::cout << "Hi\n"; };
funcPtrVec.push_back(lambdaFunc); // Works
funcVec.push_back(lambdaFunc); // Doesn't work
}
Now, in both cases my compiler says that the function signatures are the same, void function() and void lambdaFunc(). I really thought that when a lambda function doesn't capture anything it behaves like a free function, which the same signatures would seem to support. Also, I guess I'm confused even more due to the fact that in the following all seem to be treated the same, as if decaying to the same thing:
void function() { std::cout << "Hi\n"; }
void funcTakingFunc(void()) {}
void funcTakingFuncPtr(void(*)()) {}
int main()
{
auto lambdaFunc = []() { std::cout << "Hi\n"; };
void(*funcPtr)() = lambdaFunc; // Works
funcTakingFuncPtr(lambdaFunc); // Works
funcTakingFuncPtr(funcPtr); // Works
funcTakingFunc(lambdaFunc); // Works
funcTakingFunc(funcPtr); // Works
// They all work
}
So as far as I can see the only distinction between the function and the function pointer made is when given as a template argument to vector. This obviously means I don't understand templates well, but what's the reason for this? Because the two really seem the same from the examples I tried.
std::vector<void()> is not allowed; the type must be an object type, and a function type is not an object type.
There are various parts of the specification of vector requirements we could identify as being violated by a non-object type; the most obvious is the default allocator. In the table in [allocator.requirements]/2 it is specified that the type the allocator is for must be an object type.
My goal is to quickly deal with various race conditions that can cause problems if a given function is called in 2 separate threads around the same time. My quick-fix is to just guarantee the functions have been initialized by calling them before main(). This is the solution I've come up with, but I feel I'm likely re-inventing the wheel. Is there an already-available option in the MSVC2010 STL? (no boost, yet) Or is there perhaps a better way to quickly deal with these issues without having to add significant thread safety code to each function in this situation?
template <typename T, T func>
struct PreLoaderHelper
{
PreLoaderHelper()
{
wcout << L"Preload helper constructor" << endl;
func();
}
};
template <typename T, T func>
struct PreLoader
{
static PreLoaderHelper<T, func> _helper;
};
template <typename T, T func>
PreLoaderHelper<T, func> PreLoader<T, func>::_helper;
#define PRELOAD(fn) template struct PreLoader<decltype(&fn), fn>;
void foo() { wcout << L"inside foo" << endl; }
void bar() { wcout << L"inside bar" << endl; }
vector<wstring> & foobar()
{
static vector<wstring> sPresidents;
if(sPresidents.size() == 0)
{
sPresidents.push_back(L"George Washington");
sPresidents.push_back(L"John Addams");
sPresidents.push_back(L"Thomas Jefferson");
}
return sPresidents;
}
wstring foofoo(const wstring &) { wcout << L"inside foofoo" << endl; return L"foofoo";}
PRELOAD(foo);
PRELOAD(bar);
PRELOAD(foobar);
PRELOAD(foo);
int main()
{
return 0;
}
The first question: do you really have to call them before
entering main? Why not just call them the first thing in main,
before starting any threads?
Otherwise: the classical idiom is to use them in an initializer
to a static variable. The usual way is to call them from a
constructor; if you have additional data which must be
initialized, this is doubtlessly the best way. If not,
something as simple as:
static bool initialized = (function(), true);
will do the trick.
Formally, this only guarantees that they will be initialized
before anything else in the same translation unit has been used,
but practically, this will guarantee that the function is called
before main, or during the loading of the DLL, if it is in a DLL
other than the one with main.
You can do this:
int dummy = (foo(), (void)0, bar(), 0);
int main()
{
// foo() and bar() have already been called
}
Furthermore, C++11 guarantees that the following variant causes only one single call, race-free:
void call_foo()
{
static int dummy = (call_foo(), 0);
}
void some_thread_function() { call_foo(); }
If you are using C++11 then remember that:
static function variable initialization is thread safe.
You can use list initialization semantics.
Try:
std::vector<std::wstring>& plop1()
{
// Thread safe
// Guaranteed to be done once
// No setup required
// No cost if not used.
static std::vector<std::wstring> sPresidents =
{
L"George Washington",
L"John Addams",
L"Thomas Jefferson"
};
return sPresidents;
}
I would highly recommend using proper synchronization using critical sections for your situation. Entering and exiting critical sections does not add a lot of code and handles the situation gracefully.
In case you do not want to continue with your original approach of initializing functions before main(), you can use global variable initialization as it occurs prior to main function call. There is a nice article about this approach at
http://blog.fishingcactus.com/index.php/2009/01/28/fixing-c-static-and-global-variable-initialization/#sthash.pmBtrYD8.dpbs
If I just do it:
Ex1:
#include <iostream>
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
I get compilation error! Because the compile doesn´t know what is "doSomething".
But if I change the position of doSomething to come in first place, the program compiles successfully.
Ex2:
#include <iostream>
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
int main()
{
//try to call doSomething function
doSomething();
}
I can declare prototype to be like this:
Ex3:
#include <iostream>
void doSomething(void);
int main()
{
//try to call doSomething function
doSomething();
}
void doSomething()
{
std::cout << "Call me now!" << std::endl;
}
But why the first example does not work? Why I even have to declare a prototype or call functions first and main function at last?
Thanks!
You can't call a function without the compiler having seen either the definition or a declaration, first -- simple as that. A prototype or the actual definition must appear before a call.
Because the compiler hasn't seen doSomething before it's used.
Either you must prototype it, or define it first, so that the compiler knows how to analyze the usage of it.
This is a legacy from C. C is a single pass language which means that it has to do everything by only reading the file once. To be able to call a function without a forward declaration/prototype would require reading the file twice; The first time to find all the function signatures and the second time to actually compile.
C++ kept this requirement for features that were part of C, such as free functions and global variables. However classes are new to C++ and there was no need to keep the old way of doing things. So within a single class definition, multi-pass compilation is used. That's why you can do this:
class MyClass {
void foo() {bar();}
void bar() {}
};
But you can't do what you listed in your question.
I like using sentry classes in c++, but I seem to have a mental affliction that results in repeatedly writing bugs like the following:
{
MySentryClass(arg);
// ... other code
}
Needless to say, this fails because the sentry dies immediately after creation, rather than at the end of the scope, as intended. Is there some way to prevent MySentryClass from being instantiated as a temporary, so that the above code either fails to compile, or at least aborts with an error message at runtime?
I can't think of an automatic way to detect if you make this mistake or not. You could always create a macro that expands to the correct thing and use that to declare the sentry instead if you keep using it wrong.
#define MY_SENTRY_CLASS(_X) MySentryClass _sentry(_X)
and then use
MY_SENTRY_CLASS(arg);
or put a post-it on your monitor to remind you.
The only thing you could do is make the constructors private and force access through a helper function. This is far less similar than the initial construction syntax and less likely to be mistaken. You could also allocate on the heap (still a waste) but it's much easier to spot. However, if you want your class to be constructible, you can't stop people constructing rvalues of that type.
Edit: IF you know that MySentryClass always takes an argument, you could disallow construction AND and only allow operator=(arguments). This would force you to do
MySentryClass x;
x = arg;
You could do some kind of method chain for it.
MySentryClass x;
x.SetArg1(arg).SetArg2(arg2).construct();
No, there is no exit from this problem. To make objects on the stack, you have to have public constructors, and if you have public constructors, you can make the mistake you are reporting.
Not sure you'll like this solution, but the solution may well be grep:
find /path/to/project -type f -name \*.cpp -print0 | xargs grep -0 'MySentryClass('
Another thing you could do is use sed or perl to preprocess your source file, replacing MySentryClass( with \n#error MySentryClass used incorrectly\n, which hopefully will give you a line number that's close to where the error is. How to do this depends on your build system.
I think the #define is the best method.
But just as an option for not using #define:
Main
int main()
{
try
{
S arg1;
// This will not compile
// MySentry x1 = MySentry::CreateSentry(arg1);
S arg3;
MySentry x2(MySentry::CreateSentry(arg3));
S arg2;
// This will not compile
// MySentry(arg2);
S arg4;
// This will generate a runtime exception
// It will never call start() or end()
//MySentry::CreateSentry(arg4);
}
catch(std::exception const& e)
{
std::cout << "Exception : " << e.what() << "\n";
}
}
Edited. Now works better.
#include <stdexcept>
#include <iostream>
class S
{
public:
void start() {std::cout << "Start\n";}
void end() {std::cout << "End\n";}
};
class MySentry
{
struct Init
{
Init(S& s) : arg(s),bad(true) {}
~Init() {if (bad) {throw std::runtime_error("Bad usage of MySentry");}}
S& arg;
mutable bool bad;
};
public:
static Init CreateSentry(S& arg) { return Init(arg);}
explicit MySentry(Init const& arg)
: obj(arg.arg)
, bad(false)
{
arg.bad = false;
std::cout << "Created\n";
obj.start();
}
MySentry(MySentry const& rhs)
: obj(rhs.obj)
, bad(false)
{
std::cout << "Copied (this may not appear)\n";
std::cout << "If the optimizer kicks in then the copy may be elided.\n";
// But if it did not optimize out then
// We have to mark the temporaty as bad
// And not call end() in its destructor.
// Note: Never call start() here as it will always be called in the
// main private constrctor above
rhs.bad = true;
}
~MySentry()
{
if (!bad)
{
// Everything working
obj.end();
}
std::cout << "Destroyed\n";
}
private:
S& obj;
mutable bool bad;
};
What you are trying to do is perfectly legal in C++ and I don't think there is a way to disallow it.
I declared a global function in a .cpp file void functionA(). I would like functionA() to be called exactly once before the start-up ( not inside main()). The thing I realize is if the function is int functionB(), I could call it using static int A = functionB(). But for return value of void, how could I do that?
Thanks
You put it into the constructor of a global object:
void functionA();
namespace {
struct global_initializer {
global_initializer() {functionA();}
} the_global_initializer;
}
Note that this has the common drawbacks of global initialization: While globals within the same translation unit are initialized in the order of their definition, the order of initialization of globals across translation units is undefined.
Also, linkers might choose to eliminate unreferenced objects (the_global_initializer), which would prevent functionA() from being called.
static int a = functionA(), 42;
There are few places where comma expressions are useful, but this may be one of them.
You could use a static struct, it's constructor will get called before main.
#include <iostream>
void functionA(void)
{
std::cout << "Hello, ";
}
static struct BeforeMain
{
BeforeMain(void)
{
// stuff in this constructor is executed before "main" function
functionA();
}
} g_beforeMain; // shouldn't get used though
int main(void)
{
std::cout << "world!" << std::endl;
return 0;
}
This will print Hello, world!, although I'm new to C++, so this may not be the best approach.
Solution 1: Make that void function to have a return type (say int) and return a dummy return value
If you can't do Solution 1,
Solution 2: Write a wrapper function as shown. Make sure to write code so that wrapper can be called only once (unless it is fine to do so multiple times)
Wrap it up! (and document extensively).
void fA(){}
int wrapper(){
// Have checks here to ensure it is not called more than once
fA();
return 0;
}
// Extensively document such as `'x' is a bogus dummy variable.`
static int x = wrapper();
int main(){
}