Replacement for `std::bind` with Visual Studio 2019? - c++11

I've got code that compiles with Visual Studio 2017 that uses std::bind:
std::unique_lock<std::mutex> m_lock(m_mutex_wait_for_message);
m_cond_variable.wait(m_lock, std::bind(&Logging::is_message_available, this));
std::lock_guard<std::mutex> lock_guard(m_mutex_pushing_message);
We are now compiling using VS2019 and it's complaining with errors:
'bind': is not a member of 'std'
'bind': function does not take 2 arguments
CppReference.com says "Until C++20"
Questions:
What is the replacement for std::bind in the mutex locking code above?
What is the replacement for std::bind?

As others have mentioned, you're likely missing the header file that includes it. To address your other points:
When cppreference says until C++20, note that immediately underneath it says since C++20, meaning that the signature of the function changed in C++20, and it is showing both before and after. In this case, constexpr was added to the function, std::bind is still there.
As for what replaces std::bind, since C++14 you can use a lambda in place of every instance of std::bind, see here for a better explanation. Applying this to your code you can write:
m_cond_variable.wait(m_lock, [&] { is_message_available(); });
In C++20 you can leave off the () for lambdas that take no arguments.

Related

Warning (C28251) when replacing "operator new": Inconsistent annotation for 'new', this instance has no annotations

I'm trying to replace the global new operator in Visual Studio and C++. This is my code (only one new operator shown for simplicity):
void* operator new(size_t _Size)
{
// Do something
}
It works fine, however Visual Studio is giving me a warning when running Code-Analysis for my project:
warning C28251: Inconsistent annotation for 'new': this instance has no annotations. The first user-provided annotation on this built-in function is at line vcruntime_new.h(48).
Using the annotations from vcruntime_new.h for my operator new replacement, as suggested in the warning from IntelliSense, resolves the warning:
_NODISCARD _Ret_notnull_ _Post_writable_byte_size_(_Size) _VCRT_ALLOCATOR
void* __cdecl operator new(size_t _Size)
{
// Do something
}
Is it safe to use the annotations inside vcruntime_new.h for my own replacement code like shown above?
What are the consequences of this change?
Are there special use cases were the "new operator" cannot be used anymore like before because of the annotations?
And why is that change necessary?
EDIT:
Am I correct, that the annotations won't change anything in the resulting binary, and are simply for static code analysis? (Except __cdecl, which changes the assembler, but it should be standard anyway I guess?)
This applies to _Ret_notnull_ and _Post_writable_byte_size_(_Size):
Is it safe to use the annotations inside vcruntime_new.h for my own replacement code like shown above?
Yes, as long as your operator new actually follow these rules in annotation. It might not follow _Ret_notnull_ (for example non-throwing new returns nullptr), tough normally will. But it should follow _Post_writable_byte_size_(_Size), since operator new is required so.
What are the consequences of this change?
Annotations will probably help Visual Studio Code Analysis pinpoint errors, but will make you using non-standard stuff, making your program less portable and less clear.
Are there special use cases were the "new operator" cannot be used anymore like before because of the annotations?
No.
And why is that change necessary?
Because you want to avoid that warning instead of silencing it.
Am I correct, that the annotations won't change anything in the resulting binary, and are simply for static code analysis? (Except __cdecl, which changes the assembler, but it should be standard anyway I guess?)
Correct. Not even optimizer would use that (optimizer would use __assume, __restrict, and other annotations separate from static analysis).

GNU C++ import name mangling [duplicate]

