I am writing a small game on my phone in SDL2. In main I have a while loop and basic game control conditions which are bools. I pass 'initialise', 'update', 'quit' and the 'renderer' to a game function by reference that deals with the game logic. Now it's getting more complicated I want to separate certain logic to outside of game, and to do that I have to pass the references from main, to game, to more functions outside of game. Main would pass to game, game would pass to func2, and possibly func2 needs to pass to func3.
Do the C++ standards/specification limit the use of pass by reference? You could have a chain of 10+ functions passing down quit, update, etc.
//
// extra functions here
// which break up game
// each need quit, initialise, update and renderer
// so I pass by reference
//
// void func2(&rend, &quit, &update, &initialise)
void game(SDL_Renderer *rend, bool &initialise, bool &quit, bool &update)
{
static Table t{};
if (initialise)
{
// setup game
func2(rend, initialise, quit, update);
}
if(update)
{
// refresh screen
}
while (PollTouchEvent)
{
// touching screen
// can quit here
}
}
int main(int argc, char *argv[])
{
// initialise SDL
// ...
// game stuff
bool quit = false;
bool update = true;
bool initialise = true;
while (!quit)
{
game(renderer, initialise, quit, update);
}
// quit SDL
return 0;
}
There is no limit to the number of times you can pass a variable by reference, other than perhaps the size of the stack — i.e. the address of a variable that is passed by reference may need to be placed on the stack, and in extreme cases (read: deeply recursive functions) that might exceed the stack’s capacity. Such a problem isn’t very common, though.
Whether it’s a good approach to be passing lots of variables by reference is a different question. In particular, if you find yourself passing the same set of references to many different functions, consider creating a struct or class-object containing all of that information as member variables and just passing around a single reference to that object instead; that will be more efficient and also much easier to maintain/update as your program changes.
Also note that modern c++ compilers can often perform optimizations more effectively on arguments that are passed by-value than on arguments passed by-reference, since in the by-value case the optimizer doesn’t have to worry about the possibility of aliasing. Whether one approach or the other is faster would have to be measured on a case-by-case basis, though, as performance can depend a lot on the details of what is being done.
Related
Let me flush out my question a bit more:
I have a Game class that is instantiated at the beginning of the program and is destroyed only at the end of the program's lifetime.
I have a "StartMenu" member object within my Game class that I clearly want to be available at the beginning of the game's lifetime, but that shouln't be taking up memory after the user starts the game. (There is simply no reason for it to).
My current solution is to declare a StartMenu pointer as a member, dynamically allocate memory to it by a method called from the constructor, (or elsewhere if necessary) and then delete it when the user wished to play the game. Is this a good practice solution? Should the design be changed, or is there or more standard way "Start Menus" are handled?
Relevant Code:
Class Game
{
private:
StartMenu* startMenu_ptr;
//Other Game Vars
}
Initializing
Game::initStartMenu() {
startMenu_ptr = new StartMenu();
}
Deleting
Game::runStartMenu() {
if(startMenu_ptr->getOption()==1) {
delete startMenu_ptr;
startMenu_ptr = nullptr;
}
EDIT: More details are necessary. runStartMenu is called from a while loop every frame to detect updates and user input. Moreover, any updates to startMenu are recorded and then drawn in a separate method (Game::render()) to reflect user input. I cannot be reInitializing startMenu at every iteration of the loop.
Game::update() (Called from main, inside event while loop)
void Game::update() {
switch(gameState)
{
case 0:
runStartMenu();
break;
case *n*... //other game screens...
}
}
And then my draw Game::render() function: (Called from main, inside event while loop)
Game::render()
switch(gameState)
{
case 0:
drawStartMenu();
break;
case *n*... //other game screens...
}
}
Thanks.
EDIT : as requested, allow background execution of other tasks while the menu is running
As a general rule, you should never manipulate raw new and delete operators outside the context of smart pointers. For your use case, you can absolutely use static allocation and dynamic allocation doesn't bring any advantage, so I suggest you design it in a straightforward manner like so :
StartMenu::choice_t choice;
Game::runStartMenu() {
auto menuThread = std::thread([](){
auto menu = StartMenu{/* options */};
// for example :
choice = menu.show();
}); // the menu memory gets freed here
menuThread.join(); // wait for execution end
// choice handling logic
}
Then, the caller can implement menu choice logic and start the game !
I have a class called MatrixAlt and i'm trying to multi thread a function to do some work on that matrix.
My general method worked when I just implemented it in a couple of functions. But when I try to bring it into the class methods, I get an error.
The problematic line (or where it highlights anyway) is 4 lines from the end and the error message is in the comments just above it.
#include <vector>
#include <future>
#include <thread>
class MatrixAlt
{
public:
MatrixAlt();
// initilaise the matrix to constant value for each entry
void function01(size_t maxThreads);
void function02(size_t threadIndex);
};
MatrixAlt::MatrixAlt()
{
}
void MatrixAlt::function02(size_t threadIndex)
{
// do some stuff
return;
}
void MatrixAlt::function01(size_t maxThreads)
{
// To control async threads and their results
std::vector<std::future<bool>> threadsIssued;
// now loop through all the threads and orchestrate the work to be done
for (size_t threadIndex = 0; threadIndex < maxThreads; ++threadIndex)
{
// line 42 gives error:
// 'MatrixAlt::function02': non-standard syntax; use '&' to create a pointer to member
// 'std::async': no matching overloaded function found
threadsIssued.push_back(std::async(function02, threadIndex));
}
return;
}
Your first problem is solved like this
threadsIssued.push_back(std::async(&MatrixAlt::function02, this, threadIndex));
You need to specify the exact class::function and take its address and which instance of the class your doing it for, and then the parameters.
The second problem which you haven't see yet is this line
std::vector<std::future<bool>> threadsIssued;
All those futures will be lost in scope exit, like tears in rain. Time to destroy.
Freely after Blade runner.
All those moments will be lost in time, like tears in rain. Time to
die.
Whenever you have a member function in C++, that function takes the object itself as an implicit first argument. So you need to pass the object as well, but even then, it can't be called with the same syntax as a normal function that takes the object.
The simplest way to setup an asynchronous job in C++ is typically just to use lambdas. They've very clear and explicit. So, for example, you could change your call to:
threadsIssued.push_back(std::async([this] (size_t t) { this->function02(t);}, threadIndex));
This lambda is explicitly capturing the this pointer, which tells us that all of the function02 calls will be called on the same object that the calling function01 is called on.
In addition to being correct, and explicit, this also helps highlight an important point: all of the function02 objects will be running with mutable access to the same MatrixAlt object. This is very dangerous, so you need to make sure that function02 is thread safe, one way or another (usually easy if its conceptually const, otherwise perhaps need a mutex, or something else).
I'm a game developer therefore performance is really important to me.
My simple question:
I have a lot of checks(button clicks,collisions,whatever) running per frame, but I don't want to put everything in one function, therefore I would split them into other functions and just call them:
void Tick()
{
//Check 1 ..... lots of code
//Check 2 ...... lots of code
//Check 3 ..... lots of code
}
to
void Tick()
{
funcCheck1();
funcCheck2();
funcCheck3();
}
void funcCheck1()
{
//check1 lots of code
}
void funcCheck2()
{
//check2 lots of code
}
void funcCheck3()
{
//check3 lots of code
}
Does the function call per frame has any performance impact?(not inlined)
Clearly the second version is much more readable.
If you don't pass any complex objects by value, the overhead of calling several functions instead of putting all code in one function should be negligible (e.g.
put function parameters on top of the stack, add space for the return type, jump to the beginning of the called function's code)
You cannot say for sure, specifically that the compiler could inline small function automatically. The only way to be sure is to use a profiler and compare the two scenarios.
I want to pass some data around threads but want to refrain from using global variables if I can manage it. The way I wrote my thread routine has the user passing in a separate function for each "phase" of a thread's life cycle: For instance this would be a typical usage of spawning a thread:
void init_thread(void *arg) {
graphics_init();
}
void process_msg_thread(message *msg, void *arg) {
if (msg->ID == MESSAGE_DRAW) {
graphics_draw();
}
}
void cleanup_thread(void *arg) {
graphics_cleanup();
}
int main () {
threadCreator factory;
factory.createThread(init_thread, 0, process_msg_thread, 0, cleanup_thread, 0);
// even indexed arguments are the args to be passed into their respective functions
// this is why each of those functions must have a fixed function signature is so they can be passed in this way to the factory
}
// Behind the scenes: in the newly spawned thread, the first argument given to
// createThread() is called, then a message pumping loop which will call the third
// argument is entered. Upon receiving a special exit message via another function
// of threadCreator, the fifth argument is called.
The most straightforward way to do it is using globals. I'd like to avoid doing that though because it is bad programming practice because it generates clutter.
A certain problem arises when I try to refine my example slightly:
void init_thread(void *arg) {
GLuint tex_handle[50]; // suppose I've got 50 textures to deal with.
graphics_init(&tex_handle); // fill up the array with them during graphics init which loads my textures
}
void process_msg_thread(message *msg, void *arg) {
if (msg->ID == MESSAGE_DRAW) { // this message indicates which texture my thread was told to draw
graphics_draw_this_texture(tex_handle[msg->texturehandleindex]); // send back the handle so it knows what to draw
}
}
void cleanup_thread(void *arg) {
graphics_cleanup();
}
I am greatly simplifying the interaction with the graphics system here but you get the point. In this example code tex_handle is an automatic variable, and all its values are lost when init_thread completes, so will not be available when process_msg_thread needs to reference it.
I can fix this by using globals but that means I can't have (for instance) two of these threads simultaneously since they would trample on each other's texture handle list since they use the same one.
I can use thread-local globals but is that a good idea?
I came up with one last idea. I can allocate storage on the heap in my parent thread, and send a pointer to in to the children to mess with. So I can just free it when parent thread leaves away since I intend for it to clean up its children threads before it exits anyway. So, something like this:
void init_thread(void *arg) {
GLuint *tex_handle = (GLuint*)arg; // my storage space passed as arg
graphics_init(tex_handle);
}
void process_msg_thread(message *msg, void *arg) {
GLuint *tex_handle = (GLuint*)arg; // same thing here
if (msg->ID == MESSAGE_DRAW) {
graphics_draw_this_texture(tex_handle[msg->texturehandleindex]);
}
}
int main () {
threadCreator factory;
GLuint *tex_handle = new GLuint[50];
factory.createThread(init_thread, tex_handle, process_msg_thread, tex_handle, cleanup_thread, 0);
// do stuff, wait etc
...
delete[] tex_handle;
}
This looks more or less safe because my values go on the heap, my main thread allocates it then lets children mess with it as they wish. The children can use the storage freely since the pointer was given to all the functions that need access.
So this got me thinking why not just have it be an automatic variable:
int main () {
threadCreator factory;
GLuint tex_handle[50];
factory.createThread(init_thread, &tex_handle, process_msg_thread, &tex_handle, cleanup_thread, 0);
// do stuff, wait etc
...
} // tex_handle automatically cleaned up at this point
This means children thread directly access parent's stack. I wonder if this is kosher.
I found this on the internets: http://software.intel.com/sites/products/documentation/hpc/inspectorxe/en-us/win/ug_docs/olh/common/Problem_Type__Potential_Privacy_Infringement.htm
it seems Intel Inspector XE detects this behavior. So maybe I shouldn't do it? Is it just simply a warning of potential privacy infringement as suggested by the the URL or are there other potential issues that may arise that I am not aware of?
P.S. After thinking through all this I realize that maybe this architecture of splitting a thread into a bunch of functions that get called independently wasn't such a great idea. My intention was to remove the complexity of requiring coding up a message handling loop for each thread that gets spawned. I had anticipated possible problems, and if I had a generalized thread implementation that always checked for messages (like my custom one that specifies the thread is to be terminated) then I could guarantee that some future user could not accidentally forget to check for that condition in each and every message loop of theirs.
The problem with my solution to that is that those individual functions are now separate and cannot communicate with each other. They may do so only via globals and thread local globals. I guess thread local globals may be my best option.
P.P.S. This got me thinking about RAII and how the concept of the thread at least as I have ended up representing it has a certain similarity with that of a resource. Maybe I could build an object that represents a thread more naturally than traditional ways... somehow. I think I will go sleep on it.
Put your thread functions into a class. Then they can communicate using instance variables. This requires your thread factory to be changed, but is the cleanest way to solve your problem.
Your idea of using automatic variables will work too as long as you can guarantee that the function whose stack frame contains the data will never return before your child threads exit. This is not really easy to achieve, even after main() returns child threads can still run.
Having read a bit about function pointers and callbacks, I fail to understand the basic purpose of it. To me it just looks like instead of calling the function directly we use the pointer to that function to invoke it. Can anybody please explain me callbacks and function pointers? How come the callback takes place when we use function pointers, because it seems we just call a function through a pointer to it instead of calling directly?
Thanks
ps: There have been some questions asked here regarding callbacks and function pointers but they do not sufficiently explain my problem.
What is a Callbak function?
In simple terms, a Callback function is one that is not called explicitly by the programmer. Instead, there is some mechanism that continually waits for events to occur, and it will call selected functions in response to particular events.
This mechanism is typically used when a operation(function) can take long time for execution and the caller of the function does not want to wait till the operation is complete, but does wish to be intimated of the outcome of the operation. Typically, Callback functions help implement such an asynchronous mechanism, wherein the caller registers to get inimated about the result of the time consuming processing and continuous other operations while at a later point of time, the caller gets informed of the result.
An practical example:
Windows event processing:
virtually all windows programs set up an event loop, that makes the program respond to particular events (eg button presses, selecting a check box, window getting focus) by calling a function. The handy thing is that the programmer can specify what function gets called when (say) a particular button is pressed, even though it is not possible to specify when the button will be pressed. The function that is called is referred to as a callback.
An source Code Illustration:
//warning: Mind compiled code, intended to illustrate the mechanism
#include <map>
typedef void (*Callback)();
std::map<int, Callback> callback_map;
void RegisterCallback(int event, Callback function)
{
callback_map[event] = function;
}
bool finished = false;
int GetNextEvent()
{
static int i = 0;
++i;
if (i == 5) finished = false;
}
void EventProcessor()
{
int event;
while (!finished)
{
event = GetNextEvent();
std::map<int, Callback>::const_iterator it = callback_map.find(event);
if (it != callback_map.end()) // if a callback is registered for event
{
Callback function = *it;
if (function)
{
(*function)();
}
else
{
std::cout << "No callback found\n";
}
}
}
}
void Cat()
{
std::cout << "Cat\n";
}
void Dog()
{
std::cout << "Dog\n";
}
void Bird()
{
std::cout << "Bird\n";
}
int main()
{
RegisterCallBack(1, Cat);
RegisterCallback(2, Dog);
RegisterCallback(3, Cat);
RegisterCallback(4, Bird);
RegisterCallback(5, Cat);
EventProcessor();
return 0;
}
The above would output the following:
Cat
Dog
Cat
Bird
Cat
Hope this helps!
Note: This is from one of my previous answers, here
One very striking reason for why we need function pointers is that they allow us to call a function that the author of the calling code (that's us) does not know! A call-back is a classic example; the author of qsort() doesn't know or care about how you compare elements, she just writes the generic algorithm, and it's up to you to provide the comparison function.
But for another important, widely used scenario, think about dynamic loading of libraries - by this I mean loading at run time. When you write your program, you have no idea which functions exist in some run-time loaded library. You might read a text string from the user input and then open a user-specified library and execute a user-specified function! The only way you could refer to such function is via a pointer.
Here's a simple example; I hope it convinces you that you could not do away with the pointers!
typedef int (*myfp)(); // function pointer type
const char * libname = get_library_name_from_user();
const char * funname = get_function_name_from_user();
void * libhandle = dlopen(libname, RTLD_NOW); // load the library
myfp fun = (myfp) dlsym(libhandle, funname); // get our mystery function...
const int result = myfp(); // ... and call the function
// -- we have no idea which one!
printf("Your function \"%s:%s\" returns %i.\n", libname, funname, result);
It's for decoupling. Look at sqlite3_exec() - it accepts a callback pointer that is invoked for each row retrieved. SQLite doesn't care of what your callback does, it only needs to know how to call it.
Now you don't need to recompile SQLite each time your callback changes. You may have SQLite compiled once and then just recompile your code and either relink statically or just restart and relink dynamically.
It also avoids name collision. If you have 2 libs, both do sorting and both expect you to define a function called sort_criteria that they can call, how would you sort 2 different objects types with the same function?
It would quickly get complicated following all the if's and switches in the sort_criteria function, with callbacks you can specify your own function (with their nice to interpret name) to those sort functions.