I have working code in a single class that looks like this
Mesh* player_; //
renderer_3d_->DrawSkinnedMesh(*player_, player_->bone_matrices());
seems straight forward, but I'm having trouble introducing another a vector of enemies going through classes, thanks to the pointers.
I have two extra classes, enemy and manager. Enemy contains a SkinnedMeshInstance, and manager should worry about drawing it.
Manager
std::vector <Enemy> enemy_;
enemy_.push_back(Enemy(*platform_)); // Initialise (platform is required by the default constructor, not relevant to the pointer issue)
rend->DrawSkinnedMesh(enemy_[0].getSkinnedMesh(), enemy_[0].getSkinnedMesh().bone_matrices()); //render, intellisense only accepts it this way
Enemy
Mesh* mesh_instance_;
Mesh getSkinnedMesh() { return *mesh_instance_; };
What am I doing wrong here? Notice how rendering has changed how it's dereferenced. This way doesn't work as it throws some illegal access errors either at 'return *mesh_instance_;' or deeper in the framework itself, depending on how I try to change the communication. Might be simple for some but I feel like I tried everything possible.
Solved. I didn't inisialise my pointer as NULL.
Dunde, I'd like to beg the indulgence of the group to pass along a couple of "lessons painfully learned" about code such as this excerpt:
Mesh getSkinnedMesh() { return *mesh_instance_; };
First, of course, you know that you need to be absolutely-certain that variables such as mesh_instance really are global, and that they really are initialized to NULL.
Now, since you know that a call to this "accessor function" is going to take place each and every time someone needs to "get a skinned mesh," you should always take full advantage of this opportunity. If you need to "automagically create a new object-instance," do so now. And (IMHO), if there's something that you can do to verify that the pointer-value is "good" (using a try construct to detect a runtime-error that occurs while doing so), do it. In this way, you now will be able to say: "if this method returns a value to you at all, then the value which it returns is good, because otherwise it's gonna blow up."
In practice, the hardest thing about any programming bug is – knowing that it exists, and where it is. "If you've got a traceback, you're home free."
Related
I'm doing some performance tuning work. Basically, I have found a potential bottleneck in our code base and thinking of the best solution for it. I will try to keep this question as simple as possible. Basically, I have a method that will work with a set of double values (std::set). So the method signature looks something like:
void MyClass::CalculateStuff(const std::set<double> & mySet);
There are several places in the code that call this method. Only a few of these places need to work with this set while others don't care about the set. I suppose I could create another version of this method that includes this set and modify the existing one to use an empty set. However, this would create some overhead for the places that don't care about the set (because they would have to make additional method calls). So the other option I thought of was using a pointer to a set argument instead, like so:
void MyClass::CalculateStuff(const std::set<double> * pMySet);
The validity of the pointer would determine whether we want to use the set or not (i.e. passing NULL pointer for the set argument means that we do no work associated with the set). This would be faster but obviously not clean from an interface perspective. I suppose I could heavily comment the code.
What do you think should be done? This is probably not a huge deal but it got me thinking about how far you should go to make your code faster (if performance is very important in an application) vs. making sure the code is still clean and manageable. Where should the line be drawn in this case?
well i do games programming. and for me. i only worry about potential bottlenecks when the game starts lagging then i profile etc.
passing in by pointer will be more memory efficent as a pointer to a object is only 4bytes. but i do suggest when you pass it null. that you use nullptr as thats the current standard to define a null pointer rather then NULL or 0.
im guessing you are passing in a set to calculate something with the class's set. in which case maybe overloading operators would be the best option for you?
Background
I work with Watusimoto on the game Bitfighter. We use a variation of LuaWrapper to connect our c++ objects with Lua objects in the game. We also use a variation of Lua called lua-vec to speed up vector operations.
We have been working to solve a bug for some time that has eluded us. Random crashes will occur that suggest corrupt metatables. See here for Watusimoto's post on the issue. I'm not sure it is because of a corrupt metatable and have seen some really odd behavior about which I wish to ask here.
The Problem Manifestation
As an example, we create an object and add it to a level like this:
t = TextItem.new()
t:setText("hello")
levelgen:addItem(t)
However, the game will sometimes (not always) crash. With an error:
attempt to call missing or unknown method 'addItem' (a nil value)
Using a suggestion given in answer to Watusimoto's post mentioned above, I have changed the last line to the following:
local ok, res = pcall(function() levelgen:addItem(t) end)
if not ok then
local s = "Invalid levelgen value: "..tostring(levelgen).." "..type(levelgen).."\n"
for k, v in pairs(getmetatable(levelgen)) do
s = s.."meta "..tostring(k).." "..tostring(v).."\n"
end
error(res..s)
end
This prints out the metatable for levelgen if something when wrong calling a method from it.
However, and this is crazy, when it fails and prints out the metatable, the metatable is exactly how it should be (with the correct addItem call and everything). If I print the metatable for levelgen upon script load, and when it fails using pcall above, they are identical, every call and pointer to userdata is the same and as it should be.
It is as though the metatable for levelgen is spontaneously disappearing at random.
Would anyone have any idea what is going on?
Thank you
Note: This doesn't happen with only the levelgen object. For instance, it has happened on the TestItem object mentioned above as well. In fact, that same code crashes on my computer at the line levelgen:addItem(t) but crashes on another developer's computer with the line t:setText("hello") with the same error message missing or unknown method 'setText' (a nil value)
As with any mystery, you will need to peel it off layer by layer. I recommend going through the same steps Lua is going and trying to detect where the path taken diverge from your expectations:
What does getmetatable(levelgen).__index return? If it's a table, then check its content for addItem. If it's a function, then try to call it with (table, "addItem") and see what it returns.
Check if getmetatable returns reference to the same object before and after the call (or when it fails).
Are there several levels of metatable indirection that the call is going through? If so, try to follow the same path with explicit calls and see where the differences are.
Are you using weak keys that may cause values to disappear if there are no other references?
Can you provide a "default" value when you detect that it fails and continue to see if it "finds" this method again later? Or when it's broken, it's broken for every call after that?
What if you save a proper value for addItem and "fix" it when you detect it's broken?
What if you simply handle the error (as you do) and call it 10 times? Would it show valid results at least once (after it fails)? 100 times? If you keep calling the same method when it works, will it fail? This may help you to come up with a more reproducible error.
I'm not familiar with LuaWrapper to provide more specific questions, but these are the steps I'd take if I were you.
I strongly suspect the issue is that you have a class or struct similar to this:
struct Foo
{
Bar bar;
// Other fields follow
}
And that you've exposed both Foo and Bar to Lua via LuaWrapper. The important bit here is that bar is the first field on your Foo struct. Alternatively, you may have some class that inherits from some other base class and both the derived and base class are exposed to LuaWrapper.
LuaWrapper uses an function called an Identifier to uniquely track each object (like whether or not the given object has already been added to the Lua state). By default it uses the object address as a key. In cases like the one posed above it is possible that both Foo and Bar have the same address in memory, and thus LuaWrapper can get confused.
This may result in grabbing the wrong object's metatable when attempting to look up a method. Clearly, since it's looking at the wrong metatable it won't find the method you want, and so it will appear as if your metatable has mysteriously lost entries.
I've checked in a change that tracks each object's data per-type rather than in one giant pile. If you update your copy LuaWrapper to latest one from the repository I'm fairly certain your problem will be fixed.
After merging with upstream (commit 3c54015) LuaWrapper, this issue has disappeared. It appears to have been a bug in LuaWrapper.
Thanks Alex!
So after working on my last question, I boiled it down to this:
I need to add an unknown number user-defined classes (object_c) to a boost::intrusive::list. The classes have const members in them. All I need to do to push them to the list is to construct them and then have them persist, they automatically add themselves.
The code in question is basically
for (unsigned i = 0; i < json_objects.count(); ++i) {
ctor_data = read(json_objects[i]);
// construct object here
}
What I've tried:
mallocing an array of objects, then filling them in: Doesn't work, because I have const members.
static object_c *json_input = (object_c*) malloc(json_objects.size() * sizeof(object_c));
...
json_input[i](ctor_data); //error: no match for call to (object_c) (ctor_data&)
Making a pointer: This doesn't work, functions don't work properly with it, and it doesn't get destructed
new object_c(ctor_data);
Pushing the object back to an std::vector: This doesn't work, boost rants for dozens of lines when I try (output here)
vector_of_objects.push_back(object_c(ctor_data));
Just declaring the darn thing: Obviously doesn't work, goes out of scope immediately (dur)
object_c(ctor_data);
I'm sure there is an easy way to do this. Anyone have any ideas? I've been at this problem for most of the weekend.
#3 should be the method you need to use. You need to elabourate on what your errors are.
If it is just operator= as you show in your previous question, and you dont want to define one, you can try emplace_back as long as you are in C++11. Of Course I am talking std::vector, I need to check what is the equivalent if any in boost::intrusive. Edit: I might be wrong, but it doesnt seem to support move semantics yet..
Alternatively use #2 with smart pointers.
If you are going with #1, you would need to use placement new as #rasmus indicates.
At the end of the documentation's usage section it tells you that
“The lifetime of a stored object is not bound to or managed by the container”
So you need to somehow manage the objects’ lifetime.
One way is to have them in a std::vector, as in the documentation’s final example.
Sorry for the late reply, exam studying and all that.
It was simpler than I was making it out to be, basically. Also, for this answer, I'm referring to my class as entity_c, so that an object of entity_c actually makes sense.
What I was doing in my OP was when I push_back'd an entity_c, it was automatically adding itself to a global intrusive::list, and somehow that made it not work. After I stopped being lazy, I wrote up a minimal compilable progam and played around with that. I found out that making an std::vector to store the constructed entity_cs in worked (even though it deconstructs them when they're added? I dunno what that's about). Then all I had to do was populate a local intrusive::list with those objects, then clone the local list into the global list.
Thanks for all the help, I'll tweak that program to try and fit in different stuff, like placement new suggested by #rasmus (thanks for that, hadn't seen that before). Also thanks to #karathik for showing my emplace_new, I think I might have to go and find out about all these new C++11 features that have been added in, there are so many cool ones. I even learnt how to make my own copy constructor.
Truly and edifying educational experience.
I'm getting a seg fault that I do not understand. I'm using the Wt library and doing some fancy things with signals (which I only mention because it has enabled me to attempt to debug this).
I'm getting a pointer to one of my widgets from a vector and trying to call a method on the object it points to. Gdb shows that the pointer resolves, and if I examine the object it points to, it is exactly the one I need to modify. In this instance, the widget is broadcasting to itself, so it is registered as both the broadcaster and the listener; therefore, I was also able to verify that the 'broadcaster' pointer and the 'listener' pointer are accessing the same object. They do!
However, even though I can see that the object exists, and is initialized, and is in fact the correct object, when I try to call a method on the object, I get an immediate seg fault. I've tried a few different methods (including a few boolean returns that don't modify the object). I've tried calling them through the broadcaster pointer and the listener pointer, again, just to try to debug.
The debugger doesn't even enter the object; the segfault occurs immediately on attempting to call a method.
Code!
/* listeners is a vector of pointers to widgets to whom the broadcasting widget
* is trying to signal.
*/
unsigned int num_listeners = listeners.size();
for (int w = 0; w < num_listeners; w++)
{
// Moldable is an abstraction of another widget type
Moldable* widget = listeners.at(w);
/* Because in this case, the broadcaster and the listener are one in the same,
* these two point to the same location in memory; this part works. I know, therefore,
* that the object has been instantiated, exists, and is happy, or we wouldn't
* have gotten to this point to begin with. I can also examine the fields with gdb
* and can verify that all of this is correct.
*/
Moldable* broadcaster_debug = broadcast->getBroadcaster();
/* setStyle is a method I created, and have tested in other instances and it
* works just fine; I've also used native Wt methods for testing this problem and
* they are also met with segfaults.
*/
widget->setStyle(new_style); // segfault goes here!
}
I have read since researching that storing pointers in vectors is not the greatest idea and I should look into boost::shared_ptr. That may be so, and I will look into it, but it doesn't explain why calling a method on an object known to exist causes a segfault. I'd like to understand why this is happening.
Thanks for any assistance.
Edit:
I have created a gist with the vector operations detailed because it was more code than would comfortably fit in the post.
https://gist.github.com/3111137
I have not shown the code where the widgets are created because it's a recursive algorithm and in order to do that, I would have to show the entire class decision tree for creating widgets. Suffice to say that the widgets are being created; I can see them on the page when viewing the application in a browser. Everything works fine until I start playing with my fancy signals.
Moar Edit:
When I take a look at the disassembly in instruction stepping mode, I can see that just before the segfault occurs, the following operation takes place, the first argument of which is listed as 'void'. Admittedly, I know nothing about Assembly much to my chagrin, but this seems to be important. Can anyone explain what this instruction means and whether it might be the cause of my woes?
add $0x378,%rax //$0x378 is listed as 'void'
Another Edit:
At someone's suggestion, I created a non-virtual method that I am able to successfully call just before the seg fault, meaning the object is in fact there. If I take the same method and make it virtual, the seg fault occurs. So, why do only virtual methods create a seg fault?
I've discovered now that if in the calling class, I make sure to specify Moldable::debug_test (and Moldable::setStyle), the seg fault does not take place. However, this seems to have a similar effect as const bubbling -- every virtual method seems to want this specifier. I've never witnessed this behaviour before. While i'm willing to correct my code if that's REALLY how it's supposed to be, I'm not sure if the root problem is something else.
Getting there!
Well, I figured out the problem, though I'm sad to say it was a totally newbish mistake that due to the nature of the project was super difficult to find. I'll put the answer here, and I've also voted to close the question as too localized. Please feel free to do the same.
The BroadcastMessage class had a __broadcaster field (Moldable* __broadcaster;). When passing in the pointer to the broadcaster into the BroadcastMessage constructor, I forgot to assign the inbound pointer to that field, meaning __broadcaster was not a fully realised instance of the Moldable class.
Therefore, some methods were in fact working -- those that could be inlined, or my dummy functions that I created for testing (one of which returned a value of 1, for instance), so it was appearing that there was a full object there when in fact there was not. It wasn't until calling a more specialized method that tried to access some specific, dynamic property of the object that the segfault occurred.
What's more, most of the broadcast message lifespan was in its constructor, meaning that most of its purpose was fulfilled without issue, because the broadcaster was available in the local scope of the constructor.
However, using Valgrind as suggested, I did uncover some other potential issues. I also pretty much stripped-down and re-built the entire project. I trashed tons of unnecessary code and it runs a lot faster now as a side effect.
Anyway, thanks for all the assistance. Sorry the solution wasn't more of a discovery.
Okay: I'm fairly new to C++ and static languages on a whole. Coming from years of ruby (and other dynamic languages) I don't know if this is possible.
I've been making a game state system for... well a game. I want to make the system easy for me to cut and paste into other games without any (or very few) changes.
The two things I am wanting to improve are the way in which states switch and the way in which state pointers are held.
There could be any number of states, but there will always be at least 2 to 3 states active in memory.
Ugliness No 1.
Currently I have a state manager class with something like this in it:
void StateManager::changeState(StateID nextStateID)
{
// UNFOCUS THE CURRENT STATE //
if (currentState())
{
currentState()->onUnFocus();
// DESTROY THE STATE IF IT WANTS IT //
if(currentState()->isDestroyedOnUnFocus()) {
destroyCurrentState();
}
}
if (m_GameStates[nextStateID]) {
// SWITCH TO NEXT STATE //
setCurrentState(nextStateID);
}
else
{
// CREATE NEW STATE //
switch (nextStateID)
{
case MainMenuStateID:
m_GameStates[MainMenuStateID] = new MainMenuState;
break;
case GameStateID:
m_GameStates[MainMenuStateID] = new GameStates;
break;
};
setCurrentState(nextStateID);
}
// FOCUS NEXT STATE //
currentState()->onFocus();
}
This approach works but I don't feel it's very nice.
Is it possible to pass a type? And then call new on it?
new NextGameState; // Whatever type that may be.
Can poloymophism help here? All States are derived from a class State.
Ugliness No 2.
Another thing I think needs some improvement is the way I've been storing the states.
State* m_GameStates[MaxNumberOfStates];
All the states are initialized to NULL, so I can test if a state is there, and if not it creates one when needed.
It works well as I can call the current state:
m_GameStates[m_CurrentState];
However, I don't like this for two reasons. It seems a bit of a waste having an array full of NULL pointers when there will only be 2 or 3 pointers active at any one time. [Editor's note: what is the second reason?]
I thought about shifting this into a vector_ptr, but didn't as it would create extra complications with checking to see if a state exists. And the vector seems to reinforce Ugliness No 1. as I need to have a list to check each state.
Any advice or direction appreciated.
Thanks,
Phil.
Use a enum(eration) to define all possible states (its something like a list with constants).
Just create for one object one variable that holds the state and change the variable whenever you need to change it.
As soon as you say States, I think of the State pattern.
Basically, you can derive a bunch of objects from a State base class. All actions related to a state occur against the current state maintained by the state manager. States will move from state to state via the manager.
For instance, you can have a Paused and Unpaused state, each with a buttonPressed event. When you press a button, the current state is delivered the event. If it's in Paused, and the button was the pause button, move to Unpaused. Vice versa for Unpaused.
void StateManager::changeState(StateID nextStateID)
{
leaveState(actualState);
enterState(nextStateID);
}
I really like this one - as easy as it could be. ;-)
What I want to tell you - I think doing creation/deleting your stats in the changeState Function is too much of logic in there - it just is supposed to change the state, right?
Edit:
To come to your 2 question - I don't think using this array is really a waste - you are talking about 3 fields, not 300 or so. So if you like using arrays - go for it. If you don't, the map would be my choose, it makes things easy if you want to check if there is a state created or not and you are not limited to a magic number "maxStates". You could possible check if there is enough ram and then create X states, not fixed 2-3.
For generating states you want a factory. That way the state id stays nice an generic. For storing states I would go with a std::map
For your first problem, yes, you can pass in a type, with some caveats.
I've added a comment under your question, asking for a bit more information. Until we get that, I can't really say how it should be done, but read up on templates.
You can make a function template, which can be passed a type, for example like this:
template <typename T>
void Foo() {
T* x = new T();
...
}
Foo<int>() // call Foo with the type T set to 'int'
There are some limitations to this, as the types have to be specified at compile-time, but it is a very powerful language feature.
Another option, which might work better since you seem to have an association between a variable (MainState) and a type (MainMenu), might be the use of traits classes. Again, I'm unsure of exactly how it'd be done in your case, since we haven't seen the entirety of the function (in particular, what type is MainState, and how/when is it created?)
It might also be possible to solve the problem through polymorphism, but again, I'd need to see a bit more of the context to suggest a solution.
For your second problem, you can use the standard library map:
#include <map>
// I'm not sure what type m_CurrentState is, so use its type instead of KeyType below
std::map<KeyType, State*> m_GameStates;
// and to perform a lookup in the map:
GameStates[m_CurrentState];
Finally, a really really important bit of advice:
Stop using pointers everywhere. Stop calling new to create new objects.
As a general rule, objects should be created on the stack (Instead of Foo* f = new Foo;, just do Foo f;
And instead of using pointers, you'll often want to just copy the object itself. Alternatively, create references instead of pointers.
And when you do need to use dynamic memory allocations, you still shouldn't use new directly. Instead, create a wrapper object, which internally allocates what it needs with new in its constructor, and frees it again in the destructor.
If you do this correctly, it pretty much solves all the headaches of memory management.
The general technique is called RAII.
Take a look at Boost Statechart Library