I created a function
static int init_module(void)
{
}
Then ran CppCheck. It doesn't complain that there's no return statement, and it'd be reasonable if it complained.
Why?
Related
I am calling a Rust function in a native DLL from C# like this:
[DLLImport("rust.dll")]
public static int Foo(int i);
public static void Invoke() {
typeof(Program).GetMethod("Foo").Invoke(new object[] {null}, new object[] {1});
}
public static void Call() {
Foo(1);
}
I want to check if a the method is called directly or by using Invoke. If it's invoked the method should print "Invoked", if not it should print "Called". I'm not really sure if you can differentiate between these two things.
No, this is not possible, without doing something very weird, which definitely would not portable, futureproof or in any way robust.
From inside Rust, a function call is a function call, no matter which foreign API was used to call it.
I've got the following MQL code:
class Collection {
public: void *Get(void *_object) { return NULL; }
};
class Timer {
protected:
string name;
uint start, end;
public:
void Timer(string _name = "") : name(_name) { };
void TimerStart() { start = GetTickCount(); }
void TimerStop() { end = GetTickCount(); }
};
class Profiler {
public:
static Collection *timers;
static ulong min_time;
void Profiler() { };
void ~Profiler() { Deinit(); };
static void Deinit() { delete Profiler::timers; };
};
// Initialize static global variables.
Collection *Profiler::timers = new Collection();
ulong Profiler::min_time = 1;
void main() {
// Define local variable.
static Timer *_timer = new Timer(__FUNCTION__); // This line doesn't.
//Timer *_timer = new Timer(__FUNCTION__); // This line works.
// Start a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStart();
/* Some code here. */
// Stop a timer.
((Timer *) Profiler::timers.Get(_timer)).TimerStop();
}
which defines a Timer class which is used as a timer to profile the functions how long it took. The original version uses a list of timers to store time separately on each call, however, the code has been simplified to provide a minimum working example and focus on the actual compilation problem.
The problem is when I'm using the following line in order to initialize a static variable:
static Timer *_timer = new Timer(__FUNCTION__); // Line 30.
the compilation fails with:
'Timer' - local variables cannot be used TestProfiler.mqh 30 30
When I drop static word, the code compiles fine.
But it doesn't help me, as I want to define this variable as a static pointer to the class, as I don't want to destroy my object each time when the same function is called over and over again, so the timers can be added to the list which can be read later on. I don't really see why the MQL compiler would prevent from compiling the above code. I also believe this syntax worked fine in the previous builds.
I'm using MetaEditor 5.00 build 1601 (May 2017).
What is wrong with my static variable declaration and how can I correct it, so it can point to a Timer class?
Keyword static has two different meanings in MQL4/5: it indicates that a member of a class is static (which is obvious), and it also says that a variable is static... for instance, if you have a variable that is used only in one function, you probably do not need to declare it globally but as a static. You can find an example of isNewBar() function that has static datetime lastBar=0; in the articles about new bar at mql5.com. This keyword in such a function says that the variable is not deleted after function is finished, but remains in memory and is used with the next call. And if you need a variable in OnTick() function - it does not make sence to have it static, declare it globally.
How can I force PHPUnit to stop running completely and exit when a specific condition (an error of my own choosing) is met? Effectively, what I need is something like the below, except that in reality PHPUnit traps the exit() and continues running instead of exiting.
// PHPUnit does not alter existing but empty env vars, so test for it.
if (strlen(getenv('APP_HOME')) < 1) {
$this->fail('APP_HOME set but empty.');
exit(1); // <-- Does not work.
}
Note: I want to continue running normally for other errors and failures, hence setting stopOnError="true" or stopOnFailure="true" in my XML file is not what I need.
I think you can achieve this by doing a few overrides and adding some custom behaviour to a base test case class.
EDIT:
As found by the OP after running the below code, calling exit(1); rather than $result->stop() will cause correct termination of the test at that point.
Try the following:
class MyBaseTestCase extends \PHPUnit_Framework_TestCase
{
// Test this flag at every test run, and stop if this has been set true.
protected $stopFlag = false;
// Override parent to gain access to the $result so we can call stop()
public function run(\PHPUnit_Framework_TestResult $result = null)
{
$result = parent::run($result);
if ($this->stopFlag === true)
{
//$result->stop(); // Stop the test for this special case
exit(1); // UPDATED: This works to terminate the process at this point
}
return $result; // return as normal
}
}
Then in a test case class:
class MyTestCase extends MyBaseTestCase
{
public function testThisStopsPhpunit()
{
if (strlen(getenv('APP_HOME')) < 1) {
$this->fail('APP_HOME set but empty.');
$this->stopFlag = true; // Stop further processing if this occurs
}
}
}
I'm trying to pass a member function as a function pointer so that I don't need to rely on singletons or global functions to handle Qt messages in Qt 5. As far as I can tell my std::function is of the correct type, it has the correct signature, and bind should be allowing me to jam in the implicit this pointer, essentially passing off a member function as a global/un-owned function.
void ProgramMessageHandler::setAsMessageHandlerForProgram() {
std::function<void(QtMsgType, const QMessageLogContext &, const QString &)> funcPtr;
funcPtr = std::bind(handleMessages, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
qInstallMessageHandler(funkPtr);
}
This doesn't compile. I can succesfully create my funcPtr variable but passing it into the qInstallMessageHandler function causes the following:
log\ProgramMessageManager.cpp:16: error: cannot convert 'std::function<void(QtMsgType, const QMessageLogContext&, const QString&)>' to 'QtMessageHandler {aka void (*)(QtMsgType, const QMessageLogContext&, const QString&)}' for argument '1' to 'void (* qInstallMessageHandler(QtMessageHandler))(QtMsgType, const QMessageLogContext&, const QString&)'
oldHandler = qInstallMessageHandler(hackedPointerToHandleFunction);
^
I have read:
how to pass a member function as a function pointer?
How do you pass a member function pointer?
How to pass a member function as a parameter to a function that doesn't expect it?
Get function pointer from std::function when using std::bind
but none have helped me.
EDIT:
So it has been said that this isn't possible without a singleton or a global funtion... but why? The only difference between a member function and a global function with the same signature is that they don't have the same signature, there is an implicit this pointer as the first parameter to a member function.
Knowing that, why cannot I use std::bind to bridge this gap, by saying 'I know that the function being called takes the this argument before all of the others, force it in there, be the thing that knows about this. That would be so much cleaner than a singleton and a global function is just crap.
You are trying to pass a class instance where a function pointer is expected, while no such conversion exists.
You could do something like this:
class ProgramMessageHandler
{
static void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);
};
in main.cpp (for example):
...
qInstallMessageHandler(ProgramMessageHander::myMessageHandler);
...
You still might have to deal with some issues as in singleton classes, but I think it makes sense that there is one message handler or at least one dispatcher that would somehow redirect different message to appropriate handlers. Hope this helps
The result of std::bind is a function object and, as the error message says, you cannot convert a function object to a function pointer. A function pointer cannot store the this pointer like std::function can, you can't just "force it in there".
The only way to do something approaching what you want is to use a singleton to store the this pointer:
class ProgramMessageHandler {
private:
static ProgramMessageHandler* currentHandler;
void handleMessagesImpl(const std::string& message);
public:
void setAsMessageHandlerForProgram(){
currentHandler = this;
qInstallMessageHandler(handleMessages);
}
static void handleMessages(const std::string& message) {
if (currentHandler)
currentHandler->handleMessagesImpl(message);
}
};
ProgramMessageHandler* ProgramMessageHandler::currentHandler = nullptr;
int main() {
ProgramMessageHandler handler;
handler.setAsMessageHandlerForProgram();
// trigger messages...
}
Live demo.
i try to use std::map as property in my class. I use Visual Studio 2012, and my class is like:
public ref class MyClass
{
std::map<std::wstring,MyType> * mpMyMap;
MyClass()
{
mpMyMap = new std::map<std::wstring,MyType>();
}
~MyClass()
{
delete mpMyMap;
}
Get(std::wstring name)
{
return mpMyMap[name];
}
}
At return mpMyMap[name]; I get error, what there is no operator[] for this type. What should I do?
the bracket operator is on the map, not on the pointer of a map...
Try : return (*mpMyMap)[name];
The correct syntax is
MyType Get(std::wstring name)
{
return (*mpMyMap)[name];
}
You could also make the map an instance member instead of a pointer
std::map<std::wstring,MyType> mMyMap;
then your original code in Get would work and you'd get rid of memory management in the constructor and the destructor of MyClass.
Use
return (*mpMyMap)[name];
or
return mpMyMap->operator[]( name );
P.S. What is this
public ref class MyClass
//^^^^^^^^^^
Also, add return type for Get (MyType in your case)
mpMyMap is a pointer (for which I can see no reason), so you need to dereference it:
return (*mpMyMap)[name];
If mpMyMap must be a dynamically allocated remember to delete it in the destructor and either prevent copying of MyClass or implement copy constructor and assignment operator.
Note Get() is missing a return type (which should be either MyType or MyType&). Make the argument to Get() a const std::wstring& to avoid unnecessary copying and const as Get() does not modify it.
Since mpMyMap is pointer first variant is
Get(std::wstring name)
{
return (*mpMyMap)[name];
}
And second
Get(std::wstring name)
{
return mpMyMap->operator[](name);
}
And Get should have return-type.