I have some problems getting a macro in Unreal blueprint converted to C++. The macro influences a lot of my code, and in the picture included, the C++ code is not similar to the macro which the code is based on
The code is based on this
bool AGrid::TileValid(int Row, int Column)
{
if (((Row >= 0) && (Row < NumRows)) && ((Column >= 0) && (Column<NumColumns)))
{
return true;
}
return false;
}
Any suggestion on how I can implement this code?
I'm unsure as to what exactly isn't working?
I'm going to take a guess and say that you were expecting your (what is now a C++ function, not a Macro) TileValid Node from C++ does not have the Execution pins that the Blueprint Macro has.
Make sure that you do not mark your TileValid function with BlueprintPure, instead mark it with BlueprintCallable. Also make sure that it isnt marked as a const function, this will also affect its appearance and functionality.
BlueprintPure and/or const C++ functions which are BlueprintCallable do not require direct execution (the white lines) and are instead executed for everytime their output pin is wired into another Node, they will then be executed when that parent Node is executed. This can change their behavior, as variables they may use can change in-between subsequent executions, thus potentially altering their output.
This code did where both UFUNCTION(BlueprintCallable, BlueprintPure) in the callable H class. Removing the BlueprintPure from this code wold solve the executionable variable
Related
I cannot find it neither in the CookBook nor Advanced Part of Google Test Framework Tutorial. I have for example the following function that creates expectations:
void testFunc()
{
for (std::size_t i = 0; i < 10; i++)
EXPECT_CALL(dummyMock, mockFunc).WillOnce(Return(i))
}
And then I invoke this function in some Test Case
TEST(UnitTestCase, TestSomeMockFunc)
{
TestSomeFunction();
testFunc();
}
The question is how Google Test execute the code from testFunc. Does it make it after TestSomeFunction's execution? Or before it, for example during compilation time? And finally, where each "EXPECT_CALL" statement from testFunc is stored after execution of this function?
I'll try to answer your questions one by one, and then will proceed to the problems with your snippets.
The question is how Google Test execute the code from testFunc.
It doesn't. This part works just like any C++ code. First TestSomeFunction() is called, then follows testFunc(), which runs loop 10 times. Nothing unusual here.
Does it make it after TestSomeFunction's execution?
Yes, because testFunc() is called after TestSomeFunction(). Functions are called sequentially, GoogleMock in theory could apply some macro magic, but this is not the case.
Or before it, for example during compilation time?
EXPECT_CALL macro is expanded during preprocessing phase, before compilation. Whatever is under it, is executed during runtime, just like any other function.
And finally, where each "EXPECT_CALL" statement from testFunc is stored after execution of this function?
I don't know that, but most likely it is stored somehow in mock object (i.e. dummyMock). I believe it's there because all expectations are verified in mock's destructor.
Now, about the first snippet, this is one feature of GoogleMock that I find more annoying than useful on most occasions.
for (std::size_t i = 0; i < 10; i++)
EXPECT_CALL(dummyMock, mockFunc()).WillOnce(Return(i))
Above code create 10 call expectations, but newer call expectations shadow previous ones. So, if your code will proceed to call mockFunc 10 times, you will have 9 expectations that were not called and 1 expectation called 10 times (also failing, it wanted single call).
If you don't need each call to return different values, use simply
EXPECT_CALL(dummyMock, mockFunc()).Times(10).WillRepeatedly(Return(0));
Hovewer, if you need different values each time, there are few things to consider:
Use RetiresOnSaturation() - Add it as the last call in the chain (after WillRepeatedly()). This will let you avoid the problem of shadowing previous expectations, because each expectation will be ignored after it's fulfilled.
Reverse order of adding expectations. - GoogleMock adds new expection in a Last In, First Out (LIFO) manner. This means the latest created expectation will be the first matched against (and executed).
Thus, to create GoogleMock expectations in such a way that it will return next number with each function call, the following code should work:
void testFunc()
{
for (std::size_t i = 9; i >= 0; i++)
EXPECT_CALL(dummyMock, mockFunc()).WillOnce(Return(i)).RetiresOnSaturation();
}
Of course, expectations should be set before mock functions are called in tested code, because otherwise GoogleMock will have no knowledge that you plan to do such things.
Is it possible to define a section or scope in my code within which a different code path is executed, without using a global or passed-down state variable?
For debugging purposes, I want to be able to surround a section of faulty code with a scope or #define to temporarily switch on pre-defined debugging behavior within this section, e.g. use debug data, a more precise data type, an already validated algorithm, … This needs to work in a multi-threaded application in which multiple threads will likely execute the same shared code concurrently, but only some of them have called this code from within the defined section.
For example, here is some pseudo-code that is not working, but might illustrate what I'd like to do. A static expensive function that is called from several places concurrently:
Result Algorithms::foo()
{
#ifdef DEBUG_SECTION
return Algorithms::algorithmPrecise(dataPrecise);
#else
return Algorithms::algorithmOptimized(dataOptimized);
#endif
}
Three classes of which instances need to be updated frequently:
Result A::update()
{
return Algorithms::foo();
}
Result B::update()
{
Result result;
#define DEBUG_SECTION
...
result = a.update() + 1337;
...
#undef DEBUG_SECTION
return result;
}
Result C::update()
{
return a.update();
}
As you can see, class A directly calls foo(), whereas in class B, foo() is called indirectly by calling a.update() and some other stuff. Let us assume B::update() returns a wrong result, so I want to be able to use the debug implementation of foo() only from this location. In C::update(), the optimized version should still be used.
My conceptual idea is to define a DEBUG_SECTION around the faulty code which would use the debug implementation at this location. This, however, does not work in practice, as Algorithms::foo() is compiled once with DEBUG_SECTION not being defined. In my application, Algorithms, A, B, and C are located in separate libraries.
I want that within a section defined in the code, a different code section within shared code is executed. However, outside of this section I still want execution of the original code, which at runtime will happen concurrently, so I cannot simply use a state variable. I could add a debugFlag parameter to each call within the DEBUG_SECTION that is passed down in each recursive call that is then provided to Algorithms::foo(), but this is extremely prone to errors (you must not miss any calls, but the section could be quite huge, spread over different files, …) and quite messy in a larger system. Is there any better way to do this?
I need a solution for C++11 and MSVC.
This might work by using a template:
template<bool pDebug>
Result Algorithms::foo()
{
if(pDebug)
return Algorithms::algorithmPrecise(dataPrecise);
else
return Algorithms::algorithmOptimized(dataOptimized);
}
On the other hand this means moving your function definition into a header (or forcing template instantiation, see these answers).
The downside is that changing the call to Algorithms::foo() from instance.foo<false> to instance.foo<true> every time you want to switch between debugging and release might require effort. If you have multiple affected calls you could use a compile time const variable to reduce the typing effort, but not knowing your code exactly I can't estimate if this is a feasible solution.
If the majority of your code uses the optimized version of the function you can also set the template parameter to default to false (template<bool pDebug = false>) to avoid changing existing code that will not call the debug-version.
I'm writing a 2048 program for the terminal for university.
To play the game my program needs to either shift left, right, up, or down. So I have two options:
Write a function that takes the direction as a parameter and then
acts accordingly through if statements.
void move(string direction) {
if (direction == "up")
//do stuff
if (direction == "left")
//do stuff
//etc.
}
Write four functions, one for up, down, left right and put the if statements in main().
int main() {
cin << direction;
if (direction == up)
moveup();
//etc.
}
I read google's cpp style guide and it said functions should ideally be kept short. But if I write four functions I will also have a lot of repeated code. As of now I have used option 1 and my move() function is 70 lines long.
What is considered better practice?
The second option is generally considered to be the best. I don't see why you would have repeated code, as what move-left (for example) does is likely to be different from what move-up does. And if there is repeated code, put that code in yet another function and call it from your move functions. In general, beginner programmers do not write enough functions - it's pretty hard to have too many.
Is it good practice to put if statements in main() or inside functions to respond to user input?
Both options are fine. The latter option allows re-use of functionality and I recommend it if you have repeating patterns in the main function.
But if I write four functions I will also have a lot of repeated code.
A solution is to introduce a fifth function, that contains the parts that are common to the other functions. Then call that function from the others. This is what functions are for: partitioning re-usable functionality.
Is there a way to tell g++ more about a type, function, or specific variable (other than attributes) that I might know is safe to preform.
Example:
TurnLedOn();
TurnLedOn();
Only the first function actually turns the LED on the second function does not actually do anything....so would it be possible to tell g++ more about the function so that it gets rid of a second call if it knows that the LED is on (because it knows that a corresponding TurnLedOff() function has not been called)....
The reason I do not want to use g++ attributes is because I want to arbitrarily define optimizations, which is really not possible with attributes (and I believe the optimization I am trying here is not actually possible to begin with using attributes)
These are optimisations you need to code. Such as:
class LedSwitch {
bool isOn{false};
public:
inline void turnLedOn(){
if (!isOn) {
isOn = true;
// ...
}
}
// ...
}
// ...
If the code inlines then the compiler might then notice the bool negated in the second hardcoded sequential call, but why do that in the first place?
Maybe you should revisit design if things like this are slowing down your code.
One possibility is to make it so that the second TurnLedOn call does nothing, and make it inline and declare it in a header file so the compiler can see the definition in any source file:
extern bool isLedOn; // defined somewhere else
inline void TurnLedOn()
{
if(!isLedOn)
{
ActuallyTurnLedOn();
isLedOn = true;
}
}
Then the compiler might be able to figure out by itself that calling TurnLedOn twice does nothing useful. Of course, as with any optimization, you have no guarantees.
Contrary to your thinking, the answer by #immibis is what you were expecting.
This way to describe the complex behavior of the function TurnLedOn (i.e. needn't be called twice in a row unless unlocked by some other action) is indeed how you tell the compiler to perform this "optimization".
Could you imagine other annotations such as
#pragma call_once_toggle_pair(TurnLEDOn, TurnLEDOff)
with innumerable variants describing all your vagaries ?
The C++ language has enough provisions to let you express arbitrarily complex situations, please don't add yet a layer of complexity on top of that.
At the very first, apologies in advance for the very indistinct presentation of the question - if I knew what to ask for, I would probably know how to fix it.
... But I do not even have a faint theory, seven years of C++ experience notwithstanding. Any helpful pointers (hè) will be most appreciated.
Possibly related to this question. (same symptoms)
Not related to that one. (no explicit function pointers here)
Problem: A count of objects with certain properties, which themselves are checked by a member function of their class shows incorrect results. The source is that the check happens with gibberish values. The source of that is that the pointer "this" changes between calling the function and entering its body. Once the body is left, the pointer is again correct.
Sadly, the solution for the related question does not work here.
I am not able to produce a minimal example of the problem.
Furthermore, literally hundreds of member functions are being called correctly in the same program, as far as I know without exhibiting this behaviour.
What can I do?
As a bandaid, replacing the function call with a copy of its body works, but this is no proper solution.
I am at a complete loss as to how to proceed with my diagnosis.
Concise: What steps can I follow to attain greater insight into the nature of the problem?
A short checklist of things already taken care of:
The objects in question are properly initialised at the time of the call.
All optimisations are off. No inlining. This is a debug build with the appropriate settings in effect.
Cleaning and rebuilding the project has not yielded a different result.
Recompiling with the original (but retyped) function call after the bandaid solution had been tested successfully led to a return of the problem.
There are no compiler warnings in the compilation unit involved (warning level 3), specifically disabled project-wide are:
C4005 (macro redefinition, due to using a custom/hacked Windows SDK for compatibility reasons - this was originally a Win95 program)
C4244 (implicit cast to smaller type, due to legacy code waiting to be refactored - those are all float-to-int conversions that lack an explicit cast, all 800+ instances of them)
C4995 (calling function marked with #pragma deprecated, due to C-lib functions being called without preceding underscore - hoping to eventually switch to GCC)
"control flow guard" and "basic runtime checks" are enabled, but do not trigger.
And a hint that may or may not be relevant, but which I cannot interpret at the moment:
For the very first hex, IsSea is called normally, that is: "this" inside is identical to "this" outside
Only in all hexes that follow does the bug happen.
The altered "this" pointer does not point to the first hex though, it seems to hit unallocated space.
Here is an extract of how it looks like:
Header:
// These three are actually included from other files.
constexpr unsigned int AREA_none = 0u;
constexpr unsigned int AREA_Lake = 1u;
enum Terrain
{
OCEAN = 8,
TERRA_INCOGNITA = 10
};
class CHex
{
public:
CHex(); // initialises ALL members with defined error values
bool ReadHex(); // Init-type function calling the problematic one
bool IsSea() const // problematic function
{ return this->_Area != AREA_none && this->_Area != AREA_LAKE && this->_nTerrain == Terrain::OCEAN; }
// The body does the right thing - just WITH the wrong thing.
protected:
unsigned int _Area;
int _nNavalIndex;
Terrain _nTerrain;
static int _nNavalCount = 0;
// There are a lot more functions in here, both public and protected.
// The class also inherits a bunch from three other classes, but no virtual functions and no overlaps are involved.
}
Source:
CHex::CHex() : _Area{0u}, _nNavalIndex{0}, _nTerrain{Terrain::TERRA_INCOGNITA}
{}
bool CHex::ReadHex()
{
// Calls a lexer/parser pair to procure values from several files.
// _Area and _nTerrain are being initialised in this process.
// All functions called here work as expected and produce data matching the source files.
// _Area and _nTerrain have the correct values seen in the source files at this point.
if(this->IsSea()) // but inside that it looks as if they were uninitialised
// This ALWAYS happens because the function always returns true.
_nNavalIndex = _nNavalCount++;
// Stopping at the next instruction, all values are again correct
// - with the notable exception of the two modified by the instruction that should not have happened.
// If I replace that with the following, I receive the correct result:
/*
// direct copy of the function's body
if(this->_Area != AREA_none && this->_Area != AREA_Lake && this->_nTerrain == Terrain::OCEAN)
_nNavalIndex = _nNavalCount++; // only happens when it should; at the end, the count is correct
*/
// Sanity checks follow here.
// They too work correctly and produce results appropriate for the data.
return true; // earlier returns exist in the commented-out parts
}
Sorry again for this big mess, but well, right now I am a mess. It's like seeing fundamental laws of physics change.
--
On advice from #Ben Voigt I hacked in a diagnostic that dumps the pointers into a file. Behold:
Before ReadHex: 20A30050 (direct array access) On ReadHex: 20A30050 On IsSea: 20A30050 (with members: 0, 8) After ReadHex: 20A30050
Before ReadHex: 20A33EAC (direct array access) On ReadHex: 20A33EAC On IsSea: 20A33EAC (with members: 2, 0) After ReadHex: 20A33EAC
Before ReadHex: 20A37D08 (direct array access) On ReadHex: 20A37D08 On IsSea: 20A37D08 (with members: 2, 0) After ReadHex: 20A37D08
Before ReadHex: 20A3BB64 (direct array access) On ReadHex: 20A3BB64 On IsSea: 20A3BB64 (with members: 3, 0) After ReadHex: 20A3BB64
Before ReadHex: 20A3F9C0 (direct array access) On ReadHex: 20A3F9C0 On IsSea: 20A3F9C0 (with members: 4, 3) After ReadHex: 20A3F9C0
Before ReadHex: 20A4381C (direct array access) On ReadHex: 20A4381C On IsSea: 20A4381C (with members: 3, 0) After ReadHex: 20A4381C
[...]
They are all correct. Every single one of them. And even better: The function now evaluates correctly!
Here is the changed source (I am omitting the comments this time):
Header:
// These three are actually included from other files.
constexpr unsigned int AREA_none = 0u;
constexpr unsigned int AREA_Lake = 1u;
enum Terrain
{
OCEAN = 8,
TERRA_INCOGNITA = 10
};
extern FILE * dump;
class CHex
{
public:
CHex();
bool ReadHex();
bool IsSea() const {
fprintf(dump, "\tOn IsSea:\t%p (with members: %u, %i) ", (void*)this, this->_Area, this->_nTerrain);
return this->_Area != AREA_none && this->_Area != AREA_LAKE && this->_nTerrain == Terrain::OCEAN; }
protected:
unsigned int _Area;
int _nNavalIndex;
Terrain _nTerrain;
static int _nNavalCount = 0;
// lots more functions and attributes
}
Source:
CHex::CHex() : _Area{0u}, _nNavalIndex{0}, _nTerrain{Terrain::TERRA_INCOGNITA}
{}
bool CHex::ReadHex()
{
fprintf(dump, "On ReadHex:\t%p ", (void*)this);
// Calls a lexer/parser pair to procure values from several files.
// _Area and _nTerrain are being initialised in this process.
if(this->IsSea()) // Suddenly works!?
_nNavalIndex = _nNavalCount++;
// Sanity checks follow here.
fprintf(dump, "After ReadHex:\t%p ", (void*)this);
return true;
}
The additional outputs (as well as the initialisation and closing of dump) come from the next higher level in the control flow, another function in another class, where the loop over all hexes resides. I omitted that for now, but will add it if someone thinks it's important.
And apropos that. It now looks to me as if this fault were a result of bugs in the tools, not in the code. As a matter of fact, even though the function now evaluates correctly, the debugger still shows the wrong pointer from before and its nonsensical members.
EDIT for OP edit:
This now smells even more like a ODR violation. Changing an inline function, and having that change program behavior is exactly what could happen with the undefined behavior induced from ODR violations. Do you use templates anywhere? Also, try de-inlining IsSea() in the original version to see if that helps.
(original answer):
This smells like one of three things to me.
First, it could be a one-definition-rule violation for the function in question. Make absolutely certain there aren't multiple versions in different translation units, or different compilation settings in different units.
Secondly the compiler could be doing something because of your use of the reserved name _Area. Regardless of anything else you should fix this problem.
Thirdly, VC++ can utilize different mechanisms for member function pointers, and possibly one of those is affecting your case here (even given that you don't show use of member function pointers). See https://msdn.microsoft.com/en-us/library/83cch5a6.aspx?f=255&MSPPError=-2147217396 for some information. Another possibility is that the compiler options for such pointers are different across translation units.
This is a very sad answer, but alas, sometimes a sad answer is nevertheless correct.
Let us start with the smaller but at least somewhat useful part:
The values VS2015's debugger displays for the this pointer - and in extension all members of the object pointed to - are indeed incorrect and in a very reproducable way:
If a breakpoint is set on a member function defined in a header file, "this" displayed in the debugger will display - the entry point of this function. It will still have the type of the object in question and display all the members... but as those values are populated as offsets from the entry point of said function, their displayed contents are of course nonsensical.
All of this is purely a UI issue and does not affect the actual program execution.
And now the useless and depressing part:
The fault which originally prompted me to open this topic, which persisted through several compilations with different build settings - is gone and can no longer be reproduced after I put in the fprinf commands to dump the pointer addresses to a file in order to discover the bug described above.
Even though the code is letter by letter identical to the formerly faulty code, it now works flawlessly. Further alterations have done nothing to change this. I cannot bring it back, try as I might.
This whole dastard thing - was a fluke. Somehow. Which means that it may happen again, at any time, for no apparent reason, without any means of prevention whatsoever. Great, is it not?
...
In any case, heartfelt thanks to #Ben Voigt for raising the notion that mayhap those debugger outputs may not be related to reality in the first place.
Similarly, thanks to #dyp for pointing out and explaining an unrelated potential issue (names prefixed by '_' followed by a capital letter being reserved expressions) I was not aware of before.
Thanks to #Mark-B for actually providing hypotheses about the problem, even if none of them proved to be correct. At least there were some and one might have been.