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 |
|---|---|---|---|---|
1,425,912 | 1,425,984 | Google Protocol Buffers and HTTP | I'm refactoring legacy C++ system to SOA using gSoap. We have some performance issues (very big XMLs) so my lead asked me to take a look at protocol buffers. I did, and it looks very cool (We need C++ and Java support). However protocol buffers are solution just for serialization and now I need to send it to Java front-end. What should I use from C++ and Java perspective to send those serialized stuff over HTTP (just internal network)?
PS. Another guy tries to speed-up our gSoap solution, I'm interested in protocol buffers only.
| You can certainly send even a binary payload with an HTTP request, or in an HTTP response. Just write the bytes of the protocol buffer directly into the request/response, and make sure to set the content type to "application/octet-stream". The client, and server, should be able to take care of the rest easily. I don't think you need anything more special than that on either end.
|
1,426,093 | 1,426,126 | Set vector type at runtime | I have a program that needs to set the type of a vector as the program is executed (according to a value in a configuration file).
I have tried this:
int a = 1
if(a == 1) vector<int> test(6);
else vector<unsigned int> test(6);
test.push_back(3);
But this gives me:
Error 1 error C2065: 'test' : undeclared identifier
I'm not entirely sure why, but I think this is because the vector is not actually decided at compile time so the compiler cannot work with it whilst compiling the rest of the code.
Is there a way to decide the type of a vector at runtime similar to what I have attempted above?
I have tried to create one version outside the if and then delete it and re-write the new version inside the IF. This however feels wrong and I can't get it to work anyway.
thanks.
| The reason it does not work is that you're declaring the vectors inside the if- and else-block respectively, so they go out of scope once that block ends.
Is there a way to decide the type of a vector at runtime similar to what I have attempted above?
No, the type of a variable must be known at compile-time. Your only option is to put the line test.push_back(3) as well as any following code which accesses test into the if- and the else-block, or to avoid code-duplication into a second templated function. This could look like this:
template <class T>
do_something_with_test(vector<T>& test) {
test.push_back(3);
// work with test
}
void foo() {
int a = 1
if(a == 1) {
vector<int> test(6);
do_something_with_test(test);
}
else {
vector<unsigned int> test(6);
do_something_with_test(test);
}
}
|
1,426,403 | 1,431,357 | Sending data between Java to c++ on windows? | I want to send the raw audio buffer to c++ for audio transcoding.
I have two option
using piped stream
using direct buffers (java.nio)
Are these really my 2 best options (and which would people recommend?) Thanks!
| Direct buffers in NIO will almost certainly have better performance. This is pretty much the ideal case for direct buffers.
I'm not sure what the point of your question is - if you want to know if there are other options, then the answer is certainly yet (you could, for example, write to a file then invoke an external application to process it - or you could use JNI without direct buffers). But if you want a tightly coupled, highly performant interface between Java and C++ code, JNI along with direct buffers, is going to be the tool to use.
|
1,426,562 | 1,426,581 | Windows Magnification API, .NET and matrices | I'm trying to create a magnifier app in .NET using the Windows Magnification API. I've pretty much got everything working except for actually setting the magnification level (which defaults to 100%). The problem is, I can't find any examples anywhere on the Internet and all the documentation for the API is C++ code. This is the particular function I'm having trouble with.
bool SetMagFactor(float magfactor)
{
MAGTRANSFORM matrix;
memset(&matrix, 0, sizeof(matrix));
matrix.v[0][0] = magfactor;
matrix.v[1][1] = magfactor;
matrix.v[2][2] = 1.0f;
return MagSetWindowTransform(hwndMag, &matrix);
}
The MAGTRANSFORM structure is defined as follows:
typedef struct tagMAGTRANSFORM {
float v[3] [3];
} MAGTRANSFORM, *PMAGTRANSFORM;
The most confusing part of this is the memset - I'm not sure what it does or what its equivalent is in .NET, but what's also confusing is the multidimensional array/matrix and how I would handle this in .NET also.
How can I do it?
| The memset is just clearing out the matrix to start with. You wouldn't need to do this in .NET. I suspect the simplest way of defining the struct in C# would be to specify each element individually:
public struct MagTransform
{
readonly float m00;
readonly float m10;
readonly float m20;
readonly float m01;
readonly float m11;
readonly float m21;
readonly float m02;
readonly float m12;
readonly float m22;
public MagTransform(float magnificationFactor) : this()
{
m00 = magnificationFactor;
m11 = magnificationFactor;
m22 = 1.0f;
}
}
You may also need to specify the layout - I'm afraid I'm not so hot on marshalling.
As you can see, I've assumed the values you want based on the sample code. There will be warnings about unused values, but that's okay.
You could use a fixed buffer instead, and unsafe code... but I think I'd probably use the above. Basically you just need 9 floats.
|
1,426,665 | 1,430,104 | Problem with HDN_ENDTRACK when resizing a list column | I am having a bit of a problem when handling a HDN_ENDTRACKW message for a custom class which derives from CListCtrl .
Essentially, it seem that when this message is sent, the actual value which stores the width of the column is not updated until after my handling code has been executed.
The code inside the handle simply instructs a progress bar to resize, to fill the width of the resized column.
The code:
void ProgListCtrl::OnEndTrack(NMHDR* pNMHDR, LRESULT* pResult)
{
int width = ListView_GetColumnWidth(GetSafeHwnd(), m_nProgressColumn);
ResizeProgressbar();
}
The ListView_GetColumnWidth is there just to help with debugging at the moment.
The default value for the particular column I am changing is 150, when i resize the column in the UI, this method is called but the width stays at the same 150, the progress bar does not resize. Only when a column is resized again does the width value now reflect the value of the column after the first resize, the ResizeProgressBar method then correctly changes the progbar size to fill the column it is in. This is continuous, the width value always seems to be one step behind the actual value.
I would apreciate any help. Cheers.
| Use the information that HDN_ENDTRACK itself provides to you, ie:
void ProgListCtrl::OnEndTrack(NMHDR* pNMHDR, LRESULT* pResult)
{
NMHEADER *pHdr = (NMHEADER*) pNMHDR;
if ((pHdr->iItem == m_nProgressColumn) &&
(pHdr->pitem) &&
(pHdr->pitem->mask & HDI_WIDTH))
{
int width = pHdr->pitem->cxy;
ResizeProgressbar();
}
}
Alternatively, look at the HDN_ITEMCHANGING and HDN_ITEMCHANGED notifications instead of HDN_ENDTRACK.
|
1,426,986 | 1,426,992 | What does `*&` in a function declaration mean? | I wrote a function along the lines of this:
void myFunc(myStruct *&out) {
out = new myStruct;
out->field1 = 1;
out->field2 = 2;
}
Now in a calling function, I might write something like this:
myStruct *data;
myFunc(data);
which will fill all the fields in data. If I omit the '&' in the declaration, this will not work. (Or rather, it will work only locally in the function but won't change anything in the caller)
Could someone explain to me what this '*&' actually does? It looks weird and I just can't make much sense of it.
| The & symbol in a C++ variable declaration means it's a reference.
It happens to be a reference to a pointer, which explains the semantics you're seeing; the called function can change the pointer in the calling context, since it has a reference to it.
So, to reiterate, the "operative symbol" here is not *&, that combination in itself doesn't mean a whole lot. The * is part of the type myStruct *, i.e. "pointer to myStruct", and the & makes it a reference, so you'd read it as "out is a reference to a pointer to myStruct".
The original programmer could have helped, in my opinion, by writing it as:
void myFunc(myStruct * &out)
or even (not my personal style, but of course still valid):
void myFunc(myStruct* &out)
Of course, there are many other opinions about style. :)
|
1,427,002 | 1,434,508 | Calling Py_Finalize() from C | This is a follow up to Call Python from C++
At the startup of the programm I call the following function to initialize the interpreter:
void initPython(){
PyEval_InitThreads();
Py_Initialize();
PyEval_ReleaseLock();
}
Every thread creates it's own data structure and acquires the lock with:
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
//call python API, process results
PyGILState_Release(gstate);
Rather straight forward once you understood the GIL, but the problem is that I get a segfault when calling Py_Finalize().
void exitPython(){
PyEval_AcquireLock();
Py_Finalize();
}
The reference is rather dubious about Py_Finalize() (or maybe I'm just reading it the wrong way) and I'm not sure if PyEval_AcquireLock() can acquire the lock if there are some active threads and what happens if there are active threads when Py_Finalize() is called.
Anyways, I get a segfault even if I'm sure that all threads have finished their work, but only if at least one was created. E.g. calling initPython() followed from exitPython() creates no error.
I could just ignore the problem and hope the OS knows what it does, but I'd prefere if I could figure out what is going on..
| Yeah the whole section is rather dubious but I think I've got my mistake.
I've got to save the PyThreadState when initializing the interpreter and swap this state back in when I finish it (no idea why I need a specific ThreadState to call Finalize - shouldn't every State work as well?)
Anyways the example if other people got the same problem:
PyThreadState *mainstate;
void initPython(){
PyEval_InitThreads();
Py_Initialize();
mainstate = PyThreadState_Swap(NULL);
PyEval_ReleaseLock();
}
void exitPython(){
PyEval_AcquireLock();
PyThreadState_Swap(mainstate);
Py_Finalize();
}
The only problem with this is, that I can acquire the lock like every other thread, even if there are still threads working.
The API doesn't mention what happens when Finalize() is called while other threads are still working. Sounds like the perfect example of a race condition..
|
1,427,197 | 1,429,070 | XAudio2 and variable bitrate audio | How do I go about correctly playing audio files which may have a variable bitrate (and even a variable number of channels in some cases), such as ogg/vorbis?
XAudio expects this information in a WAVEFORMATEX structure on creation of the source voice, and doesn't seem to provide a means to change it for each buffer thats submitted...
| Unless I'm high, no audio format specifies variable output bitrate or variable number of output channels. A variable bitrate codec means that the number of bits used to encode a fixed number of samples varies. Vorbis allows for dynamically encoding the channels as well for channels that can be reproduced with simpler functions such as silence. The number of output channels remains constant, as well as the output bitrate.
Also, XAudio2 does not natively support ogg/vorbis files; it supports PCM, ADPCM, and xWMA on Windows and PCM, XMA, and xWMA on Xbox 360.
In general, for non-native formats, you have to decompress the audio yourself into the appropriate output bitrate and channel format and send that to an IXAudio2SourceVoice via IXAudio2SourceVoice::SubmitSourceBuffer.
|
1,427,931 | 1,427,960 | What is the most common way of understanding a very large C++ application? | When having a new C++ project passed along to you, what is the standard way of stepping through it and becoming acquainted with the entire codebase? Do you just start at the top file and start reading through all x-hundred files? Do you use a tool to generate information for you? If so, which tool?
| I use change requests/bug reports to guide my learning of some new project. It never makes a lot of sense to me to try and consume the entirety of something all at once. A change order or bug report gives me guidance to focus on this one tendril of the system, tracing it's activity through the code.
After a reasonable amount of these, I can get a good understanding of the fundamentals of the project.
|
1,428,117 | 1,428,542 | Linux IPC - Multiple writers, single reader | I have never written any IPC C++ on Linux before.
My problem is that I will have multiple clients (writers), and a single server (reader). All of these will be on the same machine. The writers will deliver chunks of data (a string/struct) to the reader. The reader will then read them in FIFO and do something with them.
The types of IPC on Linux are either Pipes or Sockets/Message Queues as far as I can tell.
I was just wondering if someone could recommend me a path to go down. I'm leaning towards sockets, but I have no real basis for that. Is there anything I should read/understand before embarking on this journey?
Thanks
| The main issue you should consider is what kind of data you are passing as this will in part determine your options. This comes down to whether your data is bounded or not. If it isn't bounded then something stream oriented like FIFOs or sockets are appropriate; if it is then you might make better use of of things like MQs or shared memory. Since you mention both strings and structs it is hard to say what is appropriate in your case, though if your strings are bounded within some reasonable maximum you can use anything with some minor fiddling.
The second is speed. There is never a completely correct answer for this but generally it goes something like: shared memory, MQs, FiFOs, domain sockets, network sockets.
The third is ease of use. Shared memory is the biggest PITA since you have to handle your own synchronization. Pipes are easy so long as your message lengths stay below PIPE_BUF size. The OS handles most of your headaches with MQs. Sockets are easy enough but you have the setup boilerplate.
Lastly several of the IPC mechanisms have both POSIX and SYSV variants. Generally POSIX is the way to go unless the SYSV type has some feature you really need or want.
EDIT: Count0's answer reminded me that you might be interested in something more abstract and higher level. In addition to ACE you can look at Poco. And, of course, no SO answer is complete if it doesn't mention Boost somewhere.
|
1,428,130 | 1,428,136 | Making a .exe in Visual Studio 2008 | Could anyone be kind, and tell me how to make a exe file in visual studio 2008 for a win32 console based, c++ program? Thanks
| Try using the Win32 Console Application type in the New C++ wizard. Building this will produce a native C++ executable application.
|
1,428,786 | 1,428,814 | What is the best way to find a prime number? | what will be the best way to find a prime number so that the time complexity is much reduced.
| When it comes to finding prime numbers, the Sieve of Eratosthenes and the Sieve of Atkin are two possible solutions. The Sieve of Eratosthenes has a complexity of O((n log n)(log log n)). The Sieve of Atkin has a complexity of O(N / log log n).
If you have a number and you want to find out if it's prime, that is called performing a primality test. The naive approach is to check all numbers m from 2 to sqrt(n) and verify that n % m is not 0. If you want to expand this slightly, you can throw out all even numbers (except 2). There are also some other enhancements to this naive approach that might improve performance, along with other, more advanced techniques.
|
1,428,972 | 1,430,182 | Dynamic slicing in C/C++ | After reading the book of debugging from Andreas Zeller, I became interested in Dynamic Slicing.
At the moment I only found relevant tools for Java analysis. Do you know such tools for C/C++?
| A little information in addition to Rob's
the Wisconsin Program-Slicing Tool has evolved in a tool called CodeSurfer. Good news: it's commercially available and supported, and it works great for what it does. Bad news (perhaps): it does not actually produce a reduced program that computes the same value that you selected, but it's very convenient for navigating source code that you have not written.
Frama-C handles only C (no C++ for the foreseeable future). It is nice, not great, for navigating source code, but it can produce an equivalent smaller program for the criterion that you specify, if the original program is of the kind that it can analyze automatically (no recursion, no dynamic allocation). Frama-C is Open Source and has a mailing list in which your questions will be welcome if you are interested in the techniques it uses.
The reason CodeSurfer does not risk itself to produce an equivalent program and Frama-C can only do it for code with embedded-like restrictions is, in short, that doing so requires knowing the values of pointers, which can be arbitrarily difficult to compute with precision.
|
1,429,266 | 1,430,025 | Customizing Win32's Save File Dialog | I am trying to save a file using GetSaveFileName and want to have a couple extra popups at the bottom of my save file dialog to allow the user to specify further options. I am trying to follow the MSDN documentation (specifically the Explorer-style customization) on the subject but can't seem to get my custom item to appear. I believe I set up the OPENFILENAME struct properly as I'm getting calls into my OFNHookProc. As far as I know it is during the WM_INITDIALOG message that I should be creating my subcontrols, which is what I'm doing:
HWND settings_popup =
::CreateWindowExW(WS_EX_CLIENTEDGE | WS_EX_NOPARENTNOTIFY,
L"COMBOBOX",
L"Settings:",
WS_CHILD | WS_CLIPSIBLINGS | WS_VSCROLL | WS_BORDER | CBS_DROPDOWNLIST,
10,
10,
150,
30,
dialog, // the window parameter from the OFNHookProc
NULL,
::GetModuleHandle(NULL),
NULL);
if (settings_popup)
{
HWND parent = ::GetParent(settings_popup); // for verification
::ShowWindow(settings_popup, SW_SHOW);
::EnableWindow(settings_popup, true);
}
I also return 1 from my OFNHookProc for the WM_INITDIALOG message and 0 for everything else.
In all my attempts to get the combobox to show in the dialog, it's not coming up. What am I missing from my code to make the combobox a part of my save file dialog customization?
| When calling CreateWindowEx() to create your child window, you need to use GetParent() to get the parent window of the dialog, and then use that HWND as your parent window. Do not use the dialog itself as the parent. In other words:
HWND settings_popup =
::CreateWindowExW(WS_EX_CLIENTEDGE | WS_EX_NOPARENTNOTIFY,
L"COMBOBOX",
L"Settings:",
WS_CHILD | WS_CLIPSIBLINGS | WS_VSCROLL | WS_BORDER | CBS_DROPDOWNLIST,
10,
10,
150,
30,
::GetParent(dialog),
NULL,
::GetModuleHandle(NULL),
NULL);
|
1,429,336 | 1,429,350 | Cross referencing included headers in c++ program | I am curious about a scenario set up like the following example:
Here is code that would be placed in a file called Header1.h:
#ifndef HEADER1_H
#define HEADER1_H
#include "Header2.h"
class Class1
{
Class2 class2Instance;
};
#endif
Here is code that would be placed in a file called Header2.h:
#ifndef HEADER2_H
#define HEADER2_H
#include "Header1.h"
class Class2
{
Class1 class1Instance;
};
#endif
I get error messages when I do this (because of the includes I assume), but it feels like I would need to do this in order to include each of the objects in the separate classes. Can anyone help me accomplish this, what am I doing wrong?
| The problem is that the size of Class1 depends on Class2, and vice-versa. Therefore, there's no way to calculate the size for either one. Forward-declare one of the classes, and change one of the attributes to be a pointer or reference:
#ifndef HEADER2_H
#define HEADER2_H
class Class1;
class Class2
{
Class1 *class1Instance;
// or
Class1 &class1Instance;
};
#endif
|
1,429,440 | 1,429,500 | C++ Class or Struct compatiblity with C struct | Is it possible to write a C++ class or struct that is fully compatible with C struct. From compatibility I mean size of the object and memory locations of the variables. I know that its evil to use *(point*)&pnt or even (float*)&pnt (on a different case where variables are floats) but consider that its really required for the performance sake. Its not logical to use regular type casting operator million times per second.
Take this example
Class Point {
long x,y;
Point(long x, long y) {
this->x=x;
this->y=y;
}
float Distance(Point &point) {
return ....;
}
};
C version is a POD struct
struct point {
long x,y;
};
| Yes.
Use the same types in the same order in both languages
Make sure the class doesn't have anything virtual in it (so you don't get a vtable pointer stuck on the front)
Depending on the compilers used you may need to adjust the structure packing (usually with pragmas) to ensure compatibility.
(edit)
Also, you must take care to check the sizeof() the types with your compilers. For example, I've encountered a compiler that stored shorts as 32 bit values (when most will use 16). A more common case is that an int will usually be 32 bits on a 32-bit architecture and 64 bits on a 64-bit architecture.
|
1,429,472 | 1,429,514 | Change speed of keystroke C++ | Basically, when one types, a keydown event happens. If the key is held for more than a certain time (~1 sec) then the key is repeatedly pressed until keyup hapens. I would like to change the time it takes for the key to be automatically repressed in my c++ application. How can this be done?
Thanks
| The speed at which a keypress becomes automatically recurring is controlled by Windows.
If you want to manipulate automatic recurrences of key-presses, it might be more advantageous to poll for the state of the key rather than waiting for the keydown event. It depends on how responsive you need your application to be.
This article may help you in figuring out how to query for key states: link
|
1,429,659 | 1,429,722 | Partial template specialization on a class | I'm looking for a better way to this. I have a chunk of code that needs to handle several different objects that contain different types. The structure that I have looks like this:
class Base
{
// some generic methods
}
template <typename T> class TypedBase : public Base
{
// common code with template specialization
private:
std::map<int,T> mapContainingSomeDataOfTypeT;
}
template <> class TypedBase<std::string> : public Base
{
// common code with template specialization
public:
void set( std::string ); // functions not needed for other types
std::string get();
private:
std::map<int,std::string> mapContainingSomeDataOfTypeT;
// some data not needed for other types
}
Now I need to add some additional functionality that only applies to one of the derivative classes. Specifically the std::string derivation, but the type doesn't actually matter. The class is big enough that I would prefer not copy the whole thing simply to specialize a small part of it. I need to add a couple of functions (and accessor and modifier) and modify the body of several of the other functions. Is there a better way to accomplish this?
| Impose another level of indirection in the template definitions:
class Base
{
// Generic, non-type-specific code
};
template <typename T> class TypedRealBase : public Base
{
// common code for template
};
template <typename T> class TypedBase : public TypedRealBase<T>
{
// Inherit all the template functionality from TypedRealBase
// nothing more needed here
};
template <> class TypedBase<std::string> : public TypedRealBase<T>
{
// Inherit all the template functionality from TypedRealBase
// string-specific stuff here
}
|
1,429,666 | 1,429,682 | What is the function of the ~ operator? | Unfortunately, search engines have failed me using this query.
For instance:
int foo = ~bar;
| I'm assuming based on your most active tags you're referring to C#, but it's the same NOT operator in C and C++ as well.
From MSDN:
The ~ operator performs a bitwise
complement operation on its operand,
which has the effect of reversing each
bit. Bitwise complement operators are
predefined for int, uint, long, and
ulong.
Example program:
static void Main()
{
int[] values = { 0, 0x111, 0xfffff, 0x8888, 0x22000022};
foreach (int v in values)
{
Console.WriteLine("~0x{0:x8} = 0x{1:x8}", v, ~v);
}
}
Output:
~0x00000000 = 0xffffffff
~0x00000111 = 0xfffffeee
~0x000fffff = 0xfff00000
~0x00008888 = 0xffff7777
~0x22000022 = 0xddffffdd
|
1,429,735 | 1,450,290 | Custom UserControls in C++ | In Native C++, how do you add a usercontrol like in vb .net where you do form.controls.add(controls)
Because for instance, what if I wanted to make a usercontrol class that inherits from panel? How is this done in c++
Thanks
| You will want to use MFC (Microsoft Foundation Classes) for native C++ development. MFC is the original framework for Windows applications, long before .NET.
|
1,429,782 | 1,429,819 | Qt and Sqlite examples | I am looking for some example code using Qt and it's SQL module with Sqlite driver. Main reason I need examples for is that I've prior experience with Qt's database interface and Sqlite has some weird behavior with field types (types are stored per-field, not per-column).
| The Qt 5 SQL examples use SQLite as this does not require a database server. You should be able to go from the supplied examples to your own sample code pretty quickly.
|
1,429,850 | 1,431,221 | Bringing libcurl into a C++ program | I'm trying to pull libcurl into a large C++ project.
However I am having trouble getting it to compile. I see errors coming from ws2def.h, winsock2.h, and ws2tcpip.h
Some of the errors look like this:
error C2061: syntax error : identifier 'iSockaddrLength' ws2def.h 225
error C3646: 'LPSOCKADDR' : unknown override specifier ws2def.h 225
..
error C2061: syntax error : identifier 'dwNumberOfProtocols' winsock2.h 1259
I tried compiling the file that #include "curl.h" in straight C mode, but that did not fix the problem.
| Try including windows.h BEFORE you include winsock2.h or any libcurl headers. Don't ask my why this sometimes works, but it does.
|
1,430,026 | 1,430,038 | What does sizeof(char *) do? | I was reading through the c++ Primer and this code snippet came up and I was wondering what does the sizeof(char *) do and why is it so significant?
char *words[] = {"stately", "plump", "buck", "mulligan"};
// calculate how many elements in words
size_t words_size = sizeof(words)/sizeof(char *);
// use entire array to initialize words2
list<string> words2(words, words + words_size);
Thanks in advance.
| Because otherwise you would get the number of bytes that words array takes up, not the number of elements (char pointers are either 4 or 8 bytes on Intel architectures)
|
1,430,166 | 1,430,285 | Vector Ranges in C++ | Another quick question here, I have this code:
string sa[6] = {
"Fort Sumter", "Manassas", "Perryville",
"Vicksburg", "Meridian", "Chancellorsville" };
vector<string> svec(sa, sa+6);
for (vector<string>::iterator iter = svec.begin(); iter != svec.end(); iter++)
{
std::cout << *iter << std::endl;
}
Why is it that when I do svec(sa, sa+7), the code works but it prints out an empty line after the last word and when I do sa+8 instead it crashes? Because the string array is only 6 elements big, shouldn't it crash at sa+7 also?
Thanks.
| You have an array of only six elements. When you try to access the supposed "seventh" element, you get undefined behavior. Technically, that means anything can happen, but that doesn't seem to me like a very helpful explanation, so let's take a closer look.
That array occupies memory, and when you accessed the element beyond the end, you were reading whatever value happened to occupy that memory. It's possible that that address doesn't belong to your process, but it probably is, and so it's generally safe to read the sizeof(string) bytes that reside in that space.
Your program read from it and, since it was reading it through a string array, it treated that memory as though it were a real string object. (Your program can't tell the difference. It doesn't know any better. It's just trying to carry out your instructions.) Apparently, whatever data happened to be there looked enough like a real string object that your program was able to treat it like one, at least long enough to make a copy of it in the vector and then print its (empty) value. It worked this time, but that doesn't mean it will work every time.
There was no such luck with the data in the "eighth" position of the array. It did not look enough like a valid string object. A string object usually contains a pointer to the character data, along with a length. Maybe the area of the object that would normally represent that pointer didn't contain a valid address for your program. Or maybe the part that represented the length field contained a value far larger than what was available at the address in the pointer.
|
1,430,495 | 1,430,813 | Perform a simple HTTP request using C++ / Boost via a proxy? | I'm quite a newbie with Boost, and my only experience of surfing though a proxy using a library is using .NET (that is really convenient for that purpose). I'm now trying to perform a simple HTTP request through a HTTP proxy.
Is there a tidy way to do it using boost directly?
My proxy use a NTLM authentification.
| No, Boost provides neither an HTTP client nor a way to interface with proxies. You would necessarily have to implement those features yourself.
To be clear, yes, it is possible to implement an HTTP client using Boost.Asio. But implementing a client that can reliably talk through a proxy is significantly more complex, and Asio does not provide any support for that beyond the low-level socket itself. It certainly does not include the framework for performing NTLM authentication, which may prove difficult to get right.
More complex libraries like cURL provide that support.
|
1,430,681 | 1,430,755 | Creating dummy shared object (.so) to depend on other shared objects | I'm trying to create a shared object (.so) that will make it so, by including one shared object with -lboost, I implicitly include all the boost libraries. Here's what I tried:
#!/bin/sh
BOOST_LIBS="-lboost_date_time-gcc43-mt -lboost_filesystem-gcc43-mt"
#truncated for brevity
g++ $BOOST_LIBS -shared -Wl,-soname,libboost.so.1 -o libboost.so.1.0
ln -si libboost.so.1.0 libboost.so.1
ln -si libboost.so.1 libboost.so
After placing all 3 created files (libboost.so libboost.so.1 libboost.so.1.0) in the same directory as all the boost libraries, I tried compiling a test program with it (which depends on -lboost_date_time-gcc43-mt):
g++ -lboost test.cpp
Doing this, I got the same undefined reference message as not having -lboost. Having -lboost_date_time-gcc43-mt works, but that's too wordy :) How do I get -lboost to automatically bring in the other shared libraries?
| You don't. Not really, anyway.
The linker is stripping out all of the symbol dependencies because the .so doesn't use them.
You can get around this, perhaps, by writing a linker script that declares all of the symbols you need as EXTERN() dependencies. But this implies that you'll need to list all of the mangled names for the symbols you need. Not at all worth the effort, IMO.
|
1,430,757 | 1,430,774 | Convert a vector<int> to a string | I have a vector<int> container that has integers (e.g. {1,2,3,4}) and I would like to convert to a string of the form
"1,2,3,4"
What is the cleanest way to do that in C++?
In Python this is how I would do it:
>>> array = [1,2,3,4]
>>> ",".join(map(str,array))
'1,2,3,4'
| Definitely not as elegant as Python, but nothing quite is as elegant as Python in C++.
You could use a stringstream ...
#include <sstream>
//...
std::stringstream ss;
for(size_t i = 0; i < v.size(); ++i)
{
if(i != 0)
ss << ",";
ss << v[i];
}
std::string s = ss.str();
You could also make use of std::for_each instead.
|
1,430,804 | 1,430,924 | looking for a keyboard API | looking for a library for accessing the keyboards functions, key states, etc. the language I'm planning on using is C++
| There is no such possibility in C++ standard. It depends on platform you are going to support. The only portable way is to use portable library.
You could try Qt library, which is good looking and pretty convenient. For console application you could try ncurses.
|
1,430,907 | 1,430,922 | Help in combining two functions in c++ | I am just trying something with somebody else's code.
I have two functions:
int Triangle(Render *render, int numParts, Token *nameList, Pointer *valueList)
int i;
for (i=0; i<numParts; i++)
{
switch (nameList[i])
{
case GZ_NULL_TOKEN:
break;
case GZ_POSITION:
return putTrianglePosition(render, (Coord *)valueList[i]);
break;
}
}
return SUCCESS;
}
int putTrianglePosition(Render *render, Coord vertexList[3]) /*vertexList[3][3:xyz]*/
{
Coord *pv[3];
int i,j;
// sort verts by inc. y and inc. x
pv[0] = &vertexList[0];
pv[1] = &vertexList[1];
pv[2] = &vertexList[2];
for (i=0; i<2; i++)
for (j=i+1; j<3; j++)
{
if ((*pv[i])[1]>(*pv[j])[1] ||
(*pv[i])[1]==(*pv[j])[1] && (*pv[i])[0]>(*pv[j])[0]) {
Coord *tmp;
tmp = pv[i];
pv[i] = pv[j];
pv[j] = tmp;
}
}
;
// all y the same?
if ((*pv[0])[1] == (*pv[2])[1]) {
drawHorizonLine(render, *pv[0], *pv[2]);
return SUCCESS;
}
// assign middle point
Coord mid;
mid[1] = (*pv[1])[1]; // y
float ratio = ((*pv[1])[1] - (*pv[0])[1]) / ((*pv[2])[1] - (*pv[0])[1]);
mid[0] = (*pv[0])[0] + ratio * ((*pv[2])[0] - (*pv[0])[0]); // x
mid[2] = (*pv[0])[2] + ratio * ((*pv[2])[2] - (*pv[0])[2]); // z
if (mid[0]<=(*pv[1])[0]) { // compare X
drawTrapzoid(render, *pv[0], mid, *pv[0], *pv[1]); // upper tri
drawTrapzoid(render, mid, *pv[2], *pv[1], *pv[2]); // lower tri
}else{
drawTrapzoid(render, *pv[0], *pv[1], *pv[0], mid); // upper tri
drawTrapzoid(render, *pv[1], *pv[2], mid, *pv[2]); // lower tri
}
return SUCCESS;
}
I don't want two functions here. I want to copy the putTrianglePosition() function into the Triangle() function.
I tried doing that, but I got a lot of errors.
Can somebody else show me how to do this?
| If you just change the line
return putTrianglePosition(render, (Coord *)valueList[i]);
into:
Coord* vertexList = (Coord*) valueList[i];
followed by the whole body of what's now putTrianglePosition from the opening { to the closing } included, I believe it should just work. If not, please edit your question to add the exact, complete, code as obtained by this edit and the exact, complete error messages you get.
|
1,430,935 | 1,430,977 | How to set different timeouts for each socket that select() monitors? | I am currently using the BSD sockets API. I would like to use the select() function to monitor (a) the listener socket which waits for new connections using accept(), and (b) all the client sockets created via accept() or connect(). I want the listener socket to not have any timeout, and I want each client socket to have a timeout of 120 seconds.
Is this possible using the select() function? It only accepts a single timeout value for all sockets, so my assumption is no. If so, am I doomed to making a server in which each socket runs in blocking mode in its own thread?
| Due to the logic of select() function, you should pass it minimal timeout of your ones. If this minimal timeout is hit, then the corresponding socket is timeouted and you should handle this situation. In other words, sockets with greater timeouts can never timeout, because they just wont' have chance to: the time is calculated starting from the last select() call, not the first one.
Go for threads; you can't do this with a single select().
|
1,431,144 | 1,431,171 | How to output floating point numbers in the original format in C++? | It's a coding practice. I read these numbers as double from a file:
112233 445566
8717829120000 2.4
16000000 1307674.368
10000 2092278988.8
1234567 890123
After some computation, I should output some of them. I want to make them appear just the same as in the file, no filling zeros, no scientific notation, how could I achieve it? Do I have to read in as string then convert them?
Edit: Erm...Do you guys mean that there is actually no way for the program to know how the numbers look like originally?
| If you want the output to be identical to the input, then yes, you need to read them in as strings and store the strings to be output later.
Why? When dealing with floating point numbers, the computer can't represent most decimal fractional parts exactly in binary. So in a number like 2.4, the internal representation won't be exactly 2.4, it will be slightly different. Most of the time, the C/C++ I/O libraries will take such a binary number and print 2.4, but for some numbers, it might print something like 2.40000000001 or 2.399999999.
So, that's why you want to keep the original strings around.
|
1,431,216 | 1,431,241 | What is the difference between PostMessage and AfxBeginThread? | I can acheive the same functionality by both PostMessage and AfxBeginThread ( calling asynchrously )
So where lies the the difference between PostMessage and AfxBeginThread?
| AfxBeginThread starts a whole new thread in your function.
PostMessage is using the main message loop of the process, so if you use PostMessage to do a long operation, you will freeze the message loop, making the GUI non responsive till you finish the operation.
|
1,431,560 | 3,702,932 | How to detect Oracle broken/stalled connection? | In our server/client-setup we're experiencing some weird behaviour. The client is a C/C++-application which uses OCI to connect to an Oracle server (using the OTL library).
Every now and then the DB server dies in a way (yes this is the core issue, but from application-side we're unable to solve it but have to deal with it anyway), that the machine does not respond anymore to new requests/connections but the existing ones, like the Oracle-connections, do not drop or time out. Queries sent to the DB just never return successfully anymore.
What possibilities (if any) are provided by Oracle to detect these stalled connections from the client-application side and recover in a more or less safe way?
| This is a bug in Oracle ( or call it a feature ) till 11.1.0.6 and they said the patch on Oracle 11g release 1 ( patch 11.1.0.7 ) which has the fix. Need to see that.
If it happens you will have to cancel ( kill ) the thread performing this action.
Not good approach though
|
1,431,567 | 1,431,606 | Is it possible to load a NPAPI plugin in Safari (Mac OS X)? | I've got some code that lies in a browser, and wrote C++ plugins for both IE (COM/ActiveX) and firefox (NPAPI).
I now have to get this code work on Mac OS X. I found some input on apple's site, but it's written in Objective C.
I also read about SIMBL, but it seems to deal with Objective C code only, isn't it?
So here are my questions:
Is it possible to code a pure C++ plugin for Safari (re-using my Firefox NPAPI plugin would be great)?
If it's not possible, is there a way to use an objective C plugin as a loader for some C++ code?
I'm a total noob on Mac OS, and don't even have a Mac Box to mess around, hence the very generic question.
Thanks
| The NPAPI plugin mechanism is the standard mechanism for browser plugins on MacOS (and linux -- everything other than IE really) -- if you use the NPAPI your plugin will work on Safari, Firefox, and Opera. They will also work in both 32 and 64-bit Safari. Assuming your code makes no assumptions about what browser it's running in the same NPAPI-code should work in all browsers (i've seen "NPAPI" plugins that dynamically resolve XUL related functions in the blind faith that NPAPI is used only by Firefox, despite it being the standard plugin format for more or less every non-IE browser).
"Plugins" like SIMBL misuse MacOS APIs designed for a distinct (but important) purpose to arbitrarily inject their own code into the Safari address space -- when people use these (being mislead into believing it's safe) Safari becomes substantially less stable, and frequently stops working after major updates (in an extreme case the Leopard "blue screen of death" was because of logitech using APE to do something similar to SIMBL).
|
1,431,598 | 1,431,642 | BSTR and SysAllockStringByteLen() in C++ | I'm new to C++, so this may be a noobish question; I have the following function:
#define SAFECOPYLEN(dest, src, maxlen) \
{ \
strncpy_s(dest, maxlen, src, _TRUNCATE); \
dest[maxlen-1] = '\0'; \
}
short _stdcall CreateCustomer(char* AccountNo)
{
char tmpAccountNumber[9];
SAFECOPYLEN(tmpAccountNumber, AccountNo, 9);
BSTR strAccountNumber = SysAllocStringByteLen(tmpAccountNUmber, 9);
//Continue with other stuff here.
}
When I debug through this code, I pass in the account number "A101683" for example. When it does the SysAllocStringByteLen() part, the account number becomes a combination of Chinese symbols...
Anyone that can shed some light on this?
| SysAllocStringByteLen is meant for when you are creating a BSTR containing binary data, not actual strings - no ANSI to unicode conversion is performed. This explains why the debugger shows the string as containing apparently chinese symbols, it is trying to interpret the ANSI string copied into the BSTR as unicode. You should probably use SysAllocString instead - this will convert the string correctly to unicode you must pass it a unicode string. If you are working with actual text, this is the function you should be using.
|
1,432,336 | 1,432,393 | how to find a window's SW_SHOW/SW_HIDE status | I am trying to determine a window control's visibility that has been hidden or enabled with CWnd::ShowWindow(). (or ::ShowWindow(hWnd,nCmdShow))
I cannot simply use ::IsWindowVisible(hWnd) as the control is on a tab sheet, which may itself be switched out, causing IsWindowVisible to return FALSE.
Is there a way to get the SW_SHOW/HIDE (or others) window status or do I need to use the retun value of ShowWindow() and reset accordingly?
edit:
as the control is enabled (or disabled) to show, but may not be currently visible, as the tab is switched ot, I would think that it's SW_SHOW status would remain the same, even if the window itself is not actually switched in. If I'm unrealistic in my expectations that that's fine.
So really I'm looking for 'can this window/control be shown'
| Use GetWindowPlacement. It fills WINDOWPLACEMENT structure, which has field showCmd.
showCmd
Specifies the current show state of the window. This member can be one of the following values.
|
1,432,419 | 1,432,446 | How can I code in C++ with the same indentation style both in Vi and Emacs? | How can two developers work on a same C++ code base such that they can work transparently ?
Is there any common indentation style for C++ code such that once it is established, the two developers can produce code with the same indentation level.
I have found Emacs very aggressive for Indentation, it tries to force its way, while Vi is pretty forgiving. But the emacs styles(mixed tabs and spaces) are not that much friendly to Vim.
| Get Emacs to do what you want.
From my ~/.emacs file:
(defun my-c-mode-common-hook ()
(local-set-key "\C-h" 'backward-delete-char)
;; this will make sure spaces are used instead of tabs
(setq tab-width 4 indent-tabs-mode nil)
(setq indent-tabs-mode 'nil)
(setq c-basic-offset 4)
(c-set-offset 'substatement-open 0)
(c-set-offset 'statement-case-open 0)
(c-set-offset 'case-label 0)
(c-set-offset 'brace-list-open 0)
)
(add-hook 'c-mode-hook 'my-c-mode-common-hook)
(add-hook 'c++-mode-hook 'my-c-mode-common-hook)
(add-hook 'perl-mode-hook 'my-c-mode-common-hook)
(add-hook 'cperl-mode-hook 'my-c-mode-common-hook)
(add-hook 'emacs-lisp-mode-hook 'my-c-mode-common-hook)
(add-hook 'nroff-mode-hook 'my-c-mode-common-hook)
(add-hook 'tcl-mode-hook 'my-c-mode-common-hook)
(add-hook 'makefile-mode-hook 'my-c-mode-common-hook)
|
1,432,777 | 1,432,814 | Using shared libraries vs a single executable | My colleague claims that we should dissect our C++ application (C++, Linux) into shared libraries to improve code modularity, testability and reuse.
From my point of view it's a burden since the code we write does not need to be shared between applications on the same machine neither to be dynamically loaded or unloaded and we can simply link a monolithic executable application.
Furthermore, wrapping C++ classes with C-function interfaces IMHO makes it uglier.
I also think single-file application will be much more easy to upgrade remotely at a customer's site.
Should dynamic libraries be used when there is no need to share binary code between applications and no dynamic code loading?
| I'd say that splitting code into shared libraries to improve without having any immediate goal in mind is a sign of a buzzwords-infested development environment. It is better to write code that can easily be split at some point.
But why would you need to wrap C++ classes into C-function interfaces, except for, maybe, for object creation?
Also, splitting into shared libraries here sounds like an interpreted language mindset. In compiled languages you try not to postpone till runtime what you can do at compile-time. Unnecessary dynamic linking is exactly the case.
|
1,433,278 | 1,433,727 | How to write a generic "getData" function? | I have a class, say, "CDownloader", that reads some XML data and provides access by node names. It features some getter functions, something like this:
BOOL CDownloader::getInteger ( const CString &name, int *Value );
BOOL CDownloader::getImage ( const CString &name, BOOL NeedCache, CImage *Image );
BOOL CDownloader::getFont ( const CString &name, CFont *Font );
I cannot change CDownloader class. Instead I would like to write some functions, that downloads items by using a bool flag, not an actual name. Something like this:
BOOL DownloadFont( const CDownloader &Loader, bool Flag, CFont *Font )
{
if (Flag) {
// first try the "name_1"
if ( Loader.getFont("name_1", Font) ) return TRUE;
}
// if "name_1" fails or disabled by flag, try "name_2"
return Loader.getFont("name_2", Font);
}
I can write Download(Font|Integer|Image) functions separatly, but this will result in code duplication. My idea is to write a template, but I am still at a loss: how can I determine what method should I call from CDownloader class? To specialize template for each data type means to stuck into code duplication again. To pass getter funciton as a "pointer-to-function" parameter? But the getter signatures differ in CDownloader...
Summing it up, the question is: is it possible to write a generic wrapper around CDownloader or do I have to duplicate code for each "get***" function? Thanks in advance!
| As long as you have three differently named functions and need to pick one depending on the type, at some point you have to have either an overload or some traits class to picks the right one. I don't think there's a way around that. However, since the call to one of these function is the only thing that needs this, if there is more code to these DownloadXXX() functions than you showed us, then it might still make sense.
Here's a sketch of what you might do using the overload alternative. First you need three overloads of the same function each calling one of the three different functions. The additional BOOL parameter for one of the functions somewhat wreaks havoc with the genericity, but I got around that by having all functions accept that BOOL, but two of them ignoring it:
inline BOOL Load(CDownloader& Loader, const CString &name, int &Value, BOOL)
{return Loader.getInteger(name, &Value);
inline BOOL Load(CDownloader& Loader, const CString &name, CImage &Value, BOOL NeedCache)
{return Loader.getImage(name, NeedCache, &value);
inline BOOL Load(CDownloader& Loader, const CString &name, CFont &Value, BOOL)
{return Loader.getFont(name, &Font);
Now you can go and write that generic function. You need to decide what to do about that BOOL, though:
template< typename T >
BOOL Download(const CDownloader &Loader, bool Flag, T &Obj, BOOL NeedCache /*= true*/)
{
if (Flag) {
if ( Load(Loader, "name_1", Obj, NeedCache) ) return TRUE;
}
return Load(Loader, "name_1", Obj, NeedCache);
}
However, as you can see, this is really only worth the hassle if that Download function is a lot more complicated than in your sample code. Otherwise the added complexity easily outweighs the gains that the increased genericity brings.
|
1,433,345 | 1,433,352 | or is not valid C++ : why does this code compile? | Here is a very simple C++ application I made with QtCreator :
int main(int argc, char *argv[])
{
int a = 1;
int b = 2;
if (a < 1 or b > 3)
{
return 1;
}
return 0;
}
To me, this is not valid C++, as the keyword or is not a reserved keyword.
But if I compile and run it, it works fine without any warnings ! The exit code is 0 and if I change b = 4, the exit code is 1 !
I'm not including anything to make sure there is no hidden define.
This is really strange to me. Is this something Qt is defining ? I didn't find anything in the documentation regarding that.
| According to Wikipedia:
C++ defines keywords to act as aliases
for a number of symbols that function
as operators: and (&&), bitand (&),
and_eq (&=), or (||), bitor (|), or_eq
(|=), xor (^), xor_eq (^=), not (!),
not_eq (!=), compl (~).
As MadKeithV points out, these replacements came from C's iso646.h, and were included in ISO C++ as operator keywords. The Wikipedia article for iso646.h says that the reason for these keywords was indeed for international and other non-QWERTY keyboards that might not have had easy access to the symbols.
|
1,433,389 | 2,590,365 | How to integrate the Qt libraries in SparxSystems Enterprise Architect | I like to know how one can integrate the Qt libraries into an Enterprise Architect project. I do not know if it is possible at all but I tried it with partial success:
I added a new package to my project tried to import qt through Context Menu / Code Engineering / Import Source Directory and started with the directory src/corelib/kernel. After adding quite a lot qt preprocessor macros to the EAs preprocessor macros list some classes were correctly imported but not all. E.g. I get errors on the Q_SIGNALS macro although I added it to EAs list.
Did anybody here tried that with success? And when yes can you give me some hints how to do that?
Thanks!
| I turned to support@sparxsystems.com.au , their answer:
"Thank you for your enquiry.
No, unfortunately there is no easy way to integrate Enterprise Architect with Qt at this time.
With most frameworks, we typically recommend reverse engineering the framework into Enterprise Architect, allowing you to reference the classes / interfaces defined by the framework.
It sounds like the user in the link that you provided has already attempted this, but had difficulties due to the large number of Preprocessor macros used in this code.
Sorry we could not be of more assistance."
Maybe I can get your import package ?
|
1,433,629 | 1,433,660 | How to stop a new form from using namespace System::Collections | If I create a new form called myForm, the top of myForm.h looks like this:
#pragma once
using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections; //<<<< THIS ONE
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
None of these are even needed, because the wonderful forms designer always fully-qualifies its objects.
The one marked with THIS ONE is particularly annoying because it breaks my build. This is because I use the generic form of IList all over the place - I love it so much that I put it in stdafx.h, like this:
using System::Collections::Generic::IList;
So then if I want to use myForm from any other file where I happen to use IList, like this:
#include "StdAfx.h"
#include "ABC.h"
#include "myForm.h"
ABC::ABC()
{
IList<int>^ myList;
...
}
then it fails to compile:
1>.\ABC.cpp(7) : error C2872: 'IList' : ambiguous symbol
1> could be 'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : System::Collections::Generic::IList'
1> or 'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : System::Collections::IList'
1>.\ABC.cpp(7) : error C2872: 'IList' : ambiguous symbol
1> could be 'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : System::Collections::Generic::IList'
1> or 'c:\windows\microsoft.net\framework\v2.0.50727\mscorlib.dll : System::Collections::IList'
So, how can I stop a new form from adding all these useless and destructive usings?
| You can change the default templates that Visual Studio uses by editing the zip files in the ItemTemplates directory for the specific language that you use.
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033
is where the C# templates are. I'm assuming the C++ templates would be in a similar directory but I don't have a VS instance installed with C++ handy.
|
1,433,632 | 1,433,643 | Is there a Findbugs and / or PMD equivalent for C/C++? | I was recently asked about alternatives to Coverity Prevent for a code base that includes both C/C++ and Java. Obviously, on the Java side, the free tools available include Findbugs (compiled code analysis) and PMD (static code analysis). They are very powerful, especially when you start investigating integration with IDEs (which, again, are free).
However, things are dicey when you start moving into the C/C++ realm with the various compilers, architectures, etc.
I have proposed a variety of tools for the Java side, including both Findbugs and PMD. What I am looking for is the best option for the C/C++ side when considered using the following metrics:
Price: free is better but can be beaten by better value. However, pricing models that charge per line of code are horrifying.
Feature set: how does this tool make my life better? In what ways does it detect my mistakes before I check them in, before we ship the code, etc.?
Usability: can I use the tool at my desk? Can I share the reports and / or findings? Can I integrate the tool with Fogbugz (which we use in my group)? Can I integrate the tool into CruiseControl (or the equivalent)?
The ultimate tool would be something that is as useful and usable as a combination of Findbugs and PMD with identical feature set, all for zero dollars per seat.
| The two that come to mind are Splint for C and Cppcheck for C++.
If you want to look for more options, this function of these tools is "static code analysis". That might help you find more tools for C and/or C++. Also, you might be interested in the answer to the question "What open source C++ static analysis tools are available?"
|
1,433,850 | 1,434,105 | QFontMetrics::leading() returns 0 | Why next function returns 0 ?
(My environment is: Windows Vista, vc++9, Qt4.5)
int func()
{
QPushButton button("Blah blah");
QFontMetrics fm = button.fontMetrics();
return fm.leading();
}
Calling to "fm.height()" returns reasonable results (16 px in my case).
Calling to "fm.lineSpacing()" returns same result as "fm.height()".
Calling to "fm.boundingRect(QRect(), 0, "first line\n second line\n third line").height();" returns 16 * 3, i.e. again inter-line spacing not included in result...
Is this incorrect usage from my side or something other ?
| According to the docs lineSpacing() is always equal to height() + leading()
height() is always equal to ascent()+descent()+1 (the 1 is for the base line).
From here leading is "the space vertically between lines of text - name comes from the physical piece of lead that used to be used in mechanical printing process to separate lines of text"
So, what font are you using, and does it use a zero size leading?
|
1,433,855 | 1,433,896 | Is there an easy way to find two values that, when multiplied together, produce an exact bit pattern? | For testing purposes, I need to find two 64-bit integer values that exactly multiply to a 128-bit intermediate value with a specific bit pattern. Obviously, I can generate the desired intermediate value and divide by random values until I find a combination that works, but is there a more efficient way?
| This problem sounds like integer factorisation. No fast algorithms are known unfortunately, but from glancing at that Wikipedia page it seems there are some (possibly tricky) algorithms that are faster than trial division.
|
1,434,343 | 1,434,438 | How do i sort objects? | I've created a class and created an array of objects under that class and filled it all up with data. Now i want to sort the entire array by a specific member of that class, how do I do this using the stable_sort() function?
Edit: Ok, i have this right now,
class sortContiner
{
public:
double position;
int key;
double offsetXposition;
double offsetYposition;
int origXposition;
int origYposition;
};
I've declared the array like this:
sortContiner * sortList = new sortContiner [length];
Now i want want to sort it by the sortList .position member using stable_sort() like this:
stable_sort(sortList, sortList + length, ????);
What is the comparator function supposed to look like?
| You need iterators into your array and some sorting criterion. Let's start with the iterators:
You will need a begin iterator and an end iterator. The begin iterator needs to point to the first element, the end iterator needs to point behind the last element. Pointers are perfect iterators. An array is implicitly convertible into a pointer to its first element, so you have a begin iterator. Add the number of elements in the array to it and you have an end iterator. The number of elements in the array can be obtained by dividing the size (number of bytes) of the array by the size of a single element. Putting it all together:
foo array[10];
const std::size_t array_size = sizeof(array)/sizeof(array[0]);
const int* array_begin = array; // implicit conversion
const int* array_end = begin + array_size;
Now you need something for the algorithm to decide which of two given objects of your class is the smaller one. An easy way to do this would be by overloading operator< for your class:
bool operator<(const foo& lhs, const foo& rhs)
{
// compares using foo's bar
return lhs.get_bar() < rhs.get_bar();
}
Now you can sort your array:
std::stable_sort( array_begin, array_end );
If the sorting criterion isn't as fix (say, sometimes you want to sort based on foo's bar data, sometimes based on its wrgly data), you can pass different sorting criteria to the sort algorithm as an optional third parameter. Sorting criteria should be function-like entities. That can be functions or function objects. The latter provide inlining, which is why they are usually better. Here's both:
bool compare_by_bar(const food& lhs, const foo& rhs)
{
return lhs.get_bar() < rhs.get_bar();
}
struct wrgly_comparator {
bool operator()(const food& lhs, const foo& rhs) const
{
return lhs.get_wrgly() < rhs.get_wrgly();
}
};
This is how you use them:
std::stable_sort( array_begin, array_end, compare_by_bar );
wrgly_comparator wc;
std::stable_sort( array_begin, array_end, wc );
You can also create the comparator on the fly:
std::stable_sort( array_begin, array_end, wrgly_comparator() );
Edit: Here's a few more hints based on your expanded question:
sortContainer * sortList = new sortContiner [length]; will create a dynamic array on the heap. In C++, there is no garbage collection and you are responsible for cleaning up on the heap after yourself (in this case by invoking delete[] sortList;). This is notoriously hard to do for novices and error-prone even for seasoned programmers. There's a very good chance that what you want is an automatic array: sortContainer sortList[length]; on the stack.
The identifier sortContainer tells me that the thing is a container. However, it's the type of the items to be put into the container. Be more careful by picking identifiers. Proper naming goes a long way towards readable and maintainable code.
|
1,434,437 | 1,434,482 | How do you disassemble an overloaded operator in gdb? | If I have something like bool operator ==(const uint128& x, const uint128& y); how can I get gdb to disassemble it?
| (gdb) p 'operator==(uint128 const&,uint128 const&)'
$1 = {bool (const uint128 &, const uint128 &)} 0x401040 <operator==(uint128 const&, uint128 const&)>
(gdb) disassemble $1
Dump of assembler code for function _ZeqRK7uint128S1_:
0x00401040 <_ZeqRK7uint128S1_+0>: push %ebp
... (elided)
0x00401066 <_ZeqRK7uint128S1_+38>: ret
End of assembler dump.
(gdb)
|
1,434,511 | 1,476,192 | How do I convert double to string using only math.h? | I am trying to convert a double to a string in a native NT application, i.e. an application that only depends on ntdll.dll. Unfortunately, ntdll's version of vsnprintf does not support %f et al., forcing me to implement the conversion on my own.
The aforementioned ntdll.dll exports only a few of the math.h functions (floor, ceil, log, pow, ...). However, I am reasonably sure that I can implement any of the unavailable math.h functions if necessary.
There is an implementation of floating point conversion in GNU's libc, but the code is extremely dense and difficult to comprehent (the GNU indentation style does not help here).
I've already implemented the conversion by normalizing the number (i.e. multiplying/dividing the number by 10 until it's in the interval [1, 10)) and then generating each digit by cutting the integral part off with modf and multiplying the fractional part by 10. This works, but there is a loss of precision (only the first 15 digits are correct). The loss of precision is, of course, inherent to the algorithm.
I'd settle with 17 digits, but an algorithm that would be able to generate an arbitrary number of digits correctly would be preferred.
Could you please suggest an algorithm or point me to a good resource?
| After a lot of research, I found a paper titled Printing Floating-Point Numbers Quickly and Accurately. It uses exact rational arithmetic to avoid precision loss. It cites a little older paper: How to Print Floating-Point Numbers Accurately, which however seems to require ACM subscription to access.
Since the former paper was reprinted in 2006, I am inclined to believe that it is still current. The exact rational arithmetic (which requires dynamic allocation) seems to be a necessary evil.
|
1,435,004 | 1,435,059 | variable-size type declared outside of any function | when declaring the two dimensional array
int random[height][width];
and then using it in a function
void populate(int random[height][width], int x, int y)
gives the error variable-size type declared outside of any function.
I know I'm doing something wrong, and that its something small. I just have a bad memory...
| I'm going to step up right now and tell you that multidimensional arrays are not worth the brain effort in C or C++. You're much better off using single-dimensional arrays (or, better yet, standard containers) and writing an indexing function:
inline int index (int x, int y)
{
return x + y * width;
}
Now for your problem. C++ does not support C99 variable-length arrays. The compiler must know, at compile time, the size of the array. The following, for example, won't work.
int dim = 4;
int ar[dim];
If dim were const, it would work because the compiler would be able to tell exactly how wide ar should be (because the value of dim wouldn't change). This is probably the problem you're encountering.
If you want to be able to change the size at compile-time, you'll need to do something more difficult, like write a templated reference. You can't use a pointer for multidimensional arrays because of the way they are laid out in C/C++. A templated example might look like the following aberration:
template <int Width, int Height>
void populate(int (&(&random)[Width])[Height], int x, int y);
This is ugly.
For run-time, you'll need to use new to allocate data, or use a container type.
|
1,435,541 | 1,435,568 | is this function reentrant? | void reverse_string(char* string, int str_size) {
char tmp;
int i = 0;
int j = str_size - 1;
while (i < j) {
tmp = string[i];
string[i] = string[j];
string[j] = tmp;
++i;
--j;
}
}
I think this function is reentrant, since it doesn't use any global variable. It only modifies the arguments.
My question is:
is this function reentrant?
if it is, is my argument good enough?
thanks in advance
| Yes, this is a reentrant function. Reentrant functions are defined as those that can be called whilst they are themselves executing (either due to recursion, or concurrency). In this case, recursion is moot, and you are concurrently safe (assuming differing parameters).
Your argument is fine - there's no global or shared state being accessed either explicitly or implicitly, so reentrancy is ensured. This is a combination of both your explicit code and the semantics of C. Other languages and APIs may not have this property.
Edit: On double checking, the ISO C standard doesn't seem to force the thread safety of strlen. As such, there is a tiny possibility that you could be using a C standard library with a non-thread safe strlen and as such, inherit non-reentrancy from it.
|
1,435,766 | 1,435,782 | C Variable Scope Specific Question | Here is a particular scenario that I have been unclear about (in terms of scope) for a long time.
consider the code
#include <stdio.h>
typedef struct _t_t{
int x;
int y;
} t_t;
typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;
void test(s_t & s){
t_t x = {502, 100};
s.t = x;
}
int main(){
s_t s;
test(s);
printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}
the output is
value is 502, 100
What is a bit confusing to me is the following. The declaration
t_t x
is declared in the scope of the function test. So from what I have read about C programming, it should be garbage out of this scope. Yet it returns a correct result. Is it because the "=" on the line
s.t = x;
copies the values of x into s.t?
edit---
after some experimentation
#include <stdio.h>
typedef struct _t_t{
int x;
int y;
} t_t;
typedef struct _s_t{
int a;
int b;
t_t t;
}s_t;
void test(s_t & s){
t_t x = {502, 100};
t_t * pt = &(s.t);
pt = &x;
}
int main(){
s_t s;
test(s);
printf("value is %d, %d\n", s.t.x, s.t.y);
return 0;
}
actually outputs
value is 134513915, 7446516
as expected.
|
Is it because the "=" on the line s.t = x; copies the values of x into s.t?
Yes.
By the way, this is C++. You've passed the "s" local to main as a reference to the function, which modifies it. Because it's a reference, and not a copy, it affects the caller's "s".
|
1,435,911 | 1,435,925 | C++ Process Checking | I'm creating a task-manager type application in C++, and I'm currently using:
`
void MyFrame::ProcChecker(bool showmessage=false){
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
PROCESSENTRY32 *processInfo = new PROCESSENTRY32;
processInfo->dwSize = sizeof(PROCESSENTRY32);
int index = 0;
string procList = "";
while(Process32Next(hSnapShot,processInfo) != false){
HANDLE modSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, processInfo->th32ProcessID);
MODULEENTRY32 *moduleInfo = new MODULEENTRY32;
moduleInfo->dwSize = sizeof(MODULEENTRY32);
index++;
stringstream indexstr;
indexstr << index;
Module32First(modSnapShot,moduleInfo);
procList = procList + indexstr.str() + ": " + wxString((string)processInfo->szExeFile) + "[" + wxString((string)moduleInfo->szExePath) + "]" + "\r\n";
}
if(showmessage){
MessageBox(NULL,procList.c_str(),"Processes",false);
}
}
`
The problem I'm coming across is that a lot of the processes have restricted access, and I think I need to somehow get higher privileges that the app currently has. I think it has something to do with me needing to create a kernel-mode driver. If someone could point me in the right direction it'd be greatly appreciated! :)
I'm just starting out in C++ so I understand that my current code is probably horrendous :P
| In order to query information about processes that you don't directly have access to, you need to have SeDebugPrivilege*. If this is on Vista, you most likely are running as standard user and you don't have that privilege. You need to run your program as administrator (note that TaskManager has to run as admin to get information on all processes.)
If you are running as admin, the problem is most likely that SeDebugPrivilege is not enabled by default. This is because SeDebugPrivilege is a very dangerous privilege to have all the time. You can enable SeDebugPrivilege by calling the AdjustTokenPrivileges API. This KB article shows how - you can probably find other references on the web.
*SeDebugPrivilege, among other things, is an override to OpenProcess and OpenThread. Toolhelp has to call these functions internally to query information on processes and threads in the system. These functions will check the ACL on the object to see if you have access. A user typically only has been granted permission to processes that they've created. If the calling code has SeDebugPrivilege in its token, OpenProcess and OpenThread will succeed even if the code hasn't been granted access by the ACL.
|
1,436,020 | 1,436,038 | What's the difference between deque and list STL containers? | What is the difference between the two? I mean the methods are all the same. So, for a user, they work identically.
Is that correct??
| From the (dated but still very useful) SGI STL summary of deque:
A deque is very much like a vector: like vector, it is a sequence that supports random access to elements, constant time insertion and removal of elements at the end of the sequence, and linear time insertion and removal of elements in the middle.
The main way in which deque differs from vector is that deque also supports constant time insertion and removal of elements at the beginning of the sequence. Additionally, deque does not have any member functions analogous to vector's capacity() and reserve(), and does not provide any of the guarantees on iterator validity that are associated with those member functions.
Here's the summary on list from the same site:
A list is a doubly linked list. That is, it is a Sequence that supports both forward and backward traversal, and (amortized) constant time insertion and removal of elements at the beginning or the end, or in the middle. Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed. The ordering of iterators may be changed (that is, list::iterator might have a different predecessor or successor after a list operation than it did before), but the iterators themselves will not be invalidated or made to point to different elements unless that invalidation or mutation is explicit.
In summary the containers may have shared routines but the time guarantees for those routines differ from container to container. This is very important when considering which of these containers to use for a task: taking into account how the container will be most frequently used (e.g., more for searching than for insertion/deletion) goes a long way in directing you to the right container.
|
1,436,219 | 1,436,248 | structure initialization | static struct Args {
char* arg1;
unsigned arg2;
unsigned arg3;
char* arg4;
} arg;
My program saves command line args to a structure. Sometime all of the members are set... sometimes only a couple of them.
In the case where only arg1 is set, what would the best practice be to do with the rest of the members?
Thanks.
| I would just memset the whole thing. Any 0 value or null pointer are assumed not set.
For example,
memset(&arg, 0, sizeof(arg));
...
if (arg.arg2 == 0) // Not set
|
1,436,271 | 1,436,303 | In MFC program, how to pass data between different dialog? | In web development, when we want to pass something between different pages, we might use the Session to save the data. But in MFC, what can we use to store these things?
Thanks!
| Typical MFC Applications will have a Document-View-Frame architecture. Data is stored in the Document object, and accessed globally. You can access it anywhere via AfxGetMainWnd().
AfxGetApp() will also get you a pointer to your main application, which is another good spot to store data if you're not using a Document View architecture. If there is a lot of data, you can construct a class to hold the data, then add an instance as a member variable to the CWinApp in your project.
Another option, which I don't recommend but I have seen, is to have the dialogs themselves as member variables in the CWinApp, and then each dialog can reference the other. Basically, the user clicks 'ok', but then the dialog disappears, but is not deleted. This means all the data they entered is still accessable via the dialog variable.
|
1,436,300 | 1,436,332 | in mfc how to implement dockable dialog? | i am working on a Dialog based application in MFC, I need something just like visual studio's left panel, right panel, bottom panelwhich have a close button to close the panel.
Anyone know how to implement this ?
| Try the MFC Feature Pack.
|
1,436,326 | 1,436,531 | cmath Errors when using FLTK | For some reason, whenever I add the FLTK directory to my include path, I get a bunch of errors from cmath. I am using GCC version 4.2. Here is a sample program and the build output:
main.cpp
#include <cmath>
int main()
{
return 0;
}
**** Build of configuration Debug for project CMath Test ****
make -k all
Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -I/usr/include/FL -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"main.d" -MT"main.d" -o"main.o" "../main.cpp"
In file included from ../main.cpp:1:
/usr/include/c++/4.2/cmath:100: error: ‘::acos’ has not been declared
/usr/include/c++/4.2/cmath:116: error: ‘::asin’ has not been declared
/usr/include/c++/4.2/cmath:132: error: ‘::atan’ has not been declared
/usr/include/c++/4.2/cmath:148: error: ‘::atan2’ has not been declared
/usr/include/c++/4.2/cmath:165: error: ‘::ceil’ has not been declared
/usr/include/c++/4.2/cmath:181: error: ‘::cos’ has not been declared
/usr/include/c++/4.2/cmath:197: error: ‘::cosh’ has not been declared
/usr/include/c++/4.2/cmath:213: error: ‘::exp’ has not been declared
/usr/include/c++/4.2/cmath:229: error: ‘::fabs’ has not been declared
/usr/include/c++/4.2/cmath:245: error: ‘::floor’ has not been declared
/usr/include/c++/4.2/cmath:261: error: ‘::fmod’ has not been declared
/usr/include/c++/4.2/cmath:271: error: ‘::frexp’ has not been declared
/usr/include/c++/4.2/cmath:287: error: ‘::ldexp’ has not been declared
/usr/include/c++/4.2/cmath:303: error: ‘::log’ has not been declared
/usr/include/c++/4.2/cmath:319: error: ‘::log10’ has not been declared
/usr/include/c++/4.2/cmath:335: error: ‘::modf’ has not been declared
/usr/include/c++/4.2/cmath:354: error: ‘::pow’ has not been declared
/usr/include/c++/4.2/cmath:376: error: ‘::sin’ has not been declared
/usr/include/c++/4.2/cmath:392: error: ‘::sinh’ has not been declared
/usr/include/c++/4.2/cmath:408: error: ‘::sqrt’ has not been declared
/usr/include/c++/4.2/cmath:424: error: ‘::tan’ has not been declared
/usr/include/c++/4.2/cmath:440: error: ‘::tanh’ has not been declared
make: *** [main.o] Error 1
make: Target `all' not remade because of errors.
Build complete for project CMath Test
g++ -v
Using built-in specs.
Target: x86_64-linux-gnu
Configured with: ../src/configure -v --enable-languages=c,c++,fortran,objc,obj-c++,treelang --prefix=/usr --enable-shared --with-system-zlib --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --enable-nls --with-gxx-include-dir=/usr/include/c++/4.2 --program-suffix=-4.2 --enable-clocale=gnu --enable-libstdcxx-debug --enable-objc-gc --enable-mpfr --enable-checking=release --build=x86_64-linux-gnu --host=x86_64-linux-gnu --target=x86_64-linux-gnu
Thread model: posix
gcc version 4.2.3 (Ubuntu 4.2.3-2ubuntu7)
Can anyone tell me what's wrong? Thanks!
| Pure speculation, but is there a 'math.h' header in /usr/include/FL by any chance? Or is there some other header in there that is included by cmath?
[...a little time passes...]
Still speculation, but given the comment "Yes, there is - what's going on?", I will speculate that there is no 'math.h' header in /usr/include - because if there was GCC (G++) would normally pick up from the same place as ''. So, I would check the installed software - headers under /usr/include - for sanity.
[...a little more time passes...]
Ah, well...it seems that the problem is that there are two math.h headers, and the compiler is picking the wrong one.
There are a couple of tricks you can try. First, perhaps, is to check the documentation of FLTK: are you supposed to use <FL/header.h> or just <header.h> to access its headers? If you are supposed to use the version with the sub-directory, then you don't need to add -I/usr/include/FL to the compilation command line; the references to <FL/header.h> will be handled automatically (by looking for /usr/include/FL/header.h when scanning /usr/include - just like <sys/types.h> is found under /usr/include).
If that isn't part of the answer, then you can try using the flags:
-I/usr/include -I/usr/include/FL
This says "search /usr/include before searching /usr/include/FL (and then search /usr/include again after searching /usr/include/FL)". That should solve the immediate problem - however it might cause trouble with whatever is supposed to include /usr/include/FL/math.h. This is definitely not as reliable as the first option.
|
1,436,351 | 1,436,751 | How many threads does it take to make them a bad choice? | I have to write a not-so-large program in C++, using boost::thread.
The problem at hand, is to process a large (maybe thousands or tens of thousands. Hundreds and millons are a possibility as well) number of (possibly) large files. Each file is independent from another, and they all reside in the same directory. I´m thinking of using the multi threaded aproach, but the question is, how many threads should I use? I mean, what order of magnitude? 10, 500, 12400?
There are some synchronization issues, each thread should return a struct of values (which are accumulated for each file), and those are added to a "global" struct to get the overall data. I realize that some threads could "get hungry" because of synchronization, but if it's only an add operation, does it matter?
I was thinking of
for(each file f in directory){
if (N < max_threads)//N is a static variable controlling amount of threads
thread_process(f)
else
sleep()
}
This is in HP - UX, but I won't be able to test it often, since it's a remote and quite unaccessible server.
| According to Amdahl's law that was discussed by Herb Sutter in his article:
Some amount of a program's processing is fully "O(N)" parallelizable (call this portion p), and only that portion can scale directly on machines having more and more processor cores. The rest of the program's work is "O(1)" sequential (s). [1,2] Assuming perfect use of all available cores and no parallelization overhead, Amdahl's Law says that the best possible speedup of that program workload on a machine with N cores is given by
In your case I/O operations could take most of the time, as well as synchronization issues. You could count time that will be spend in blocking(?) slow I/O operations and approximately find number of threads that will be suitable for your task.
Full list of concurrency related articles by Herb Sutter could be found here.
|
1,436,374 | 1,438,819 | getpeername() doesn't work with connections to localhost | EDIT: Restating the problem, if I am listening to port 54321 and a local process listening to port 12345 connects to me, creating socket s, how do I actually find the port it is listening on?
sockaddr_in addr;
int len = sizeof(addr);
getpeername(s, (sockaddr*)&addr, &len);
cout << string(inet_ntoa(addr.sin_addr)) << ":" << ntohs(addr.sin_port) << endl;
Shouldn't the output be 127.0.0.1:12345? Instead I get 127.0.0.1:62305, or some other arbitrary port number. Is this an error on my part, or is it supposed to be this way?
| It looks like you have two processes listening on two ports - that's two listening sockets independent of each other. Then you create a third, client, socket in one of the processes and connect to the other one. That third socket gets an ephemeral port assigned to it by TCP stack (62305 in your case). So the connection is represented by the tuple {source ip, source port, target ip, target port} - {127.0.0.1,62305,127.0.0.1,54321} here. This connection has absolutely nothing to do with any listening sockets the connecting process might have. You have to explicitly design your application to communicate port numbers among peers if you need to know them. If you just want to know what process has what sockets, there's always lsof.
|
1,436,617 | 1,436,630 | Is there any relation between Virtual destructor and Vtable | If we write virtual function it adds a vtable in object of that class. Is it true for virtual destructor too ? Is vtable used to implement virtualness of destructor
| Yes. Some information is needed to allow the right destructor to be called when the object is deleted via a base class pointer. Whether that information is a small integer index or a pointer doesn't matter (although dynamic linkage probably implies that it's a pointer). Naturally, that information needs to be adjacent to (inside) the pointed-to object.
Adding a virtual method of any kind, including a destructor, to a class that had none before, will increase sizeof(class).
|
1,436,737 | 1,437,036 | What's your deep comprehension of pointer,reference and Handle in C,C++ and Java? | What's your deep comprehension of pointer,reference and Handle in C,C++ and Java?
We usually think about the pointer,reference and Handle on the specify language level, it's easy to make confusion by the newbie like me.
Actually all those concept in java, just a encapsulation of pointer.
All pointer just a encapsulation of main memory addresses .
So all of those ,just a encapsulation wiles.
all above, it's my personal glimpse. And what's your comprehension ?
welcome to share with me.
| Each language has differences to this respect. In C there are only pointers that are variables holding a memory address. In C you can use pointer arithmetic to move through memory, if you have an array, you can get a pointer to the first element and navigate the memory by incrementing the pointer.
Java references are similar to pointers in that they refer to a location in memory, but you cannot use pointer arithmetic on them. Only assignments are allowed. Note that the reference is not the object, but a way of accessing an object. This can be seen in argument passing semantics: objects are not passed by reference, references are passed by value:
public static void swap( Object o1, Object o2 )
{
Object tmp = o1;
o1 = o2;
o2 = tmp;
}
The previous piece of code is a complex no-op. References to two objects are passed by value, they are played with inside the method and nothing happens from the caller perspective: the real objects do not suffer any change, nor do the references the caller has into those objects. That is, if the call is swap( ref1, ref2 ), the system will make copies of the references into o1 and o2, the copies are changed within the method, but the caller variables ref1 and ref2 will remain unchanged after the method call.
In C++ you have two concepts: pointers are the same as C pointers and close to Java references, while C++ references are aliases into the objects they refer. C++ references can only be initialized with one object/data element in construction and from there on, using the original object and the reference is exactly the same. Besides the fact that references don't hold the resource and thus the destructor will not be called when the reference goes out of scope, nor will the reference notice if the referred object is destroyed, for all other uses the two names are the same element.
template <typename T>
void swap( T & a, T & b )
{
T tmp( a );
a = b;
b = tmp;
}
The code above in C++ differs from the Java version in that it does change the caller objects. If a caller uses swap( var1, var2 ), then the references are bound to those variables, and it is var1 and var2 the ones that suffer the change. After the call, the value of var1 and var2 is actually swapped.
Handles are in a different level, they are not language construct but tokens provided by a library so that you can later on refer to some resource that the library manages internally. The most general case are integer handles that are ids (or offsets) into a resource table, but I have seen strings used as handles. It is the library internally who decides what is exactly a handler (a pointer, an integer, a string or a more complex data structure). Handles are meant to be opaque in that the only sensible use is to store them and later give it back to the same library as part of other function signatures.
|
1,436,968 | 1,437,115 | Variadic function without specified first parameter? | Out of curiosity, I thought I'd try and write a basic C++ class that mimics C#'s multiple delegate pattern. The code below mostly does the job, with the nasty sacrifice of losing almost all type-safety, but having to use the initial dummy parameter to set up the va_list really seems a bit off. Is there a way to use va_list without this?
I do realize there are ways to do this with (for example) boost, but I was aiming for something dead simple that used just the standard library.
#include <vector>
#include <iostream>
#include <string>
#include <stdarg.h>
#include <algorithm>
using namespace std;
class CDelegate
{
public:
virtual bool operator()(va_list params) = 0;
};
class CMultipleDelegateCaller
{
public:
typedef vector<CDelegate*> CDelegateVector;
CMultipleDelegateCaller& operator+=(CDelegate &rDelegate)
{
m_apDelegates.push_back(&rDelegate);
return (*this);
}
CMultipleDelegateCaller& operator-=(CDelegate &rDelegate)
{
CDelegateVector::iterator iter =
find(m_apDelegates.begin(), m_apDelegates.end(), &rDelegate);
if (m_apDelegates.end() != iter) m_apDelegates.erase(iter);
return (*this);
}
bool Call(int iDummy, ...)
{
va_list params;
CDelegate* pDelegate;
CDelegateVector::iterator iter;
for (iter = m_apDelegates.begin(); iter != m_apDelegates.end(); ++iter)
{
pDelegate = *iter;
va_start(params, iDummy);
if (!(*pDelegate)(params)) return false;
va_end(params);
}
return true;
}
private:
CDelegateVector m_apDelegates;
};
class CTestDelegate:
public CDelegate
{
public:
CTestDelegate():m_iId(++s_iCount) {}
virtual bool operator()(va_list params)
{
int iIntParam = va_arg(params, int);
char* szCharPtrParam = va_arg(params, char*);
string* psStringParam = va_arg(params, string*);
cout<<m_iId<<"{"
<<iIntParam<<", "
<<szCharPtrParam<<", "
<<*psStringParam<<"}"<<endl;
return true;
}
int m_iId;
static int s_iCount;
};
int CTestDelegate::s_iCount = 0;
int main(int argc, char* argv[])
{
CMultipleDelegateCaller cDelegateCaller;
CTestDelegate cTestDelegate1;
CTestDelegate cTestDelegate2;
cout<<"--------------------"<<endl;
cDelegateCaller += cTestDelegate1;
cDelegateCaller += cTestDelegate2;
string sString("World");
cDelegateCaller.Call(1, 2, "Hello", &sString);
cout<<"--------------------"<<endl;
cDelegateCaller -= cTestDelegate1;
cDelegateCaller.Call(1, 2, "Hello", &sString);
cout<<"--------------------"<<endl;
cDelegateCaller -= cTestDelegate2;
cDelegateCaller.Call(1, 2, "Hello", &sString);
cout<<"--------------------"<<endl;
cin>>sString;
return 0;
}
| Functions with ellipsis in C++ is only for compatibility with C. Using C++ I'd return temporary helper object in Call function and add template operator% to pass variable number of arguments. To use it in the following way:
cDelegateCaller.Call() % 2 % "Hello" % sString; // dummy argument isn't required
As to your question, Standard requires to invoke va_start before any access to the unnamed arguments. And va_start requires second argument which is the identifier of the rightmost parameter in the variable parameter list in the function definition.
|
1,437,053 | 1,437,748 | Boost advocacy - help needed |
Possible duplicates
Is there a reason to not use Boost?
What are the advantages of using the C++ BOOST libraries?
OK, the high-level question is "Please provide me with what you consider to be the most effective arguments of why entire Boost, or some specific parts of it, should be compiled on our company's system and endorsed in software engineering standards".
Details of what I need:
Would gladly accept both positive arguments (why install), as well as proposed rebuttals of likely counter-arguments I might hear (see question context below).
Arguments should be made aimed at both technical Software Engineering team members and/or very technical senior managers - in other words, for the latter, the details of the argument may/should be technical, but the thrust of the argument should be "how would this make/save the company X money vs losing the company Y money as a cost of adding it to our toolset".
Context of the question:
I'm a developer in a company with several hundred developers, many dosens of whom do C++.
I had the (mis)fortune of being reassigned from my beloved Perl development spot to a team where I am also doing C++ development. So far I found numerous things that I could easily have done in Perl that are very hard/cumbersome to do in C++ (foreach loop as an example), and anytime I hit one of these, the answer 50% likely ends up being "You can't do this in standard C++ but you can do it with Boost"
Our toolkit includes some legacy RogeWave libraries, and VERY limited number of Boost libraries (e.g. no regex, no foreach), of very old vintage.
Any development must use libraries compiled and vetted by Software Engineering team. That is a hard and fast rule.
SE team is somewhat resistant to adding new libraries, for a variety of reasons (e.g. effort to do this; functionality conflicts with RogeWave, for example for RegEx; the risk of installing and using any new software; cost of educating developers, etc...). They will add the libraries if presented with sufficient business need or majorly convincing cost/benefit ratio argument, but they have pretty tough threshold.
So, I'm looking for examples of which parts of Boost are so wonderful (with exact cost/benefit estimates) that installing them would be an Obviously Worth It Effort for Software Engineering.
Thanks in advance for any ideas/suggestions/examples.
Please don't mark this question as subjective as I am looking for measurable answers, not merely wonderful feelings :)
| Wherever I worked in the last decade, when they had their own smart pointer class, I found bugs in that - usually within a few weeks. And, no, I never went and looked at it hoping to find errors.
I got into the habit of posting the following quote from the TR1 smart pointer proposal:
The Boost developers found a shared-ownership smart pointer exceedingly difficult to implement correctly. Others have made the same observation. For example, Scott Meyers [Meyers01] says:
"The STL itself contains no reference-counting smart pointer, and writing a good one - one that works correctly all the time - is tricky enough that you don't want to do it unless you have to. I published the code for a reference-counting smart pointer in More Effective C++ in 1996, and despite basing it on established smart pointer implementations and submitting it to extensive pre- publication reviewing by experienced developers, a small parade of valid bug reports has trickled in for years. The number of subtle ways in which reference-counting smart pointers can fail is remarkable."
This plus a detailed analysis of the bug(s) I found usually got me the job of incorporating the boost libs into the code base. :)
|
1,437,184 | 1,437,248 | Virtual inheritance - gcc vs. vc++ | I have a problem with Visual Studio 2008 concerning virtual inheritance.
Consider the following example:
#include<iostream>
class Print {
public:
Print (const char * name) {
std::cout << name << std::endl;
}
};
class Base : public virtual Print {
public:
Base () : Print("Base") {}
};
class A : public Base {
public:
A () : Print("A") {}
};
class B : public A {
public:
B () : Print("B") {}
};
int main (int argc, char** argv) {
A a; // should print "A"
B b; // should print "B"
return 0;
}
This code compiles just fine if I use gcc on my linux machine.
But if I try to build the same on windows with Visual Studio, the compilation fails with error message "error C2614: 'B': illegal member initialization: 'Print' is not a base or member."
Why does this not work?
| From the standard [class.base.init]: "Unless the mem-initializer-id names a nonstatic data member of the constructor’s class or a direct or virtual base of that class, the mem-initializer is ill-formed."
Evidently gcc interprets your case as legal as Print is a non-direct, but virtual base of B, however MSVC 2008 doesn't see Print as a virtual base of B - only a virtual base of a non-virtual base. (Incidentally, your example compiles on VS2005, so it's a surprising change in behaviour.)
I'd lean towards the gcc interpretation as being correct (otherwise the phrasing 'a direct base' would have been sufficient).
To work around this problem, you could derive B virtually from Print. As Print is already a virtual base of A this doesn't have any overall effect on the class layout or the number of base class Print sub-objects.
|
1,437,327 | 1,437,364 | Saving to disk an in-memory database | I made a database through sqlite in c++.
The db has been created in memory (using the ":memory:" parameter insted of a filename), in order to have a very quick behavior.
The database is created by the following lines:
sqlite3* mem_database;
if((SQLITE_OK == sqlite3_open(":memory:", &mem_database)){
// The db has been correctly created and
// I can do some stuff with it.
}
sqlite3_close(mem_database);
My problem is: how can I write the in-memory database to disk? (through c/c++ of course).
I read something about the ATTACH and DETACH sqlite commands, but I can get them working only with the sqlite interactive shell (not from c/c++ code).
Greets.
| Check out this example: Loading and Saving In-Memory Databases
|
1,437,337 | 1,437,348 | Specification on C++ and C#? | If you want to read the "source" of a language in C you go to C Programming Language by Kernighan; Ritchie; 0131103628
And in Java you read Goslings The Java(tm) Language Specification; 0321246780
But what do you read if you want to read a good book about the "specs" on C++ and C#?
| C++: Stroustrup's book and/or Stroustrup's D&E or Stroustrups ARM though the latter two are not in date. The ISO spec is available (see Charles bailey's answer) and is the final word if that's the type of doc you want. The most thorough answer is in the comments by aJ :- The Definitive C++ Book Guide and List. The equivalent of K&R for C++ is the first one.
C#: The C# Programming Language (3rd Edition) by Anders Hejlsberg, Mads Torgersen, Scott Wiltamuth, and Peter Golde). If you're looking for the generally accepted definitive book on C#, that's C# in depth.
|
1,437,417 | 1,437,639 | Is it possible to use Qt threading without inheriting any Qt object? | The only way to enable threading demonstrated in qt documentation is through inheriting QThread and then override its run() method.
class MyThread : public QThread
{
public:
void run();
};
void MyThread::run()
{
QTcpSocket socket;
// connect QTcpSocket's signals somewhere meaningful
...
socket.connectToHost(hostName, portNumber);
exec();
}
I wonder if there is any way to use qt thread without ever inheriting from any qt objects?
| You can use multithreading without inheriting from QObject with QtConcurrent::run():
QFuture QtConcurrent::run ( Function function, ... )
Runs function in a separate thread. The thread is taken from the global QThreadPool. Note that the function may not run immediately; the function will only be run when a thread is available.
|
1,437,450 | 1,440,923 | Windows Limited User Installation | I have a Win32 application that includes an EXE, an ActiveX control (DLL) and a COM server (EXE) and I am using Inno Setup 5 to build my installer. Many of our customers use limited user accounts where the user has no admin rights and because the COM components require to be registered (which writes to HKEY_CLASSES_ROOT), my setup file must run with elevated (admin) privileges. I think this in unavoidable (sadly, I can't use registration-free COM because of the EXE COM server I have). However, I would like to create an update installer that can be ran as a limited user and am looking for some advice.
What I am thinking is the following:
The initial setup (first time installation) installs the application into %ALLUSERSPROFILE%\Application Data\CompanyName\AppName instead of %PROGRAMFILES%. The COM components are registered as normal (as they won't already exist).
Subsequent updates (using a different Inno Setup script) will simply copy the new files into %ALLUSERSPROFILE%\Application Data\CompanyName\AppName. Hopefully even a limited user will have write access to this folder and as the COM components have already been registered, admin access won't be required.
This would mean that my customers could upgrade to the latest and greatest version without the hassle of using an Administrator account. Is this acceptable or is this likely to bite me on the backside? I'm pretty sure Google Chrome does something similar but as it has no COM components (as far as I can tell) even the initial setup can be as a limited user.
Any advice from others who have faced this issue would be very welcome indeed.
| I don't know for sure, but I seem to recall COM servers support per-user installation, and maybe that goes for EXE servers as well.
If so, change your registration code to write information to HKEY_CURRENT_USER\Software\Classes instead of HKEY_CLASSES_ROOT.
The COM infrastructure should do the lookup first per-user and then per-machine.
It's worth an experiment anyway.
|
1,437,816 | 1,437,853 | Sort vectors by last elements | Have a "vector of vectors"
that looks something like this
3 1 2 0 77
0 3 1 2 44
1 0 3 2 29
3 0 1 2 49
I would like to sort them according to the last element in every row so that it would look like this in the end
1 0 3 2 29
0 3 1 2 44
3 0 1 2 49
3 1 2 0 77
Of course my real example is a lot more complex... but this is basically what I need to get done.
Right now I use this snippet which seems to sort according to the first elements.
vector<vector<int>>population;
partial_sort( population.begin(),population.begin()+10, population.end() );
| You can use std::sort with a function (or functor object) that provides a strict weak ordering for vectors. I.e. you define a vector-less-than function that orders two vectors correctly, something like this (off the top of my head).
Edit: after comments, added checking for one or two empty vectors, which does make things trickier.
bool CustomVectorCompare(const std::vector<int> &i_lhs, const std::vector<int> &i_rhs)
{
if(i_rhs.empty())
return false; // If right side is empty, left can only be equal or larger
if(i_lhs.empty())
return true; // Consider an empty vector to be "smaller"
// than any non-empty vector.
return i_lhs.back() < i_rhs.back();
}
std::sort(population.begin(), population.end(), CustomVectorCompare);
|
1,438,038 | 1,465,440 | Writing to binary file in C++ and C# | I have 2 applications. One in C++ (windows) open a binary file and only reads from it, i use:
fstream m_fsDataIN.open("C:\TTT", ios::in | ios::binary | ios::app);
and the second application (is in C#) opens the file and writes to it. I use:
byte[] b = ... //have a binary data
System.IO.BinaryWriter bw = new System.IO.BinaryWriter(
System.IO.File.Open(@"C:\TTT",
System.IO.FileMode.Append,
System.IO.FileAccess.Write,
System.IO.FileShare.ReadWrite));
bw.Write(b);
bw.Flush();
bw.Close();
The problem is that the 8 first bytes are written incorrectly, comparing to what appears in the b array.
When I open the file in the C# application, using System.IO.FileMode.Append it works OK.
I checked in the application and it writes wrong 8 bytes.
I want to add that the first 8 bytes are 2 counters that each was created using IPAddressHostToNetworkAddress.
I think that the problem is in the C++ application, in how I open the file.
Help,
Thnaks
| The problem was in the C++ application.
The program contained configuration which produced another file handler.
Using Process Explorer I found out about it.
Removing the configuration of that extra file handler resolved the problem.
|
1,438,053 | 1,438,080 | Converting old C code to work with threads | I have a very old, very very large, fully working, C program which plays a board game. I want to convert it (or should I say parts of it) to work in multiple threads, so that I can take advantage of multi-core processors. In the old program there is a global UBYTE array called board[]. There are a great many (highly optimized, highly speed critical) functions which manipulate the contents of board[]. I now want to make the process work as follows:
step 1. Perform a large number of
operations in a single thread
performing many manipulations of the
single board[]. These are the things that are too complex to perform on multiple cores.
Step 2. farm out
multiple copies of "board[]" to a
collection of threads and have each
thread spend some time doing their
own separate manipulations of their
own private "board[]"'s.
Step 3.
the threads finish their work and
return some answers to the main
thread.
For arguments sake lets say there will be 32 sub threads.
Now one way to do this would be to make one global board[] and 32 sub-boards with a different name like sub_board[32][] and then write a new bunch of board manipulation functions that work on the new 2 dimensional sub_board[][], but this would ruin my optimization because there would need to be an additional multiply and add for every access to the game board. Also the new versions of the old board manipulation functions will be slightly messier.
Now I have not been a C++ programmer before (but I'm learning as fast as I can) and someone has suggested the following trick involving C++ (I'm not sure that I've got all the details correct): I leave the existing board[] as is. I leave all the existing board manipulation functions as is. I make a new class (lets call it thread_type) which contains a board[] and a new set of board manipulation functions. Something like this:
class thread_type
{
UBYTE board[]; // boards for slave threads to work with
void board_manipulation_A(void);
void board_manipulation_B(void);
}
The board manipulation functions are identical to the old ones (so I can cut and paste) other than being declared with "thread_type::" at the the start. Then in main() I have:
class thread_type slave[32];
Now I can manipulate a single global board[] with all my old code in the base thread. Then I can copy the main board[] to slave[n].board[] then have
For (i = 0; i < 32;i++)
{
// there will have to be some extra thread/mutex
// related code around here but I'm not showing it for simplicity
slave[n].do_your_stuff();
}
Now inside each of the 32 threads, each one will be working on their own different "board[]" with code that is pretty much identical to the old original (fully debugged and optimized) code. I could even avoid the cut and past of the old code altogether by doing some #define tricks, i.e. having the function declarations written like this
void THREAD_OR_BASE board_manipulation_A(void);
and then run through this once with
#define THREAD_OR_BASE // zilch
and once with
#define THREAD_OR_BASE thread_type::
This way I can be quite certain that any time I make a modification to board_manipulation_A() it will appear both in the base thread version and the sub-thread one.
My questions are: A) Will it all work? B) Did I miss some vital step? C) could I have achieved the same thing with some simpler method?
Edit: instead of 32 threads, I should have said "as many threads as there are cores"
| If you don't need to merge thread result boards back in the same one, looks to me like a good strategy, making each thread have their own copy of the board and working on it, I don't see why it shouldn't work.
However, looks to me like the threads will perform a lot of cpu-bound operations, if thats true, you shouldn't have that many threads, it's better to have the same threads as cores your cpu has or few more, if more, they'll compete for the cpu resources, and your performance will be degraded.
|
1,438,285 | 1,438,293 | C++ iterators breaking in Visual C++ but not GNU g++ | I am trying to learn more about list containers and how to iterate through them, but it seems that g++ has no problem with it, but Visual Studio C++ pukes all over the place!
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main(){
list <string> data;
list <int>::iterator it;
data.push_back("fee");
data.push_back("fi");
data.push_back("foo");
data.push_back("fum");
// something breaks back here ?!?!
for(it=data.begin(); it!=data.end(); it++){
cout << *it << endl;
}
return 0;
}
| Try
list<string>::iterator
instead of
list<int>::iterator.
|
1,438,901 | 1,447,747 | does borland compiler fail when we try to compile a large data case | if yes.. then which compiler is best for compiling them?
| may be it is trying to write on read only memory. try using next higher version of borland
|
1,439,165 | 1,441,492 | Is anybody having problems inputing strings in Xcode 3.2? | For some reason excode is throwing this error when I try to cin into a string.
test(5640) malloc: * error for object 0x1000041c0: pointer being freed was not allocated
* set a breakpoint in malloc_error_break to debug
Program received signal: “SIGABRT”.
sharedlibrary apply-load-rules all
Here is the code that produced that:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string hello;
cout << "Enter a string";
cin >> hello;
return 0;
}
So does anybody have a solution?
| According to this forum: http://discussions.apple.com/message.jspa?messageID=10236050#10236050
Technically, that is a warning message, not an error. This is a bug in the GCC C++ library. Remind me again why I don't write C++ code anymore. You would think in 2009 they would have silly things like this fixed.
You could avoid this by making sure your hello variable is initialized to something to start with.
Or, you can turn off the pedantic warnings. Select your debug target and double click it or Command-i. Scroll down to "GCC 4.2 - Preprocessing". Select "Preprocessor Macros" and delete it. You will no longer get the warning message. You will still be freeing unallocated memory, but you can complain to GCC about that.
|
1,439,172 | 1,439,265 | testing code in C C++ | I don't know how you guys test your code every time you code a little and for different levels of testing: unit testing, Integration testing, ...
For example, for unit testing a function you just wrote, do you write another whole set of main function and Makefile to test it? Or do you modify the main function of your project to test the function. Or do you just run your project under debugging, and stop at where the function is about to be called and modify the values of its arguments?
I believe there must be some convenient and common ways that most people are using and only I am not aware of.
| xUnit is a family of unit testing modules. x is replaced by a letter for the language of framework used. The family currently consists of:
CUnit (for C)
CppUnit
NUnit (.NET)
EmbUnit ; embedded unit test for C
I've worked in projects using CppUnit with good results. Recently I've tried to integrate this in an automatic build environment (i.e. Hudson) and I came across many obstacles.
Ideally, the build automatically builds and runs the unit tests. In that case, code is run from the test environment (and thus has it's own main loop). An extra complication in my case is that I work with embedded systems; printf is not always possible. I expect that if you run on PC, CUnit and CppUnit can help you a lot to implement good unit testing. Please look at how to use the results; a continuous integration system will increase your effiency a lot.
Another framework worth to give a look is Maestra. It relies on C99 (which Microsoft has never implemented, but for gcc it is great!)
|
1,439,187 | 1,439,462 | modify values of elements of an array in gdb for C++ | Just wonder how to modify the values of multiple elements of an array under gdb for C++?
Thanks and regards!
| Something like:
print memcpy (the_array_you_want_to_modify, {newvalue1, newvalue2, ..., newvalueN}, N * sizeof(the_array_you_want_to_modify[0]))
may be what you're looking for?
|
1,439,455 | 1,439,472 | C++ Events/Notifications & Default handling method list | Is there a list any where of C++ Events/Notifications & Default handling method list.
For example, it would be useful to know that by default, the HDN_DIVIDERDBLCLICK notification is normally handled by the CWnd::OnLButtonDblClk method.
This would make it easier to find the correct method when wanting to call it when you write your own handler for the notification.
I currently cant find any simple way of finding this information.
Thanks.
| This page at MSDN lists the WM_XXX messages and the signatures of the corresponding handler methods.
For notification messages that are emitted by controls, you'll want to look on the documentation page for the control. So, for example, the documentation for HDN_DIVIDERDBLCLICK is on the reference page for CHeaderCtrl (also see this page which briefly states that they are handled by the OnChildNotify handler function).
|
1,439,508 | 1,440,638 | Store QList<T> in QVariant and stream to QDataStream? | Here's the demo code:
QList<Custom> L;
QVariant v(QVariant::fromValue(l));
QDataStream d;
d << v;
The problem seems to be that d doesn't know how to stream v, because v doesn't know how to do a metatype save on L. I have registered Custom and L as metatypes and I've also registered their IO streams, but L has no meta object, and I think that is the problem.
Can I get around this somehow?
Later edit:
After debugging the QMetaType code, I've found out that when calling qRegisterMetaTypeStreamOperators<Type>("TypeString") "TypeString" must be "Type", not just any string. This was mentioned in the docs, but it's not really clear. The QtCentre link also mentioned this. I've decided to accept Kaleb Pederson's answer because it is my fault that I found the answer the hard way. :)
| You need to register output operators for the given type. See also a similar question on QtCentre.
What this implies is that you need to define non-member output operators matching the signature defined in the documentation and then call qRegisterMetaTypeStreamOperators.
|
1,439,959 | 1,440,307 | distinguishing between static and non-static methods in c++ at compile time? | For some tracing automation for identifying instances i want to call either:
a non-static method of the containing object returning its identifier
something else which always returns the same id
My current solution is to have a base class with a method which() and a global function which() which should be used if not in the context of an object.
This however does not work for static member functions, here the compiler prefers the non-static method over the global one.
Simplified example:
class IdentBase
{
public:
Ident(const std::string& id) _id(id) {}
const std::string& which() const { return _id; }
private:
const std::string _id;
};
const std::string& which() { static const std::string s("bar"); return s; }
#define ident() std::cout << which() << std::endl
class Identifiable : public IdentBase
{
public:
Identifiable() : Ident("foo") {}
void works() { ident(); }
static void doesnt_work() { ident(); } // problem here
};
Can i somehow avoid using work-arounds like a special macro for static member functions (maybe using some template magic)?
| You might be able to to use is_member_function_pointer from the Boost TypeTraits library. sbi's suggestion of using different code in the static and non-static cases is probably better though.
|
1,440,118 | 1,440,163 | programmatically check for subsystem | I have a .exe created with a windows subsystem. I copy that .exe to another .exe, and I run:
editbin.exe /SUBSYSTEM:CONSOLE my.exe
So my intention is to have a .exe that runs with a GUI, and another .exe that is meant for command line operations (no GUI).
How do I check what subsystem is currently active in my C++ code?
| Subsystem type (GUI, console, etc.) is stored in the PE header, which you can access via the ImageHlp functions. You can get it with the following code:
// Retrieve the header for the exe. GetModuleHandle(NULL) returns base address
// of exe.
PIMAGE_NT_HEADERS header = ImageNtHeader((PVOID)GetModuleHandle(NULL));
if (header->OptionalHeader.Subsystem == IMAGE_SUBSYSTEM_WINDOWS_CUI)
{
// Console application.
}
Relevent MSDN entries:
ImageNtHeader
IMAGE_NT_HEADERS
IMAGE_OPTIONAL_HEADER
|
1,440,222 | 1,440,231 | Constructors with default parameters in Header files | I have a cpp file like this:
#include Foo.h;
Foo::Foo(int a, int b=0)
{
this->x = a;
this->y = b;
}
How do I refer to this in Foo.h?
| .h:
class Foo {
int x, y;
Foo(int a, int b=0);
};
.cc:
#include "foo.h"
Foo::Foo(int a,int b)
: x(a), y(b) { }
You only add defaults to declaration, not implementation.
|
1,440,285 | 1,440,308 | How to detect hot plugging of monitor in a win32 application? | I need some kind of event from Windows whenever there is a monitor that's getting plugged into system. Is there any API in Windows to do that. BTW, it is an C++ application
| Use RegisterDeviceNotification to register for getting WM_DEVICECHANGE notification.
|
1,440,287 | 1,440,328 | How to create a container of noncopyable elements | Is there a way use STL containters with non-copyable elements?
something like this:
class noncopyable
{
noncopyable(noncopyable&);
const noncopyable& operator=(noncopyable&);
public:
noncopyable(){};
};
int main()
{
list<noncopyable> MyList; //error C2248: 'noncopyable::noncopyable' : cannot access private member declared in class 'noncopyable'
}
| No, non-copyable elements can't be in C++ container classes.
According to the standard, 23.1 paragraph 3, "The type of objects stored in these components must met the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types."
|
1,440,324 | 1,440,338 | Application configured incorrectly error C++ | I'm new to c++. I made a c++ program using VS 2008 Professional. I started with the Win32 template that created a window for me. I compiled it on Vista 32. I brought the compiled exe to my old XP sp2 computer, and it tells me the application configuration is incorrect. Is there something im doing wrong? How do I make it platform independent?
Thanks
| Try installing Microsoft Visual C++ 2008 SP1 Redistributable Package and make sure you use the release build of your application.
|
1,440,418 | 1,440,544 | Why don't member function temporaries bind to the right type? | Suppose that we have the following base and derived classes:
#include <string>
#include <iostream>
class Car {
public:
void Drive() { std::cout << "Baby, can I drive your car?" << std::endl; }
};
class Porsche : public Car {
};
..and also the following template function:
template <typename T, typename V>
void Function(void (T::*m1)(void), void (V::*m2)(void)) {
std::cout << (m1 == m2) << std::endl;
}
Why does this compile using GCC:
int main(int argc, char** argv) {
void (Porsche::*ptr)(void) = &Porsche::Drive;
Function(ptr, ptr);
return 0;
}
...but not this?
int main(int argc, char** argv) {
void (Porsche::*ptr)(void) = &Porsche::Drive;
Function(&Porsche::Drive, ptr);
return 0;
}
| int main(int argc, char** argv) {
void (Porsche::*ptr)(void) = &Porsche::Drive;
Function(&Porsche::Drive, ptr);
return 0;
}
ptr has type void (Porsche::*)(), but &Porsche::Drive has type void (Car::*)() (because the member is found in Car, not in Porsche). Thus the function called compares these two member pointers with those types, and the standard says
In addition, pointers to members can be compared, or a pointer to member and a null pointer constant. Pointer to member conversions (4.11) and qualification conversions (4.4) are performed to bring them to a common type. If one operand is a null pointer constant, the common type is the type of the other operand. Otherwise, the common type is a pointer to member type similar (4.4) to the type of one of the operands, with a cv-qualification signature (4.4) that is the union of the cv-qualification signatures of the operand types.
4.11 describes an implicit Standard conversion from void (Base::*)() to void (Derived::*)(). Thus, the comparison would find the common type void (Porsche::*)(). For an object of type Porsche, both member pointers would refer to the same function (which is Car::Drive) - so the comparison would yield true. The comeau web compiler follows this interpretation and compiles your code.
|
1,440,468 | 1,440,601 | Set debugging macro conditionally with make | In my C++ project, I have a convention where whenever the macro DEBUG is defined, debugging printf-esque statements are compiled into the executable.
To indicate whether or not I want these compiled into the executable, I normally would pass the macro name to gcc with the -Dmacro option. So, in the Makefile I (currently) have:
CXXFLAGS += -g -I ../ -Wall -Werror -DDEBUG
However, this is not very flexible; if I didn't want debug statements in my final program, I'd have to modify the Makefile to remove the -DDEBUG.
Is there a way to modify the Makefile such that I can conditionally select whether to compile with -D in the CXXFLAGS at compile time by passing in, say, another target name or a commandline switch? Not sure how'd I go about doing that.
| You can conditionally define other variables based on the target in the makefile.
all: target
debug: target
debug: DEBUG=PLOP
target:
@echo "HI $(DEBUG)"
So now:
> make
HI
>
> make debug
HI PLOP
>
|
1,440,581 | 1,440,589 | Enum and their Values | What would be the value of Field.Format("%04d", ErrorCode) in the procedure below if the AErrorCode is ERR_NO_HEADER_RECORD_FOUND_ON_FILE?
Somewhere in a .h file:
enum AErrorCode
{
ERR_UNKNOWN_RECORD_TYPE_CODE = 5001,
ERR_NO_HEADER_RECORD_FOUND_ON_FILE,
ERR_DUPLICATE_HEADER_RECORD_FOUND,
ERR_THIRD_PARTY_LETTER_RECORD_HAS_A_ZERO_REFERRAL_AMOUNT = 5101,
ERR_CALL_OCA_UNKNOWN_PROBLEM = 5999
};
In some procedure:
void TADataset::SetErrorStatus(AErrorCode ErrorCode)
{
NDataString Field;
Field.Format("%04d", ErrorCode);
AckRecord.SetField("oca_error_stat", "E");
AckRecord.SetField("error_cd", Field);
}
| ERR_NO_HEADER_RECORD_FOUND_ON_FILE == 5002
If you don't specify any value at all, it starts at 0 and increments the next element in the enum. If you specify a value, then it starts incrementing starting by the next element. Unless you reset the counter again by specifying another value for a successor element.
|
1,440,689 | 1,440,730 | windows process management | Why does the root directory of a process, started by a windows process manager, change to the directory of where the pm is located?
Using msdn process manager code to create a pm service to run a few exes.
The exes save log files in the root relative to their location.
When started by the process manager, they are saving to the process manager directory?
Any advice is appreciated, thanks.
| Tosses 'should be on superuser!!!' shield
The PM is a process itself started from wherever the PM shortcut points to, so the WD will be the location of the executable. If you start another process from that, it will fork (errr, windows equivelent) another process with the same WD. If you think about it, what else would you expect it to do?
|
1,440,767 | 1,440,865 | Cross-platform development? | I am looking for a solution which would allow me to code for Linux and Windows using C++.
On Windows I use Visual Studio (I tried other stuff on Windows but I work with DirectX and as far as I know, it's the best solution).
On Linux I use NetBeans (which I like very much).
My problem is that I want the project be independent of Visual Studio and NetBeans.
For a while I thought that CMake was the solution, however the learning process is too important, I rather spend my time coding than learning all the tricks with CMake. So I settled for Boost.Jam. It worked fine on Linux but sucked with Visual Studio.
I created a small Hello World program, on Windows. I created a Visual Studio Makefile project and while it's compiling and linking correctly. I can run the executable but not from Visual Studio, which can't find the executable (no matter what I do). I can't debug either. Also I can't see the compilation error message when I get one. All I can see from Visual Studio is that there is a makefile action in progress and that there is a mistake about it (even though the program is created and run fine).
I've been browsing the Boost.Jam documentation for a while but let's face it, it's pretty poor (no wonder not a lot of people heard of it) or I'm pretty not suited for the job (meaning stupid lol but yet why so few heard of it).
I have three questions:
I'd like to know if somebody heard of a project which use Boost.Jam with visual studio? If yes can I have a look at it ?
Is there a tool out there with real Visual Studio integration?
How many people think that learning to use CMake (correctly) cost a lot of time? Any tricks to speed up?
| You should take the time to learn CMake and to speed up the learning process buy/read "Mastering CMake 4th Edition"
If you have problems you should use the CMake mailing list, which is active (August 2009 had ~600 messages)
|
1,440,768 | 1,440,802 | Initializing a polygon in boost::geometry | I am new to the generic geometry library that is proposed for inclusion with boost:
http://geometrylibrary.geodan.nl/
I have two vectors vector<int> Xb, Yb that I am trying to create a polygon from. I am trying to get something along the lines of the following code snippet:
polygon_2d P;
vector<double>::const_iterator xi;
vector<double>::const_iterator yi;
for (xi=Xb.begin(), yi=Yb.begin(); xi!=Xb.end(); ++xi, ++yi)
P.push_back (make<point_2d>(*xi, *yi));
The above code does not work, complaining that P does not have a push_back member function. How do I initialize the polygon from points that have coordinates vector<int> Xb,vector<int> Yb?
| append(P, make<point_2d>(*xi, *yi));
|
1,440,901 | 1,440,948 | Question on DLL Exporting/Importing and Extern on Windows | I have some quick questions on windows dll.
Basically I am using the ifdefs to handle the dllexport and dllimport, my question is actually regarding the placement of the dllexports and dllimports as well as extern keyword.
I am putting the dllimports/dllexports on the header files but do I have to put the dllexport and dllimports on the actualy definition?
What about for typedefs?
Do I put the dllimport/dllexport in front? as in
dllexport typedef map<string, int> st_map
Also regarding the extern keyword I have seen it being used like this:
extern "C" {
dllexport void func1();
}
I have also seen it being used like this:
extern dllexport func1();
One includes the "C" and the other does not, my question is what is the difference and do I need to use it? If I do then do I use it for both dllexport and dllimport also do I have to use it on both the header file declarations and the definitions?
My project is going to be shared library, it contains several class files which I want to export, some typdefs i want to export and some global functions which I also want to export all into a dll.
Anyone enlighten me please?
EDIT:
Okay I thought I'll post a small extract of what i've done, also notice that I am building the library for both linux and windows so I do a check for that:
mydll.h
#ifdef WINDOWS
# ifdef PSTRUCT_EXPORT
# define WINLIB __declspec(dllexport)
# else
# define WINLIB __declspec(dllimport)
# endif
#else
# define WINLIB
#endif
WINLIB void funct1();
Now in the source code:
mydll.cpp
#define PSTRUCT_EXPORT
void funct1() <---- do I need to add WINLIB in front of it?
Or is doing it in the header enough?
| First, you don't need to import or export typedefs. As long as they're in the header files that both sides use, you're good. You do need to import/export functions and class definitions.
Presumably you use the same header files for both the importing and exporting code, so you could do some makefile magic to define a preprocessor macro on each side, then do something like this:
#if defined( LIBRARY_CODE )
#define MYAPI __declspec(dllexport)
#else
#define MYAPI __declspec(dllimport)
#endif
extern MYAPI void func1();
class MYAPI MyClass {
...
};
Regarding C vs. C++ functions, you can do this:
#if defined( __cplusplus__ ) // always defined by C++ compilers, never by C
#define _croutine "C"
#else
#define _croutine
#endif
extern _croutine void function_with_c_linkage();
Make sure you import this header file from your C++ source file (containing the implementation of this function) or the compiler won't know to give it C linkage.
|
1,440,977 | 1,441,022 | How can you calculate the percentage overlap of two rectangles? | I wrote a drawing function that draws various on-screen sprites. These sprites can only overlap up to a point. If they have to much overlap, they become too obscured. As a result I need to detect when these sprites are too much overlapped. Luckily, the problem is simplified in that the sprites can be treated as orthogonal rectangles. I'd like to know by how much these rectangles overlap. Right now, I just brute force it by testing each pixel in one rectangle to see if the other contains it. I count these and calculate the percentage overlap. I think there's probably a better, less brute force approach. What algorithm can I use to determine this?
I'm using wxwidgets.
| The results depends on how you define overlapping percentage, to keep it symmetric, I would code it like this:
double CalculatePercentOverlap(const wxRect& rect1, const wxRect& rect2)
{
wxRect inter = rect1.Intersect(rect2);
if (inter.IsEmpty())
return 0;
return (double)(inter.GetWidth()*inter.GetHeight()) * 2.0 /
(double)(rect1.GetWidth()*rect1.GetHeight() +
rect2.GetWidth()*rect2.GetHeight());
}
|
1,441,143 | 1,443,562 | How to set the line where a QToolBar is displayed? | I would like to ask if anyone knows how to display 2 QToolBars in two lines, one on top of the other? I found the class QStyleOptionToolBar, but I don't know how to use it...
It is easy to drag one toolbar with the mouse to be placed below the other, so I think there must be a way how this can be done from the source code as well...
Any hint would be appreciated!
Claus
| Try calling QMainWindow::addToolBarBreak(Qt::ToolBarArea) in between adding the two tool bars.
|
1,441,391 | 1,441,610 | C++ Unit-Testing Framework for z/OS (IBM Mainframe) | Does anyone know of a C++ unit-testing framework (e.g. CppUnit, Google Test, etc.) that can be used to write tests on z/OS?
I do most of my development on Windows using the Dignus C++ compiler, which you can use as a cross-compiler and generate object code to run on z/OS. I tried writing a sample test using Google Test, but the compiler could not compile/link the Google Test code. Google Test does not claim to support z/OS, so this was expected. But, it was worth a try!
Thanks so much for any responses this!
| Try CPP Unit Lite (by CppUnit's author). It uses fairly straightforward C++ code, there's a good chance it'll work on z/OS's compiler.
|
1,441,423 | 1,441,439 | Change repeat key threshold c++ | I'm building a c++ tetris game (not c++ .Net). I feel my controls are weird. I want to make it so that when user presses one of the arrow keys, about 10ms of holding it down will start the repeat function windows has. It is set to about 500ms by default, and it is too laggy for my game. How can I set the speed at which it changes from the keydown to the repeat keydown? Not how many times / sec it repeats.
Thanks
*what I want to do is change the repeat delay to short
In control panel in keyboard settings there is repeat rate, how do i set this?
| Typically what you would do for this is instead of reacting to the WM_CHAR message that is subject to the normal key repeat settings, you would look for WM_KEYDOWN and WM_KEYUP, and take action based on a timer that you've got running. If you set the timer to fire every 50 ms for example, then you can repeat every 50 ms and still take the first action immediately when you get the WM_KEYDOWN message.
|
1,441,510 | 1,441,516 | directory structures C++ | C:\Projects\Logs\RTC\MNH\Debug
C:\Projects\Logs\FF
Is there an expression/string that would say go back until you find "Logs" and open it? (assuming you were always below it)
The same executable is run out of "Debug", "MNH" or "FF" at different times, the executable always should save it's log files into "Logs".
What expression would get there WITHOUT referring to the entire path C:\Projects\Logs?
Thanks.
| It sounds like you're asking about a relative path.
If the working directory is C:\Projects\Logs\RTC\MNH\Debug\, the path ..\..\..\file represents a file in the Logs directory.
If you might be in either C:\Projects\Logs\RTC\MNH\ or C:\Projects\Logs\RTC\MNH\Debug\, then no single expression will get you back to Logs from either place. You could try checking for the existence of ..\..\..\..\Logs and if that doesn't exist, try ..\..\..\Logs, ..\..\Logs and ..\Logs, which one exists would tell you how "deep" you are and how many ..s are required to get you back to Logs.
|
1,441,885 | 1,443,309 | Obtaining a pointer to Lua object instance in C++ | I am using Luabind to expose a base class from C++ to Lua from which I can derive classes in Lua. This part works correctly and I am able to call C++ methods from my derived class in Lua.
Now what I want to do is obtain a pointer to the Lua-based instance in my C++ program.
C++ -> Binding
class Enemy {
private:
std::string name;
public:
Enemy(const std::string& n)
: name(n) {
}
const std::string& getName() const {
return name;
}
void setName(const std::string& n) {
name = n;
}
virtual void update() {
std::cout << "Enemy::update() called.\n";
}
};
class EnemyWrapper : public Enemy, public luabind::wrap_base {
public:
EnemyWrapper(const std::string& n)
: Enemy(n) {
}
virtual void update() {
call<void>("update");
}
static void default_update(Enemy* ptr) {
ptr->Enemy::update();
}
};
// Now I bind the class as such:
module(L)
[
class_<Enemy, EnemyWrapper>("Enemy")
.def(constructor<const std::string&, int>())
.property("name", &Enemy::getName, &Enemy::setName)
.def("update", &Enemy::update, &EnemyWrapper::default_update)
];
Lua-based Derived Class
class 'Zombie' (Enemy)
function Zombie:__init(name)
Enemy.__init(self, name)
end
function Zombie:update()
print('Zombie:update() called.')
end
Now let's say I have the following object created from Lua:
a = Zombie('example zombie', 1)
How can I get a reference of that object as a pointer to the base class in C++?
| If in Lua you do
zombie = Zombie('example zombie', 1)
then you can get the value of the zombie like this:
object_cast<Enemy*>(globals(L)["zombie"]);
(object_cast and globals are members of the luabind namespace, L is your Lua state)
This assumes you know the names of the variables you create in Lua.
You can always call a C++ method from Lua that takes a pointer to Enemy:
void AddEnemy(Enemy* enemy) { /* ... */ }
//...
module(L) [ def("AddEnemy", &AddEnemy) ]
and call it from Lua
a = Zombie("zombie", 1);
AddEnemy(a)
Be aware that if you do
AddEnemy(Zombie("temp zombie", 1));
Lua will delete the "temp zombie" after the method call and invalidate any pointers to the object.
|
1,441,904 | 1,441,924 | Building command line applications | How can I move away from (in c++) the annoying menus like:
(a) Do something
(b) Do something else
(c) Do that 3rd thing
(x) exit
Basically I want to be able to run the program then do something like "calc 32 / 5" or "open data.csv", where obviously I would have written the code for "calc" and "open". Just a shove in the right direction would be great, I am sure I can figure it all out, I just need something to google-fu.
| You should pick up The C++ Programming Language, which is the book on C++ (there are others, but this one is great). It has an example program, spread over a few chapters, on tokenizing, parsing arguments, and making a calculator.
|
1,441,947 | 1,441,970 | dynamic code compilation | I'm working on a program that renders iterated fractal systems. I wanted to add the functionality where someone could define their own iteration process, and compile that code so that it would run efficiently.
I currently don't know how to do this and would like tips on what to read to learn how to do this.
The main program is written in C++ and I'm familiar with C++. In fact given most of the scenarios I know how to convert it to assembly code that would accomplish the goal, but I don't know how to take the extra step to convert it to machine code. If possible I'd like to dynamically compile the code like how I believe many game system emulators work.
If it is unclear what I'm asking, tell me so I can clarify.
Thanks!
| Some CPU emulators treat the machine code as if it was byte code and they do a JIT compile, almost as if it was Java. This is very efficient, but it means that the developers need to write a version of the compiler for each CPU their emulator runs on and for each CPU emulated.
That usually means it only works on x86 and is annoying to anyone who would like to use something different.
They could also translate it to LLVM or Java byte code or .Net CIL and then compile it, which would also work.
In your case I am not sure that sort of thing is the best way to go. I think that I would do this by using dynamic libraries. Make a directory that is supposed to contain "plugins" and let the user compile their own. Make your program scan the directory and load each DLL or .so it finds.
Doing it this way means you spend less time writing code compilers and more time actually getting stuff done.
|
1,442,154 | 1,442,171 | Can I add manifest file to someone else's exe? | I have some EXEs for which I do not have code. Can I still add manifest files?
Also, according to my understanding of the topic, for a program to be Vista compliant, it should not write to any secured locations like HKLM, Program Files etc.
For registry we can use HKCU, but about the files that are getting created in Program Files? should they be created in an unsecured location during the execution of EXE?
Thanks
| You should be able to create a manifest file without source code.
It it OK to require administrative privileges for installation or updates, so you can put the EXEs and DLLs (and supporting files) in Program Files.
It is not OK to require administrative privileges for regular usage, so you should put data files and settings in the registry in HKCU or in the user's Application Data folder.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.