question_id
int64 25
74.7M
| answer_id
int64 332
74.7M
| title
stringlengths 20
150
| question
stringlengths 23
4.1k
| answer
stringlengths 20
4.1k
|
|---|---|---|---|---|
587,703
| 596,743
|
Windows API: Detecting when a driver install has finished
|
I'm writing some software that automatically connects a Bluetooth device using the Windows Bluetooth API. When it connects, Windows automatically starts installing the Bluetooth HID device driver, as expected:
This takes about 10-15 seconds, after which Windows displays the familar "ready for use" message:
The problem is that BluetoothSetServiceState() returns as soon as the driver install begins, not when the device is actually ready for use. This causes some problems for my code, because it invokes a separate library for device communication as soon as it's "connected". The first few calls fail because the drivers haven't finished installing, and making those connection attempts appears to interfere with the driver installation, because if I try to use the communication library before the driver installation has finished Windows wants to restart before the device can be used.
What I'm looking for is a way to hook that "ready to use" event, when driver installation has actually finished, so I don't make my communication library calls prematurely. Is there some Windows API call I can use to either register a function callback or directly polling the state of driver installation?
I'm writing this in vanilla C/C++, no .NET. Thanks for your help!
|
You might want to have a look at
this sample code and RegisterDeviceNotification function. I'm not sure for 100%, but it seems to work if you specify correct guid for your device class.
|
587,767
| 587,849
|
How to output to the console in C++/Windows
|
When using iostream in C++ on Linux, it displays the program output in the terminal, but in Windows, it just saves the output to a stdout.txt file. How can I, in Windows, make the output appear in the console?
|
Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated.
So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advice here. Either freopen stdout and stderr with "CON", or do the other linker/compile workarounds there.
In case the link gets broken again, here is exactly what was referenced from libSDL:
How do I avoid creating stdout.txt and stderr.txt?
"I believe inside the Visual C++ project that comes with SDL there is a SDL_nostdio target > you can build which does what you want(TM)."
"If you define "NO_STDIO_REDIRECT" and recompile SDL, I think it will fix the problem." > > (Answer courtesy of Bill Kendrick)
|
588,307
| 588,352
|
C++ obtaining milliseconds time on Linux -- clock() doesn't seem to work properly
|
On Windows, clock() returns the time in milliseconds, but on this Linux box I'm working on, it rounds it to the nearest 1000 so the precision is only to the "second" level and not to the milliseconds level.
I found a solution with Qt using the QTime class, instantiating an object and calling start() on it then calling elapsed() to get the number of milliseconds elapsed.
I got kind of lucky because I'm working with Qt to begin with, but I'd like a solution that doesn't rely on third party libraries,
Is there no standard way to do this?
UPDATE
Please don't recommend Boost ..
If Boost and Qt can do it, surely it's not magic, there must be something standard that they're using!
|
You could use gettimeofday at the start and end of your method and then difference the two return structs. You'll get a structure like the following:
struct timeval {
time_t tv_sec;
suseconds_t tv_usec;
}
EDIT: As the two comments below suggest, clock_gettime(CLOCK_MONOTONIC) is a much better choice if you have it available, which should be almost everywhere these days.
EDIT: Someone else commented that you can also use modern C++ with std::chrono::high_resolution_clock, but that isn't guaranteed to be monotonic. Use steady_clock instead.
|
588,700
| 588,747
|
Programmer productivity with STL vs. custom utility classes
|
I work in an environment where, for historical reasons, we are using a hodgepodge of custom utility classes, most of which were written before STL arrived on the scene. There are many reasons why I think it is a good idea to at least write new code using STL, but the main one is that I believe it increases programmer productivity. Unfortunately, that is a point that I don't know how to prove.
Are there any studies out there that attempt to quantify, or even just hint at, a productivity gain from using STL?
Update: I guess I should have been more specific. I am not advocating rewriting existing code, and I am not worried about the new hires that will get a running start. The former would be foolish, and the latter by itself is not enough to convince people.
|
There are no studies that will show STL is more productive just because it is STL. Productivity gains from using it are due to it being a standard programmers are familiar with it, and because the code is already written and tested.
If your company already has utility classes that employees are familiar with, and this utility code is used throughout an existing codebase, then switching to STL could actually be detrimental to productivity.
That said for new code using STL would be a good move. I would not necessarily argue this from a productivity standpoint, but one of maintainability. If you have code that predates STL it sounds like code at your company has quite a long lifetime and is likely to be maintained by a number of new programmers over the years.
You may also want to broach the use of STL as a way for everyone to keep their C++ skillset sharp. While I wouldn't reject a C++ candidate who didn't know STL, I would definitely view it as a black mark.
|
588,857
| 588,916
|
'Start Debugging' takes forever in VisualStudio 2005
|
I have a large project that has > 1000 files.
When I press the green 'Play' button to start debugging, once everything is built, it can take up to 5 minutes for the app to start running.
It looks like Visual Studio is loading and unloading various DLLs, but it also just sits there occasionally doing nothing.
Running from the command line takes only a few seconds.
What's going on? How can I speed it up?
[EDIT] It turned out to be our Symbol Server. The administrator had killed it without informing anyone. Doh.
Thanks for your help guys.
|
Some thoughts and suggestions:
It could be caused by complex dependency checking that VS2005 does to ensure that no components have changes and have to be re-built prior to debugging. Sometimes tweaking the inter-project dependencies in the solution can help.
Are you using source control integration in Visual Studio? If so, sometimes accessing the source control repository elsewhere on the network can cause Visual Studio to slow down like this. If using a source control system like ClearCase where you can reduce unnecessary LAN communication (e.g. using a snapshot view), consider doing this.
I also find that running the executable separately (from outside Visual Studio) and then using VS2005 to attach to the process can be much faster. This is predominantly the way I work, and I find it much less frustrating.
Another thing to consider is whether you are using a symbol server to access debug symbols for the Windows DLLs. If so, VS2005 can sometimes try to access the symbol server every time you debug. The way around this is to load the symbols once, and then uncheck the symbol server URL under Tools->Options->Debugging->Symbols. As long as the OS libraries haven't changed since you last downloaded the symbols, there's no reason to access the remote server every time.
|
588,859
| 591,844
|
ramdisk with a file mirror
|
I wanted to speed up compilation so i was thinking i could have my files be build on a ramdisk but also have it flushed to the filesystem automatically and use the filesystem if there is not enough ram.
I may need something similar for an app i am writing where i would like files to be cached in ram and flushed into the FS. What are my options? Is there something like this that already exist? (perhaps fuse?) The app is a toy app (for now) and i would need to compile c++ code repeatedly. As we know, the longer it takes to compile when there is a specific problem to solve before progressing. the less we can get done.
|
Ram-disks went the way of the dodo with the file system cache. It can make much better decisions than a static cache, having awareness of RAM usage by other programs and the position of the disk write head. The lazy write-back is for free.
|
589,076
| 589,126
|
When is it not a good idea to pass by reference?
|
This is a memory allocation issue that I've never really understood.
void unleashMonkeyFish()
{
MonkeyFish * monkey_fish = new MonkeyFish();
std::string localname = "Wanda";
monkey_fish->setName(localname);
monkey_fish->go();
}
In the above code, I've created a MonkeyFish object on the heap, assigned it a name, and then unleashed it upon the world. Let's say that ownership of the allocated memory has been transferred to the MonkeyFish object itself - and only the MonkeyFish itself will decide when to die and delete itself.
Now, when I define the "name" data member inside the MonkeyFish class, I can choose one of the following:
std::string name;
std::string & name;
When I define the prototype for the setName() function inside the MonkeyFish class, I can choose one of the following:
void setName( const std::string & parameter_name );
void setName( const std::string parameter_name );
I want to be able to minimize string copies. In fact, I want to eliminate them entirely if I can. So, it seems like I should pass the parameter by reference...right?
What bugs me is that it seems that my localname variable is going to go out of scope once the unleashMonkeyFish() function completes. Does that mean I'm FORCED to pass the parameter by copy? Or can I pass it by reference and "get away with it" somehow?
Basically, I want to avoid these scenarios:
I don't want to set the MonkeyFish's name, only to have the memory for the localname string go away when the unleashMonkeyFish() function terminates. (This seems like it would be very bad.)
I don't want to copy the string if I can help it.
I would prefer not to new localname
What prototype and data member combination should I use?
CLARIFICATION: Several answers suggested using the static keyword to ensure that the memory is not automatically de-allocated when unleashMonkeyFish() ends. Since the ultimate goal of this application is to unleash N MonkeyFish (all of which must have unique names) this is not a viable option. (And yes, MonkeyFish - being fickle creatures - often change their names, sometime several times in a single day.)
EDIT: Greg Hewgil has pointed out that it is illegal to store the name variable as a reference, since it is not being set in the constructor. I'm leaving the mistake in the question as-is, since I think my mistake (and Greg's correction) might be useful to someone seeing this problem for the first time.
|
One way to do this is to have your string
std::string name;
As the data-member of your object. And then, in the unleashMonkeyFish function create a string like you did, and pass it by reference like you showed
void setName( const std::string & parameter_name ) {
name = parameter_name;
}
It will do what you want - creating one copy to copy the string into your data-member. It's not like it has to re-allocate a new buffer internally if you assign another string. Probably, assigning a new string just copies a few bytes. std::string has the capability to reserve bytes. So you can call "name.reserve(25);" in your constructor and it will likely not reallocate if you assign something smaller. (i have done tests, and it looks like GCC always reallocates if you assign from another std::string, but not if you assign from a c-string. They say they have a copy-on-write string, which would explain that behavior).
The string you create in the unleashMonkeyFish function will automatically release its allocated resources. That's the key feature of those objects - they manage their own stuff. Classes have a destructor that they use to free allocated resources once objects die, std::string has too. In my opinion, you should not worry about having that std::string local in the function. It will not do anything noticeable to your performance anyway most likely. Some std::string implementations (msvc++ afaik) have a small-buffer optimization: For up to some small limit, they keep characters in an embedded buffer instead of allocating from the heap.
Edit:
As it turns out, there is a better way to do this for classes that have an efficient swap implementation (constant time):
void setName(std::string parameter_name) {
name.swap(parameter_name);
}
The reason that this is better, is that now the caller knows that the argument is being copied. Return value optimization and similar optimizations can now be applied easily by the compiler. Consider this case, for example
obj.setName("Mr. " + things.getName());
If you had the setName take a reference, then the temporary created in the argument would be bound to that reference, and within setName it would be copied, and after it returns, the temporary would be destroyed - which was a throw-away product anyway. This is only suboptimal, because the temporary itself could have been used, instead of its copy. Having the parameter not a reference will make the caller see that the argument is being copied anyway, and make the optimizer's job much more easy - because it wouldn't have to inline the call to see that the argument is copied anyway.
For further explanation, read the excellent article BoostCon09/Rvalue-References
|
589,144
| 589,160
|
Basic Pixel/Cell Counting Algorithm
|
Good night :)
I am currently playing with the DevIL library that allows me to load in image and check RGB values per pixel. Just as a personal learning project, I'm trying to write a very basic OCR system for a couple of images I made myself in Photoshop.
I am successfully able to remove all the distortions in the image and I'm left with text and numbers. I am currently not looking for an advanced neural network that learns from input. I want to start out relatively easy and so I've set out to identify the individual characters and count the pixels in those characters.
I have two problems:
Identifying the individual characters.
Most importantly: I need an algorithm to count connected pixels (of the same color) without counting pixels I've previously counted. I have no mathemathical background so this is the biggest issue for me.
Any help in the matter is appreciated, thanks.
edit:
I have tagged this question as C++ because that is what I am currently using. However, pseudo-code or easily readable code from another language is also fine.
|
The flood fill algorithm will work for counting the included pixels, as long as you have the images filtered down to simple black & white bitmaps.
Having said that, you can perform character recognition by comparing each character to a set of standard images of each character in your set, measuring the similarity, and then choosing the character with the highest score.
Take a look at this question for more information.
|
589,208
| 589,229
|
Are there any reasons not to use Boost::shared_ptrs?
|
I've asked a couple questions (here and here) about memory management, and invariably someone suggests that I use boost::shared_ptrs.
Given how useful they seem to be, I'm seriously considering switching over my entire application to use boost::shared_ptrs.
However, before I jump in with both feet and do this, I wanted to ask -- Has anyone had any bad experiences with boost::shared_ptrs? Is there some pitfall to using them that I need to watch out for?
Right now, they seem almost too good to be true - taking care of most of my garbage collection concerns automatically. What's the downside?
|
The downside is they're not free. You especially shouldn't use shared_ptr/shared_array when scoped_ptr/scoped_array (or plain old stack allocation) will do. You'll need to manually break cycles with weak_ptr if you have any. The vector question you link to is one case where I might reach for a shared_ptr, the second question I would not. Not copying is a premature optimization, especially if the string class does it for you already. If the string class is reference counted, it will also be able to implement COW properly, which can't really be done with the shared_ptr<string> approach. Using shared_ptr willy-nilly will also introduce "interface friction" with external libraries/apis.
|
589,535
| 589,543
|
naming convention for public and private variable?
|
Is it wrong to use m_varname as public and the same class with _variable as private
|
Some concerns:
Why do you have public variables?
Identifiers starting with _ and __ are reserved for system libraries. In practice this doesn't matter very often, but it's nice to be aware.
With those things said, there's nothing wrong with creating a naming convention, regardless of how it looks. Just be consistent.
|
589,836
| 589,857
|
Problem regarding OpenGL and the process of converting C to C++
|
Alright. So I wanted to use a file written in c in c++. I ran the code in c and had absolutely no problems.
Since I don't know c, I worked with some conversion software for a while, but it wasn't effective (guessing the coding format wasn't in the style it needed). I decided to try it out myself and it looked like all I had to do was change a few malloc statements to new statments and replace free with delete. So I ran the program and it appears most of the functions work fine, but this one gives me trouble.
When I'm trying to update the display of a new image (I'm reading tiff image data and displaying it on the screen) I run into problems in these particular statements:
glutReshapeWindow(ImageWidth,ImageLength);
glClear(GL_COLOR_BUFFER_BIT);//these
glRasterPos2i(0, 0);//three
glDrawPixels(ImageWidth, ImageLength, GL_RGB,
GL_UNSIGNED_BYTE, ImageData);//statements are the ones giving me the error
I included the first statement in the codeblock to show that it doesn't immediately blow up any any sort of OpenGl call.
I keep getting errors along the lines of
Cannot access memory at address 0xfbad248c
Cannot access memory at address 0xfbad248c
Cannot access memory at address 0xaabbeeaa
I know this might be sort of vague, but what could be some common sources of this error? It worked in c, what may have caused this error in the quick switch to c++?
Thanks and let me know if you need any more information.
Alright, so I'm not really using the standard OpenGL library I believe (this is for a class and I was given the library files by an instructor). I have the the code
#include <GL/glut.h>
as my #include. These libraries are exactly the same as the one found in the c file as I merely copied and pasted them into my c++ project. (I've also worked with them in a limited manner in another c++ project). Just in case, I checked my file system for the files "OPENGL32.DLL" and "GLU32.DLL" and did not find them.
I should probably include these additional details:
A init() method is called at the beginning of the program before the actual input loop is called:
void
init(void)
{
glClearColor (0.0, 0.0, 0.0, 0.0);
glShadeModel(GL_FLAT);
makeCheckImage();
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
}
This method seems to work fine (a simple checkerboard pattern is created shortly after this function call). I'm not sure which sort of OpenGL files these pertain to ("OPENGL32.DLL" or "GLU32.DLL") but hopefully this can narrow the problem down a little bit.
As for the ImageData line, I don't believe the ImageData object is corrupted or something of the sort, because of some of reasons you were talking about and the fact that the code in the very first code block I posted (the source of errors) is within an else block as such:
if (ImageData == NULL) {/*code*/}
else{/*this is where the error code is*/}
I can post info on the makefiles if you think it would be helpful (just don't want to clutter up this thread with the stuff if it's not).
|
The first statement that doesn't give an error is an command from GLU32.DLL, the others should be OPENGL32.DLL commands. Check if you linked the libraries correctly and try to copy the DLLs in the program directory.
The last line could also be some error with your ImageData, but since you said it worked in C and you only replaced malloc/free with new/delete, it's unlikely that something is wrong there, anyway you should check this, too. A possibility would be to read the whole ImageData array without an OpenGL call involved. By the way, I hope that ImageLength isn't the length of the complete image file, but the height of the image.
EDIT: OK, so it seems to be a bit different. The init function you posted seems to access other gl... functions, so your libraries somehow work. By the way, it's interesting that you couldn't find the DLLs. They are usually stored in the Windows\System32 path.
"if (ImageData == NULL)" is a first step, but you should also try to read all ImageWidth*ImageLength entries for debug purposes, perhaps you allocated the wrong number of bytes.
Another reason for the crash could be that the header files you use aren't up-to-date and not compatible with your calls or the DLLs.
If all this doesn't solve your problem, posting the makefile would indeed be useful.
|
589,985
| 590,010
|
Vectors, structs and std::find
|
Again me with vectors. I hope I'm not too annoying. I have a struct like this :
struct monster
{
DWORD id;
int x;
int y;
int distance;
int HP;
};
So I created a vector :
std::vector<monster> monsters;
But now I don't know how to search through the vector. I want to find an ID of the monster inside the vector.
DWORD monster = 0xFFFAAA;
it = std::find(bot.monsters.begin(), bot.monsters.end(), currentMonster);
But obviously it doesn't work. I want to iterate only through the .id element of the struct, and I don't know how to do that. Help is greatly appreciated. Thanks !
|
std::find_if:
it = std::find_if(bot.monsters.begin(), bot.monsters.end(),
boost::bind(&monster::id, _1) == currentMonster);
Or write your own function object if you don't have boost. Would look like this
struct find_id : std::unary_function<monster, bool> {
DWORD id;
find_id(DWORD id):id(id) { }
bool operator()(monster const& m) const {
return m.id == id;
}
};
it = std::find_if(bot.monsters.begin(), bot.monsters.end(),
find_id(currentMonster));
|
590,021
| 590,074
|
Is there a cross-platform way of getting a list of running applications?
|
I need to get a list of applications that are currently running so that my C++ application and make them take focus.
Has anybody done this?
|
There is no real cross platform way of doing that. The whole concept of processes, applications, etc. is an operating system specific concept. If you use a certain library to solve the issue, you are not really cross platform, you are limited to the platforms that are supported by this library. E.g. Qt is not universal cross platform, it runs on a lot of platforms, but not on every known one and on platforms where it won't run, a Qt solution won't work. Most UNIX like platforms support the POSIX API (some more, some less) and if you limit yourself to POSIX functions, the solution will work in Linux, BSD, Mac OS X, Solaris, and similar OSes. It will not work on Windows, though. Microsoft decided to drop POSIX support (not that their POSIX support was great to begin with), however Cygwin brings back POSIX support to Windows (Cygwin emulates a complete Linux glibc API on top of Windows). The problem is that not even POSIX is really offering a set of functions to solve your problem here - the way how a POSIX tool like ps gets process information is entirely different on a Linux system compared to a BSD system for example.
The second issue is that you are talking "focus". Focus is something that does not apply to applications. A background application that has no UI and no windows cannot have "focus". What would "focus" mean for such an application? So you are not really interested in a list of running applications, but in a list of running UI applications that have windows and whose windows may get focus. An entirely different thing. The windows systems are even more different between different platforms and POSIX ignores UIs altogether.
Also you have a Visual-C++ tag on your question, so how cross platform must your code really be, as Visual-C++ is a Windows only thing, isn't it? What platforms are you really trying to support (please update your question accordingly), since I doubt there is any better solution than writing a different piece of code for every single supported platform.
|
590,027
| 590,042
|
Can I un-singleton a singleton
|
I want to use a library that makes heavy use of singletons, but I actually need some of the manager classes to have multiple instances. The code is open source, but changing the code myself would make updating the lib to a newer version hard.
What tricks are there, if any, to force creation of a new instance of a singleton or even the whole library?
|
The answer is "it depends". A good example is the C++ heap used by Microsofts C runtime. This is implemented as a singleton, of course. Now, when you statically link the CRT into multiple DLLs, you end up with multiple copies. The newer implementations have a single heap, whereas the older CRTs created one heap per library linked in.
|
590,098
| 590,488
|
Detect RPC connection loss from server-side on Windows
|
Is there any way to check the status of the RPC connection from the server-side? I am looking for a way to detect if the connection from the client is lost, be it client crash or other connectivity issues.
|
Use Context Handles for managing server state between calls for a particular client. RPC uses keep-alive's to detect client disconnects and will execute your context handle rundown routine if the client disconnects.
|
590,264
| 590,297
|
Is it practically safe to write static data from multiple threads
|
I have some status data that I want to cache from a database. Any of several threads may modify the status data. After the data is modified it will be written to the database. The database writes will always be done in series by the underlying database access layer which queues database operations in a different process so I cam not concerned about race conditions for those.
Is it a problem to just modify the static data from several threads? In theory it is possible that modifications are implemented as read, modify, write but in practice I can't imagine that this is so.
My data handling class will look something like this:
class StatusCache
{
public:
static void SetActivityStarted(bool activityStarted)
{ m_activityStarted = activityStarted; WriteToDB(); }
static void SetActivityComplete(bool activityComplete);
{ m_activityComplete = activityComplete; WriteToDB(); }
static void SetProcessReady(bool processReady);
{ m_processReady = processReady; WriteToDB(); }
static void SetProcessPending(bool processPending);
{ m_processPending = processPending; WriteToDB(); }
private:
static void WriteToDB(); // will write all the class data to the db (multiple requests will happen in series)
static bool m_activityStarted;
static bool m_activityComplete;
static bool m_processReady;
static bool m_processPending;
};
I don't want to use locks as there are already a couple of locks in this part of the app and adding more will increase the possibility of deadlocks.
It doesn't matter if there is some overlap between 2 threads in the database update, e.g.
thread 1 thread 2 activity started in db
SetActivityStarted(true) SetActivityStarted(false)
m_activityStated = true
m_activityStarted = false
WriteToDB() false
WriteToDB() false
So the db shows the status that was most recently set by the m_... = x lines. This is OK.
Is this a reasonable approach to use or is there a better way of doing it?
[Edited to state that I only care about the last status - order is unimportant]
|
No, it's not safe.
The code generated that does the writing to m_activityStarted and the others may be atomic, but that is not garantueed. Also, in your setters you do two things: set a boolean and make a call. That is definately not atomic.
You're better off synchronizing here using a lock of some sort.
For example, one thread may call the first function, and before that thread goes into "WriteDB()" another thread may call another function and go into WriteDB() without the first going there. Then, perhaps the status is written in the DB in the wrong order.
If you're worried about deadlocks then you should revise your whole concurrency strategy.
|
590,362
| 591,442
|
Allocating large blocks of memory with new
|
I have the need to allocate large blocks of memory with new.
I am stuck with using new because I am writing a mock for the producer side of a two part application. The actual producer code is allocating these large blocks and my code has responsibility to delete them (after processing them).
Is there a way I can ensure my application is capable of allocating such a large amount of memory from the heap? Can I set the heap to a larger size?
My case is 64 blocks of 288000 bytes. Sometimes I am getting 12 to allocate and other times I am getting 27 to allocate. I am getting a std::bad_alloc exception.
This is: C++, GCC on Linux (32bit).
|
With respect to new in C++/GCC/Linux(32bit)...
It's been a while, and it's implementation dependent, but I believe new will, behind the scenes, invoke malloc(). Malloc(), unless you ask for something exceeding the address space of the process, or outside of specified (ulimit/getrusage) limits, won't fail. Even when your system doesn't have enough RAM+SWAP. For example: malloc(1gig) on a system with 256Meg of RAM + 0 SWAP will, I believe, succeed.
However, when you go use that memory, the kernel supplies the pages through a lazy-allocation mechanism. At that point, when you first read or write to that memory, if the kernel cannot allocate memory pages to your process, it kills your process.
This can be a problem on a shared computer, when your colleague has a slow core leak. Especially when he starts knocking out system processes.
So the fact that you are seeing std::bad_alloc exceptions is "interesting".
Now new will run the constructor on the allocated memory, touching all those memory pages before it returns. Depending on implementation, it might be trapping the out-of-memory signal.
Have you tried this with plain o'l malloc?
Have you tried running the "free" program? Do you have enough memory available?
As others have suggested, have you checked limit/ulimit/getrusage() for hard & soft constraints?
What does your code look like, exactly? I'm guessing new ClassFoo [ N ]. Or perhaps new char [ N ].
What is sizeof(ClassFoo)? What is N?
Allocating 64*288000 (17.58Meg) should be trivial for most modern machines... Are you running on an embedded system or something otherwise special?
Alternatively, are you linking with a custom new allocator? Does your class have its own new allocator?
Does your data structure (class) allocate other objects as part of its constructor?
Has someone tampered with your libraries? Do you have multiple compilers installed? Are you using the wrong include or library paths?
Are you linking against stale object files? Do you simply need to recompile your all your source files?
Can you create a trivial test program? Just a couple lines of code that reproduces the bug? Or is your problem elsewhere, and only showing up here?
--
For what it's worth, I've allocated over 2gig data blocks with new in 32bit linux under g++. Your problem lies elsewhere.
|
590,792
| 590,816
|
How to kill a MFC Thread?
|
I spawn a thread using AfxBeginThread which is just an infinite while loop:
UINT CMyClass::ThreadProc( LPVOID param )
{
while (TRUE)
{
// do stuff
}
return 1;
}
How do I kill off this thread in my class destructor?
I think something like
UINT CMyClass::ThreadProc( LPVOID param )
{
while (m_bKillThread)
{
// do stuff
}
return 1;
}
and then set m_bKillThread to FALSE in the destructor. But I still need to wait in the destructor until the thread is dead.
|
Actively killing the thread:
Use the return value of AfxBeginThread (CWinThread*) to get the thread handle (m_hThread) then pass that handle to the TerminateThread Win32 API. This is not a safe way to terminate threads though, so please read on.
Waiting for the thread to finish:
Use the return value of AfxBeginThread (CWinThread*) to get the member m_hThread, then use WaitForSingleObject(p->m_hThread, INFINITE); If this function returns WAIT_OBJECT_0, then the thread is finished. Instead of INFINITE you could also put the number of milliseconds to wait before a timeout happens. In this case WAIT_TIMEOUT will be returned.
Signaling to your thread that it should end:
Before doing the WaitForSingleObject just set some kind of flag that the thread should exit. Then in your main loop of the thread you would check for that bool value and break the infinite loop. In your destructor you would set this flag then do a WaitForSingleObject.
Even better ways:
If you need even more control you can use something like boost conditions.
|
590,822
| 590,876
|
Dealing with accuracy problems in floating-point numbers
|
I was wondering if there is a way of overcoming an accuracy problem that seems to be the result of my machine's internal representation of floating-point numbers:
For the sake of clarity the problem is summarized as:
// str is "4.600"; atof( str ) is 4.5999999999999996
double mw = atof( str )
// The variables used in the columns calculation below are:
//
// mw = 4.5999999999999996
// p = 0.2
// g = 0.2
// h = 1 (integer)
int columns = (int) ( ( mw - ( h * 11 * p ) ) / ( ( h * 11 * p ) + g ) ) + 1;
Prior to casting to an integer type the result of the columns calculation is 1.9999999999999996; so near yet so far from the desired result of 2.0.
Any suggestions most welcome.
|
A very simple and effective way to round a floating point number to an integer:
int rounded = (int)(f + 0.5);
Note: this only works if f is always positive. (thanks j random hacker)
|
591,078
| 591,239
|
Can the list of C++ files in a Visual Studio project be dynamically filled?
|
I have a tool that generates most (but not all) files that need to be compiled in Visual Studio. The tool reads a configuration file and generates c++ files afterwards. This list can differ from one call to another when the configuration is altered.
I am wondering whether it would be possible to adapt the compiling process to my needs, which would be :
Launch the tool (not needed if configuration file has been modified)
Retrieve new list of C++ files to be compiled (ideally isolated in a folder inside the project)
Compile C++ files
EDIT: Having to close Visual Studio for this process to work is a no-go for me. The idea would be to have cpp files dynamically added as the first step of the compilation process.
|
Use a pre-build step to run your tool.
Also, create a file containing the list of includes and sources
This file name should be fixed (so that you don't have to change project properties or the vcproj file) -- add it to the project. E.g:
Project Properties > Command Line > Additional Options > @headerListingFile
You are not trying to integrate lex/yacc output with VS, are you?
|
591,338
| 591,349
|
how to declare volatile iterator in c++
|
Is there a way to declare an iterator which is a member variable in a class and that can be incremented using a member function even though the object of that class is const.
|
That would be with the "mutable" keyword.
class X
{
public:
bool GetFlag() const
{
m_accessCount++;
return m_flag;
}
private:
bool m_flag;
mutable int m_accessCount;
};
|
591,533
| 591,623
|
how to handle exceptions in C# DLL loaded by C++
|
I have a DLL that is created in C# for the purpose of providing a COM interface to a third-party C# library. I have a C++ program that uses that COM interface so that it can communicate with the C# library. Sometimes, exceptions get thrown on the C# side and all I get back on the C++ side is an HRESULT from the COM invocation that says means "exception occurred" (or something to that effect). Is there any way for me to get the entire exception information so that I can print an informative message to my C++ app's log? If not, is there anything I can do on the C# side to intercept all exceptions before they trigger whatever mechanism returns the HRESULT to C++ so that I can log them on the C# side?
|
There is a mapping of a managed exception to an HRESULT. Consult the table in this MSDN article. .NET retrieves error info from a COM object with IErrorInfo. That might well work the other way around too. Worth a shot.
|
592,067
| 592,073
|
Am I geting a structure copy here?
|
Here is a fake code sample
vector<Fred> gFred;
{
// init gFred
Fred &fred = gFred[0];
size_t z = 0;
do
{
fred = gFred[z];
// do odd processing with fred
z++;
}
while (fred.lastElementInSet == 0);
}
The thing that caught my attention was the fact that gFred[0] was being overwritten.
This leads me to think that rather than init fred as a reference to a new element,
fred = gFred[z];
What is actually happening is that gFred[1] is overwriting gFred[0].
I'm thinking the correct thing to do here, is whap myself upsida head a few times, and turn this into a pointer implementation and move on with my life.
Have I diagnosed this correctly? or do I need more education?
|
Yes, you are getting a structure copy there. References cannot be rebound, i.e., they stay the same once they are initialized.
And your solution is also appropriate. Dunno about smacking yourself in the head though.
|
592,075
| 592,148
|
why doesn't winmain set the errorlevel?
|
Why does this program correctly display a message box, but does not set the error level?
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
MessageBox(NULL, _T("This should return 90 no?"), _T("OK"), MB_OK);
return 90;
}
I compiled the code above to the name an executable called a.exe. The I did this in command prompt:
c:\> a.exe
(message box is displayed, I press ok)
c:\> echo %ERRORLEVEL%
0
I get the same results if I use exit(90); right before the return. It still says 0.
I also tried to start the program via CreateProcess and obtain the result with GetExitCodeProcess but it also returns 0 to me. I did error checking to ensure it was all started correctly.
I originally saw this problem in a more complex program so I made this simple program to verify the problem. Results are the same, both programs that have WinMain always return 0.
I tried both x64, x86 and unicode and MBCS compiling options. All give 0 as an error level/status code.
|
If your program is a Windows app, rather than a Console app, the command interpreter doesn't wait for it to complete (before you press OK, take a look at the command window and you'll see that it's ready for the next command).
If this is the case, building your application as Console subsystem app would solve the problem. If you need to run as a Windows app, you might try to wait for the command to complete and see if that works (I haven't tried this but it seems like a good approach):
start /wait a.exe
echo %ERRORLEVEL%
|
592,160
| 592,205
|
static vs extern "C"/"C++"
|
What is the difference between a static member function and an extern "C" linkage function ? For instance, when using "makecontext" in C++, I need to pass a pointer to function. Google recommends using extern "C" linkage for it, because "makecontext" is C. But I found out that using static works as well. Am I just lucky or...
class X {
public:
static void proxy(int i) {}
}
makecontext(..., (void (*)(void)) X::proxy, ...);
vs
extern "C" void proxy(int i) {}
makecontext(..., (void (*)(void)) proxy, ...);
EDIT: Can you show a compiler or architecture where the static member version does not work (and it's not a bug in the compiler) ?
|
Yes, you are just lucky :) The extern "C" is one language linkage for the C language that every C++ compiler has to support, beside extern "C++" which is the default. Compilers may supports other language linkages. GCC for example supports extern "Java" which allows interfacing with java code (though that's quite cumbersome).
extern "C" tells the compiler that your function is callable by C code. That can, but not must, include the appropriate calling convention and the appropriate C language name mangling (sometimes called "decoration") among other things depending on the implementation. If you have a static member function, the calling convention for it is the one of your C++ compiler. Often they are the same as for the C compiler of that platform - so i said you are just lucky. If you have a C API and you pass a function pointer, better always put one to a function declared with extern "C" like
extern "C" void foo() { ... }
Even though the function pointer type does not contain the linkage specification but rather looks like
void(*)(void)
The linkage is an integral part of the type - you just can't express it directly without a typedef:
extern "C" typedef void(*extern_c_funptr_t)();
The Comeau C++ compiler, in strict mode, will emit an error for example if you try to assign the address of the extern "C" function of above to a (void(*)()), beause this is a pointer to a function with C++ linkage.
|
592,763
| 592,950
|
Numerical range iterators in boost?
|
I'm aware of the range iterators in boost, and as for this reference, it seems there should be an easy way of doing what I want, but it's not obvious to me.
Say I want to represent a numerical range, 0 to 100 (inclusive or not), say range(0,100). I would like to do something like:
for_each(range<int>(0,100).begin(), range<int>(0,100).end(), do_something);
where do_something is a functor. This iterators shouldn't have the overhead of having an underneath vector or something like this, but to just offer a sequence of integers. Is this possible with the range implementation in boost? Possible at all with normal, standard STL iterators?
|
boost::counting_iterator
#include <boost/iterator/counting_iterator.hpp>
std::for_each( boost::counting_iterator<int>(0),
boost::counting_iterator<int>(100),
do_something );
|
593,037
| 593,139
|
How do I iterate a collection of Excel columns in C++ using Automation?
|
I want to do the moral equivalent of the following VBA code:
For Each col In Worksheets("Sheet1").Columns
# do stuff
Next col
I have generated MFC wrappers for the Excel type library that get me this far (the generated types all derive from COleDispatchDriver:
CApplication app;
app.CreateDispatch( clsid, e );
CWorkbooks wbks( app.get_Workbooks() );
CWorkbook book( wbks.Open( filename, /* optional args */ ) );
CRange cols( app.get_Columns() );
long numCols = cols.get_Count();
and from there I'm stuck. It looks like I can sort of iterate over cells using Range::get_Item( rowid, colid ), and then get the column from the cell, but I was looking for a more direct translation of the above loop.
(EDIT) Clarification: I don't actually care about the individual cells. My goal is to determine which columns have width 0 (are hidden) and delete them from the worksheet.
|
I assume that you're trying to traverse all the cells in the spreadsheet. You can get the active worksheet's "all cells" range, and loop through its rows and columns :
CSheets sheets = book.get_WorkSheets();
CWorkSheet sheet = sheets.get_ActiveSheet();
Range cells = sheet.get_Cells();
int nRows = cells.get_Rows().get_Count();
int nCols = cells.get_Columns().get_Count();
for (int i = 0; i <= nRows; i++)
{
for (int j = 0; j <= nCols; j++)
{
Range cell = cells.get_Item(i+1,j+1);
//Do stuff with individual cell
}
}
EDIT: In response to OP clarification:
This will probably do what you're looking for:
CSheets sheets = book.get_WorkSheets();
CWorkSheet sheet = sheets.get_ActiveSheet();
Range cols= sheet.get_Columns();
int nCols = cols.get_Count();
for (int i = nCols; i > 0; i--)
{
Range topCellOfCol = cells.get_Item(1, i);
Range entireCol = topCellOfCol.get_EntireColumn();
if (entireCol.get_Hidden())
entireCol.Delete( xlShiftToLeft );
}
|
593,244
| 593,263
|
dumping c++ structures to a text file
|
how would one go about writing the contents of a structure in C++ to a text file? What I want to do is, say I have a structure called A, with data members A.one, A.two, and so on, and I want to write them out line by line into a text file, like so
Structure A
A.one = value
A.two = value
...
Structure B
B.one = value
B.two = value
Basically I want to make a dump.. Is there an easy way to do this? What's the best I/O method for this? CFile? iostream? Thanks.. Is there an easier way to dump all of the values of member data of a class?
EDIT: Crap, thanks guys..
|
No reflection in C++, so you have to do it manually, eg (using iostream, for simplicty):
dump_A(std::cout, "A", a);
void dump_A(std::iostream& os, const char* name, A const& a)
{
os << "Structure " << name << '\n'
<< name << ".one = " << a.one << '\n'
<< name << ".two = " << a.two << '\n';
}
|
593,403
| 593,421
|
Always-in-front dialogs
|
Is there a way to create a modeless dialog box in C++ MFC which always stays on top of the other windows in the application? I'm thinking sort of like the Find dialog in Visual Studio 2005 - where it stays on top, but you can still edit the underlying text.
(If it makes any difference, it's not MDI; it's a dialog-based app)
|
Note: This does not work under Windows 10, and may not work under Windows 7 and 8 (Reports vary).
From Nish:
###Making your dialog stay on top
Haven't you seen programs which have
an "always-stay-on-top" option? Well
the unbelievable thing is that you can
make your dialog stay on top with just
one line of code. Simply put the
following line in your dialog class's
OnInitDialog() function.
SetWindowPos(&this->wndTopMost,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
Basically what we are doing is to use
the SetWindowPos function to change
the Z-order of our dialog window. We
make our dialog stay on top of all
other windows by moving it to the top
of the Z-order. Now even when you
activate some other window, our window
will stay on top. But I'd advise you
to make sure you know exactly what you
are doing when you do this, for it
might annoy people if they can't get
your window out of the way when they
want to do that.
As you mentioned in the comments, the above line makes the window sit on top of every application. You'll need to do
SetWindowPos(&this->wndTop,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
To make a window sit on top of only your application.
|
593,608
| 593,612
|
Accessing vector elements inside another vector through an iterator?
|
std::vector< std::vector<coords> >::iterator iter;
for(iter = characters.begin(); iter != characters.end(); iter++)
{
std::vector<coords>* cha = iter; // doesn't work.
}
// does work.
std::vector<coords>* character = &characters.at(0);
coords* first = &character->at(0);
And I don't get why. Isn't iter supposed to be a pointer to an element of the type that it's container is supposed to 'contain'?
Anyone willing to shed light on this?
By doesn't work I mean:
error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'std::vector<_Ty> *'
Which doesn't make a whole lot of sense to me.
|
An iterator is a type that can be dereferenced like a pointer, i.e., it has an explicit operator*() and operator->(). It doesn't have to be a pointer.
So use &*iter if you want to get the address of the vector.
|
593,792
| 593,832
|
C++ Directory Restructuring
|
I have a source code of about 500 files in about 10 directories. I need to refactor the directory structure - this includes changing the directory hierarchy or renaming some directories.
I am using svn version control. There are two ways to refactor: one preserving svn history (using svn move command) and the other without preserving. I think refactoring preserving svn history is a lot easier using eclipse CDT and SVN plugin (visual studio does not fit at all for directory restructuring).
But right now since the code is not released, we have the option to not preserve history.
Still there remains the task of changing the include directives of header files wherever they are included. I am thinking of writing a small script using python - receives a map from current filename to new filename, and makes the rename wherever needed (using something like sed). Has anyone done this kind of directory refactoring? Do you know of good related tools?
|
If you're having to rewrite the #includes to do this, you did it wrong. Change all your #includes to use a very simple directory structure, at mot two levels deep and only using a second level to organize around architecture or OS dependencies (like sys/types.h).
Then change your make files to use -I include paths.
Voila. You'll never have to hack the code again for this, and compiles will blow up instantly if something goes wrong.
As far as the history part, I personally find it easier to make a clean start when doing this sort of thing; archive the old one, make a new repository v2, go from there. The counterargument is when there is a whole lot of history of changes, or lots of open issues against the existing code.
Oh, and you do have good tests, and you're not doing this with a release coming right up, right?
|
594,089
| 594,092
|
Does std::vector.clear() do delete (free memory) on each element?
|
Consider this code:
#include <vector>
void Example()
{
std::vector<TCHAR*> list;
TCHAR* pLine = new TCHAR[20];
list.push_back(pLine);
list.clear(); // is delete called here?
// is delete pLine; necessary?
}
Does list.clear() call delete on each element? I.e. do I have to free the memory before / after list.clear()?
|
No (you need to do the delete yourself at the end as you suggest in your example as the destruction of the bald pointer doesnt do anything). But you can use a boost [or other RAII-based idiom] smart pointer to make it Do The Right Thing (auto_ptr would not work correctly in a container as it has incompatible behaviour under copying etc.), but be sure you understand the pitfalls of such smart pointers before use. (As Benoit mentions, in this case, basic_string is what you're really looking for here.)
Having said that there's a need to understand the pitfalls of smart pointers, having them take care of the memory management implicitly so you dont have to do it explicitly is far less error-prone.
EDIT: Substantially revised to encompass the elements Benoit brought into his far more thorough answer, thanks to strong prodding from the Earwicker and James Matta - thanks for pushing me to do the due diligence on this!
|
594,135
| 594,151
|
What's up with static_cast with multiple arguments?
|
Can anyone tell me what this cast has for effect (besides setting happyNumber to 1337), if any at all, and if it has no other effect, how come I can write code like this??? Is this a compiler bug, or some "hidden away feature" of C++?
int happyNumber = static_cast<int>(123.456, TRUE, "WTF" , false , "IS" , NULL , "GOING" , 0xff , "ON???" , 1337);
I was surprised this would compile at all. I found it through a bug where I accidentally set the second parameter to something that was meant to go in a function call of the expression being cast. This resulted in a nasty bug where the object was cast from the second parameter, calling the function with only one argument. It compiled... And didn't initially boom...
I am using Microsoft Visual C++ 2008.
|
Static cast takes one argument, but its argument is an expression, and expressions can include the comma operator. Comma is used in situations where you want to evaluate two or more expressions at once for their side effects, e.g.:
int i, j;
for (i=0, j=0; i < 10; i++,j++) {
// do stuff
}
It's somewhat useful because without it you could only evaluate one expression each for the initializer, condition, and continue parts of the for loop (or any other place an expression is expected). It doesn't usually make for the clearest code, though, and the semantics are odd. As you observed, a comma-separated sequence evaluates to the value of its last expression.
|
594,162
| 594,172
|
Intercepting/Rerouting TCP SYN packets to C++ program in linux
|
I am trying to find the easiest way to intercept TCP SYN packets sent by my computer in a c++ program. There are couple of options that I know. One would be monitor all traffic and just selectively work with the SYN packets doing nothing with the rest. Another option I came across was to use a packet filtering utility which will forward the SYN packets to my program. Someone suggested me to use netfilter for the same.
I was wondering if there are other options or should I delve into netfilter. Also, any pointers on how to do it this with netfilter would be helpful.
EDIT: I want to intercept the SYN packet and may need to modify it (reroute to different destination, change destination port etc) before reinjecting it back to the network
Edit: I was able to do this using a combination of iptables and libnetfilter_queue. I used ipfilter to redirect all TCP SYN packets to a particular queue (this was using a simple command)
Then in a C program I was able to use libnetfilter_queue API to access the packets in the queue analyze them and reinject them back to the network.
|
If you merely want to see the packets, use libpcap and packet filtering - that'll work on most any UNIX variant.
If you want to somehow intercept and rewrite the packets, please supply more information about what you're trying to do, and what's supposed to happen to the packets afterwards.
As you suggest, that might be an application for netfilter and its queue module, although that requires a 2.6.14 or later kernel:
Main Features
receiving queued packets from the kernel nfnetlink_queue subsystem
issuing verdicts and/or reinjecting altered packets to the kernel
nfnetlink_queue subsystem
|
594,253
| 594,293
|
How to debug a DLL file in Delphi
|
I am a developer working on Visual C++, but in my project there are some Delphi components. I need to debug the Delphi components to fix some issues.
What are the things that are a must to generate a DLL file in debug and then start debugging in Delphi?
|
In Delphi 7 you would do this:
Project | Options | Compiler | Debugging | Debug information (check)
Then go to Run | Parameters | Host Application and enter the name of your exe.
Add some breakpoints in your DLL code and then click run. Your exe will be loaded and you can debug the DLL parts in the Delphi IDE.
If your exe is already running, click Run | Attach to process
-- I've tested this and found that I also needed to check the "Include remote debug symbols" on the Linker page of project options in Delphi 7.
I was able to get a breakpoint to hit using the Run | Parameters as well as Run | Attach to process methods. The test DLL I had created had a single stdcall function and was dynamically loaded by a Visual C++ console application.
|
594,521
| 594,630
|
STL iterator with custom template
|
i have the following template method,
template <class T>
void Class::setData( vector<T> data )
{
vector<T>::iterator it;
}
and i'm getting the following compilation error ( XCode/gcc )
error: expected `;' before 'it'
i found someone else with a similar problem here (read down to see it's the same even though it starts out with a different issue) but they seem to have resolved by updating Visual Studio. This makes me guess that it is a compiler issue and that it should compile, is that correct? Iteration via indexing from 0 to size works, however it is not the way i would prefer to implement this function. Is there another way around this?
Thanks
|
Classic case of when to use the typename keyword. Hoping that you have #include-ed vector and iterator and have a using namespace std; somewhere in scope. Use:
typename vector<T>::iterator it;
Look up dependent names. Start here.
|
594,522
| 594,542
|
When would you use an array rather than a vector/string?
|
I'm a beginner C++ programmer and so I've learnt using arrays rather than vectors (this seems to be the general way to do things, then move on to vectors later on).
I've noticed that a lot of answers on SO suggest using vectors over arrays, and strings over char arrays. It seems that this is the "proper" way to code in C++.
That all being said, when is it still worth using a classic array/char* (if ever)?
|
When writing code that should used in other projects, in particular if you target special platforms (embedded, game consoles, etc.) where STL might not be present.
Old projects or projects with special requirements might not want to introduce dependencies on STL libraries. An interface depending on arrays, char* or whatever will be compatible with anything since it's part of the language. STL however is not guaranteed to be present in all build environments.
|
594,703
| 597,288
|
Exporting class from executable to dll
|
I need in a DLL to use a class, defined in an executable (DLL and executable are compiled by the same compiler). But I don't want the source code of this class definition to be available to DLL, only declaration.
One possible way to do it is to make all the necessary class methods to be virtual (so that DLL linker will not need these methods' definitions). The disadvantages of this approach:
I cannot create objects of exported classes
in DLL code using new (a have to
create additional functions in
executable's code).
I have to make all these methods virtual,
even if otherwise they don't need to
be virtual.
There is a way to export a class from a DLL to an executable using Microsoft's __declspec(dllexport) storage-class extended attribute.
Is there a way to export a class from executable to DLL using the same technique?
My old Borland C 6 compiler does not allow me to create import library during the build of executable project. (So, when compiling the DLL, linker gives me unresolved external error messages for all imported non-virtual class methods.) Is it a limitation of this very compiler, or maybe I'm missing something important?
|
So far as I know, it is ok to use MS VS's dllexport to export a class or function from a exe and use it in a DLL. and it runs cool if your DLL and Exe execute in one process.
|
594,730
| 594,769
|
Overriding static variables when subclassing
|
I have a class, lets call it A, and within that class definition I have the following:
static QPainterPath *path;
Which is to say, I'm declaring a static (class-wide) pointer to a path object; all instances of this class will now have the same shared data member. I would like to be able to build upon this class, subclassing it into more specialised forms, layering behaviour, and with each class having its own unique path object (but not having to repeat the boring bits like calculating bounding boxes or calling the painting routines).
If I subclass it to create a class F (for example), I want F to use the inherited drawing routines from A, but to use the static (class-wide) path object declared in F. I have tried having the declaration above in the private section (and repeating it in the derived class F), and tried having it in the protected section, all with no joy.
I can sort of see why this is happening:
void A::paint() {
this->path...
is referring to A::path instead of F::path, even when the object is of class F.
Is there an elegant way to get round this, and allow each class to maintain a static path object, while still using drawing code defined in the base class, and having all classes (except perhaps the base class) be real and instantiatable?
|
Use a virtual method to get a reference to the static variable.
class Base {
private:
static A *a;
public:
A* GetA() {
return a;
}
};
class Derived: public Base {
private:
static B *b;
public:
A* GetA() {
return b;
}
};
Notice that B derives from A here. Then:
void Derived::paint() {
this->GetA() ...
}
|
594,903
| 594,915
|
Switching to Linux for Windows development, bad idea?
|
I was contemplating switching to Linux for C++ development, coming from a Windows environment. Is this a bad idea? My workplace uses Windows and Visual Studio for our projects (some C# and java too, but right now I'm only developing in C++). If they decide to put me on a C# project, would development still possible (mono?)? What are the difficulties in this sort of transition?
Would I have a problem working on their projects and vice versa? I read somewhere that there'd be problems with precompiled headers and such (we do use them), and encodings (tabs/spaces, line endings, etc)..
If it's not too hard to do this switch, how do I get started? IDE? vim+make?
Thanks.
By the way, we make MOSTLY windows software..
EDIT: Thanks guys, I guess that makes sense..
|
That's a bad idea. I can see at least two reasons :
Develop on the same OS you write software for
Visual Studio rocks
|
595,216
| 595,275
|
regular expression to split up searchphrase
|
I was hoping someone could help me writing a regex for c++ that matches words in a searchphrase, and explain it bit by bit for learning purposes.
What I need is a regex that matches string within " " like "Hello you all", and single words that starts/ends with * like *ack / overfl*.
For the quote part I have \"[\^\\s][\^\"]*\" but I can't figure out the wildcard (*) part, and how I should combine it with the quote regex.
|
Try this regular expression:
(?:\*?\w+\*?|"(?:[^\x5C"]+|\x5C(?:\x5C\x5C)*")*")+
For readability I replaced the backslash characters by \x5C.
The expression "(?:[^\x5C"]+|\x5C(?:\x5C\x5C)*")*" will also match "foo \"bar\"" and other proper escaped quote sequences (but only the " might be escaped).
So foo* bar *baz *quux* "foo \"bar\"" should be splitted into:
foo*
bar
*baz
*quux*
"foo \"bar\""
If you don’t want to match bar in the example above, use this:
(?:\*\w+|\w+\*|"(?:[^\x5C"]+|\x5C(?:\x5C\x5C)*")*")+
|
595,314
| 595,381
|
parser: parsing formulas in template files
|
I will first describe the problem and then what I currently look at, in terms of libraries.
In my application, we have a set of variables that are always available. For example: TOTAL_ITEMS, PRICE, CONTRACTS, ETC (we have around 15 of them). A clients of the application would like to have certain calculations performed and displayed, using those variables. Up until now, I have been constantly adding those calculations to the app. It's pain in the butt, and I would like to make it more generic by way of creating a template, where the user can specify a set of formulas that the application will parse and calculate.
Here is one case:
total_cost = CONTRACTS*PRICE*TOTAL_ITEMS
So, want to do something like that for the user to define in the template file:
total_cost = CONTRACTS*PRICE*TOTAL_ITEMS and some meta-date, like screen to display it on. Hence they will be specifying the formula with a screen. And the file will contain many formulas of this nature.
Right now, I am looking at two libraies: Spirit and matheval
Would anyone make recommendations what's better for this task, as well as references, examples, links?
Please let me know if the question is unclear, and I will try to further clarify it .
Thanks,
Sasha
|
If you have a fixed number of variables it may be a bit overkill to invoke a parser. Though Spirit is cool and I've been wanting to use it in a project.
I would probably just tokenize the string, make a map of your variables keyed by name (assuming all your variables are ints):
map<const char*,int*> vars;
vars["CONTRACTS"] = &contracts;
...
Then use a simple postfix calculator function to do the actual math.
Edit:
Looking at MathEval, it seems to do exactly what you want; set variables and evaluate mathematical functions using those variables. I'm not sure why you would want to create a solution at the level of a syntax parser. Do you have any requirements that MathEval does not fulfill?
|
595,787
| 597,061
|
What is a good scripting language to integrate into high-performance applications?
|
I'm a game's developer and am currently in the processing of writing a cross-platform, multi-threaded engine for our company. Arguably, one of the most powerful tools in a game engine is its scripting system, hence I'm on the hunt for a new scripting language to integrate into our engine (currently using a relatively basic in-house engine).
Key features for the desired scripting system (in order of importance) are:
Performance - MUST be fast to call & update scripts
Cross platform - Needs to be relatively easy to port to multiple platforms (don't mind a bit of work, but should only take a few days to port to each platform)
Offline compilation - Being able to pre-parse the script code offline is almost essential (helps with file sizes and load times)
Ability to integrate well with c++ - Should be able to support OO code within the language, and integrate this functionality with c++
Multi-threaded - not required, but desired. Would be best to be able to run separate instances of it on multiple threads that don't interfere with each other (i.e. no globals within the underlying code that need to be altered while running). Critical Section and Mutex based solutions need not apply.
I've so far had experience integrating/using Lua, Squirrel (OO language, based on Lua) and have written an ActionScript 2 virtual machine.
So, what scripting system do you recommend that fits the above criteria? (And if possible, could you also post or link to any comparisons to other scripting languages that you may have)
Thanks,
Grant
|
We've had good luck with Squirrel so far. Lua is so popular it's on its way to becoming a standard.
I recommend you worry more about memory than speed. Most scripting languages are "fast enough" and if they get slow you can always push some of that functionality back down into C++. Many of them burn through lots of memory, though, and on a console memory is an even more scarce resource than CPU time. Unbounded memory consumption will crash you eventually, and if you have to allocate 4MB just for the interpreter, that's like having to throw 30 textures out the window to make room.
|
596,093
| 596,154
|
C++ Etiquette about Member Variables on the Heap
|
Is it considered bad manners/bad practice to explicitly place object members on the heap (via new)? I would think you might want to allow the client to choose the memory region to instantiate the object. I know there might be a situation where heap members might be acceptable. If you know a situation could you describe it please?
|
If you have a class that's designed for copy semantics and you're allocating/deallocating a bunch of memory unnecessarily, I could see this being bad practice. In general, though, it's not. There are a lot of classes that can make use of heap storage. Just make sure you're free of memory leaks (deallocate things in the destructor, reference count, etc.) and you're fine.
If you want more flexibility, consider letting your user specify an Allocator. I'll explain.
Certain classes, e.g. std::vector, string, map, etc. need heap storage for the data structures they represent. It's not considered bad manners; when you have an automatically allocated vector, the user is expected to know that a buffer is allocated when the vector constructor gets called:
void foo() {
// user of vector knows a buffer that can hold at least 10 ints
// gets allocated here.
std::vector<int> foo(10);
}
Likewise, for std::string, you know there's an internal, heap-allocated char*. Whether there's one per string instance is usually up to the STL implementation; often times they're reference counted.
However, for nearly all of the STL classes, users do have a choice of where things are put, in that they can specify an allocator. vector is defined kind of like this:
template <typename T, typename Alloc = DefaultAllocator<T> >
class vector {
// etc.
};
Internally, vector uses Alloc (which defaults to whatever the default allocator is for T) to allocate the buffer and other heap storage it may need. If users doesn't like the default allocation strategy, they can specify one of their own:
vector<int, MyCustomAllocator> foo(10);
Now when the constructor allocates, it will use a MyCustomAllocator instead of the default. Here are some details on writing your own STL allocator.
If you're worried that it might be "bad manners" to use the heap for certain storage in your class, you might want to consider giving users of your class an option like this so that they can specify how things are to be allocated if your default strategy doesn't fit their needs.
|
596,122
| 596,135
|
Template Function under GCC
|
Duplicate. See this.
Can someone tell me why this does not compile under GCC? Both MSVC6, and VS2008 will compile it, with no warnings, even.
The code...
#include <iostream>
#include <vector>
#include <ctime>
#include <cstdlib>
using namespace std;
template <typename T>
T range(vector<T> &v)
{
vector<T>::iterator i = v.begin();
Throws an error on the last line, expected ; before i.
Do I need to typedef?
Most of the compiling I do is with MSVC6, or VS2008. I don't do a whole lot with GCC, so I'm a little in the dark.
|
The compiler does not know enough to parse vector::iterator as a type at that point. Use the typename keyword to give it a hint:
typename vector<T>::iterator i = v.begin();
|
596,162
| 596,180
|
Can you remove elements from a std::list while iterating through it?
|
I've got code that looks like this:
for (std::list<item*>::iterator i=items.begin();i!=items.end();i++)
{
bool isActive = (*i)->update();
//if (!isActive)
// items.remove(*i);
//else
other_code_involving(*i);
}
items.remove_if(CheckItemNotActive);
I'd like remove inactive items immediately after update them, inorder to avoid walking the list again. But if I add the commented-out lines, I get an error when I get to i++: "List iterator not incrementable". I tried some alternates which didn't increment in the for statement, but I couldn't get anything to work.
What's the best way to remove items as you are walking a std::list?
|
You have to increment the iterator first (with i++) and then remove the previous element (e.g., by using the returned value from i++). You can change the code to a while loop like so:
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i++); // alternatively, i = items.erase(i);
}
else
{
other_code_involving(*i);
++i;
}
}
|
596,185
| 596,348
|
Is it possible to get a char* name from a template type in C++
|
I want to get the string name (const char*) of a template type. Unfortunately I don't have access to RTTI.
template< typename T >
struct SomeClass
{
const char* GetClassName() const { return /* magic goes here */; }
}
So
SomeClass<int> sc;
sc.GetClassName(); // returns "int"
Is this possible? I can't find a way and am about to give up. Thanks for the help.
|
No and it will not work reliable with typeid either. It will give you some internal string that depends on the compiler implementation. Something like "int", but also "i" is common for int.
By the way, if what you want is to only compare whether two types are the same, you don't need to convert them to a string first. You can just do
template<typename A, typename B>
struct is_same { enum { value = false }; };
template<typename A>
struct is_same<A, A> { enum { value = true }; };
And then do
if(is_same<T, U>::value) { ... }
Boost already has such a template, and the next C++ Standard will have std::is_same too.
Manual registration of types
You can specialize on the types like this:
template<typename>
struct to_string {
// optionally, add other information, like the size
// of the string.
static char const* value() { return "unknown"; }
};
#define DEF_TYPE(X) \
template<> struct to_string<X> { \
static char const* value() { return #X; } \
}
DEF_TYPE(int); DEF_TYPE(bool); DEF_TYPE(char); ...
So, you can use it like
char const *s = to_string<T>::value();
Of course, you can also get rid of the primary template definition (and keep only the forward declaration) if you want to get a compile time error if the type is not known. I just included it here for completion.
I used static data-members of char const* previously, but they cause some intricate problems, like questions where to put declarations of them, and so on. Class specializations like above solve the issue easily.
Automatic, depending on GCC
Another approach is to rely on compiler internals. In GCC, the following gives me reasonable results:
template<typename T>
std::string print_T() {
return __PRETTY_FUNCTION__;
}
Returning for std::string.
std::string print_T() [with T = std::basic_string<char, std::char_traits<char>, std::allocator<char> >]
Some substr magic intermixed with find will give you the string representation you look for.
|
596,360
| 597,545
|
Good c++ lib for threading
|
I prefer a lib solely based on pthreads. What is a good c++ lib to for threading?
|
I looked at some options some time ago. Here are some:
Boost Thread - This is the most standard choice. Boost is the most standard library for C++, that is not in the official standard.
POCO - Has thread support and a lot more. Is my preferred choice because it lets you set thread priorities, something boost doesn't support. Thread priorities are important for my application domain (soft real-time).
Zthread - Looks a good library. I have no experience with it.
ACE - Well known library. I have no experience with it.
Then you have libraries that let you operate at an higher abstraction level like Thread Buildings Blocks.
|
596,411
| 596,427
|
Simple C++ Threading
|
I am trying to create a thread in C++ (Win32) to run a simple method. I'm new to C++ threading, but very familiar with threading in C#. Here is some pseudo-code of what I am trying to do:
static void MyMethod(int data)
{
RunStuff(data);
}
void RunStuff(int data)
{
//long running operation here
}
I want to to call RunStuff from MyMethod without it blocking. What would be the simplest way of running RunStuff on a separate thread?
Edit: I should also mention that I want to keep dependencies to a minimum. (No MFC... etc)
|
#include <boost/thread.hpp>
static boost::thread runStuffThread;
static void MyMethod(int data)
{
runStuffThread = boost::thread(boost::bind(RunStuff, data));
}
// elsewhere...
runStuffThread.join(); //blocks
|
596,636
| 596,643
|
C++: difference between ampersand "&" and asterisk "*" in function/method declaration?
|
Is there some kind of subtle difference between those:
void a1(float &b) {
b=1;
};
a1(b);
and
void a1(float *b) {
(*b)=1;
};
a1(&b);
?
They both do the same (or so it seems from main() ), but the first one is obviously shorter, however most of the code I see uses second notation. Is there a difference? Maybe in case it's some object instead of float?
|
Both do the same, but one uses references and one uses pointers.
See my answer here for a comprehensive list of all the differences.
|
596,964
| 596,987
|
Help me make this code exception-safe
|
So I have this library code, see...
class Thing
{
public:
class Obj
{
public:
static const int len = 16;
explicit Obj(char *str)
{
strncpy(str_, str, len);
}
virtual void operator()() = 0;
private:
char str_[len];
};
explicit Thing(vector<Obj*> &objs) : objs_(objs) {}
~Thing() {
for(vector<Obj*>::iterator i = objs_.begin(); i != objs_.end(); ++i) {
delete *i;
}
}
private:
vector<Obj*> objs_;
}
And in my client code...
class FooObj : public Thing::Obj
{
virtual void operator()() {
//do stuff
}
}
class BarObj : public Thing::Obj
{
virtual void operator()() {
//do different stuff
}
}
vector<Objs*> objs;
int nStructs = system_call(*structs);
for(int i = 0; i < nStructs; i++) {
objs.push_back(newFooObj(structs[i].str));
}
objs.push_back(newBarObj("bar1");
objs.push_back(newBarObj("bar2");
Thing thing(objs);
// thing does stuff, including call Obj::()() on the elements of the objs_ vector
The thing I'm stuck on is exception safety. As it stands, if any of the Obj constructors throw, or the Thing constructor throws, the Objs already in the vector will leak. The vector needs to contain pointers to Objs because they're being used polymorphically. And, I need to handle any exceptions here, because this is being invoked from an older codebase that is exception-unaware.
As I see it, my options are:
Wrap the client code in a giant try block, and clean up the vector in the catch block.
Put try blocks around all of the allocations, the catch blocks of which call a common cleanup function.
Some clever RAII-based idea that I haven't thought of yet.
Punt. Realistically, if the constructors throw, the application is about to go down in flames anyway, but I'd like to handle this more gracefully.
|
Since your Thing destructor already knows how to clean up the vector, you're most of the way towards a RAII solution. Instead of creating the vector of Objs, and then passing it to Thing's constructor, you could initialize Thing with an empty vector and add a member function to add new Objs, by pointer, to the vector.
This way, if an Obj's constructor throws, the compiler will automatically invoke Thing's destructor, properly destroying any Objs that were already allocated.
Thing's constructor becomes a no-op:
explicit Thing() {}
Add a push_back member:
void push_back(Obj *new_obj) { objs_.push_back(new_obj); }
Then the allocation code in your client becomes:
Thing thing(objs);
int nStructs = system_call(*structs);
for(int i = 0; i < nStructs; i++) {
thing.push_back(newFooObj(structs[i].str));
}
thing.push_back(newBarObj("bar1");
thing.push_back(newBarObj("bar2");
As another poster suggested, a smart pointer type inside your vector would also work well. Just don't use STL's auto_ptr; it doesn't follow normal copy semantics and is therefore unsuitable for use in STL containers. The shared_ptr provided by Boost and the forthcoming C++0x would be fine.
|
597,063
| 597,250
|
extend a abstract base class w/o source recompilation?
|
ignore this, i thought of a workaround involving header generation. It isnt the nicest solution but it works. This question is to weird to understand. Basically i want to call a virtual function that hasnt been declared in the lib or dll and use it as normal (but have it not implemented/empty func).
I have an abstract base class in my library. All my plugins inherit from it, the user plugin inherits from this class and his application uses this class as a plugin pointer. I want that user to be able to extend the class and add his functions. The problem is, I am sure if he adds a virtual function and try to call it, the code will crash due to my objects not having the extra data in its vtable. How can I work around that? I thought of inheriting it but that would lead to ugly problems when a 3rd user comes to play. I dont want him to typecast to send the extended functions.
I was thinking of a msg function like intptr_t sendMsg(enum msgName, void* argv); But that removes the safty and I'd need to typecast everything. Whats the best solution for this? I would much rather use vtables then use a sendMsg function. How can I work around this?
|
Are you asking if you can add virtual functions to the base class without recompiling? The short answer to that is "no". The long answer is in your question, you'd have to provide some kind of generic "call_func" interface that would allow you to call functions "dynamically".
|
597,078
| 597,081
|
__FILE__, __LINE__, and __FUNCTION__ usage in C++
|
Presuming that your C++ compiler supports them, is there any particular reason not to use __FILE__, __LINE__ and __FUNCTION__ for logging and debugging purposes?
I'm primarily concerned with giving the user misleading data—for example, reporting the incorrect line number or function as a result of optimization—or taking a performance hit as a result.
Basically, can I trust __FILE__, __LINE__ and __FUNCTION__ to always do the right thing?
|
__FUNCTION__ is non standard, __func__ exists in C99 / C++11. The others (__LINE__ and __FILE__) are just fine.
It will always report the right file and line (and function if you choose to use __FUNCTION__/__func__). Optimization is a non-factor since it is a compile time macro expansion; it will never affect performance in any way.
|
597,138
| 599,949
|
Referencing a platform-specific library from a non-specific .NET app
|
I often need to include little bits of native code in my C# apps, which I tend to do via C++/CLI. Usually I just need to use a C++ library for which there exists no good alternative for .NET; but sometimes performance is a factor too.
This is problematic; doing so means adding a reference to a specific x86 or x64 library. Most libraries support both 64-bit and 32-bit compilation, or require only minor modifications to work under 64-bit. However, I can only reference one of the versions from a particular C# project build target. That means I need to add several build targets by hand for every project in the solution.
VS.NET is extremely unhelpful in this case: If you add a C++ library and C# library to the same solution, and the C# and C++ libraries have both 32 and 64 bit targets, your solution will contain an "Any CPU" target, a "Mixed Platforms" target, a x64 target, a x86 target (which is what C# calls 32-bit), a win32 target (which is what C++ calls 32-bit), and maybe more; all in at least two versions (being Release and Debug, unless you've added more).
This get's messy fast, and for no good reason. The obvious behaviour shouldn't be that tricky: if I have a C# project referencing a C++ project, then it should be somewhat obvious that the 64-bit version should reference the 64-bit version, and similarly for 32-bits.
The worst part of it all is that all this results in two separate but identical executables: a Any CPU .NET project can work unmodified in both 32 and 64 bit modes, but I've not found a way to load the appropriate platform specific supporting libraries depending on the mode the app was started in.
To summarize this long ramble:
Is it possible to make working with VS on cross-platform apps less of a pain - to get it to add the appropriate references to the appropriate build targets without hand-holding?
Is there a simple way to make a .NET executable with platform-specific references that can run both in 32-bit and 64-bit mode, loading the appropriate assemblies as needed?
|
The main question you should ask yourself is, do you need a 64-bit version. For details see blogs posts by Scott Hanselman and myself.
If you really need both versions, you can also load both the 32bit and 64bit library into the GAC, so the runtime can chose the correct one automatically.
If you don't want to GAC your libraries, you can also take a look at this StackOverflow post, where a way to load the correct assembly is described. I don't really like this solution though, because it really requires a plugin model
|
597,182
| 597,246
|
Windows GUI C++ Programming
|
I want to learn C++ GUI programming using Visual Studio 2008. I'm not sure where to start though. I learned C++ in high school, but not GUI. I've been doing C# for about 3 years now and thats how I "learned" GUI programming. Now I want to learn how to write GUI's without the use of the .NET framework, so where do I start?
|
MFC is almost outdated now. I would recommend to use WTL instead .
Well it is also not a good idea just to start programming for GUI in C++ when there are so many good frameworks available like QT cross platform framework.
|
597,217
| 599,121
|
Trying to include iPhone OpenGLES headers in C++ code
|
I have some C++ doing OpenGL drawing and am trying to figure out how to include the opengl headers without it giving me thousands of errors in the obj-c code.
|
I'm not getting any errors.
Are you doing
#include <OpenGLES/ES1/gl.h>
?
|
597,260
| 597,330
|
How to determine a windows executables DLL dependencies programmatically?
|
How to determine what DLL's a binary depends on using programmatic methods?
To be clear, I am not trying to determine the DLL dependencies of the running exec, but of any arbitrary exec (that may be missing a required DLL). I'm looking for a solution to implement in a C/C++ application. This is something that needs to be done by my application at runtime and can't be done by a third party app (like depends).
|
Take a look at the IMAGE_LOAD_FUNCTION API. It will return a pointer to a LOADED_IMAGE structure, which you can use to access the various sections of a PE file.
You can find some articles that describe how the structures are laid out here, and here. You can download the source code for the articles here.
I think this should give you everything you need.
Update:
I just downloaded the source code for the article. If you open up EXEDUMP.CPP and take a look at DumpImportsSection it should have the code you need.
|
597,292
| 597,299
|
Where exactly do function pointers point?
|
Given that all the primitive data types and objects have memory allocated, it is intuitively easy to imagine the pointers to these types.
But where exactly do function pointers point to? Given that instructions are converted into machine code and reside in memory, should we consider they point to the memory location corresponding to the start of the functions instructions?
We face many errors in pointers due to illegal memory access. Is it the case that errors occur when function pointers point to data memory instead of instruction memory?
|
Function pointer also point into memory, the only difference is that there is executable code at that memory location instead of data.
On many platforms if you try to execute data (e.g. regular memory) you'll crash or cause an exception. This is known as Data Execution Prevention - a security measure to prevent applications inadvertently running dodgy code that may be placed there by malware.
|
597,311
| 597,316
|
Why does the child process here not print anything?
|
Assume all the variables have been declared previously... because they have been. The child process does not print anything which makes me think it's not being executed. The parent process runs fine, albeit it doesn't get the shared memory.
I apologize for the length of this code...
// create 5 child process
for(int k=0;k<5;k++){
// fork a child process
pid = fork();
// error occured on fork
if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
// this is what the child process will run
else if (pid == 0) {
//create a shared mem segment
segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR);
//attach the shared memory segment
shared_memory = (char *) shmat(segment_id, NULL, 0);
printf("this is child");
double x = 0;
double sum = 0;
// Run process that sums the function
for(int i=0; i<n; i++){
// get random number in range of x1-x2
x = rand()%(x2 - x1 + 1) + x1;
sum = sum + f(x);
}
//write output to the shared memory segment
sprintf(shared_memory, "%f", sum);
execlp("/bin/ls", "ls", NULL);
}
// this is what the parent process will run
else {
//print output from shared memory
printf("\n*%s", shared_memory);
//detach shared memory
shmdt(shared_memory);
//Here we add the shared memory to the array
// To add together at the end
// but since I cant get the memory to share
// the array can't be implemented
//remove the shared memory segment
shmctl(segment_id, IPC_RMID, NULL);
wait(NULL);
}
} // End of for statement
|
The C stdout stream internally buffers data. It's likely that your "this is child" message is being buffered, and the buffer isn't being flushed by execlp, so it just disappears. Try a fflush(stdout); after the printf. Incidentally, you should do this before the fork() as well, so that child and parent don't both try to write output buffered from before the fork.
|
597,436
| 597,709
|
void* as unknown variable type
|
I'm currently working on a sprite engine in C++. I have an abstract class IEngine with a virtual function init_api. This takes in a void*.
// Initialise the engines' API
// api_params - void* to api parameters for initalisation
// hWnd - window handle
virtual bool init_api( void* api_params, HWND hWnd ) = 0;
I then have a DirectX implemented engine class CEngineDX. Which then casts api_params to a D3DPRESENT_PARAMETERS*, so it can be used for initialising DirectX.
// Cast api_params to a D3DPRESENT_PARAMETERS
D3DPRESENT_PARAMETERS* presentParams = NULL;
presentParams = reinterpret_cast< D3DPRESENT_PARAMETERS* >( api_params );
I'm quite happy with this setup but wanted to get some other programmers view on this "solution" if you like.
Cheers for the replies!
Carl
|
Another way to do it is just have a common header and different *.cpp files for each implementation. That way you can include just the D3D or just the OGL files in your project. IMO its better to choose the API at compile time so your not linking against both libraries.
As for the void*, I don't really like it. I think you'd be better off defining your own types and then mapping them to the API types with wrapper structs / classes and typedefs. You can forward declare these, and put the actual implementation in your *.cpp files.
One other benefit of this method is that your not paying for virtual functions you don't need, although I realize the cost of a virtual call is pretty small.
|
597,532
| 597,550
|
How do you structure your comparison functions?
|
I frequently encounter situations, especially with sorting in C++, where I am comparing a series of fields in order to compare a larger structure. A simplified example:
struct Car{
Manufacturer make;
ModelName model;
Year year;
};
bool carLessThanComparator( const Car & car1, const Car & car2 ){
if( car1.make < car2.make ){
return true;
}else if( car1.make == car2.make ){
if( car1.model < car2.model ){
return true;
}else if( car1.model == car2.model ){
if( car1.year < car2.year ){
return true;
}
}
}
return false;
}
My instinctive approach seems cumbersome, especially for more than 3 fields. How would you structure this series of comparisons in C++? Do other languages provide a more succinct or elegant syntax?
|
Well, if your function hits a return in the if clause, there's no need for an explicit else, since it would have already bailed out. That can save on the "indent valley":
bool carLessThanComparator( const Car & car1, const Car & car2 ) {
if( car1.make < car2.make )
return true;
if ( car1.make != car2.make )
return false;
if( car1.model < car2.model )
return true;
if( car1.model != car2.model )
return false;
if( car1.year < car2.year )
return true;
return false;
}
I like MarkusQ's LISPish short-circuiting approach as well.
|
597,813
| 597,820
|
How to print subscripts/superscripts on a CLI?
|
I'm writing a piece of code which deals with math variables and indices, and I'd need to print subscripts and superscripts on a CLI, is there a (possibly cross-platform) way to do that? I'm working in vanilla C++.
Note: I'd like this to be cross-platform, but since from the first answers this doesn't seem to be possible I'm working under MacOS and Ubuntu Linux (so bash).
Thank you
|
Since most CLIs are really only terminals (pretty dumb ones mostly but sometimes with color), the only cross-platform way I've ever done this is by allocating muliple physical lines per virtual line, such as:
2
f(x) = x + log x
2
It's not ideal but it's probably the best you're going to get without a GUI.
Following you extra information as to what platforms you're mainly interested in:
With Ubuntu at least, gnome-terminal runs in UTF-8 mode by default so the following code shows how to generate the superscripts and subscripts:
#include <stdio.h>
static char *super[] = {"\xe2\x81\xb0", "\xc2\xb9", "\xc2\xb2",
"\xc2\xb3", "\xe2\x81\xb4", "\xe2\x81\xb5", "\xe2\x81\xb6",
"\xe2\x81\xb7", "\xe2\x81\xb8", "\xe2\x81\xb9"};
static char *sub[] = {"\xe2\x82\x80", "\xe2\x82\x81", "\xe2\x82\x82",
"\xe2\x82\x83", "\xe2\x82\x84", "\xe2\x82\x85", "\xe2\x82\x86",
"\xe2\x82\x87", "\xe2\x82\x88", "\xe2\x82\x89"};
int main(void) {
int i;
printf ("f(x) = x%s + log%sx\n",super[2],sub[2]);
for (i = 0; i < 10; i++) {
printf ("x%s x%s ", super[i], sub[i]);
}
printf ("y%s%s%s z%s%s\n", super[9], super[9], super[9], sub[7], sub[5]);
return 0;
}
The super and sub char* arrays are the UTF-8 encodings for the Unicode code points for numeric superscripts and subscripts (see here). The given program will output my formula from above (on one line instead of three), then another test line for all the choices and a y-super-999 and z-sub-75 so you can see what they look like.
MacOS doesn't appear to use gnome-terminal as a terminal program but references here and here seem to indicate the standard terminal understands UTF-8 (or you could download and install gnome-terminal as a last resort).
|
597,857
| 597,859
|
Is friendship inherited in C++?
|
Suppose I have a Base class:
class Base {
friend SomeOtherClass;
};
And there is another (different) class that inherits from Base:
class AnotherClass : public Base {}
Is friendship inherited as well?
|
In principle, a derived class inherits every member of a base class except:
* its constructor and its destructor
* its operator=() members
* its friends
So, no. Friends are not inherited.
|
598,036
| 598,038
|
How do I implement operator[] for dynamic array?
|
I need to implement a dynamic array by myself to use it in a simple memory manager.
struct Block {
int* offset;
bool used;
int size;
Block(int* off=NULL, bool isUsed=false, int sz=0): offset(off), used(isUsed), size(sz) {}
Block(const Block& b): offset(b.offset), used(b.used), size(b.size) {}
};
class BlockList {
Block* first;
int size;
public:
BlockList(): first(NULL), size(0) {}
void PushBack(const Block&);
void DeleteBack();
void PushMiddle(int, const Block&);
void DeleteMiddle(int);
int Size() const { return size; }
void show();
Block& operator[](int);
Block* GetElem(int);
void SetElem(int, const Block&);
~BlockList();
};
I need to overload operator[].
Block& BlockList::operator\[\](int index) {
try {
if (index >= size)
throw out_of_range("index out of range");
else
return (first[sizeof(Block)*index]);
}
catch(exception& e) {
cerr << e.what() << endl;
}
}
void BlockList::PushBack(const Block& b) {
if(!size)
first = new Block(b);
else {
Block* temp = new Block[size + 1];
int i = 0;
for (i = 0; i < size; i++)
temp[sizeof(Block)*i] = this->operator[](i);
delete []first;
temp += sizeof(Block);
temp->offset = b.offset;
temp->size = b.size;
temp->used = b.used;
first = temp;
}
size++;
}
When I use PushBack to push the first element, it works OK, but when it comes to the second, third, ..., the program didn't crash, but it just shows results I didn`t expect to see.
Here is how I get the contents of my array:
void BlockList::show() {
for (int i = 0; i < size; i++) {
Block current(operator[](i));
cout << "off: " << current.offset << " size: " << current.size << endl;
}
}
|
first is a Block pointer so you only need to pass in index.
Block* first;
...
first[0] //returns the first element
first[1] //returns the second element
In your example you are passing in too high of an index value when indexing first because you're using sizeof inside.
Corrected code:
Block& BlockList::operator[](int index) {
try {
if (index >= size)
throw out_of_range("index out of range");
else
return (first[index]);//<--- fix was here
}
catch(exception& e) {
cerr << e.what() << endl;
}
}
|
598,143
| 606,900
|
Explain about linkages(external/internal) in c++?
|
Explain about linkages(external/internal) in c++?
How does linkage differ for a function,constant,inline function,template function ,class and template class
|
http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=41
check section 3.5 in standard http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf
|
598,148
| 598,150
|
Is it legal to use the increment operator in a C++ function call?
|
There's been some debate going on in this question about whether the following code is legal C++:
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive)
{
items.erase(i++); // *** Is this undefined behavior? ***
}
else
{
other_code_involving(*i);
++i;
}
}
The problem here is that erase() will invalidate the iterator in question. If that happens before i++ is evaluated, then incrementing i like that is technically undefined behavior, even if it appears to work with a particular compiler. One side of the debate says that all function arguments are fully evaluated before the function is called. The other side says, "the only guarantees are that i++ will happen before the next statement and after i++ is used. Whether that is before erase(i++) is invoked or afterwards is compiler dependent."
I opened this question to hopefully settle that debate.
|
Quoth the C++ standard 1.9.16:
When calling a function (whether or
not the function is inline), every
value computation and side effect
associated with any argument
expression, or with the postfix
expression designating the called
function, is sequenced before
execution of every expression or
statement in the body of the called
function. (Note: Value computations
and side effects associated with the
different argument expressions are
unsequenced.)
So it would seem to me that this code:
foo(i++);
is perfectly legal. It will increment i and then call foo with the previous value of i. However, this code:
foo(i++, i++);
yields undefined behavior because paragraph 1.9.16 also says:
If a side effect on a scalar object is
unsequenced relative to either another
side effect on the same scalar object
or a value computation using the value
of the same scalar object, the
behavior is undefined.
|
598,175
| 598,176
|
How do I call a object's member function as a unary_function for std algorithms?
|
I have a class that looks like this.
class A
{
public:
void doSomething();
}
I have an array of these classes. I want to call doSomething() on each item in the array. What's the easiest way to do this using the algorithms header?
|
Use std::mem_fun_ref to wrap the member function as a unary function.
#include <algoritm>
#include <functional>
std::vector<A> the_vector;
...
std::for_each(the_vector.begin(), the_vector.end(),
std::mem_fun_ref(&A::doSomething));
You can also use std::mem_fun if your vector contains pointers to the class, rather than the objects themselves.
std::vector<A*> the_vector;
...
std::for_each(the_vector.begin(), the_vector.end(),
std::mem_fun(&A::doSomething));
|
598,471
| 598,808
|
Weird vertexshader/pixelshader glitch
|
i've got a little problem with my water effect
as you can see here, it doesn't show up the right way.
another screen with a diffrent texture applied shows the error in the transform something more clearly
my HLSL code:
V2P vs(float4 inPos : POSITION, float2 inTex: TEXCOORD)
{
V2P Output = (V2P)0;
float4x4 viewproj = mul (matView, matProjection);
float4x4 worldviewproj = mul (matWorld,viewproj);
float4x4 reflviewproj = mul (matRLView, matProjection);
float4x4 reflworldviewproj = mul (matWorld, reflviewproj);
Output.Position = mul(inPos, worldviewproj);
Output.RLMapTex = mul(inPos, reflworldviewproj);
return Output;
}
P2F ps(V2P PSIn)
{
P2F Output = (P2F)0;
float2 ProjectedTexCoords;
ProjectedTexCoords.x = PSIn.RLMapTex.x / PSIn.RLMapTex.w /2.0f + 0.5f;
ProjectedTexCoords.y = -PSIn.RLMapTex.y / PSIn.RLMapTex.w /2.0f + 0.5f;
float2 ProjectedRefCoords;
ProjectedRefCoords.x = ( PSIn.Position.x / PSIn.Position.w) /2.0f + 0.5f;
ProjectedRefCoords.y = (-PSIn.Position.y / PSIn.Position.w) /2.0f + 0.5f;
Output.Color = tex2D(samRLMap, ProjectedTexCoords);
return Output;
}
the reflection map is rendered on a render target while flipping the y value of the eye along the waterheight. (and with up vector 0,-1,0)
so, my question: what could be the cuase of this?
|
I guess i found it, the matrix i used for the reflected view, is wrong.
When i use the standard view, it works fine
|
598,552
| 598,555
|
Should I learn C before learning C++?
|
I visited a university CS department open day today and in the labs tour we sat down to play with a couple of final-year projects from undergraduate students. One was particularly good - a sort of FPS asteroids game. I decided to take a peek in the src directory to find it was done in C++ (most of the other projects were Java 3D apps).
I haven't done any C before but I have looked through some C code before. From what I saw in the .cpp code in this game it didn't look very different.
I'm interested in learning either C or C++ but will probably learn the other later on. Is there any advantage to me learning one before the other and if so, which one?
|
There is no need to learn C before learning C++.
They are different languages. It is a common misconception that C++ is in some way dependent on C and not a fully specified language on its own.
Just because C++ shares a lot of the same syntax and a lot of the same semantics, does not mean you need to learn C first.
If you learn C++ you will eventually learn most of C with some differences between the languages that you will learn over time. In fact its a very hard thing to write proper C++ because intermediate C++ programmers tend to write C/C++.That is true whether or not you started with C or started with C++.
If you know C first, then that is good plus to learning C++. You will start with knowing a chunk of the language. If you do not know C first then there is no point focusing on a different language. There are plenty of good books and tutorials available that start you from knowing nothing and will cover anything you would learn from C which applies to C++ as well.
Please see further reasoning in this answer.
|
598,584
| 599,053
|
Memory modifying in C++
|
im trying to learn to modify games in C++ not the game just the memory its using to get ammo whatnot so can someone point me to books
|
The most convenient way to manipulate a remote process' memory is to create a thread within the context of that program. This is usually accomplished by forcibly injecting a dll into the target process. Once you have code executing inside the target application you are free to use standard memory routines. e.g (memcpy, malloc, memset).
I can tell you right now that the most convenient and easy to implement method is the CreateRemoteThread / LoadLibrary trick.
As other people have mentioned, simple hacks can be performed by scanning memory for known values. But if you want to perform anything more advanced you will need to look into debugging and dead-list analysis. (Tools: ollydbg and IDA pro, respectively).
You have scratched the surface of a very expansive hacking topic, there is a wealth of knowledge out there..
First a few internet resources:
gamedeception.net - A community dedicated to game RE (Reverse Engineering) and hacking.
http://www.edgeofnowhere.cc/viewtopic.php?p=2483118 - An excellent tutorial on various DLL injection methods.
Openrce.org - Community for reverse code engineering.
I can also recommend a book to you - http://www.exploitingonlinegames.com/
Windows API Routines you should research (msdn.com):
CreateRemoteThread
LoadLibraryA
VirtualAllocEx
VirtualProtectEx
WriteProcessMemory
ReadProcessMemory
CreateToolhelp32Snapshot
Process32First
Process32Next
|
598,913
| 599,050
|
Most important things about C++ templates… lesson learned
|
What are most important things you know about templates: hidden features, common mistakes, best and most useful practices, tips...common mistakes/oversight/assumptions
I am starting to implement most of my library/API using templates and would like to collect most common patterns, tips, etc., found in practice.
Let me formalize the question: What is the most important thing you've learned about templates?
Please try to provide examples -- it would be easier to understand, as opposed to convoluted and overly dry descriptions
Thanks
|
From "Exceptional C++ style", Item 7: function overload resolution happens before templates specialization. Do not mix overloaded function and specializations of template functions, or you are in for a nasty surprise at which function actually gets called.
template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f<int*>(int *t) { ... } // (c)
...
int *pi; f(pi); // (b) is called, not (c)!
On top of Item 7:
Worse yet, if you omit the type in template specialization, a different function template might get specialized depending on the order of definition and as a result a specialized function may or may not be called.
Case 1:
template<class T> void f(T t) { ... } // (a)
template<class T> void f(T *t) { ... } // (b)
template<> void f(int *t) { ... } // (c) - specializes (b)
...
int *pi; f(pi); // (c) is called
Case 2:
template<class T> void f(T t) { ... } // (a)
template<> void f(int *t) { ... } // (c) - specializes (a)
template<class T> void f(T *t) { ... } // (b)
...
int *pi; f(pi); // (b) is called
|
598,939
| 598,989
|
Why do I get E_NOINTERFACE when creating an object that supports that interface?
|
Note:
Using CoGetClassObject, to create multiple objects through a class object for which there is a CLSID in the system registry
Single threaded apartment
For instance:
hresult = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED);
IClassFactory *pIClassFactory;
hresult = CoGetClassObject (clsid, CLSCTX_LOCAL_SERVER, NULL, IID_IClassFactory, (LPVOID *)&pIClassFactory);
hresult = pIClassFactory->QueryInterface (IID_IUnknown, (LPVOID *)&pUnk);
hresult = pUnk->QueryInterface (__uuidof(IExample), (LPVOID *)&pISimClass);
Note:
E_NOINTERFACE is returned
*ppvObject is set to NULL
Question:
How can I confirm, that it is indeed registered - if this is the problem?
|
The problem here is that you are confusing the class object and the object itself. CoGetClassObject will give you a pointer to an object that implements IClassFactory and intended to create an instance of the object you are interested in. It is not an actual instance of that object.
In your example, you are getting an IUnknown pointer by calling QueryInterface on the IClassFactory pointer. This pointer still points to the instance of the class object, hence doing QueryInterface for the interface you are interested in results in an error. Instead you need to call IClassFactory::Createinstance to get the IUnknown pointer to the actual object and do the QueryInterface on that pointer.
|
598,948
| 598,970
|
Creating a project, from Makefile to static/dynamic libraries in UNIX
|
Guys, would you describe a few things about c++ building blocks, on unix.
I want to create an application that links against static libs and dynamic libs (.so).
Question 1: How do I create static library using gcc/g++ ?How do I make my app link against it.
Question 2: How to specify it in the makefile, linking against static and dynamic libs, assuming that both libraries have header files
Summary: I have been using makefiles and libraries for years, written by someone else. Thus every time I modified it, I simply cut-and-pasted things around, without really understanding it. Now I want to get down to the ground and understand the building/linking/Creating Makfile process in-depth.
What is a good book describing these concepts in intimate details?
Thanks
|
Static libraries are usually archived with the ar command. Once you build all of the object files (preferably with the -fPIC switch on GCC), you can run ar like so:
ar -rs archivename.a list.o of.o objects.o
The man page describes the options.
Dynamic libraries are built usually with the -shared switch to gcc or ld and the output file name with a .so extension.
Autotools handles this with the libtool program. I'm not familiar with its use.
Linking against these libraries can be done either by listing the libraries with the -l (ell) switch (such as -lX to link to libX.so) or by specifying them directly with absolute paths (such as adding /usr/lib/libX.so to your command). Static libraries are linked by specifying -static before -l or the appropriate absolute path to the .a archive.
|
599,120
| 599,691
|
How do you translate this code from Processing to C++?
|
I wrote this code in Processing (www.processing.org) and was wondering how would one implement it using C++?
int i = 0;
void setup()
{
size(1000,1000);
}
void draw()
{
// frameRate(120);
PImage slice = get();
set(0,20,slice);
if( i % 2 == 0 ) fill(128); else fill(0);
i++;
rect(0,0,width,20);
}
As you can see this simply scrolls down rectangles of alternating colors as fast as possible. Can the C++ implementation be as short? OpenGL?
|
You could also take a look at OpenFrameworks but I doubt that any C++ library will give you such a short implementation.
|
599,264
| 599,274
|
Is there a way to split one texture into an array of them using SOIL in C++?
|
I'm using SOIL in my project, and I need to take in a single texture, and than convert it into an array of textures using different parts of the first texture. (To use a sprite sheet).
I'm using SDL and OpenGL by the way.
|
The typical way to use sprite sheeting with a modern 3D api like OpenGL is to use texture coordinates to address different parts of your individual texture. While you can split it up it is much more resource friendly to use texture coordinates.
For example, if you had a simple sprite sheet with 3 frames horizontally, each 32 pixels by 32 pixels (for a total size of 96x32), you would use the following code to draw the 3rd frame:
// I assume you have bound your source texture
// This is the U coordinate's origin in texture space
float xStart = 64.0f / 96.0f;
// This is one frame width in texture space
float xIncrement = 32.0f / 96.0f;
glBegin(GL_QUADS);
glTexCoord2f(xStart, 0);
glVertex2f(-16.0f, 16.0f);
glTexCoord2f(xStart, 1.0f);
glVertex2f(-16.0f, -16.0f);
glTexCoord2f(xStart + xIncrement, 0);
glVertex2f(16.0f, 16.0f);
glTexCoord2f(xStart + xIncrement, 1.0f);
glVertex2f(16.0f, -16.0f);
glEnd();
|
599,308
| 599,327
|
Proper stack and heap usage in C++?
|
I've been programming for a while but It's been mostly Java and C#. I've never actually had to manage memory on my own. I recently began programming in C++ and I'm a little confused as to when I should store things on the stack and when to store them on the heap.
My understanding is that variables which are accessed very frequently should be stored on the stack and objects, rarely used variables, and large data structures should all be stored on the heap. Is this correct or am I incorrect?
|
No, the difference between stack and heap isn't performance. It's lifespan: any local variable inside a function (anything you do not malloc() or new) lives on the stack. It goes away when you return from the function. If you want something to live longer than the function that declared it, you must allocate it on the heap.
class Thingy;
Thingy* foo( )
{
int a; // this int lives on the stack
Thingy B; // this thingy lives on the stack and will be deleted when we return from foo
Thingy *pointerToB = &B; // this points to an address on the stack
Thingy *pointerToC = new Thingy(); // this makes a Thingy on the heap.
// pointerToC contains its address.
// this is safe: C lives on the heap and outlives foo().
// Whoever you pass this to must remember to delete it!
return pointerToC;
// this is NOT SAFE: B lives on the stack and will be deleted when foo() returns.
// whoever uses this returned pointer will probably cause a crash!
return pointerToB;
}
For a clearer understanding of what the stack is, come at it from the other end -- rather than try to understand what the stack does in terms of a high level language, look up "call stack" and "calling convention" and see what the machine really does when you call a function. Computer memory is just a series of addresses; "heap" and "stack" are inventions of the compiler.
|
599,321
| 599,353
|
How to get system time in C++?
|
In fact i am trying to calculate the time a function takes to complete in my program.
So i am using the logic to get system time when i call the function and time when the function returns a value then by subtracting the values i get time it took to complete.
So if anyone can tell me some better approach or just how to get system time at an instance it would be quite a help
|
Your question is totally dependant on WHICH system you are using. Each system has its own functions for getting the current time. For finding out how long the system has been running, you'd want to access one of the "high resolution performance counters". If you don't use a performance counter, you are usually limited to microsecond accuracy (or worse) which is almost useless in profiling the speed of a function.
In Windows, you can access the counter via the 'QueryPerformanceCounter()' function. This returns an arbitrary number that is different on each processor. To find out how many ticks in the counter == 1 second, call 'QueryPerformanceFrequency()'.
If you're coding under a platform other than windows, just google performance counter and the system you are coding under, and it should tell you how you can access the counter.
Edit (clarification)
This is c++, just include windows.h and import the "Kernel32.lib" (seems to have removed my hyperlink, check out the documentation at: http://msdn.microsoft.com/en-us/library/ms644904.aspx). For C#, you can use the "System.Diagnostics.PerformanceCounter" class.
|
599,335
| 599,403
|
Linker errors with private members of class in header file
|
I'm trying to build a project in Visual Studio 2008. I'm getting a bunch of linker errors that are really bothering me. My application is a Win32 console application using only native ANSI C++.
They are all linker errors of the same pattern.
Linker errors are related to every single private static data member of classes I have defined in my own header files.
I'm guessing this is probably a simple fact of c++ I'm not already aware of?
Example:
I refer to the members of SingleDelay within function definitions of SingleDelay's member classes in a file Delays.cpp.
ie:
SingleDelay::tick(void *output, void *input, int nbufferFrames)<br>{
//.. code here<br>
x = dry * castInput + wet * castInput;<br>
}
Error 38 error LNK2001: unresolved external symbol "private: static double SingleDelay::dry" (?dry@SingleDelay@@0NA) Delays.obj testall
Definition of SingleDelay in Delays.h:
class SingleDelay{
private:
static double dry; //% of dry signal<br>
static double wet; //% of wet signal<br>
static unsigned int delay; //Delay in milliseconds<br>
static int delayCell; //Index in the delayBuffer of the delay to add<br>
static double *delayBuffer; //Delay buffer is 1 second long at sample rate SAMPLE_RATE<br>
static unsigned int bufferCell; //Pointer to the current delay buffer cell<br>
public:
//Tick function
static void tick(void *output, void *input,int nBufferFrames);
//Set and Get functions
static void setSingleDelay(double tDry, double tWet, unsigned int tDelay);
static void setSingleDelay(void);
static void setDry(double tDry);
static void setWet(double tWet);
static void setDelay(unsigned int tDelay);
static double getDry(){ return dry;}
static double getWet(){ return wet;}
static unsigned int getDelay(){ return delay;}
static void initializeDelayBuffer(){
destroyDelayBuffer();
delayBuffer = new double[bufferLength];
}
static void destroyDelayBuffer(){
delete[ ] delayBuffer;
}
};
|
Maybe you haven't added the library and include paths of the library you use to the project definitions?
C++ error are always fun to look at. Or not. In any case, do you initialize your static variables anywhere? You need to do this in a .cpp file somewhere. And remember to use static variables with care. They are actually global variables in disguise, and can make future changes, such as multi-threading, more difficult.
|
599,640
| 599,649
|
static member variable of a subclassed class
|
Is it OK to have a static member variable defined in a base class, and having several derived classes each using its own instance of this member variable?
The following code compiles successfully, and prints the right output, but I am still not sure that doing something like that is a good practice. In the following example, how can it work, if I explicitly define only one instance of s (by calling: string A::s;) but I actually use 2 instances?
class A
{
protected:
void SetS(string new_s){s = new_s;}
void PrintS(){cout << s << endl;};
private:
static string s;
};
class B : public A
{
public:
void foo(){ SetS("bbb"); PrintS();};
};
class C : public A
{
public:
void foo(){ SetS("ccc"); PrintS();};
};
string A::s;
int main()
{
B b;
b.foo(); // results in output: bbb
C c;
c.foo(); // results in output: ccc
b.foo(); // results in output: bbb
}
|
A very odd use of inheritance indeed. The base class is supposed to define interfaces ideally and contain as little or no state at all if possible according to good OO design principle.
This works because your foo() resets the value of A::s everytime it is called. Try printing the address of A::s. There is one and only one object. This will not work if you don't set the value everytime and you have multiple objects using another member function bar() to read the value of A::s.
You may run into sync issues if B and C objects are created in separate threads as well. You will end up with UB.
|
599,664
| 599,723
|
Statically initializing a structure with arrays of varying length
|
I've got a static map of identifier<=>struct pairs, and each struct should contain some arrays. Everything is known at compile time. That is, I want to have something like this here:
ID1 => name: someString
flagCount: 3
flags: [1, 5, 10]
statically created (if possible). Of course, a declaration like:
struct Info
{
const char* name;
int flagCount;
int flags[];
};
would be ideal, as long as I could initialize it like ...
Info infos [] = { ... };
which is not possible, due to the varying length arrays (except I'm missing something). Alternatively, I though about (ab)using boost::assign for this, but I'm wondering if there is a recommended solution to this. I'm fine if I can store only the info structures into an array, and to the mapping elsewhere.
Edit: A note on the current solution. At the moment, I have:
struct Info
{
Info (const std::vector<int>& flags) : flags {}
std::vector<int> flags;
};
and I use:
const std::map<ID, Info> map = boost::assign::map_list_of
("ID1", Info (boost::assign::list_of (1)(2)(3));
which works, I'm just curious whether there is a simpler solution (template-based?).
|
The elements in an array must be the same size as each other, otherwise you can't use infos[i] to access them - the compiler would have to step through the array and look at the size of each element up to i to find where the next one started. You can allocate enough memory for each element contiguously, and then create an array of pointers to the elements (pointers being a fixed size). If you only need the mapping and not to index the infos then your map will be identifier to pointer.
Alternatively, as you know the size at compile time, if there are only a few flags, make the Info::flags array large enough for the maximum flags, or make it a pointer to an array of flags, so that Info is a fixed size struct.
|
599,744
| 599,748
|
What does the three dots in the parameter list of a function mean?
|
I came across a function definition like:
char* abc(char *f, ...)
{
}
What do the three dots mean?
|
These type of functions are called variadic functions (Wikipedia link). They use ellipses (i.e., three dots) to indicate that there is a variable number of arguments that the function can process. One place you've probably used such functions (perhaps without realising) is with the various printf functions, for example (from the ISO standard):
int printf(const char * restrict format, ...);
The ellipses allow you to create functions where the number of parameters are not known beforehand, and you can use stdargs.h functions (va_start, va_arg and va_end) to get the specific arguments.
You do have to know the types of the arguments you extract and have some way of deciding when you're done. The printf functions do this with the format string (for both types and count), while my example code below always assumes const char * as the type with a sentinel value NULL to decide completion.
This link here has a good treatise on the use of variable argument lists in printf.
As an example, the following program contains a function outStrings(), that allows you to print an arbitrary number of strings:
#include <stdio.h>
#include <stdarg.h>
void outStrings(const char *strFirst, ...) {
// First argument handled specially.
printf("%s", strFirst);
va_list pArg;
va_start(pArg, strFirst);
// Just get and process each string until NULL given.
const char *strNext = va_arg(pArg, const char *);
while (strNext != NULL) {
printf("%s", strNext);
strNext = va_arg(pArg, const char *);
}
// Finalise processing.
va_end(pArg);
}
int main(void) {
char *name = "paxdiablo";
outStrings("Hello, ", name, ", I hope you're feeling well today.\n", NULL);
}
|
599,769
| 600,094
|
How to find what objects a given CLSID supports
|
Question:
Based on a CLSID, how can I find out what objects (or interfaces) it supports for IClassFactory::CreateInstance
Note:
Currently using CLSIDFromProgID to obtain CLSID
|
You could use OleView.
But if you want to do this programatically then you could use the method that OleView uses.
OleView achieves this by just iterating through all the interfaces declared in HKEY_CLASSES_ROOT\Interface and then calling QueryInterface for each of them.
|
599,996
| 600,010
|
C++ FILE readInt function? (from a binary file)
|
Is there a function for FILE (fopen?) that allows me to just read one int from a binary file?
So far I'm trying this, but I'm getting some kind of error I can't see cause the program just crashes without telling me.
void opentest()
{
FILE *fp = fopen("dqmapt.mp", "r");
int i = 0;
int j = 0;
int k = 0;
int * buffer;
if (fp)
{
buffer = (int *) (sizeof(int));
i = (int) fread(buffer,1, (sizeof(int)), fp);
fscanf(fp, "%d", &j);
fclose(fp);
}
printf("%d\n", i);
printf("%d\n", j);
}
|
Now that you have changed your question, let me ask one. What is the format of the file you are trying to read?
For a binary file there are some changes required how you open the file:
/* C way */
FILE *fp = fopen("text.bin", "rb"); /* note the b; this is a compound mode */
/* C++ way */
std::ifstream ifs("test.txt", ios::in | ios::binary);
Reading in the contents is easy. But remember, your file has 2 integers at the begining -- width, height which determine how many more to read i.e. another width * height number of integers. So, your best bet is to read the first two integers first. You will need to use two buffers -- one for the width and height and then depending on their value another one to read the rest of the file. So, lets read in the first two integers:
char buf[ 2 * sizeof(int) ]; /* will store width and height */
Read in the two integers:
/* C way */
fread(buf, sizeof(int), 2, fp); /* the syntax changes, FILE pointer is last */
/* C++ way*/
ifs.read(buf, sizeof buf);
Now, the tricky part. You have to convert the stuff to double. This again depends on your system endianness -- whether a simple assignment works or whether a byte swapping is necessary. As another poster has pointed out WriteInt() writes integers in big-endian format. Figure out what system you are on. And then you can proceed further.
FILE is a C datastructure. It is included in C++ for C compatibility. You can do this:
/* The C way */
#include <stdio.h>
#include <stdlib.h>
int main(void) {
FILE *fp = fopen("test.txt", "r");
int i = 0;
if (fp) {
fscanf(fp, "%d", &i);
fclose(fp);
}
printf("%d\n", i);
}
You can use the std::ifstream thing to open a file for reading. You have to read in the contents using some other incantation to read the file contents and extract the desired information out of it yourself.
/* The C++ way */
#include <fstream>
#include <iostream>
int main() {
std::ifstream ifs("test.txt");
int i = 0;
if (ifs.good()) {
ifs >> i;
}
std::cout << i << std::endl;
}
Note you can use the C style functions in C++ as well, though this is the least recommended way:
/* The C way in C++ */
#include <cstdio>
#include <cstdlib>
int main() {
using namespace std;
FILE *fp = fopen("test.txt", "r");
int i = 0;
if (fp) {
fscanf(fp, "%d", &i);
fclose(fp);
}
printf("%d\n", i);
}
[Note: Both examples assume you have a text file to read from]
|
600,175
| 600,265
|
C++ "smart" predicate for stl algorithm
|
I need to designe predicate for stl algorithms such as find_if, count_if.
namespace lib
{
struct Finder
{
Finder( const std::string& name ):
name_( name )
{
}
template< typename TElement >
bool operator( const TElement& element )
{
return element.isPresent( name_ );
}
/* template< typename TElement >
bool operator( const TElement& element )
{
const Data& data = element.getData();
return data.isPresent( name_ );
}*/
};
}
But I need it to have different operators () according to presence of some certain methods in TElement. Like if it has "getData" I'd like to check that data and if it hasn't I'd do some other actions.
I am aware of SFINAE. But I don't have boost:: on the project.
So either there is some easy implementation of template "has_method" or you know some other design solution.
I can't point specific types and simply overload because I'd like to put this Predicate to the one of the project library, which don't know about those specific classes with "getData" method.
Solution with class traits are good as far as there is no namespaces. Predicate Finder in in "lib" namespace and class with "getData" is in "program" namespace.
Thanks.
|
Why use template mathods at all? Just use the specific class that you want to base it on or a common base classes if there are lots of class types.
e.g.
struct Finder
{
Finder( const std::string& name ):
name_( name )
{
}
bool operator( const IsPresentBaseClass& element )
{
return element.isPresent( name_ );
}
bool operator( const GetDataBaseClass& element )
{
const Data& data = element.getData();
return data.isPresent( name_ );
}
};
If this pattern happens a lot with different class types and you know the types before using the predicate you could template the predicate itself.
e.g.
template<class T1, class T2>
struct Finder
{
Finder( const std::string& name ):
name_( name )
{
}
bool operator( const T1& element )
{
return element.isPresent( name_ );
}
bool operator( const T2& element )
{
const Data& data = element.getData();
return data.isPresent( name_ );
}
};
Or another approach you could use is to use some sort of class traits to hold the information.
e.g.
struct UseIsPresent
{
template<class T>
static bool CompareElement( const T& element, const std::string& name )
{
return element.isPresent( name );
}
};
struct UseGetData
{
template<class T>
static bool CompareElement( const T& element, const std::string& name )
{
const Data& data = element.getData();
return data.isPresent( name );
}
};
// default to using the isPresent method
template <class T>
struct FinderTraits
{
typedef UseIsPresent FinderMethodType;
};
// either list the classes that use GetData method
// or use a common base class type, e.g. UseGetData
template <>
struct FinderTraits<UseGetData>
{
typedef UseGetData FinderMethodType;
};
struct Finder
{
Finder( const std::string& name )
: name_( name )
{
}
template<class T>
bool operator()( const T& element )
{
return FinderTraits<T>::FinderMethodType::CompareElement<T>(element, name_);
}
std::string name_;
};
The downsides of all these methods is that at some point you need to know the types to be able to split them up into which method to use.
|
600,228
| 600,632
|
Creating/Opening Events in C++ and checking if they are fired
|
I have two threads that use an event for synchronization.
In each thread they use the same call:
::CreateEvent( NULL,TRUE,FALSE,tcEventName )
The producer thread is the one that makes the call first, while the consumer thread makes the call last, so it's technically opening, not creating the event... I assume.
But, when SetEvent is called in the producer thread, the same event never gets triggered in the consumer thread (I'm using WaitForMultipleObjects())
Is there a tool that can tell me if the event is actually getting triggered properly.
Also, when I call CreateEvent() in each thread, the returned handle value is different for each... should they be the same?
Is there a better way to do this that will ensure it will work?
This is on Windows XP using Visual Studio 2005
Edit: I did some more checking and found that calling CreateEvent in the producer thread (the second one to call CreateEvent) sets LastError to 183 (ERROR_ALREADY_EXISTS),
however CreateEvent still returns a handle to the event...what gives? How can it error as already existing but still return a handle? Or is it supposed to do that?
|
According to the MSDN documentation for CreateEvent,
If the function succeeds, the return value is a handle to the event object. If the named event object existed before the function call, the function returns a handle to the existing object and GetLastError returns ERROR_ALREADY_EXISTS.
Based on your description, I don't see a problem with what you're doing. There's nothing I see to indicate you're doing something incorrectly. For me, though, I usually create the event once using CreateEvent() and then pass the handle to the thread(s) that I want to be signaled by that event. But there is nothing technically wrong with your approach.
You do realize that WaitForMultipleObjects() returns the index of the first signaled handle in the handles array, right? For example, if your named event is the second one in the list, but the first handle is signaled the vast majority of the time (e.g., by a fast-acting thread or a manual reset event that is signaled but never reset), WaitForMultipleObjects() will always return WAIT_OBJECT_0. In other words, your consumer thread will never see the fact that your named event is signaled because the first handle is "always" signaled. If this is the case, put your named event first in the list.
You don't happen to have the bWaitAll parameter to WaitForMultipleObjects() set to TRUE, do you? If you do, then all of the handles in the handles array have be signaled before the function returns.
Who calls ResetEvent() for your named event? It should be the consumer. It's not accidentally being called by some third-party thread, is it?
These are simply some things to double-check. If the event still doesn't behave as you expect, replace the WaitForMultipleObjects() with WaitForSingleObject() to see if your named event properly signals the consumer thread.
Hope this helps.
|
600,400
| 600,541
|
Database Structure & Hard drive seek time confusion
|
could some one help me out trying to understand how hard drive seeking works.
I have a small binary database file which read performance is absolutely essential. If I need to skip a few bytes in the file is it quicker to use seek() or to read() then discard the unwanted data.
If the average seek time of a hard drive is 10ms and the read speed is 300MB/s I calculated that it's quicker to read() than seek() with a value smaller than 3MB. Is true? Is there an overhead when performing a new seek, which reading an existing stream doesn't have?
Which do you think be a more suitable file structure for an index.
Entry1:Value:PointerIntoToData
Entry2:Value:PointerIntoToData
Entry3:Value:PointerIntoToData
Data, Data, Data
Or
Entry1:Value:Data
Entry2:Value:Data
Entry3:Value:Data
When reading an entry if the value is not correct it will be ignored. So when streaming the file is it quicker to:
1. when an entry is not required use seek() to skip over it
2. when a entry is not needed read it then discard the data
3. or the use first structure, when an entry is required seek() into a data repository at the end.
Entry is 4 bytes, value is 8 bytes & data is 12KB
Cheers
|
All seek system call does is changing a position in file where the next read will be. It does not move the drive head. Drive heads move when data is read or written and you don't have direct control over what OS will do next.
Reading lots of data you aren't going to need has impact because all read data needs space in OS buffers and causes older data to be discarded. So using seek over big files will mess with filesystem cache less.
All I write beneath assumes you cannot fit whole database in memory. If you can, just do that. Read everything and try to append new and changed data at the end of file. Don't worry about wasted space, just do some compacting once in a while.
If your database is too big:
Data is read and written to physical drive in blocks (or pages). Similarly the basic unit of disk IO in your OS is page. If OS caches data from disk it's also in whole pages. So thinking whether you need to move forward few bytes using seek or read makes little sense. If you want to make it fast, you need to take into account how disk IO really works.
First, already mentioned by nobugz, locality of reference. If the data you use in each operation is located close together in a file, your OS will need to read or write less pages. On the other hand, if you spread your data, many pages will need to be read or written at once, which will always be slow.
As to data structure for index. Typically they are organized as B-trees. It's a data structure made especially for effective searching of large quantities of data stored in memory with paged reads and writes.
And both strategies for organizing data is used in practice. For example, MS SQL Server by default stores data the first way: data is stored separately and indices only contain data from indexed columns and physical addresses of data rows in files. But if you define clustered index then all data will be stored within this index. All other indexes will point to the data via clustered index key instead of physical address. The first way is simpler but the other may be much more effective if you often do scans of ranges of data based on clustered index.
|
600,502
| 600,510
|
Will the C/C++ compiler optimize this if statement?
|
I have code like this, and I find it a bit hard to read:
// code1
if( (expensiveOperation1() && otherOperation() && foo())
|| (expensiveOperation2() && bar() && baz()) {
// do something
}
I just changed it to the following, to make it more readable:
// code2
const bool expr1 = expensiveOperation1() && otherOperation() && foo();
const bool expr2 = expensiveOperation2() && bar() && baz();
if(expr1 || expr2){
// one of the conditions met
}
But should I now be concerned about efficiency?
I mean, in code1, if the first conjunctive clause is fulfilled then it won't even bother to look at the second one because it's already clear that the statement will be true.
But in my more readable example, both cond1 and cond2 have to be computed. Or will the compiler be smart enough to change my code2 into code1 if expr2 is not used anywhere else?
|
I would say it shouldn't, since they're not logically equivalent if any of the functions have side-effects.
The following would be equivalent however, and it'd have the advantage allowing you to give descriptive names to the test functions, making the code more self-documenting:
// code3
inline bool combinedOp1()
{
return expensiveOperation1() && otherOperation() && foo();
}
inline bool combinedOp2()
{
return expensiveOperation2() && bar() && baz();
}
And then call it as follows:
if (combinedOp1() || combinedOp2())
{
// do something
}
|
600,519
| 600,560
|
vector resizing - portable way to detect
|
I have a vector that I am loading with a know amount of elements (N).
The processing dynamically creates new elements, which are appended to the vector.
I am expecting about 2 * N additional elements to be created,
so I resize the vector to 3 * N.
If the additional elements exceed that, I would like a program abort, rather than a dynamic expansion of the vector.
Is there a way to detect that, that is portable between AIX/TRU64/Linux?
|
Detect what? Whether the vector will be resized? Whether it has been?
The only real way to achieve this is to provide checking functionality either in a custom allocator or a function that adds elements to the vector.
e.g
template<class T>
void add_element(std::vector<T>& container, T const& v)
{
if (container.capacity()+1 >= 3*N)
{
// terminate/exception/whatever
}
container.push_back(v);
}
|
600,912
| 600,927
|
Pointer mysteriously resetting to NULL
|
I'm working on a game and I'm currently working on the part that handles input. Three classes are involved here, there's the ProjectInstance class which starts the level and stuff, there's a GameController which will handle the input, and a PlayerEntity which will be influenced by the controls as determined by the GameController. Upon starting the level the ProjectInstance creates the GameController, and it will call its EvaluateControls method in the Step method, which is called inside the game loop. The EvaluateControls method looks a bit like this:
void CGameController::EvaluateControls(CInputBindings *pib) {
// if no player yet
if (gc_ppePlayer == NULL) {
// create it
Handle<CPlayerEntityProperties> hep = memNew(CPlayerEntityProperties);
gc_ppePlayer = (CPlayerEntity *)hep->SpawnEntity();
memDelete((CPlayerEntityProperties *)hep);
ASSERT(gc_ppePlayer != NULL);
return;
}
// handles controls here
}
This function is called correctly and the assert never triggers. However, every time this function is called, gc_ppePlayer is set to NULL. As you can see it's not a local variable going out of scope. The only place gc_ppePlayer can be set to NULL is in the constructor or possibly in the destructor, neither of which are being called in between the calls to EvaluateControls. When debugging, gc_ppePlayer receives a correct and expected value before the return. When I press F10 one more time and the cursor is at the closing brace, the value changes to 0xffffffff. I'm at a loss here, how can this happen? Anyone?
|
Are you debugging a Release or Debug configuration? In release build configuration, what you see in the debugger isn't always true. Optimisations are made, and this can make the watch window show quirky values like you are seeing.
Are you actually seeing the ASSERT triggering? ASSERTs are normally compiled out of Release builds, so I'm guessing you are debugging a release build which is why the ASSERT isn't causing the application to terminate.
I would recommend build a Debug version of the software, and then seeing if gc_ppePlayer is really NULL. If it really is, maybe you are seeing memory heap corruption of some sort where this pointer is being overridden. But if it was memory corruption, it would generally be much less deterministic than you are describing.
As an aside, using global pointer values like this is generally considered bad practice. See if you can replace this with a singleton class if it is truly a single object and needs to be globally accessible.
|
601,152
| 601,170
|
Is a finally block without a catch block a java anti-pattern?
|
I just had a pretty painful troubleshooting experience in troubleshooting some code that looked like this:
try {
doSomeStuff()
doMore()
} finally {
doSomeOtherStuff()
}
The problem was difficult to troubleshoot because doSomeStuff() threw an exception, which in turn caused doSomeOtherStuff() to also throw an exception. The second exception (thrown by the finally block) was thrown up to my code, but it did not have a handle on the first exception (thrown from doSomeStuff()), which was the real root-cause of the problem.
If the code had said this instead, the problem would have been readily apparent:
try {
doSomeStuff()
doMore()
} catch (Exception e) {
log.error(e);
} finally {
doSomeOtherStuff()
}
So, my question is this:
Is a finally block used without any catch block a well-known java anti-pattern? (It certainly seems to be a not-readily-apparent subclass of the obviously well-known anti-pattern "Don't gobble exceptions!")
|
In general, no, this is not an anti-pattern. The point of finally blocks is to make sure stuff gets cleaned up whether an exception is thrown or not. The whole point of exception handling is that, if you can't deal with it, you let it bubble up to someone who can, through the relatively clean out-of-band signaling exception handling provides. If you need to make sure stuff gets cleaned up if an exception is thrown, but can't properly handle the exception in the current scope, then this is exactly the correct thing to do. You just might want to be a little more careful about making sure your finally block doesn't throw.
|
601,180
| 601,212
|
why does printf show a 0 for vector size when cout shows the correct size?
|
I don't get why I get 0 when I use printf and %d to get the size of my vector:
vector<long long> sieve;
int size;
...
//add stuff to vector
...
size = sieve.size();
printf("printf sieve size: %d \n", size); //prints "printf sieve size: 0"
std::cout << "cout sieve size: ";
std::cout << size;
std::cout << " \n ";
//prints "cout sieve size: 5 (or whatever the correct sieve size is)"
If I iterate through the vector via
if(i=0;i<sieve.size();i++)
I get the correct number of iterations.
What am I doing wrong or what is up with printf? size() returns an int right??
Here's my entire little script:
#include <iostream>
#include <vector>
#include <stack>
#include <math.h>
int main (int argc, char * const argv[]) {
unsigned long long answer = 0;
unsigned long long cur = 2;
std::vector<long long> sieve;
unsigned long long limit;
unsigned long long value;
unsigned int i;
int size;
bool isPrime;
std::cout << "Provide a value to find its largest prime factor: ";
std::cin >> value;
limit = ceil(sqrt(value));
sieve.push_back(2);
while(cur++ < limit){
isPrime = true;
sieve.begin();
for(i=0; i<sieve.size();i++){
if(!(cur % sieve[i])){
isPrime = false;
break;
}
}
if(isPrime){
if(!(value % cur)){
std::printf("Is prime factor: %d\n", cur);
sieve.push_back(cur);
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("current last: %d sieve size: %ld\n", answer, size);
for(i=0; i<sieve.size();i++){
std::printf("sieve iter: %d sieve val: %d\n", i, sieve[i]);
std::cout << size;
std::cout << " wtf\n";
}
}
}
}
answer = sieve[sieve.size() - 1];
size = sieve.size();
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
return 0;
}
|
Now, with the complete source, it is clear.
You declared:
int size;
Then you used:
std::printf("current last: %d sieve size: %ld\n", answer, size);
std::printf("Limit: %d Answer: %d sieve size: %ld\n", limit, answer, size);
If size is int, you should use "%d", not "%ld". A good compiler would have warned you about this. GCC gives these warnings for your original version:
test.cpp: In function ‘int main(int, char* const*)’:
test.cpp:17: warning: converting to ‘long long unsigned int’ from ‘double’
test.cpp:30: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:34: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:34: warning: format ‘%ld’ expects type ‘long int’, but argument 3 has type ‘int’
test.cpp:36: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘long long int’
test.cpp:45: warning: format ‘%d’ expects type ‘int’, but argument 2 has type ‘long long unsigned int’
test.cpp:45: warning: format ‘%d’ expects type ‘int’, but argument 3 has type ‘long long unsigned int’
test.cpp:45: warning: format ‘%ld’ expects type ‘long int’, but argument 4 has type ‘int’
This tells a lot.
You should declare size as:
std::vector<long long>::size_type size;
Then you should use it as:
std::printf("current last: %llu sieve size: %llu\n", (unsigned long long) answer, (unsigned long long) size);
std::printf("Limit: %llu Answer: %llu sieve size: %llu\n", (unsigned long long) limit, (unsigned long long) answer, (unsigned long long) size);
Of course, using iostream avoids you these problems, specially the ugly casting in printf() to transform size to a type known to printf.
|
601,219
| 601,283
|
Overloading operator << - C++
|
Background
I have a container class which uses vector<std::string> internally. I have provided a method AddChar(std::string) to this wrapper class which does a push_back() to the internal vector. In my code, I have to add multiple items to the container some time. For that I have to use
container.AddChar("First");
container.AddChar("Second");
This makes the code larger. So to make it more easier, I plan to overload operator <<. So that I can write
container << "First" << "Second"
and two items will get added to underlying vector.
Here is the code I used for that
class ExtendedVector
{
private:
vector<string> container;
public:
friend ExtendedVector& operator<<(ExtendedVector& cont,const std::string str){
cont.AddChar(str);
return cont;
}
void AddChar(const std::string str)
{
container.push_back(str);
}
string ToString()
{
string output;
vector<string>::iterator it = container.begin();
while(it != container.end())
{
output += *it;
++it;
}
return output;
}
};
It is working as expected.
Questions
Is operator overload written correctly?
Is it a good practice to overload operators in situations like this?
Will there be any performance issues or any other issues with this code?
Any thoughts?
Edit
After hearing the excellent comments, I decided not to overload << as it doesn't make sense here. I removed the operator overload code and here is the final code.
class ExtendedVector
{
private:
vector<string> container;
public:
ExtendedVector& AddChar(const std::string str)
{
container.push_back(str);
return *this;
}
.. other methods
}
This allows me to add
container.AddChar("First").AddChar("Second")
In C#, I can do this more easily by using the params keyword. Code will be like
void AddChar(params string[] str)
{
foreach(string s in str)
// add to the underlying collection
}
I know in C++, we can use ... to specify variable langth of parameters. But AFAIK, it is not type safe. So is it a recommended practice to do so? So that I can write
container.AddChar("First","Second")
Thanks for the replies.
|
Is operator overload written correctly?
It is, but one can do better. Like someone else mentioned, your function can be defined entirely out of existing, public functions. Why not make it use only those? Right now, it is a friend, which means it belongs to the implementation details. The same is true if you put operator<< as a member into your class. However, make your operator<< a non-member, non-friend function.
class ExtendedVector {
...
};
// note, now it is *entirely decoupled* from any private members!
ExtendedVector& operator<<(ExtendedVector& cont, const std::string& str){
cont.AddChar(str);
return cont;
}
If you change your class, you will not be sure that that your operator<< will still work. But if your operator<< entirely depends only on public functions, then you can be sure that it will work after changes were made to implementation details of your class only. Yay!
Is it a good practice to overload operators in situations like this?
As another guy said again, this is arguable. In many situations, operator overloading will look "neat" at first sight, but will look like hell next year, because you have no clue anymore what you had in mind when giving some symbols special love. In the case of operator<<, i think this is an OK use. Its use as an insertion operator for streams is well known. And i know of Qt and KDE applications that use it extensively in cases like
QStringList items;
items << "item1" << "item2";
A similar case is boost.format which also reuses operator% for passing arguments for placeholders in its string:
format("hello %1%, i'm %2% y'old") % "benny" % 21
It's of course also arguable to use it there. But its use for printf format specifies are well known and so its use is OK there too, imho. But as always, style is also subjective so take it with a grain of salt :)
How can i accept variable length arguments in a typesafe way?
Well, there is the way of accepting a vector if you are looking for homogeneous arguments:
void AddChars(std::vector<std::string> const& v) {
std::vector<std::string>::const_iterator cit =
v.begin();
for(;cit != v.begin(); ++cit) {
AddChar(*cit);
}
}
It's not really confortable to pass it though. You have to construct your vector manually and then pass... I see you already have the right feeling about the vararg style functions. One should not use them for this kind of code and only when interfacing with C code or debugging functions if at all. Another way to handle this case is to apply preprocessor programming. This is an advanced topic and is quite hacky. The idea is to automatically generate overloads up to some upper limit roughly like this:
#define GEN_OVERLOAD(X) \
void AddChars(GEN_ARGS(X, std::string arg)) { \
/* now access arg0 ... arg(X-1) */ \
/* AddChar(arg0); ... AddChar(arg(N-1)); */ \
GEN_PRINT_ARG1(X, AddChar, arg) \
}
/* call macro with 0, 1, ..., 9 as argument
GEN_PRINT(10, GEN_OVERLOAD)
That is pseudo code. You can have a look at the boost preprocessor library here.
Next C++ version will offer far better possibilities. Initializer lists can be used:
void AddChars(initializer_list<std::string> ilist) {
// range based for loop
for(std::string const& s : ilist) {
AddChar(s);
}
}
...
AddChars({"hello", "you", "this is fun"});
It's also possible in next C++ to support arbitrary many (mixed-type) arguments using variadic templates. GCC4.4 will have support for them. GCC 4.3 already partially supports them.
|
601,268
| 601,285
|
visual c++: #include files from other projects in the same solution
|
I am working on a game using Visual C++. I have some components in separate projects, and have set the project dependencies. How do I #include a header file from a different project? I have no idea how to use classes from one project in another.
|
Settings for compiler
In the project where you want to #include the header file from another project, you will need to add the path of the header file into the Additional Include Directories section in the project configuration.
To access the project configuration:
Right-click on the project, and select Properties.
Select Configuration Properties->C/C++->General.
Set the path under Additional Include Directories.
How to include
To include the header file, simply write the following in your code:
#include "filename.h"
Note that you don't need to specify the path here, because you include the directory in the Additional Include Directories already, so Visual Studio will know where to look for it.
If you don't want to add every header file location in the project settings, you could just include a directory up to a point, and then #include relative to that point:
// In project settings
Additional Include Directories ..\..\libroot
// In code
#include "lib1/lib1.h" // path is relative to libroot
#include "lib2/lib2.h" // path is relative to libroot
Setting for linker
If using static libraries (i.e. .lib file), you will also need to add the library to the linker input, so that at linkage time the symbols can be linked against (otherwise you'll get an unresolved symbol):
Right-click on the project, and select Properties.
Select Configuration Properties->Linker->Input
Enter the library under Additional Dependencies.
|
601,337
| 601,386
|
Change boost thread priority in Windows
|
Im trying to change the thread priority in boost but im having no luck. Im getting a bad handle error (type 6) from the GetLastError function. I though native_handle() returned the handle for the thread?
Any one know how to do this?
void baseThread::applyPriority(uint8 priority)
{
#ifdef WIN32
if (!m_pThread)
return;
BOOL res;
HANDLE th = m_pThread->native_handle();
switch (priority)
{
case REALTIME : res = SetPriorityClass(th, REALTIME_PRIORITY_CLASS); break;
case HIGH : res = SetPriorityClass(th, HIGH_PRIORITY_CLASS); break;
case ABOVE_NORMAL : res = SetPriorityClass(th, ABOVE_NORMAL_PRIORITY_CLASS); break;
case NORMAL : res = SetPriorityClass(th, NORMAL_PRIORITY_CLASS); break;
case BELOW_NORMAL : res = SetPriorityClass(th, BELOW_NORMAL_PRIORITY_CLASS); break;
case IDLE : res = SetPriorityClass(th, IDLE_PRIORITY_CLASS); break;
}
if (res == FALSE)
{
int err = GetLastError();
}
#endif
}
edit: Final code:
void baseThread::applyPriority(uint8 priority)
{
#ifdef WIN32
if (!m_pThread)
return;
BOOL res;
HANDLE th = m_pThread->native_handle();
switch (priority)
{
case REALTIME : res = SetThreadPriority(th, THREAD_PRIORITY_TIME_CRITICAL); break;
case HIGH : res = SetThreadPriority(th, THREAD_PRIORITY_HIGHEST); break;
case ABOVE_NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_ABOVE_NORMAL); break;
case NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_NORMAL); break;
case BELOW_NORMAL : res = SetThreadPriority(th, THREAD_PRIORITY_BELOW_NORMAL); break;
case IDLE : res = SetThreadPriority(th, THREAD_PRIORITY_LOWEST); break;
}
#endif
}
|
Use SetThreadPriority function to set the thread priority. SetPriorityClass is used to set the priority of the process. You also have to change the priority values, see documentation for SetThreadPriority for details.
|
601,430
| 601,536
|
Multibyte character constants and bitmap file header type constants
|
I have some existing code that I've used to write out an image to a bitmap file. One of the lines of code looks like this:
bfh.bfType='MB';
I think I probably copied that from somewhere. One of the other devs says to me "that doesn't look right, isn't it supposed to be 'BM'?" Anyway it does seem to work ok, but on code review it gets refactored to this:
bfh.bfType=*(WORD*)"BM";
A google search indicates that most of the time, the first line seems to be used, while some of the time people will do this:
bfh.bfType=0x4D42;
So what is the difference? How can they all give the correct result? What does the multi-byte character constant mean anyway? Are they the same really?
|
All three are (probably) equivalent, but for different reasons.
bfh.bfType=0x4D42;
This is the simplest to understand, it just loads bfType with a number that happens to represent ASCII 'M' in bits 8-15 and ASCII 'B' in bits 0-7. If you write this to a stream in little-endian format, then the stream will contain 'B', 'M'.
bfh.bfType='MB';
This is essentially equivalent to the first statement -- it's just a different way of expressing an integer constant. It probably depends on the compiler exactly what it does with it, but it will probably generate a value according to the endian-ness of the machine you compile on. If you compile and execute on a machine of the same endian-ness, then when you write the value out on the stream you should get 'B', 'M'.
bfh.bfType=*(WORD*)"BM";
Here, the "BM" causes the compiler to create a block of data that looks like 'B', 'M', '\0' and get a char* pointing to it. This is then cast to WORD* so that when it's dereferenced it will read the memory as a WORD. Hence it reads the 'B', 'M' into bfType in whatever endian-ness the machine has. Writing it out using the same endian-ness will obviously put 'B', 'M' on your stream. So long as you only use bfType to write out to the stream this is the most portable version. However, if you're doing any comparisons/etc with bfType then it's probably best to pick an endian-ness for it and convert as necessary when reading or writing the value.
|
601,558
| 602,001
|
Multithreading reference?
|
I am asking about a good reference for multithreading programming in terms of concepts
with good examples using C++/C#?
|
Good reference for reading:
Thread Management In The CLR
Round-Robin Access To The ThreadPool
Multithreading with C#
Why are thread safe collections so hard?
Threading in C#
Jeffrey Richter’s Power Threading Library
Implementing a Thread-Safe Queue using Condition Variables
Threading Building Blocks.org!
Sutter’s Mill - Effective Concurrency: Understanding Parallel Performance
Sutter’s Mill - Effective Concurrency: Use Threads Correctly = Isolation + Asynchronous Messages
Thread Synchronization (C# Programming Guide)
How to synchronize access to a shared resource in a multithreading environment by using Visual C#
Use Threads Correctly = Isolation + Asynchronous Messages
Parallel and Multi-Core Computing with C/C++
Thinking in Concurrently in .NET
Programming the Thread Pool in the .NET Framework
Visual Basic .NET: Tracing, Logging, and Threading Made Easy with .NET
Juice Up Your App with the Power of Hyper-Threading
Concurrency Hazards - Solving 11 Likely Problems In Your Multithreaded Code
INFO: Descriptions and Workings of OLE Threading Models - COM STA MTA
C# Threading
Thread Synchronization (C# Programming Guide)
Overview of concurrency in .NET Framework 3.5
Multi-threading in .NET: Introduction and suggestions
Oracle - Multithreaded Programming Guide
Multithreading Tutorial
64-Bit Programming with Visual C++
How to: Create and Terminate Threads (C# Programming Guide)
|
601,676
| 601,688
|
Where is Visual C++ Redistributable Installer in VS 2008?
|
I have Visual Studio 2008 SP1 Professional installed. I have built a C++ application and I want to install the redistributable runtime on another machine. Is the installer available in VS installation? Or do I have to download it?
|
Take a look in %ProgramFiles%\Microsoft SDKs\Windows\v6.0A\Bootstrapper\Packages\ for the platform(s) you require.
|
601,680
| 601,685
|
"Bus error" accessing a set<int> from a struct
|
Searched for a while, but I can't figure out why this would raise a bus error.
Any help would be much appreciated.
typedef struct {
set<int> pages;
} someStruct;
...
void someFunction() {
...
someStruct *a = createSomeStruct(); // just mallocs and returns
a->pages.insert(5);
...
}
|
malloc doesn't initialize the memory it allocates. try with new.
|
601,763
| 601,828
|
How to get IP address of boost::asio::ip::tcp::socket?
|
I'm writing a server in C++ using Boost ASIO library. I'd like to get the string representation of client IP to be shown in my server's logs. Does anyone know how to do it?
|
The socket has a function that will retrieve the remote endpoint. I'd give this (long-ish) chain of commands a go, they should retrieve the string representation of the remote end IP address:
asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.
asio::ip::tcp::endpoint remote_ep = socket.remote_endpoint();
asio::ip::address remote_ad = remote_ep.address();
std::string s = remote_ad.to_string();
or the one-liner version:
asio::ip::tcp::socket socket(io_service);
// Do all your accepting and other stuff here.
std::string s = socket.remote_endpoint().address().to_string();
|
601,777
| 613,946
|
How to configure Eclipse with CDT?
|
I've been trying to use CDT with Eclipse 3.4 under Windows XP with cygwin.
What do I need to do, in order to get startet?
I used "eclipse-cpp-ganymede-SR1-win32.zip" found on the Eclipse homepage.
Edit:
The main problem is, that I cannot compile and run the code.
In the run configuration, I tried gcc.exe for the C/C++ Application:
After adding the path of make.exe to my $Path, and starting from scratch, it works perfectly.
|
I finally found. Thanks guys.
After downloading and unpacking "eclipse-cpp-ganymede-SR1-win32.zip", you need to install either Cygwin or MinGW.
Make sure the compiler (e.g. gcc.exe) and make.exe is on your $Path.
Start Eclipse and everything should work fine.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.