I came across an interesting error when I was trying to link to an MSVC-compiled library using MinGW while working in Qt Creator. The linker complained of a missing symbol that went like _imp_FunctionName. When I realized That it was due to a missing extern "C", and fixed it, I also ran the MSVC compiler with /FAcs to see what the symbols are. Turns out, it was __imp_FunctionName (which is also the way I've read on MSDN and quite a few guru bloggers' sites).
I'm thoroughly confused about how the MinGW linker complains about a symbol beginning with _imp, but is able to find it nicely although it begins with __imp. Can a deep compiler magician shed some light on this? I used Visual Studio 2010.
This is fairly straight-forward identifier decoration at work. The imp_ prefix is auto-generated by the compiler, it exports a function pointer that allows optimizing binding to DLL exports. By language rules, the imp_ is prefixed by a leading underscore, required since it lives in the global namespace and is generated by the implementation and doesn't otherwise appear in the source code. So you get _imp_.
Next thing that happens is that the compiler decorates identifiers to allow the linker to catch declaration mis-matches. Pretty important because the compiler cannot diagnose declaration mismatches across modules and diagnosing them yourself at runtime is very painful.
First there's C++ decoration, a very involved scheme that supports function overloads. It generates pretty bizarre looking names, usually including lots of ? and # characters with extra characters for the argument and return types so that overloads are unambiguous. Then there's decoration for C identifiers, they are based on the calling convention. A cdecl function has a single leading underscore, an stdcall function has a leading underscore and a trailing #n that permits diagnosing argument declaration mismatches before they imbalance the stack. The C decoration is absent in 64-bit code, there is (blessfully) only one calling convention.
So you got the linker error because you forgot to specify C linkage, the linker was asked to match the heavily decorated C++ name with the mildly decorated C name. You then fixed it with extern "C", now you got the single added underscore for cdecl, turning _imp_ into __imp_.

Visual Studio 2010 IntelliSense: hints on F# operators

