Iteration over set elements in C++ does not compile - visual-studio-2010

I haven't worked with C++ for several years and now I'm required to maintain a C++ project. I have the following piece of code which seems to compile in one project, but not in the other.
list.h
#include "mytype.h"
#include <set>
typedef std::set<MYTYPE> MYTYPE_LIST;
typedef MYTYPE_LIST::iterator MYTYPE_LIST_ITERATOR;
class LIST {
[...]
MYTYPE_LIST list;
};
list.cpp
void
LIST::somemethod(MYTYPE* requester)
{
MYTYPE_LIST_ITERATOR it;
for (it = list.begin(); it != list.end() ; it++ )
{
MYTYPE& info = (*it); // Error on this line
[...]
}
}
I am compiling my project with VS 2010, and I get the following errors on the marked line:
error C2440: 'initializing' : cannot convert from 'const MYTYPE' to 'MYTYPE &'
IntelliSense: qualifiers dropped in binding reference of type "MYTYPE &" to initializer of type "const MYTYPE"
I googled these errors, and as far as I understand, (*it) should not be const (because 'it' is not a ::const_iterator, see here), and therefor, I should be able to assign it to the reference variable.

In a std::set the data is the key, and since keys are constant you can't get a non-const reference.

Eventually I found that in VS 2010, Microsoft introduced a change which breaks backward compatibility with this code.
Apparently, this change was made for good reasons - modifying a set element might break the set's invariants. See here, "Problem 3: error C2662: 'NamedNumber::change_name' : cannot convert 'this' pointer from 'const NamedNumber' to 'NamedNumber &'".
The other project was compiled with and old version of Visual Studio, so we had no problem there.

Related

How to get gcc to compile 16-bit unicode strings

So I'm trying to compile this project : https://github.com/dmitrystu/libusb_stm32 with Segger Embedded studio which uses gcc. The process is choking on this error :
pasting formed 'u"Open source USB stack for STM32"', an invalid preprocessing token
which is caused by this line :
static const struct usb_string_descriptor manuf_desc_en = USB_STRING_DESC("Open source USB stack for STM32");
So USB_STRING_DESC is a macro :
#define USB_STRING_DESC(s) {.bLength = sizeof(CAT(u,s)),.bDescriptorType = USB_DTYPE_STRING,.wString = {CAT(u,s)}}
And CAT is a macro CAT(x,y) x##y. The intent must be to convert a string of type 8-bit char into a 16-bit Unicode type but the compiler doesn't like it. Is there some #include or compiler setting that may be missing that I have to add here? Clearly the author of this code expects it to work so there must be some fault in my setup.
Also I'm not clear on how the sizeof() operation is supposed to work here. As I understand it there is no way to get the length of a string at compile time so that operation will always return the size of a pointer.
In response to Keith's question, the gcc version is 4.2.1. Poking around the compiler settings the default option is the C99 standard, when I changed it to C11 everything compiled just fine. Thanks!

same code doesn't work on my own project (strcpy) in visual studio 2017

I'm working on some exercises for school.
The projects i have from my teacher work without any errors.
When i copy the code to a new project made on my computer, it shows this error:
Compiler Warning (level 3) C4996
I looked at both compiler settings and made them equal, this didn't work.
So i tried to make a project property file from my teachers project and insert it into my own project. Also this doesn't work.
Can somebody help me solving this issue?
This is the code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char s1[32];
char s2[32];
strcpy(s1, "abc def.");
strcpy(s2, "ghi_x");
printf("s1=\"%s\" en s2=\"%s\"\n", s1, s2);
printf("s1 bevat %d symbolen en s2 bevat %d symbolen\n", strlen(s1), strlen(s2));
printf("De functie strcmp(s1,s2) geeft %d als functiewaarde\n", strcmp(s1, s2));
getchar();
return 0;
}
The Error I get is
Severity Code Description Project File Line Suppression State Error C4996 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details
A quick Google search shows that "Compiler Warning (level 3) C4996" means you're using deprecated functions. The most likely culprits are your str* functions since they are generally unsafe. Switch to using their strn* counterparts (e.g. strncpy).

Is <random> fully supported in Visual Studio 2012

