Toggling a bool value is being flagged in the Visual Studio IDE - visual-c++

Take this simple code:
void CChristianLifeMinistryEditorDlg::OnOptionsAddTimeToConcludingComments()
{
BOOL bAddTime = CChristianLifeMinistryUtils::AddRemainingTimeToConcludingComments();
bAddTime = !bAddTime;
CChristianLifeMinistryUtils::SetAddRemainingTimeToConcludingComments(bAddTime);
UpdateMenuGUI();
SetModified(true);
}
The !bAddTime is being flagged:
It says:
Using logical '!' when bitwise '~' was probably intended.
I have used this technique before to toggle boolean values it appears to operate correctly. So why the warning? It is not related to Visual Assist.

Simply change
BOOL bAddTime = ...
to
bool bAddTime = ...
I guess the static code analysis gets confused by BOOL being a type alias for int.

Related

Make msvc C4706 go away without pragmas

Following code in MSVC generates warning about assignment in conditional expression.
https://godbolt.org/z/i_rwY9
int main()
{
int a;
if ((a = 5)) {
return 1;
}
return a;
}
Note that I tried to use the double () around if since that makes the warning go away with g++, but I do not know how to make it go away in msvc without extracting the assignment from condition.
Is there a way to nudge msvc to figure out that this assignment is intentional?
I know I can use pragmas to disable this warning, but pattern is very common so I would like to get a solution without pragmas if one exists.
The MSVC compiler will give this warning unless you can convince it that you really do know what you're doing. Adding at least one 'real' logical test will achieve this:
int main()
{
int a;
if ((a = 5) != 0) {
return 1;
}
return a;
}
Note that the constant 5 can readily be replaced with any variable or valid expression: adding the explicit != 0 test does nothing to actually change the outcome of the code (and it is unlikely to change the generated assembly).

Evaluating the subscript operator in the watch window

I have a simple array wrapper class, which goes like this:
class MyArray
{
int * m_Data;
int m_Size;
public:
MyArray(int aSize) : m_Size(aSize), m_Data(new int[aSize])
{
}
int & operator [](int aIndex)
{
return m_Data[aIndex];
}
const int & operator [](int aIndex) const
{
return m_Data[aIndex];
}
};
MyArray a(10);
Whenever I try to evaluate a subscript operator in the debugger (quick watch, immediate window etc): e.g. a[0], I get a[0] no operator "[]" matches these operands error. I know I can dig through class fields to get to the content of the array. But it is so much easier to just copy a part of code line and evaluate it in the watch window.
I tried removing const and non-const [] operators. I also tried using () operator, it didn't work either, but it gave a different error message. I tried this in VS2012 and VS2013 Preview: same thing.
Is there any way to fix this?
If I replace the subscript operator with a member function:
int & Item(int aIndex)
{
return m_Data[aIndex];
}
Then watch window is able to show me the result. But I would prefer to use subscript operator.
I found a solution, which is not very convenient, but seems to work. If I use the expanded form of the operator call, then it works in VC++2012:
a.operator[](0)
It's not clear to me why these two forms are different to VC++ debugger. So I posted a new question here

duck typing in D

I'm new to D, and I was wondering whether it's possible to conveniently do compile-time-checked duck typing.
For instance, I'd like to define a set of methods, and require that those methods be defined for the type that's being passed into a function. It's slightly different from interface in D because I wouldn't have to declare that "type X implements interface Y" anywhere - the methods would just be found, or compilation would fail. Also, it would be good to allow this to happen on any type, not just structs and classes. The only resource I could find was this email thread, which suggests that the following approach would be a decent way to do this:
void process(T)(T s)
if( __traits(hasMember, T, "shittyNameThatProbablyGetsRefactored"))
// and presumably something to check the signature of that method
{
writeln("normal processing");
}
... and suggests that you could make it into a library call Implements so that the following would be possible:
struct Interface {
bool foo(int, float);
static void boo(float);
...
}
static assert (Implements!(S, Interface));
struct S {
bool foo(int i, float f) { ... }
static void boo(float f) { ... }
...
}
void process(T)(T s) if (Implements!(T, Interface)) { ... }
Is is possible to do this for functions which are not defined in a class or struct? Are there other/new ways to do it? Has anything similar been done?
Obviously, this set of constraints is similar to Go's type system. I'm not trying to start any flame wars - I'm just using D in a way that Go would also work well for.
This is actually a very common thing to do in D. It's how ranges work. For instance, the most basic type of range - the input range - must have 3 functions:
bool empty(); //Whether the range is empty
T front(); // Get the first element in the range
void popFront(); //pop the first element off of the range
Templated functions then use std.range.isInputRange to check whether a type is a valid range. For instance, the most basic overload of std.algorithm.find looks like
R find(alias pred = "a == b", R, E)(R haystack, E needle)
if (isInputRange!R &&
is(typeof(binaryFun!pred(haystack.front, needle)) : bool))
{ ... }
isInputRange!R is true if R is a valid input range, and is(typeof(binaryFun!pred(haystack.front, needle)) : bool) is true if pred accepts haystack.front and needle and returns a type which is implicitly convertible to bool. So, this overload is based entirely on static duck typing.
As for isInputRange itself, it looks something like
template isInputRange(R)
{
enum bool isInputRange = is(typeof(
{
R r = void; // can define a range object
if (r.empty) {} // can test for empty
r.popFront(); // can invoke popFront()
auto h = r.front; // can get the front of the range
}));
}
It's an eponymous template, so when it's used, it gets replaced with the symbol with its name, which in this case is an enum of type bool. And that bool is true if the type of the expression is non-void. typeof(x) results in void if the expression is invalid; otherwise, it's the type of the expression x. And is(y) results in true if y is non-void. So, isInputRange will end up being true if the code in the typeof expression compiles, and false otherwise.
The expression in isInputRange verifies that you can declare a variable of type R, that R has a member (be it a function, variable, or whatever) named empty which can be used in a condition, that R has a function named popFront which takes no arguments, and that R has a member front which returns a value. This is the API expected of an input range, and the expression inside of typeof will compile if R follows that API, and therefore, isInputRange will be true for that type. Otherwise, it will be false.
D's standard library has quite a few such eponymous templates (typically called traits) and makes heavy use of them in its template constraints. std.traits in particular has quite a few of them. So, if you want more examples of how such traits are written, you can look in there (though some of them are fairly complicated). The internals of such traits are not always particularly pretty, but they do encapsulate the duck typing tests nicely so that template constraints are much cleaner and more understandable (they'd be much, much uglier if such tests were inserted in them directly).
So, that's the normal approach for static duck typing in D. It does take a bit of practice to figure out how to write them well, but that's the standard way to do it, and it works. There have been people who have suggested trying to come up with something similar to your Implements!(S, Interface) suggestion, but nothing has really come of that of yet, and such an approach would actually be less flexible, making it ill-suited for a lot of traits (though it could certainly be made to work with basic ones). Regardless, the approach that I've described here is currently the standard way to do it.
Also, if you don't know much about ranges, I'd suggest reading this.
Implements!(S, Interface) is possible but did not get enough attention to get into standard library or get better language support. Probably if I won't be the only one telling it is the way to go for duck typing, we will have a chance to have it :)
Proof of concept implementation to tinker around:
http://dpaste.1azy.net/6d8f2dc4
import std.traits;
bool Implements(T, Interface)()
if (is(Interface == interface))
{
foreach (method; __traits(allMembers, Interface))
{
foreach (compareTo; MemberFunctionsTuple!(Interface, method))
{
bool found = false;
static if ( !hasMember!(T, method) )
{
pragma(msg, T, " has no member ", method);
return false;
}
else
{
foreach (compareWhat; __traits(getOverloads, T, method))
{
if (is(typeof(compareTo) == typeof(compareWhat)))
{
found = true;
break;
}
}
if (!found)
{
return false;
}
}
}
}
return true;
}
interface Test
{
bool foo(int, double);
void boo();
}
struct Tested
{
bool foo(int, double);
// void boo();
}
pragma(msg, Implements!(Tested, Test)());
void main()
{
}