Is it possible to make Visual Studio to display tooltips on operators?
The following image demonstrates a tooltip hint for a function, but it does not work for operators.
Operators usually have simple type specs like 'T -> 'T -> 'T, but such hints can be useful for custom ones.
Following Daniel's suggestion, I'm posting a workaround that I've been using for myself.
The workaround is only partially helpful, and I'm still looking for any better ideas.
let (!><) a = ()
let z1 = op_BangGreaterLess 5
This code is fully valid, since an operator expression generates a function with a compiler-generated name. See this MSDN article, section "Overloaded Operator Names" for complete list of operator names.
Good news is that op_BangGreaterLess supports IntelliSense hints and it also supports "Go to Definition" (F12) command of IDE, pointing to an original operator declaration.
Bad news is that IntelliSense does not allow rapid entry of the full operator name (Ctrl+Space), so you have to type the entire name manually.
I'm afraid this is not possible (and even in Visual Studio 2012, I don't get tooltips for operators).
I suppose this could be implemented, but as you say, operators usually have simple types. When using custom operators, these should be probably simple enough so that people can use them without looking at their type (or the associated XML documentation). Otherwise, it might be better to use a named function.
That said, if you're using F# Interactive, then you can easily use that to explore the operator type:
> (!><);;
val it : ('a -> unit) = <fun:clo#2>
If I cannot use F# Interactive, I usually define a simple dummy symbol to get the IntelliSense:
let dummy () = (!><)
Note that I added unit argument to define a function and avoid value restriction error.

Can You Use MSVC 6.0's Debugger to 'Step Into' a Macro?

I am using MSVC 6.0 to call a macro in the Win32API and I'm getting an access violation. I know that the pointers I'm passing to the macro contain valid addresses, though they're evidently not pointing to the correct data.
The macro accepts multiple pointers, and I'm not sure which pointer is erroneous, so I'd like to use MSVC's debugger to 'step into' the macro to see exactly where the problem is. When I've tried thus far, the debugger just throws the access violation error.
Is it possible to 'step into' a macro using MSVC 6.0's debugger? If not, is there anyway for me to check what the macro expands to, so I can get a better idea of what I'm not doing correctly?
If you really need to trace the macro code, the only way would be to find the definition of the macro, manually "instantiate" the macro code (substituting the parameters) in place where it is "called", and then trace it in the debugger as ordinary code.
Alternative variant would be to step through the disassembly, if your skill level is sufficient to back-associate the disassembled code with the original macro code.
You cannot step into the macro because at the point compiler does its job, the macro is already expanded. However, you can step through a macro - if you just do "step", you will actually step through all code inside the macro as if it was expanded, line by line. If you to "step into", you will step into every function call made from that macro. If the macro is small enough, and/or you know it very well, you can do a "blind step through" that way.
You can step into functions that are called from the macro but as far as I know can not really step through the macro lines themselves. And yes if you code compiles - you can find the macro definition (use MSVC function/class browser to find where it is defined, some header file probably)
I'd just step into the disassembly - usually, even if you're not an assembly expert, short runs of code (a few lines) the assembly map back to the C/C++ code pretty readily (especially in non-Release builds). Hopefully the macro isn't so hairy that that isn't the case here.
Remember that plenty of debugging occurs even without source code, so having the source and the disassembly together usually isn't too bad. And if it's something you haven't much experience with, it's great experience to get.

Xcode equivalent of ' __asm int 3 / DebugBreak() / Halt?

What's the instruction to cause a hard-break in Xcode? For example under Visual Studio I could do '_asm int 3' or 'DebugBreak()'. Under some GCC implementations it's asm("break 0") or asm("trap").
I've tried various combos under Xcode without any luck. (inline assembler works fine so it's not a syntax issue).
For reference this is for an assert macro. I don't want to use the definitions in assert.h both for portability, and because they appear to do an abort() in the version XCode provides.
John - Super, cheers. For reference the int 3 syntax is the one required for Intel Macs and iPhone.
Chris - Thanks for your comment but there are many reasons to avoid the standard assert() function for codebases ported to different platforms. If you've gone to the trouble of rolling your own assert it's usually because you have additional functionality (logging, stack unwinding, user-interaction) that you wish to retain.
Your suggestion of attempting to replace the hander via an implementation of '__assert" or similar is not going to be portable. The standard 'assert' is usually a macro and while it may map to __assert on the Mac it doesn't on other platforms.
http://developer.apple.com/documentation/DeveloperTools/Conceptual/XcodeProjectManagement/090_Running_Programs/chapter_11_section_3.html
asm {trap} ; Halts a program running on PPC32 or PPC64.
__asm {int 3} ; Halts a program running on IA-32.
You can just insert a call to Debugger() — that will stop your app in the debugger (if it's being run under the debugger), or halt it with an exception if it's not.
Also, do not avoid assert() for "portability reasons" — portability is why it exists! It's part of Standard C, and you'll find it wherever you find a C compiler. What you really want to do is define a new assertion handler that does a debugger break instead of calling abort(); virtually all C compilers offer a mechanism by which you can do this.
Typically this is done by simply implementing a function or macro that follows this prototype:
void __assert(const char *expression, const char *file, int line);
It's called when an assertion expression fails. Usually it, not assert() itself, is what performs "the printf() followed by abort()" that is the default documented behavior. By customizing this function or macro, you can change its behavior.
__builtin_trap();
Since Debugger() is depreciated now this should work instead.
https://developer.apple.com/library/mac/technotes/tn2124/_index.html#//apple_ref/doc/uid/DTS10003391-CH1-SECCONTROLLEDCRASH
For posterity: I have some code for generating halts at the correct stack frame in the debugger and (optionally) pausing the app so you can attach the debugger just-in-time. Works for simulator and device (and possibly desktop, if you should ever need it). Exhaustively detailed post at http://iphone.m20.nl/wp/2010/10/xcode-iphone-debugger-halt-assertions/
I found the following in an Apple Forum:
Xcode doesn't come with any symbolic breaks built in - but they're
quick to add. Go to the breakpoints window and add:
-[NSException raise]
kill(getpid(), SIGINT);
Works in the simulator and the device.
There is also the following function that is available as cross platform straight Halt() alternative:
#include <stdlib.h>
void abort(void);
We use it in our cross platform engine for the iPhone implementation in case of fatal asserts. Cross platform across Nintendo DS/Wii/XBOX 360/iOS etc...

Resources