I have this sample code and it throws an error:
std::random_device rd; // only used once to initialise engine
std::mt19937 rng(rd); // random-number engine used
std::uniform_int_distribution<int> uni(0, 7); // guaranteed unbiased
int random_integer = uni(rng);
The error is:
Error 1 error C2039: 'generate' : is not a member of
'std::random_device' c:\program files (x86)\microsoft visual studio
12.0\vc\include\random 1618 1 Life
Can somone explain me please, why is this happening? It seems to be an error in the header file and not in my code.
How can I fix it?
Thank you.
std::mt19937 has two constructors, one taking a single 32-bit unsigned value as parameter (default value 5489u), the other taking a seed-sequence (a template type) as a parameter. The latter is required to have a method called generate.
As a random_device does not have such a method, your code is not valid.
What you probably wanted to do is
std::mt19937 rng(rd());
That is extracting a value from the device and use that as a parameter.

Function pointer in Visual Studio 2012

Please explain me where I am wrong. I want to switch between several encoding utilities using pointer to function. I declare it like
int (*enc_routine)();
Later I switch coding utilities like
enc_routine = g723_24_encoder;
where utility by itself is something like
extern int g723_24_encoder(
int sample,
int in_coding,
struct g72x_state *state_ptr);
Everything was cute and fine on Linux, but now I am on Visual Studio 2012 and it says:
a value of type "int (*)(int sample, int in_coding, g72x_state *state_ptr)" cannot be assigned to an entity of type "int (*)()"
Thank you for help (if any)!
You need to declare the parameters for your function pointer. You can't declare it to take no parameters and set it equal to a function that requires 3 parameters. I'm shocked it worked on linux.

warning: comparison is always true due to limited range of data type causes crash

I have a warning that I am unable to find the cause of.
I am following instructional code in a text on Cocoa programming that implements a document based image slide show. This warning causes a while loop to be executed more than the correct number of times which causes the program to crash. The code downloaded from the author's website does not have this problem.
I assumed it was a simple matter of a typo in my version but carefully reading both versions of code I was unable to come across any differences. I then systematically replaced every .h, .m, .xib and other resource file in my version with the author's version cleaning all targets and rebuilding after each replacement.
However the warning does not go away until I finally replace the .xcodeproj file with the author's version. At which point the warning clears and the code runs without crashing. I then experimented the other way by replacing each of the .h and .m files in the author's version with my .h and .m files all at once, cleaned all targets, built and again no warnings or crashes. I thought it might be some setting in the .plist file but swapping the two versions of that file seem to have no effect. I seem to be able to narrow it down to the project.pbxproj file in the .xcodeproj bundle but I can't see how any of the build settings listed there could cause the problem.
I would appreciate it if anyone could offer any insight to the problem or can recommend a method to debug it. The warning and the related code segment with the while loop are as follows:
Build warning:
SlideShowDocument.m: In function '-[SlideShowDocument removeSlidesAtIndexes:]':
SlideShowDocument.m:191: warning: comparison is always true due to limited range of data type
Debugger console output:
Slide Master[665:a0f] HIToolbox: ignoring exception '*** -[NSCFArray objectAtIndex:]: index (4294967295) beyond bounds (3)' that raised inside
Code:
- (void)removeSlidesAtIndexes:(NSIndexSet*)indexes;
{
NSMutableArray *slideList = [NSMutableArray array];
unsigned int index = [indexes firstIndex];
while (index != NSNotFound) {
Slide *slide = [mSlides objectAtIndex:index];
[slideList addObject:slide];
index = [indexes indexGreaterThanIndex:index];
}
if ([slideList count]) {
//remove the slides from the master list
[self recordSlideChange];
[mSlides removeObjectsInArray:slideList];
[self notifySlidesChanged];
}
}
NSUInteger could be bigger than unsigned int, and this can depend on the build target (32bit vs 64bit, LP64 vs ILP64). From NSUInteger:
#if __LP64__ || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
If that's the case for one of your targets, NSNotFound, which is an enum value equal to NSIntegerMax (see here) won't fit in an unsigned int. So some integer promotion will come into play, and you'll never hit equality (which the compiler is telling you about) on this line:
while (index != NSNotFound) {
Declare index as an NSUInteger (the type used by by NSIndexSet for the indexes) and that problem should be solved portably.

Resources