Why IntPtr.ToInt32 throws OverflowException in 64 bit mode and Explicit(IntPtr to Int32) doesn't

The operator's description on MSDN has a remark:
An exception is only thrown if the value of value requires more bits
than the current platform supports.
while ToInt32's description doesn't so I suppose the title is not entirely correct(for brevity),
a more correct question would be: "Why IntPtr.ToInt32 throws OverflowException in 64 bit mode for values that fit in Int32 and Explicit(IntPtr to Int32) doesn't"
In decompiled IntPtr ToInt32 and the operator look very similar:
public static explicit operator int(IntPtr value)
{
return (int) value.m_value;
}
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe int ToInt32()
{
return (int) this.m_value;
}
I wonder what makes ToInt32 throw the exception, is it the unsafe keyword?
Your disassembler can't do a proper job here, mscorlib.dll is special. It is not an AnyCPU assembly, Microsoft builds and ships different versions of it, based on the processor architecture. I'd recommend you use the Reference Source, you'll get the original source code. Which looks like this:
[ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
public unsafe int ToInt32() {
#if WIN32
return (int)m_value;
#else
long l = (long)m_value;
return checked((int)l);
#endif
}
It is the checked keyword that provides the OverflowException.

What's a possible justification for not wrapping long argument lists? (StyleCop SA1115)

I'm stuck in a battle between ReSharper and StyleCop, and I'd like to let ReSharper win, but I want to hear the arguments in favour of StyleCop before I do that.
When I'm writing long argument lists ReSharper sensibly chops the parameter list and restarts it on the next line. I find that much more readable.
When I run StyleCop over the code it wants me to leave those lines really long. I don't like that, so I want to ignore that StyleCop rule (SA1115). I can't think of a good reason why SC would want those long lines in the first place – is it just a case of "we've always done it this way"?
StyleCop doesn't want you to put all your parameters on one really long line. However, it also doesn't want you to just arbitrarily insert a newline to move part of the parameter list down to the next line. StyleCop would like you to do one of the following:
public void MyMethod(int param1, int param2, int param3)
public void MyMethod(
int param1, int param2, int param3)
public void MyMethod(
int param1,
int param2,
int param3)
It's probably there to remind you that your argument list is too long and should be shortened.
Whilst playing about with the code from this question, I also fell foul of SA1115 via running StyleCop from the VS IDE. After some mucking about, here is the end result which StyleCop felt was OK:
public static string Format<T>(string pattern, T template)
{
Dictionary<string, string> cache = new Dictionary<string, string>();
return RegexExpression.Replace(
pattern,
match =>
{
string key = match.Groups[1].Value;
string value;
if (!cache.TryGetValue(key, out value))
{
var prop = typeof(T).GetProperty(key);
if (prop == null)
{
throw new ArgumentException("Not found: " + key, "pattern");
}
value = Convert.ToString(prop.GetValue(template, null));
cache.Add(key, value);
}
return value;
});
}
Just thought I'd share it.
It seems the rule technically says "parameter must follow comma." Pretty nit-picky if you ask me, but some people believe in starting continuation lines with the commas in order to really show hey! This line is a continuation! E.g.
void Foo( int blah
, string blork
, ...
Whatever floats your boat, personally :)

Resources