What are the benefits of using Q_UNUSED macro over omitting an argument name in the function?
Q_UNUSED version:
void f(int x) {
Q_UNUSED(x);
}
Omitting version:
void f(int) {
}
I thought there are guidelines which say to use it somewhy, but I did not found anything about it there. Next thought was that someday the omitting did not exist in the standard but the compiler does not throw the error on omitting the variable name for any standard (98, 03, 11, 14, 17).
So why Qt uses this macro if it is useless and makes one more place to write a mistake?
Q_UNUSED can prevent the compiler from overreacting at more than one case of parameter not handled. Also, we can have an object instantiated with no single call from it:
MyClass myObject;
Q_UNUSED(myObject)
The most frequent case for me is QMutexLocker:
void qtFunc()
{
// and no other line of code in that function accesses `lock`
QMutexLocker lock(&m_mutex);
// it just protects this scope with some object shared with other threads
Q_UNUSED(lock) // shut up, compiler
}
And theoretically (maybe often) we can have a similar situation, not necessarily mutex locker when we initially write the code with the object on stack and then decided instead to pass the reference to it via the parameter before we figured out the final use of it. I personally don't like to revisit such insignificant "moments" in the code to fix some warning. So I use Q_UNUSED right and left when the code unfinished.
P.S. Of course the very fact of compiler emitting the "unused-variable" warning depends on compiler's options.
Related
Is there a way in C++ to design a function / add some "attributes" to it in such a way that calling it several times in the code would raise a compile time error?
To give a bit of background / motivation: I was programming on Mbed-OS and I did a couple of mistakes that look like:
rtos::Thread thread;
[lots of code]
thread.start(persistent_function_1);
[lots of code in a setup function]
thread.start(persistent_function_2);
This had the (logical) consequence that the persistent_function_1, which should have been allowed to execute for the lifetime of the program, only got to execute until the thread was re-purposed to run persistent_function_2. It took me a long time to find this bug, and I was wondering if I can do something to my thread.start function to make sure I get a compiler error if I make this sort of mistake again.
I don't think there is a way to coerce the C++ language directly to detect double invocation of start() at compile time (put differently, I don't think #user4581301's suggestion would work): to statically assert a property you'd need to somehow change the entity. I'm sure you could write a custom checker using clang but I guess that isn't what you are after. It would, obviously, be possible to have a run-time assertion which reports that an already start()ed thread is started again. Again, that doesn't seem to be what you are after.
The "obvious" solution is no to have "[lots of code]" in a function to start with. In fact, std::thread entirely side-steps that issue by enforcing that there is no code between the object declaration and its start: the std::thread is started upon construction. The setup with "[lots of code]" between the object declaration and the start would be something like
my::thread thread([&]{
[lots of code]
return persistent_function_1;
}());
The caveat is that you'd need to set up your various variables sort of out of order. That is, the preferred approach would be to declare the thread object at the site where it is actually started:
[lots of code]
my::thread thread(persistent_function_1);
In both of these cases my::thread would be a trivial wrapper around rtos::thread which doesn't expose a separate start() method. As I don't know why rtos::thread separates construction and start() and a plausible reason could be the ability to set up various thread parameters, it may be reasonable to actually use two separate arguments to my::thread's constructor:
A function taking a my::thread::properties entity as parameter which allows the necessary manipulations of the thread object.
The function to be started.
That is, something like
my::thread thread([](my::thread::properties& properties) {
[lots of code manipulating the properties]
},
persistent_function_1);
This way, it remains possible to manipulate the thread but you can't possible start() a thread twice.
One option is to wrap the thread in a new manager object, with the rough shape of
class thread_manager {
rtos::Thread thread;
const std::function<...> execution_function;
/* .
.
. */
public:
thread_manager(rtos::Thread _thread, std::function<...> function, ...)
: thread { _thread }
, execution_function { function }
, ...
void start();
}
and disallowing any other usage of threading (which can be justified on the basis of encapsulation, although as pointed out in comments, yahoos are always a risk).
There is no current mechanism for detecting an expression that appears twice. But you can torture the compiler to get something close
namespace
{
template<int>
struct once
{
once() {}
friend void redefine() {}
};
}
#define ONCE(expr) (once<__COUNTER__>{}, (expr))
If ONCE ever appear twice in the same TU, the compiler will complain about redefining redefine.
ONCE(thread.start(persistent_function_1)); // ok
ONCE(thread.start(persistent_function_2)); // error
I have three threads in an application I'm building, all of which remain open for the lifetime of the application. Several variables and functions should only be accessed from specific threads. In my debug compile, I'd like a check to be run and an error to be thrown if one of these functions or variables is accessed from an illegal thread, but I don't want this as overhead in my final compilation. I really just want this so I the programmer don't make stupid mistakes, not to protect my executing program from making mistakes.
Originally, I had a 'thread protected' class template that would wrap around return types for functions, and run a check on construction before implicitly converting to the intended return type, but this didn't seem to work for void return types without disabling important warnings, and it didn't resolve my issue for protected variables.
Is there a method of doing this, or is it outside the scope of the language? 'If you need this solution, you're doing it wrong' comments not appreciated, I managed to near halve my program's execution time with this methodology, but it's just too likely I'm going to make a mistake that results in a silent race condition and ultimately undefined behavior.
What you described is exactly what assert macro is for.
assert(condition)
In a debug build condition is checked. If it is false, the program will throw an exception at that line. In a release build, the assert and whatever is inside the parentheses aren't compiled.
Without being harsh, it would have been more helpful if you had explained the variables you are trying to protect. What type are they? Where do they come from? What's their lifetime? Are they global? Why do you need to protect a returned type if it's void? How did you end up in a situation where one thread might accidentally access something. I kinda have to guess but I'll throw out some ideas here:
#include <thread>
#include <cassert>
void protectedFunction()
{
assert(std::this_thread::get_id() == g_thread1.get_id());
}
// protect a global singleton (full program lifetime)
std::string& protectedGlobalString()
{
static std::string inst;
assert(std::this_thread::get_id() == g_thread1.get_id());
return inst;
}
// protect a class member
int SomeClass::protectedInt()
{
assert(std::this_thread::get_id() == g_thread1.get_id());
return this->m_theVar;
}
// thread protected wrapper
template <typename T>
class ThreadProtected
{
std::thread::id m_expected;
T m_val;
public:
ThreadProtected(T init, std::thread::id expected)
: m_val(init), m_expected(expected)
{ }
T Get()
{
assert(std::this_thread::get_id() == m_expected);
return m_val;
}
};
// specialization for void
template <>
class ThreadProtected<void>
{
public:
ThreadProtected(std::thread::id expected)
{
assert(std::this_thread::get_id() == expected);
}
};
assert is oldschool. We were actually told to stop using it at work because it was causing resource leaks (the exception was being caught high up in the stack). It has the potential to cause debugging headaches because the debug behavior is different from the release behavior. A lot of the time if the asserted condition is false, there isn't really a good choice of what to do; you usually don't want to continue running the function but you also don't know what value to return. assert is still very useful when developing code. I personally use assert all the time.
static_assert will not help here because the condition you are checking for (e.g. "Which thread is running this code?") is a runtime condition.
Another note:
Don't put things that you want to be compiled inside an assert. It seems obvious now, but it's easy to do something dumb like
int* p;
assert(p = new(nothrow) int); // check that `new` returns a value -- BAD!!
It's good to check the allocation of new, but the allocation won't happen in a release build, and you won't even notice until you start release testing!
int* p;
p = new(nothrow) int;
assert(p); // check that `new` returns a value -- BETTER...
Lastly, if you write the protected accessor functions in a class body or in a .h, you can goad the compiler into inlining them.
Update to address the question:
The real question though is where do I PUT an assert macro? Is a
requirement that I write setters and getters for all my thread
protected variables then declare them as inline and hope they get
optimised out in the final release?
You said there are variables that should be checked (in the debug build only) when accessed to make sure the correct thread is accessing them. So, theoretically, you would want an assert macro before every such access. This is easy if there are only a few places (if this is the the case, you can ignore everything I'm about to say). However, if there are so many places that it starts to violate the DRY Principal, I suggest writing getters/setters and putting the assert inside (This is what I've casually given examples of above). But while the assert won't add overhead in release mode (since it's conditionally compiled), using extra functions (probably) adds function call overhead. However, if you write them in the .h, there's a good chance they'll be inlined.
Your requirement for me was to come up with a way to do this without release overhead. Now that I've mentioned inlining I'm obligated to say that the compiler knows best. There usually are compiler-specific ways to force inlining (since the compiler is allowed to ignore the inline keyword). You should be profiling the code before trying to inline things. See the answer to this question. Is it good practice to make getters and setters inline?. You can easily see if the compiler is inlining the function by looking at the assembly. Don't worry, you don't have to be good at assembly. Just find the calling function and look for a call to the getter/setter. If the function was inlined, you won't see a call and you'll see probably a mov instead.
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.
Based on a poorly stated and recently deleted SO question ("Is it possible to call a function without calling it?") I have a similar question, hopefully put in a more logical perspective.
Is it possible / what are the best practices, to disable a function call from a codebase ? By disabling I don't mean greping through the whole code to manually comment out the function (which is a valid but somewhat tedious task). The only ways I can think of are
Returning as soon as entering function
ret_type foo()
{
return ret_type();
// actual implementation is not allowed to run
}
which would be a bit dangerous when the return code is used by caller functions.
Replace the declaration with an idle macro
ret_type foo();
#define foo() do { void; } while (0);
Is there a standard way, maybe a compiler hook, a pragma directive to do this and if not what are some other ways?
Is there a standard way, maybe a compiler hook, a pragma directive to do this and if not what are some other ways?
Let's just think for a minute, together. Let's consider two main cases:
the function returns void
the function returns something
In the first case you can simply take the body of the function and comment it out. BOOM: disabled.
In the second case you have a return value. Let's consider other two cases:
the returned value is used
the returned value is not used
In the first case you should ask yourself: can I return a dummy value and get away with it? If the answer is yes, then do so. If not, then you can't do anything about it except refactor your entire code.
In the second case you can comment it out, but why you are returning a value in the first place.
I have a ScopedLock class which can help to release lock automatically when running out of scope.
However, the problem is: Sometimes team members write invalid lock-code such as
{
ScopedLock(mutex); // anonymous
xxx;
}
The above code is wrong because the ScopedLock object is constructed and destructed immediately, so it fails to lock the expected area (xxx). I want the compiler to give an error when trying to compile such code. Can this be done?
I have searched g++ warning options, but fail to find the right one.
I have seen an interesting trick in one codebase, but it only works if your scoped_lock type is not a template (std::scoped_lock is).
#define scoped_lock(x) static_assert(false, "you forgot the variable name")
If you use the class correctly, you have
scoped_lock lock(mutex);
and since the scoped_lock identifier isn't followed by an open paren, the macro won't trigger and the code will remain as it is. If you write\
scoped_lock(mutex);
the macro will trigger and the code will be substituted with
static_assert(false, "you forgot the variable name");
This will generate an informative message.
If you use a qualified name
threads::scoped_lock(mutext);
then the result will still not compile, but the message won't be as nice.
Of course, if your lock is a template, the bad code is
scoped_lock<mutex_type>(mutex);
which won't trigger the macro.
No, unfortunately there is no way to do this, as I explored in a blog post last year.
In it, I concluded:
I guess the moral of the story is to remember this story when using scoped_locks.
You can try to force all programmers in your team to use a macro, or a range-for trick, but then if you could guarantee that in every case then you'd be able to guarantee catching this bug in every case also.
You are looking for a way to programmatically catch this specific mistake when it's made, and there is none.
You can use a class and deleted function with the same name. Unfortunately this requires adding "class" keyword before the type.
class Guard
{
public:
explicit Guard(void)
{
}
};
static void Guard(void) = delete;
int main()
{
// Guard(); // Won't compile
// Guard g; // Won't compile
class Guard g;
}
To avoid this, introduce a macro which does this for you, always using the same name for the locker:
#define LOCK(mutex) ScopedLock _lock(mutex)
Then use it like this:
{
LOCK(mutex);
xxx;
}
As an alternative, Java's synchronize block can be simulated using a macro construct: In a for-loop running always exactly once, I instantiate such a locker in the initialization statement of the for-loop, so it gets destroyed when leaving the for-loop.
However, it has some pitfalls, unexpected behavior of a break statement being one example. This "hack" is introduced here.
Of course, none of the above methods fully avoid accidental code like your example. But if you're used to write locking mutexes using one of the two macros, it will less likely happen. As the name of the locker class will then never appear in the code except in the macro definition, you can even introduce a commit hook in a version control system to avoid committing invalid code.
AFAIK there's no such a flag in gcc. A static analyzer may better suit your needs.
In C++17, a type can be marked [[nodiscard]], in which case a warning is encouraged for an expression that discards a value of that type (including by the case described here that resembles a declaration of a variable). In C++20, it can be applied to individual constructors as well if only some of them cause this sort of problem.
replace it with macro
#define CON2(x,y) x##y
#define CON(x,y) CON2(x,y)
#define LOCK(x) ScopedLock CON(unique_,__COUNTER__)(mutex)
usage
{
LOCK(mutex);
//do stuff
}
This macro will generate unique names for locks, allowing lockeng of other mutexes in inner scopes