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 |
|---|---|---|---|---|
2,308,266 | 2,308,303 | Floating Point Exception Caused By rand() In c++ | I have an issue that I can't seem to solve. I am randomly generating numbers in order to determine if my numbers are relativity prime.
Here is the function that gives me a Floating Point Exception:
bool modularExponentiationTest(unsigned long long exponent, unsigned long long modulus)
{
short index = 0;
unsigned long long base;
unsigned long long result;
do
{
result = 1;
base = rand() % exponent; // <--CAUSED BY THIS
while (exponent > 0)
{
if (exponent & 1)
result = (result * base) % modulus;
exponent >>= 1;
base = (base * base) % modulus;
}
if (result != 1)
return false;
}while(++index < 10);
return true;
}
I did seed random in a different function by doing the following:
srand(time(NULL));
Thank you very much for your help!
| You're shifting exponent to the right in the while loop until it reach 0.
So the second time you reach base = rand() % exponent; exponent is 0 and you have a division by 0
|
2,308,282 | 2,331,416 | cURL - "hanging" socket connection on Linux | I have a program to send POST request to a server.
I'm using cURL to send request.
My program run on Windows and Linux (on the moment Ubuntu 9.10).
When server receive request it processing it and return error code (0000 if no errors) and error description (if any).
Server's web server is Microsoft IIS.
When I run my program at Windows it work well.
But when I run the program at Linux it hangs up for 30 seconds (cURL's timeout) and return error "Operation timed out after 30000 milliseconds with 5 bytes received".
As I know problem in server side - server doesn't send response's size and doesn't close socket connection.
cURL logs (from Linux):
11:00:09.544 Process() curl: libcurl/7.19.5 OpenSSL/0.9.8g zlib/1.2.3.3 libidn/1.15
11:00:09.941 DebugCallback() About to connect() to sms1.redoxygen.net port 80 (#0)
11:00:09.941 DebugCallback() Trying 203.145.62.146...
11:00:10.084 DebugCallback() Connected to sms1.redoxygen.net (203.145.62.146) port 80 (#0)
11:00:10.085 DebugCallback() POST /sms.dll?private&type=26 HTTP/1.1
Host: sms1.redoxygen.net
Content-Length: 244
11:00:10.086 DebugCallback() [244 bytes of DATA]
11:00:10.087 ReadCallback() No more data to send
11:00:10.292 WriteCallback() HTTP/1.1 200 OK
11:00:10.293 DebugCallback() Content-Type: text/html
11:00:10.294 DebugCallback() no chunk, no close, no size. Assume close to signal end
11:00:10.294 WriteCallback()
11:00:10.466 DebugCallback() 0000
11:00:40.500 DebugCallback() Operation timed out after 30000 milliseconds with 5 bytes received
11:00:40.501 DebugCallback() Closing connection #0
On Windows logs are almost the same, but without timeout - it close socket immediately after reciving "0000 ".
I can analyse received data and close connection if I get "0000 ", but it's a "dirty hack".
Any ideas?
| I found the reason of the issue.
The reason is - VirtualBox.
I'm using VirtualBox to run Ubuntu. If I'm run my program from real (not virtual) PC it work fine (even on Ubuntu).
Looks like there is a bug in latest version of VirtualBox.
|
2,308,293 | 2,308,347 | Efficiency of Bitwise XOR in c++ in comparison to more readable methods | I've recently been writing some code for a research project that I'm working on, where efficiency is very important. I've been considering scraping some of the regular methods I do things in and using bitwise XORs instead. What I'm wondering is if this will make if a difference (if I'm performing this operation say several million times) or if it's the same after I use 03 in g++.
The two examples that come to mind:
I had an instance where (I'm working with purely positive ints) I needed to change n to n-1 if n was odd or n to (n+1) if n was even. I figured I had a few options:
if(n%2) // or (n%2==0) and flip the order
n=n-1
else
n=n+1
or
n=n+2*n%2-1; //This of course was silly, but was the only non-bitwise 1 line I could come up with
Finally:
n=n^1;
All of the methods clearly do the same thing, but my feeling was that the third one would be the most efficient.
The next example is on a more general note. Say I'm comparing two positive integers, will one of these perform better than the others. Or will the difference really not be noticeable, even if I perform this operation several million times:
if(n_1==n_2)
if(! (n_1 ^ n_2) )
if( n_1 ^ n_2) else \do work here
Will the compiler just do the same operation in all of these instances? I'm just curious if there is an instance when I should use bitwise operations and not trust the compiler to do the work for me.
Fixed:In correct statement of problem.
| It's easy enough to check, just fire up your disassembler. Take a look:
f.c:
unsigned int f1(unsigned int n)
{
n ^= 1;
return n;
}
unsigned int f2(unsigned int n)
{
if (n % 2)
n=n-1;
else
n=n+1;
return n;
}
Build and disassemble:
$ cc -O3 -c f.c
$ otool -tV f.o
f.o:
(__TEXT,__text) section
_f1:
00 pushq %rbp
01 movq %rsp,%rbp
04 xorl $0x01,%edi
07 movl %edi,%eax
09 leave
0a ret
0b nopl _f1(%rax,%rax)
_f2:
10 pushq %rbp
11 movq %rsp,%rbp
14 leal 0xff(%rdi),%eax
17 leal 0x01(%rdi),%edx
1a andl $0x01,%edi
1d cmovel %edx,%eax
20 leave
21 ret
It looks like f1() is a bit shorter, whether or not that matters in reality is up to some benchmarking.
|
2,308,390 | 2,308,393 | How do I define a function inside of a class using C++? | How do I define a function inside of a class using C++?
| There are 2 answers:
1) Combining both the declaration and the definition:
class C
{
public:
//declaration and definition of f
void f()
{
}
};
2) Separating the declaration and the definition:
class C
{
public:
//declaration of f
void f();
};
//definition of f
void C::f()
{
}
Typically in option #2 you would separate the declaration into a header file and the definition inside a source file.
|
2,308,391 | 2,308,400 | Operator Overloading working but giving stack overflow and crashing in C++ | I wrote this Node class and = operator overload function and this is the only way I could get it to compile and run but it just overflows and bomb my program. Can someone please fix it so it works. I don't have a lot of experience with overloading operator in C++. I just want to set a Node object equal to another Node object. Thanks in advance!
class Node
{
public:
Node();
int y;
Node& operator=(const Node& n);
};
Node::Node(){ y = -1; }
Node& Node::operator=(const Node& n) { return *this = n; }
.
Build issues:
1>c:\users\aaron mckellar\documents\school stuff\cs445\test\test\main.cpp(57) : warning C4717: 'Node::operator=' : recursive on all control paths, function will cause runtime stack overflow
1>Linking...
1>LINK : C:\Users\Aaron McKellar\Documents\School Stuff\CS445\Test\Debug\Test.exe not found or not built by the last incremental link; performing full link
| in your operator= you need to do the work of setting the member variables equal to the passed in Node's value.
Node& Node::operator=(const Node& n)
{
y = n.y;
return *this;
}
A corresponding example of what you did in English: The definition of a dog is a dog. Instead of saying the definition of a dog is a domesticated form of the wolf, a member of the Canidae family of the order Carnivora.
|
2,308,439 | 2,308,453 | Open default browser as standard user (C++) | I'm currently using ShellExecute "open" to open a URL in the user's browser, but running into a bit of trouble in Win7 and Vista because the program runs elevated as a service.
When ShellExecute opens the browser, it seems to read the "Local Admin" profile instead of the user's. So for example, if the user at the keyboard has Firefox as his default browser, it may open IE (which is the admin's default).
I know that the "runas" verb can be used to elevate, but how do you do it the other way around? Is there a way to open a URL in the default browser on a standard user's desktop from a service?
| ShellExecute will execute the program in the context of the same session and same user as the process you are running.
If you'd like to use a different session or user token you can use the CreateProcessAsUser Win32 API.
There are several ways to obtain a user token, for example you can call the Win32 API:
LogonUser if you know the username and password
WTSQueryUserToken for any given session ID.
OpenProcessToken if you have another process handle
|
2,308,646 | 2,308,656 | Different ways of constructing an object in C++ | I want to construct an object in the stack, using C++.
Do you know what is the difference between these to ways of calling the constructor (with and without parenthesis):
a)
MyClass object ;
b)
MyClass object() ;
I am using MFC and when constructing the global variable for the main app, if I use the latter way, I get an exception, I thought these two ways were equivalent.
Thank you guys for any information.
| This is one of those gotchas of C++.
MyClass object();
is the way that a function prototype is defined in C++, so the compiler thinks you are trying to declare another function in the middle of another function.
If you want to invoke the default constructor (i.e. the one which takes no arguments), use this syntax instead:
MyClass object;
See also Garth Gilmour's answer to the now-deleted question What is your (least) favorite syntax gotcha?:
In C++
Employee e1("Dave","IT"); //OK
Employee e2("Jane"); //OK
Employee e3(); //ERROR - function prototype
|
2,308,657 | 2,308,688 | Question about COM Release() method | I am learning about COM and reading about this code:
STDMETHODIMP_ (ULONG) ComCar::Release()
{
if(--m_refCount==0) delete this;
return m_refCount;
}
My question is, if the m_refCount==0 and the object is deleted, how could the instance member variable m_refCount still exist and be returned? Please forgive me if my question is so naive cause I am a totally newbie on COM. Many thanks.
A related thread is here: How could a member method delete the object?
| Your concern is valid, the ref count should be moved into a local variable before the object is deleted.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
ULONG refCount = --m_refCount; // not thread safe
if(refcount==0) delete this;
return refCount;
}
But even that code is still wrong because it's not thread safe.
you should use code like this instead.
STDMETHODIMP_ (ULONG) ComCar::Release()
{
LONG cRefs = InterlockedDecrement((LONG*)&m_refCount);
if (0 == cRefs) delete this;
return (ULONG)max(cRefs, 0);
}
|
2,308,681 | 2,308,685 | What is the difference between a static variable in C++ vs. C#? | Do static variables have the same or similar functionality in C# as they do in C++?
Edit:
With C++ you can use static variables in many different contexts - such as: 1) Global variables, 2) Local function variables, 3) Class members - Would similar usages in C# behave similar to that of C++?
| Static has multiple meanings in C++.
Static variables in C# basically only have a single meaning: variables scoped to a type. In C#, static on a type is used to denote a type-scoped variable. Static on a method is a type-scoped method. Static can also be used on a class to denote that the entire class is comprised only of static methods, properties, and fields.
There is no equivelent to static variables within a function scope, or non-class scoped static values.
Edit:
In reponse to your edit, C# basically only uses static for class members. Globals and local static function variables are not supported in C#. In addition, as I mentioned above, you can flag an entire class "static", which basically just makes the compiler check that there are no non-static members in the class.
|
2,308,829 | 2,308,863 | Passing pointer to 2D array c++ | I'm having this problem for quite a long time - I have fixed sized 2D array as a class member.
class myClass
{
public:
void getpointeM(...??????...);
double * retpointM();
private:
double M[3][3];
};
int main()
{
myClass moo;
double *A[3][3];
moo.getpointM( A ); ???
A = moo.retpointM(); ???
}
I'd like to pass pointer to M matrix outside. It's probably very simple, but I just can't find the proper combination of & and * etc.
Thanks for help.
| double *A[3][3]; is a 2-dimensional array of double *s. You want double (*A)[3][3];
.
Then, note that A and *A and **A all have the same address, just different types.
Making a typedef can simplify things:
typedef double d3x3[3][3];
This being C++, you should pass the variable by reference, not pointer:
void getpointeM( d3x3 &matrix );
Now you don't need to use parens in type names, and the compiler makes sure you're passing an array of the correct size.
|
2,308,952 | 2,529,790 | Installing allegro c++ | I am trying to setup allegro to work with visual studio express 2008. But I don't know the set of instructions. I want to to recognize the allegro library. I would like to get some help regarding the installation procedure.
| The Allegro wiki has instructions for configuring a Visual Studio Express 2008 project...
with Allegro 4 (stable version)
with Allegro 5 (development version)
Here are some other excellent resources for Allegro-related development:
Allegro.cc annotated manual
Allegro.cc forums
Mailing lists for Allegro users and developers
|
2,309,091 | 2,309,156 | can not find C/C++ in project properties | I am following a tutorial and one of the steps its asking is to go to my projects properties and click on c/c++ and add a path to "Additional Include Directories" property. I am using visual C++ Express Edition 2008. the tutorial is using the same thing. Is there away to get this or an alternative ??
This is my screen
This is tutorials screen
| You don't have the C++ compiler options until you're actually using the C++ compiler. In this case, you don't have a .cpp file. So just add one and the compiler options will appear.
|
2,309,132 | 2,309,148 | How to convert virtual key code to character code? | In the onkeydown() handler I am getting 219 as the keycode for '['; however, the actual character value of '[' is 91. Is there any way to map these two?
| If you are using Windows, you should look into the ToUnicodeEx function.
|
2,309,301 | 2,309,416 | Not able to set read-only property in CFile in MFC? | I am creating a file which will have some details in it, and I don't want anybody to be able to edit it.
So, I decided to keep it as a read-only file. I tried the following code but it's popping up an exception when I set the status.
Please tell me if there's an alternative solution.
Here's my code:
CFile test(L"C:\\Desktop\\myText.txt",CFile::modeCreate|CFile::modeWrite);
CFileStatus status;
test.GetStatus(status);
status.m_attribute = CFile::readonly;
test.SetStatus(L"C:\\Desktop\\myText.txt",status);
| Try one of the following:
Close the file before changing the status with a call to CFile::Close() (test.Close() in your example.)
OR in the readonly attribute with the existing attributes, e.g. status.m_attribute |= CFile::readonly.
|
2,309,419 | 2,309,635 | Python equivalent of std::set and std::multimap | I'm porting a C++ program to Python. There are some places where it uses std::set to store objects that define their own comparison operators. Since the Python standard library has no equivalent of std::set (a sorted key-value mapping data structure) I tried using a normal dictionary and then sorting it when iterating, like this:
def __iter__(self):
items = self._data.items()
items.sort()
return iter(items)
However, profiling has shown that all the calls from .sort() to __cmp__ are a serious bottleneck. I need a better data structure - essentially a sorted dictionary. Does anyone know of an existing implementation? Failing that, any recommendations on how I should implement this? Read performance is more important than write performance and time is more important than memory.
Bonus points if it supports multiple values per key, like the C++ std::multimap.
Note that the OrderedDict class doesn't fit my needs, because it returns items in the order of insertion, whereas I need them sorted using their __cmp__ methods.
| For the sorted dictionary, you can (ab)use the stable nature of python's timsort: basically, keep the items partially sorted, append items at the end when needed, switching a "dirty" flag, and sort the remaining before iterating. See this entry for details and implementation (A Martelli's answer):
Key-ordered dict in Python
|
2,309,465 | 2,309,527 | C/C++ in Eclipse, can I use a #define to set a breakpoint, but only when steping through code? | Years ago I had a little #define which I used in Borland C++ Builder. From memory, it was something approximately like
#define BREAK_IF_DEBUGGING asm(0xA3);
or something like that. It relied on 0XA3 (or whatever it was) being the op code for the interrupt which Borland were using to trigger a breakpoint.
Can I do the same thing in Eclipse? (I'll probably wrap it in a few #idef ECLIPSE and #ifdef TESTING)
What I hope to achieve here is that
- the code compiles away to nothing in the release version, of course.
- if I run by unit tests with Ctrl-F11 then I don't want a breakpint to be triggered (which it won't because of Ctrl-F11 being "Run")
- if I "Run with Debug" using F11) then if executions hits any use of the macro then it will stop at a breakpoint.
Why? Because I want to set & forget. Just put one of these in each error leg (or embed it in my LOG_ERROR macro).
Often when I choose my initial breakpoint, it is too late, so this macro says "I think I want to run to line X, but if execution passes through one of those error branches first, I'd like to stop there & sniff around".
Whether you like the idea or not, can you tell me how to do it?
| what about
#define BREAK_IF_DEBUGGING asm("int3");
(the lack of space between int and 3 is intentional : int 3 being encoded differently from other interrupts, the gnu assembler mark this difference with this special syntax)
|
2,309,604 | 2,313,382 | Does anyone actually use stream extraction operators? | I've written tons of operator<<(std::ostream &, const T &) functions -- they're incredibly useful.
I've never written an operator>>(std::istream &, T &) function in real code or even used the extraction operators for built-in types (OK, maybe for std::string). Are these appropriate only for short example programs and textbooks? Is operator>> a failed feature of C++?
Questions have been asked about safely overloading stream operators. What I wonder is if anyone does this in practice.
Even for something simple like reading input from a file in C++ I can't suggest using operator>>. It's too difficult to write code that is robust in detecting and handling errors in input (or I don't know how).
If you disagree please show a good example of using operator>> -- maybe by answering that last question I linked to.
Wrapup: Thanks for the responses everyone, lots of good opinions. Manuel's answer made me reconsider my reluctance to using op>> so I accepted that one.
| I think stream extractor operators can be very useful when combined with STL algorithms like std::copy and with the std::istream_iterator class.
Read this answer to see what I'm talking about.
|
2,309,767 | 2,310,038 | C++ windows bitmap draw text | How can I draw text (with setting font and size) on image and save it as JPEG?
For example
CBitmap bitmap;
bitmap.CreateBitmap(width, height, 1, 32, rgbData);
Here I want to draw some text on bitmap:
CImage image;
image.Attach(bitmap);
image.Save(_T("C:\\test.bmp"), Gdiplus::ImageFormatJPEG);
| CBitmap bitmap;
CBitmap *pOldBmp;
CDC MemDC;
CDC *pDC = GetDC();
MemDC.CreateCompatibleDC(pDC);
bitmap.CreateCompatibleBitmap(pDC, width, height );
pOldBmp = MemDC.SelectObject(&MyBmp);
CBrush brush;
brush.CreateSolidBrush(RGB(255,0,0));
CRect rect;
rect.SetRect (0,0,40,40);
MemDC.SelectObject(&brush);
MemDC.DrawText("Hello",6, &rect, DT_CENTER );
MemDC.SetTextColor(RGB(0,0,255));
GetDC()->BitBlt(0, 0, 50, 50, &MemDC, 0, 0, SRCCOPY);
//When done, than:
MemDC.SelectObject(pOldBmp);
ReleaseDC(&MemDC);
ReleaseDC(pDC);
bitmap.Save(_T("C:\\test.bmp"), Gdiplus::ImageFormatJPEG);
Try this code snippet
|
2,310,368 | 2,310,476 | Raising or lowering RTS on serial port (C++) | I have a piece of code that can read current state of serial port CTS line, and application then goes into appropriate mode bases on value there.
Using null-modem cable described here:
http://www.lammertbies.nl/comm/info/RS-232_null_modem.html#full
i can detect RTS line on some other port that is connected via that null-modem cable.
Is there a way of programmatic raising or lowering RTS line?
Platform is Win32, c++, but any info on when is RTS line raised or lowered would be helpful.
| Take a look at EscapeCommFunction.
EscapeCommFunction(hPort, SETRTS);
The hardware handshaking must be disabled, i.e. dcb.fRtsControl should be set to something other than RTS_CONTROL_HANDSHAKE when calling SetCommState.
|
2,310,458 | 2,311,365 | CScrollbar works on one pc but not on any others | I've written some code in c++ using a CScrollbar which scrolls a CWnd and treeview at the same time. This works perfectly find on my pc, but on other pc's in the office it has problems:
it only scrolls up
it allows the user to scroll when they don't need to
I've tested this on Vista, XP, and Windows 7 and they all have the same result. My pc is running Windows XP.
My question is: do you know what might be the cause, and if not, how might I go about finding the cause? I don't really know where to start.
| The only thing I can think of would be an uninitialised variable. Potentially in one of your SetScrollInfo calls. e.g Are you setting the fMask member of SCROLLINFO correctly?
|
2,310,483 | 2,313,676 | Purpose of Unions in C and C++ | I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code
union ARGB
{
uint32_t colour;
struct componentsTag
{
uint8_t b;
uint8_t g;
uint8_t r;
uint8_t a;
} components;
} pixel;
pixel.colour = 0xff040201; // ARGB::colour is the active member from now on
// somewhere down the line, without any edit to pixel
if(pixel.components.a) // accessing the non-active member ARGB::components
is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately?
Update:
I wanted to clarify a few things in hindsight.
The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++.
After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1:
If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.
While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined.
C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R:
This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.
Extract from Stroustrup's TC++PL (emphasis mine)
Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion".
Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.
| The purpose of unions is rather obvious, but for some reason people miss it quite often.
The purpose of union is to save memory by using the same memory region for storing different objects at different times. That's it.
It is like a room in a hotel. Different people live in it for non-overlapping periods of time. These people never meet, and generally don't know anything about each other. By properly managing the time-sharing of the rooms (i.e. by making sure different people don't get assigned to one room at the same time), a relatively small hotel can provide accommodations to a relatively large number of people, which is what hotels are for.
That's exactly what union does. If you know that several objects in your program hold values with non-overlapping value-lifetimes, then you can "merge" these objects into a union and thus save memory. Just like a hotel room has at most one "active" tenant at each moment of time, a union has at most one "active" member at each moment of program time. Only the "active" member can be read. By writing into other member you switch the "active" status to that other member.
For some reason, this original purpose of the union got "overridden" with something completely different: writing one member of a union and then inspecting it through another member. This kind of memory reinterpretation (aka "type punning") is not a valid use of unions. It generally leads to undefined behavior is described as producing implementation-defined behavior in C89/90.
EDIT: Using unions for the purposes of type punning (i.e. writing one member and then reading another) was given a more detailed definition in one of the Technical Corrigenda to the C99 standard (see DR#257 and DR#283). However, keep in mind that formally this does not protect you from running into undefined behavior by attempting to read a trap representation.
|
2,310,487 | 2,310,529 | receiving datagrams sent by client over internet | I made two console app: Broadcasting listener and UDP writer (for practice only). Each run on different machine over the internet.
Broadcasting listener:
INADDR_ANY, port 5555
Udp writer:
Enabled Broadcasting (setsockopt, SO_BROADCAST)
Case:
The writer send some datagrams to listener server (ip: 113.169.123.138). Listener can receive those datagrams.
The writer broadcasting to 255.255.255.255. Listener can not receive anythings.
Question:
What i need to do to make case 2 work?
| Your broadcasts are meant for your subnet and not the internet.
For example DHCP -- this application is meant to perform broadcasts to assign IP addresses to machines logically part of a particular subnet.
If you join the reader machines subnet via a VPN, then the reader machine will be able to receive your broadcast.
|
2,310,656 | 2,310,692 | Reverse iteration from a given map iterator | I want to find an element in the map using map::find(key), and then iterate the map in reverse order from the point where I found the element, till the beginning (i.e. until map::rend()).
However, I get a compile error when I try to assign my iterator to a reverse_iterator. How do I solve this?
| Converting an iterator to a reverse iterator via the constructor should work fine, e.g. std::map<K, V>::reverse_iterator rit(mypos).
A minimal example using std::vector:
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
typedef std::vector<int> intVec;
intVec vec;
for(int i = 0; i < 20; ++i) vec.push_back(i);
for(intVec::reverse_iterator it(std::find(vec.begin(), vec.end(), 10));
it != vec.rend(); it++)
std::cout << *it;
}
|
2,310,659 | 2,310,667 | Odd C++ member function declaration syntax: && qualifier | From Boost::Thread:
template <typename R>
class shared_future
{
...
// move support
shared_future(shared_future && other);
shared_future(unique_future<R> && other);
shared_future& operator=(shared_future && other);
shared_future& operator=(unique_future<R> && other);
...
}
What on earth are those double-ampersands ? I went over "BS The C++ Langauge 3d edition" and couldn't find any explanation.
| This is a C++0x addition for rvalue references.
See http://www.artima.com/cppsource/rvalue.html.
|
2,310,911 | 2,317,119 | Why is it not possible to store a function pointer of a base class? | The following code gives an compilation error for void b() { m = &A::a; }; stating that A::a() is protected. (Which it is - but that should be no problem)
However the compiler doesn't care when I write B::a(). Even though both mean the same I would prefer A::a() because it states explicitely that a() is defined in A.
So what is the reason why A::a() is forbidden?
EDIT
Maybe someone can find an example that would be problematic if A::a() was allowed in B::b(). If there is such an example, I will mark it as answer to the question.
/EDIT
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdio>
class A {
protected:
void a(){ std::cout << "A::a()" << std::endl; };
};
typedef void (A::*f)();
class B : public A {
public:
void b() { m = &A::a; }; // wont compile
// void b() { m = &B::a; }; // works fine
void c() { (this->*m)(); };
protected:
f m;
};
int main(){
B b;
b.b();
b.c();
}
// compile with
// g++ -Wall main.cpp -o main
Explanation of the code:
In B I want to store a function pointer to a method in A to be able to call that later in B::c(). And yes, this happens in real life too. :-)
| The reason should be similar to why you can't do this in B either:
class B: public A
{
//...
void foo(A& x) {
x.a(); //error
}
void foo(B& x) {
x.a(); //OK
}
};
That protected doesn't mean that B can access the A part of any class as long it is an A / derived from A. The protected stuff is only available for this and other instances of B.
|
2,310,939 | 2,310,952 | Remove last character from C++ string | How can I remove last character from a C++ string?
I tried st = substr(st.length()-1); But it didn't work.
| For a non-mutating version:
st = myString.substr(0, myString.size()-1);
|
2,311,049 | 2,311,062 | deriving a templated class in c++ | I have a templated base class which follows:
template<class scalar_type, template<typename > class functor>
class convex_opt{ ..
};
How to derive a class from this templated class?
| template<class scalar_type, template<typename > class functor>
class derived : public convex_opt<scalar_type, functor> {
...
?
|
2,311,382 | 2,311,491 | std::stringstream and std::ios::binary | I want to write to a std::stringstream without any transformation of, say line endings.
I have the following code:
void decrypt(std::istream& input, std::ostream& output)
{
while (input.good())
{
char c = input.get()
c ^= mask;
output.put(c);
if (output.bad())
{
throw std::runtime_error("Output to stream failed.");
}
}
}
The following code works like a charm:
std::ifstream input("foo.enc", std::ios::binary);
std::ofstream output("foo.txt", std::ios::binary);
decrypt(input, output);
If I use a the following code, I run into the std::runtime_error where output is in error state.
std::ifstream input("foo.enc", std::ios::binary);
std::stringstream output(std::ios::binary);
decrypt(input, output);
If I remove the std::ios::binary the decrypt function completes without error, but I end up with CR,CR,LF as line endings.
I am using VS2008 and have not yet tested the code on gcc. Is this the way it supposed to behave or is MS's implementation of std::stringstream broken?
Any ideas how I can get the contents into a std::stringstream in the proper format? I tried putting the contents into a std::string and then using write() and it also had the same result.
| AFAIK, the binary flag only applies to fstream, and stringstream never does linefeed conversion, so it is at most useless here.
Moreover, the flags passed to stringstream's ctor should contain in, out or both. In your case, out is necessary (or better yet, use an ostringstream) otherwise, the stream is in not in output mode, which is why writing to it fails.
stringstream ctor's "mode" parameter has a default value of in|out, which explains why things are working properly when you don't pass any argument.
|
2,311,625 | 2,311,643 | What is the importance of invoking base class constructor explicitly? | class A {
A() { }
};
class B : public A {
B() : A() { }
};
Why do we need to call the base class's constructor explicitly inside B's constructor? Isn't it implicit?
| It is implicit. You'll need this syntax in case A has a constructor that has arguments, this is the way to pass them.
|
2,311,752 | 2,312,262 | Boost.Bind to access std::map elements in std::for_each | I've got a map that stores a simple struct with a key. The struct has two member functions, one is const the other not. I've managed calling the const function using std::for_each without any problems, but I've got some problems calling the non-const function.
struct MyStruct {
void someConstFunction() const;
void someFunction();
};
typedef std::map<int, MyStruct> MyMap;
MyMap theMap;
//call the const member function
std::for_each(theMap.begin(), theMap.end(),
boost::bind(&MyStruct::someConstFunction, boost::bind(&MyMap::value_type::second, _1)));
//call the non-const member function
std::for_each(theMap.begin(), theMap.end(),
boost::bind(&MyStruct::someFunction, boost::bind(&MyMap::value_type::second, _1)));
The call to the const member function works fine, but it seems boost internally expects a const MyStruct somewhere, and thus fails with the following compilation error in MSVC7.1.
boost\bind\mem_fn_template.hpp(151): error C2440: 'argument' : cannot convert from 'const MyStruct *__w64 ' to 'MyStruct *const '
I'd appreciate any help on how to set the template parameters correctly, so bind does recognize the parameters correctly and let me call the non const function.
thanks,
Carl
| IIRC, Boost.Bind uses boost::mem_fn for its binding to members capability. Now, if you look at mem_fun (scroll down to the // data member support part), you'll see that it typedefs its result_type as a const&, while is still has overloads of the function call operator supporting the extraction of a non-const member from a non-const argument.
It thus seems that the problem is that this confuses Boost.Bind's return type deduction mechanism. A solution would thus to explicitly tell Bind that the result is not const:
//call the non-const member function
std::for_each(theMap.begin(), theMap.end(),
boost::bind(&MyStruct::someFunction,
boost::bind<MyStruct&>(&MyMap::value_type::second, _1)
)
);
|
2,311,881 | 2,311,894 | How to insert pair into map | I have the following map structure: map < pair < int,int >, object* > and I wish to insert into it.
How would I do it since I am trying to insert a pair and an object and I must make a pair out of this?
Should I create a new pair using make_pair() out of the pair and object that I have? If so, could you please let me know how to do this?
| object * myObject = // get an object somehow
myMap.insert(std::make_pair(std::make_pair(1,2), myObject));
or
typedef map<pair<int, int>, object *> MapType;
object * myObject = // get an object somehow
myMap.insert(MapType::value_type(std::make_pair(1,2), myObject));
|
2,312,023 | 2,312,525 | Linking FriendlyNames from the Registry to drive letters for USB storage devices | I am writing an application that allows Syncing to USB storage devices and I would like to display the FriendlyName for the devices that can be found in the registry at HKLM\SYSTEM\CurrentControlSet\Enum\USBSTOR\
I am using GetLogicalDrives to get the list of available devices, GetDriveType to filter by DRIVE_REMOVABLE and GetVolumeInformation to retrieve the volume name and serial number.
I would like to also get the FriendlyName out of the registry by linking the USBSTOR entries to a drive letter so I know which entry is which drive.
| Tricky but possible. Have a peek at my post here. That approach is roughly in the right direction here, too. You don't want to use undocumented registry fields. Instead, use the Device Information Functions from the SetupAPI and Configuration Management API
|
2,312,106 | 2,312,503 | template specialization for CPPUnit isn't being used | If you've used CPPUnit before, you are probably aware of its assertion_traits class that is templatized to handle arbitrary types. This is what allows it to print the "actual" and "expected" values for non-string types when test cases fail. I have used this with success several times, but for one specific type it isn't working for me. Here is a partial declaration for my class, its parent's class, and some non-member operators (the whole thing is huge, plus my company won't let me post it):
class _declspec(dllexport) HWDBDateTime
{
public:
HWDBDateTime();
HWDBDateTime(const HWDBDateTime& other);
HWDBDateTime& operator=(const HWDBDateTime& other);
RWCString asString() const;
RWCString asString(const char *format, const boost::local_time::time_zone_ptr pZone = STimeZone::GetServerTimeZone()) const;
};
bool _declspec(dllexport) operator==(const HWDBDateTime& dt1, const HWDBDateTime& dt2);
bool _declspec(dllexport) operator!=(const HWDBDateTime& dt1, const HWDBDateTime& dt2);
bool _declspec(dllexport) operator< (const HWDBDateTime& dt1, const HWDBDateTime& dt2);
bool _declspec(dllexport) operator<=(const HWDBDateTime& dt1, const HWDBDateTime& dt2);
bool _declspec(dllexport) operator> (const HWDBDateTime& dt1, const HWDBDateTime& dt2);
bool _declspec(dllexport) operator>=(const HWDBDateTime& dt1, const HWDBDateTime& dt2);
class _declspec(dllexport) STimeStamp : public HWDBDateTime
{
public:
STimeStamp();
STimeStamp(const STimeStamp& other);
STimeStamp(const HWDBDateTime& other);
explicit STimeStamp(double d);
STimeStamp& operator=(double d);
operator double() const;
};
And here is my attempt at specializing the CPPUnit assertions class:
template <>
struct CppUnit::assertion_traits<STimeStamp>
{
static bool equal( STimeStamp x, STimeStamp y )
{
return x == y;
}
static std::string toString( STimeStamp x )
{
return (const char *)x.asString();
}
};
I've tried it passing by value, as seen above, also passing const references, I've tried casting the values inside the functions to HWDBDateTime (since that's where the operators and asString() methods are defined), nothing seems to help. I've put it at the top of my test suite's CPP file, and I've put it into a master header file that contains project-wide assertion_traits specializations, such as one for RWCString that works flawlessly. Somehow, whenever a test case fails, it insists on printing out my time as a floating-point value (presumably a double; a specialization for double is built in to CPPUnit) -- this is why I made sure to include my to/from double conversion operators in the minimized code above.
Is there something inherently wrong with what I'm doing? Does the specialization need to be present at a certain point in the compilation process, and maybe I just haven't found that point? Would this mythical point be per-translation-unit or per-project? I'm using VS2008.
| C++ type matching is the issue here.
The original type is probably const STimeStamp&. When coming from const T& most compilers prefers the implicit cast operators (in your case double) over creating a copy T.
This may be compiler specific...
|
2,312,129 | 2,312,217 | C++ class for arrays with arbitrary indices | Do any of the popular C++ libraries have a class (or classes) that allow the developer to use arrays with arbitrary indices without sacrificing speed ?
To give this question more concrete form, I would like the possibility to write code similar to the below:
//An array with indices in [-5,6)
ArbitraryIndicesArray<int> a = ArbitraryIndicesArray<int>(-5,6);
for(int index = -5;index < 6;++index)
{
a[index] = index;
}
| Really you should be using a vector with an offset. Or even an array with an offset. The extra addition or subtraction isn't going to make any difference to the speed of execution of the program.
If you want something with the exact same speed as a default C array, you can apply the offset to the array pointer:
int* a = new int[10];
a = a + 5;
a[-1] = 1;
However, it is not recommended. If you really want to do that you should create a wrapper class with inline functions that hides the horrible code. You maintain the speed of the C code but end up with the ability to add more error checking.
As mentioned in the comments, after altering the array pointer, you cannot then delete using that pointer. You must reset it to the actual start of the array. The alternative is you always keep the pointer to the start but work with another modified pointer.
//resetting the array by adding the offset (of -5)
delete [] (a - 5);
|
2,312,151 | 2,312,645 | Multiassignment in VB like in C-Style languages | Is there a way to perform this in VB.NET like in the C-Style languages:
struct Thickness
{
double _Left;
double _Right;
double _Top;
double _Bottom;
public Thickness(double uniformLength)
{
this._Left = this._Right = this._Top = this._Bottom = uniformLength;
}
}
| Expanding on Mark's correct answer
This type of assignment style is not possible in VB.Net. The C# version of the code works because in C# assignment is an expression which produces a value. This is why it can be chained in this manner.
In VB.Net assignment is a statement and not an expression. It produces no value and cannot be changed. In fact if you write the code "a = b" as an expression it will be treated as a value comparison and not an assignment.
Eric's recent blog post on this subject for C#
http://blogs.msdn.com/ericlippert/archive/2010/02/11/chaining-simple-assignments-is-not-so-simple.aspx
At a language level assignment is a statement and not an expression.
|
2,312,231 | 2,312,413 | C++ types and functions | I'm having some trouble compiling my code - it has to do with the types I'm passing in. Here is what the compiler says:
R3Mesh.cpp: In copy constructor 'R3Mesh::R3Mesh(const R3Mesh&)':
R3Mesh.cpp:79: error: no matching function for call to 'R3Mesh::CreateHalfEdge(R3MeshVertex*&, R3MeshFace*&, R3MeshHalfEdge*&, R3MeshHalfEdge*&)'
R3Mesh.h:178: note: candidates are: R3MeshHalfEdge* R3Mesh::CreateHalfEdge(const R3MeshVertex*&, const R3MeshFace*&, const R3MeshHalfEdge*&, const R3MeshHalfEdge*&)
R3Mesh.cpp: In constructor 'R3MeshHalfEdge::R3MeshHalfEdge(const R3MeshVertex*&, const R3MeshFace*&, const R3MeshHalfEdge*&, const R3MeshHalfEdge*&)':
R3Mesh.cpp:1477: error: invalid conversion from 'const R3MeshVertex*' to 'R3MeshVertex*'
R3Mesh.cpp:1477: error: invalid conversion from 'const R3MeshFace*' to 'R3MeshFace*'
R3Mesh.cpp:1477: error: invalid conversion from 'const R3MeshHalfEdge*' to 'R3MeshHalfEdge*'
R3Mesh.cpp:1477: error: invalid conversion from 'const R3MeshHalfEdge*' to 'R3MeshHalfEdge*'
Here is how I define my R3MeshHalfEdge:
struct R3MeshHalfEdge {
// Constructors
R3MeshHalfEdge(void);
R3MeshHalfEdge(const R3MeshHalfEdge& half_edge);
R3MeshHalfEdge(const R3MeshVertex*& vertex, const R3MeshFace*& face,
const R3MeshHalfEdge*& opposite, const R3MeshHalfEdge*& next);
R3MeshVertex *vertex;
R3MeshFace *face;
R3MeshHalfEdge *opposite;
R3MeshHalfEdge *next;
int id;
};
This is what the first error complains about:
R3MeshHalfEdge *R3Mesh::
CreateHalfEdge(const R3MeshVertex*& vertex, const R3MeshFace*& face,
const R3MeshHalfEdge*& opposite, const R3MeshHalfEdge*& next)
{
// Create half_edge
R3MeshHalfEdge *half_edge = new R3MeshHalfEdge(vertex, face, opposite, next);
// Set half_edge ID
half_edge->id = half_edges.size();
// Add to list
half_edges.push_back(half_edge);
// Return half_edge
return half_edge;
}
This is what the second error complains about:
R3MeshHalfEdge::
R3MeshHalfEdge(const R3MeshVertex*& vertex, const R3MeshFace*& face,
const R3MeshHalfEdge*& opposite, const R3MeshHalfEdge*& next)
: vertex(vertex),
face(face),
opposite(opposite),
next(next),
id(0)
{
}
Here is where I call the CreateHalfEdge function:
for(int i=0; i<mesh.NFaces(); i++)
{
R3MeshFace *f = mesh.Face(i);
vector<R3MeshVertex *> face_vertices; // assume vertices are stored in order around the perimeter of the face
for(unsigned int j = 0; j<f->vertices.size(); j++)
{
R3MeshVertex *v1 = f->vertices[j];
R3MeshVertex *v2;
if(j==f->vertices.size()-1)
v2 = f->vertices[0];
else
v2 = f->vertices[j+1];
int v1_id = v1->id;
int v2_id = v2->id;
R3MeshHalfEdge *next = NULL;
R3MeshHalfEdge *opposite = NULL;
R3MeshHalfEdge *half_edge = CreateHalfEdge(v1, f, opposite, next);
}
... }
| The constructor is wrong:
R3MeshHalfEdge(const R3MeshVertex*& vertex, const R3MeshFace*& face,
const R3MeshHalfEdge*& opposite, const R3MeshHalfEdge*& next);
You pass pointers to const and assign them to pointers to non-const, which fails.
Correct it like so:
R3MeshHalfEdge(R3MeshVertex* vertex, R3MeshFace* face,
R3MeshHalfEdge* opposite, R3MeshHalfEdge* next);
As a remark:
there are two level of const with pointers: pointers to const (const X*) and const pointers (X* const) the former can point to something else but cannot change the object pointed to while the latter cannot be rebound to another object but can change the object pointed. You can combine them to have a const pointer to const (const X* const)
don't pass pointers by reference (*&) unless you intend to modify the pointer itself, and not the object pointed.
|
2,312,252 | 2,312,280 | C++ long overflowing prematurely | I'm having a bizarre problem with C++ where the long data type is overflowing long before it should. What I'm doing (with success so far) is to have integers behave like floats, so that the range [-32767,32767] is mapped to [-1.0,1.0]. Where it stumbles is with larger arguments representing floats greater than 1.0:
inline long times(long a, long b) {
printf("a=%ld b=%ld ",a,b);
a *= b;
printf("a*b=%ld ",a);
a /= 32767l;
printf("a*b/32767=%ld\n",a);
return a;
}
int main(void) {
printf("%ld\n",times(98301l,32767l));
}
What I get as output is:
a=98301 b=32767 a*b=-1073938429 a*b/32767=-32775
-32775
So times(98301,32767) is analogous to 3.0*1.0. This code works perfectly when the arguments to times are less than 32767 (1.0), but none of the intermediate steps with the arguments above should overflow the 64 bits of long.
Any ideas?
| long is not necessarily 64 bits. try 'long long' instead.
|
2,312,363 | 2,312,518 | C++ template class T trouble | template <class T>
class List
{
public:
List();
~List();
...
protected:
template <class T> struct Item
{
struct Item* next;
T data;
};
...
struct Item<T>* allocate();
};
template <class T>
struct Item<T>* List<T>::allocate() // error here
{
...
return object; // struct Item<T>*
}
how can i do that?
| The problem is deeper in fact:
You don't have to declare Item as being template, because it's a nested class within a template class it has access to T.
template <class T>
class List
{
public:
private:
struct Item { ... };
};
And then you would define access like so:
template <class T>
typename List<T>::Item List<T>::access(...) {}
The point here is that List is a template class, so its parameters must be specified, while once T is specified for List it's not necessary to precise it once again.
Note typename ;)
|
2,312,502 | 2,312,582 | How to get 2-Sat values | Whenever I search for an algorithm for 2-Sat, I get back the algorithm for the decision form of the problem: Does there exist a legal set of values that satisfy all the clauses. However, that does not allow me to easily find a set of satisfying boolean values.
How can I efficiently find a legal set of values that will satisfy a 2-Sat instance?
I am working in c++ with the boost library and would appreciate code that can be easily integrated.
Thanks in advance
| If you have a decision algorithm for detecting if there exists a valid assignment to 2-SAT, you can use that to actually find out the actual assignment.
First run 2-SAT decision algorithm on the whole expression. Assume it says there is a valid assignment.
Now if x_1 is a literal, Assign x_1 to be 0. Now compute the 2-SAT for the resulting expression (you will have to assign some other literals because of this, for instance if x_1 OR x_3 appears, you also need to set x_3 to 1).
If the resulting expresion is 2-Satisfiable, then you can take x_1 to be 0, else take x_1 to 1.
Now you can find this out about each literal.
For a more efficient algorithm, I would suggest you try using the implication graph approach.
You can find more info here: http://en.wikipedia.org/wiki/2-satisfiability
The relevant portion:
a 2-satisfiability instance is
solvable if and only if every variable
of the instance belongs to a different
strongly connected component of the
implication graph than the negation of
the same variable. Since strongly
connected components may be found in
linear time by an algorithm based on
depth first search, the same linear
time bound applies as well to
2-satisfiability.
The literals in each strongly connected component are either all zero or all 1.
|
2,312,737 | 2,312,772 | What's a good way of *temporarily* sorting a vector? | I've got a std::vector which I need to sort by selected algorithms for certain operations, but to maintain its original state (e.g. items ordered by when they were entered) the rest of the time.
Obviously I can use std::copy to create a temporary vector and sort that, but I'm wondering if there's a better way, possibly by timestamping the items entered.
Cheers
| You could create a std::vector that holds all the indexes of the first vector. You could then sort the index-vector as you like. This should be fast and most importantly, doesn't mean you have to copy the first vector (which is probably more costly!).
|
2,312,802 | 2,312,831 | : error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [40]' | I am reading a book and It told me to open a empty WIN32 project. I created source file called main.cpp and put it in the source folder (This is the only file I have in my project). In that file put the following code:
#include <windows.h>
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nShowCmd)
{
MessageBox(NULL, "Motoko kusangai has hacked your system!", "Public Security Section 9", MB_OK | MB_ICONEXCLAMATION);
}
And run it. But I get the following error:
1>c:\users\numerical25\documents\visual studio 2008\projects\begin\begin\main.cpp(6) : error C2664: 'MessageBoxW' : cannot convert parameter 2 from 'const char [40]' to 'LPCWSTR'
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1>Build log was saved at "file://c:\Users\numerical25\Documents\Visual Studio 2008\Projects\Begin\Begin\Debug\BuildLog.htm"
1>Begin - 1 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
What am I doing wrong?
| You need to use a wide string in this case because you are compiling for unicode. Try prefixing all of your string constants with L.
MessageBox(
NULL,
L"Motoko kusangai has hacked your system!",
L"Public Security Section 9",
MB_OK | MB_ICONEXCLAMATION);
|
2,312,860 | 2,312,931 | correct idiom for std::string constants? | I have a map that represents a DB object. I want to get 'well known' values from it
std::map<std::string, std::string> dbo;
...
std::string val = map["foo"];
all fine but it strikes me that "foo" is being converted to a temporary string on every call. Surely it would be better to have a constant std::string (of course its probably a tiny overhead compared to the disk IO that just fetched the object but its still a valid question I think). So what is the correct idiom for std::string constants?
for example - I can have
const std::string FOO = "foo";
in a hdr, but then I get multiple copies
EDIT: No answer yet has said how to declare std::string constants. Ignore the whole map, STL, etc issue. A lot of code is heavily std::string oriented (mine certainly is) and it is natural to want constants for them without paying over and over for the memory allocation
EDIT2: took out secondary question answered by PDF from Manuel, added example of bad idiom
EDIT3: Summary of answers. Note that I have not included those that suggested creating a new string class. I am disappointed becuase I hoped there was a simple thing that would work in header file only (like const char * const ). Anyway
a) from Mark b
std::map<int, std::string> dict;
const int FOO_IDX = 1;
....
dict[FOO_IDX] = "foo";
....
std:string &val = dbo[dict[FOO_IDX]];
b) from vlad
// str.h
extern const std::string FOO;
// str.cpp
const std::string FOO = "foo";
c) from Roger P
// really you cant do it
(b) seems the closest to what I wanted but has one fatal flaw. I cannot have static module level code that uses these strings since they might not have been constructed yet. I thought about (a) and in fact use a similar trick when serializing the object, send the index rather than the string, but it seemed a lot of plumbing for a general purpose solution. So sadly (c) wins, there is not simple const idiom for std:string
| The copying and lack of "string literal optimization" is just how std::strings work, and you cannot get exactly what you're asking for. Partially this is because virtual methods and dtor were explicitly avoided. The std::string interface is plenty complicated without those, anyway.
The standard requires a certain interface for both std::string and std::map, and those interfaces happen to disallow the optimization you'd like (as "unintended consequence" of its other requirements, rather than explicitly). At least, they disallow it if you want to actually follow all the gritty details of the standard. And you really do want that, especially when it is so easy to use a different string class for this specific optimization.
However, that separate string class can solve these "problems" (as you said, it's rarely an issue), but unfortunately the world has number_of_programmers + 1 of those already. Even considering that wheel reinvention, I have found it useful to have a StaticString class, which has a subset of std::string's interface: using begin/end, substr, find, etc. It also disallows modification (and fits in with string literals that way), storing only a char pointer and a size. You have to be slightly careful that it's only initialized with string literals or other "static" data, but that is somewhat mitigated by the construction interface:
struct StaticString {
template<int N>
explicit StaticString(char (&data)[N]); // reference to char array
StaticString(StaticString const&); // copy ctor (which is very cheap)
static StaticString from_c_str(char const* c_str); // static factory function
// this only requires that c_str not change and outlive any uses of the
// resulting object(s), and since it must also be called explicitly, those
// requirements aren't hard to enforce; this is provided because it's explicit
// that strlen is used, and it is not embedded-'\0'-safe as the
// StaticString(char (&data)[N]) ctor is
operator char const*() const; // implicit conversion "operator"
// here the conversion is appropriate, even though I normally dislike these
private:
StaticString(); // not defined
};
Use:
StaticString s ("abc");
assert(s != "123"); // overload operators for char*
some_func(s); // implicit conversion
some_func(StaticString("abc")); // temporary object initialized from literal
Note the primary advantage of this class is explicitly to avoid copying string data, so the string literal storage can be reused. There's a special place in the executable for this data, and it is generally well optimized as it dates back from the earliest days of C and beyond. In fact, I feel this class is close to what string literals should've been in C++, if it weren't for the C compatibility requirement.
By extension, you could also write your own map class if this is a really common scenario for you, and that could be easier than changing string types.
|
2,313,432 | 2,313,488 | How to retrieve the Interface ID of a COM class so that it can be passed to CoCreateInstance? | I want to programaticly retrieve the Interface ID for any class so that I can pass it to CoCreateInstance. Any help is very much appreciated!!
See "How Do I Get This" below:
HRESULT hResult;
CLSID ClassID;
void *pInterface;
if(!(hResult = SUCCEEDED(CoInitialize(NULL))))
{
return 1;
}
if(S_OK == CLSIDFromProgID(OLESTR("Scripting.FileSystemObject"), &ClassID))
{
hResult = CoCreateInstance(ClassID, NULL, CLSCTX_INPROC_SERVER,
<<How Do I Get This?>>, (LPVOID *)&pInterface);
}
CoUninitialize();
EDIT: Thanks for all of the help, seems to work perfectly now! :
HRESULT hResult;
CLSID ClassID;
IClassFactory *pClf;
void *pVdb;
if(!(hResult = SUCCEEDED(CoInitialize(NULL))))
{
return 1;
}
if(SUCCEEDED(CLSIDFromProgID(OLESTR("Scripting.FileSystemObject"), &ClassID))
{
IDispatch *pDispatch;
if(SUCCEEDED(CoCreateInstance(ClassID, NULL, CLSCTX_INPROC_SERVER,
IID_IDispatch, (void **)&pDispatch))
{
OLECHAR *sMember = L"FileExists";
DISPID idFileExists;
if(SUCCEEDED(pDispatch->GetIDsOfNames(
IID_NULL, &sMember, 1, LOCALE_SYSTEM_DEFAULT, &idFileExists))
{
unsigned int puArgErr = 0;
VARIANT VarResult;
EXCEPINFO pExcepInfo;
VariantInit(&VarResult);
VariantInit(&pExcepInfo);
DISPPARAMS pParams;
memset(&pParams, 0, sizeof(DISPPARAMS));
pParams.cArgs = 1;
VARIANT Arguments[1];
VariantInit(&Arguments[0]);
pParams.rgvarg = Arguments;
pParams.cNamedArgs = 0;
pParams.rgvarg[0].vt = VT_BSTR;
pParams.rgvarg[0].bstrVal = SysAllocString(L"C:\\Test.txt");
hResult = pDispatch->Invoke(
idFileExists,
IID_NULL,
LOCALE_SYSTEM_DEFAULT,
DISPATCH_METHOD,
&pParams,
&VarResult,
&pExcepInfo,
&puArgErr
);
SysFreeString(pParams.rgvarg[0].bstrVal);
printf("File Exists? %d\n", abs(VarResult.boolVal));
}
pDispatch->Release();
}
}
CoUninitialize();
| You need to know upfront what interface you ask for. This you get from the product specifications, from SDK header files, or you can import the TLB of the COM object into your project.
the easisest way is to use #import
|
2,313,659 | 2,313,991 | Calling a second dialog from a dialog window fails to make either one active | Sorry for stupid questions, I'm doing everything as described in this tutorial:
http://www.functionx.com/visualc/howto/calldlgfromdlg.htm
I create the dialog window and try to call another dialog in response to a button press using the following code:
CSecondDlg Dlg;
Dlg.DoModal();
Modal window appears but isn't active, and main window isn't active too and everything lags.
Here is a screenshot:
Two dialogs interfering with each other http://img713.imageshack.us/img713/3919/63418833w.gif
And here are the definitions for my dialogs:
IDD_DIARY_TEST_DIALOG DIALOGEX 0, 0, 320, 200
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU
EXSTYLE WS_EX_APPWINDOW
CAPTION "diary_test"
FONT 8, "MS Shell Dlg", 0, 0, 0x1
BEGIN
DEFPUSHBUTTON "Second",IDC_SECOND_BTN,209,179,50,14
PUSHBUTTON "Cancel",IDCANCEL,263,179,50,14
CTEXT "TODO: Place dialog controls here.",IDC_STATIC,10,96,300,8
END
IDD_SECOND_DLG DIALOGEX 0, 0, 195, 127
STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_DISABLED | WS_CAPTION
CAPTION "Second"
FONT 8, "MS Shell Dlg", 400, 0, 0x0
BEGIN
LTEXT "TODO: layout property page",IDC_STATIC,53,59,90,8
PUSHBUTTON "Button1",IDC_BUTTON1,61,93,50,14
END
| Let's just compare the styles of the two dialogs:
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU STYLE DS_SETFONT | DS_FIXEDSYS | WS_POPUP | WS_VISIBLE | WS_DISABLED | WS_CAPTION
I've indicated the differences in bold, and the reason for your problems should now be obvious: your second dialog is disabled (WS_DISABLED), thus preventing it from being activated! Another difference, the missing DS_MODALFRAME style, will cause it to appear slightly abnormal (but shouldn't greatly affect the behavior); the final difference (WS_SYSMENU) merely prevents a system menu (and left icon, right close button) from being displayed.
The other oddity illustrated in your screenshot, the second dialog displayed mixed into the controls on the first, is probably due to your initial use of WS_CHILD as patriiice surmised...
Given this and the other code you posted, I suspect you originally created this as a property page. Property pages, while similar to normal dialog templates, are intended to be displayed as child windows; normal modal dialogs are not.
|
2,313,735 | 2,313,971 | Is there a better alternative to preprocessor redirection for runtime tracking of an external API? | I have sort of a tricky problem I'm attempting to solve. First of all, an overview:
I have an external API not under my control, which is used by a massive amount of legacy code.
There are several classes of bugs in the legacy code that could potentially be detected at run-time, if only the external API was written to track its own usage, but it is not.
I need to find a solution that would allow me to redirect calls to the external API into a tracking framework that would track api usage and log errors.
Ideally, I would like the log to reflect the file and line number of the API call that triggered the error, if possible.
Here is an example of a class of errors that I would like to track. The API we use has two functions. I'll call them GetAmount, and SetAmount. They look something like this:
// Get an indexed amount
long GetAmount(short Idx);
// Set an indexed amount
void SetAmount(short Idx, long amount);
These are regular C functions. One bug I am trying to detect at runtime is when GetAmount is called with an Idx that hasn't already been set with SetAmount.
Now, all of the API calls are contained within a namespace (call it api_ns), however they weren't always in the past. So, of course the legacy code just threw a "using namespace api_ns;" in their stdafx.h file and called it good.
My first attempt was to use the preprocessor to redirect API calls to my own tracking framework. It looked something like this:
// in FormTrackingFramework.h
class FormTrackingFramework
{
private:
static FormTrackingFramework* current;
public:
static FormTrackingFramework* GetCurrent();
long GetAmount(short Idx, const std::string& file, size_t line)
{
// track usage, log errors as needed
api_ns::GetAmount(Idx);
}
};
#define GetAmount(Idx) (FormTrackingFramework::GetCurrent()->GetAmount(Idx, __FILE__, __LINE__))
Then, in stdafx.h:
// in stdafx.h
#include "theAPI.h"
#include "FormTrackingFramework.h"
#include "LegacyPCHIncludes.h"
Now, this works fine for GetAmount and SetAmount, but there's a problem. The API also has a SetString(short Idx, const char* str). At some point, our legacy code added an overload: SetString(short Idx, const std::string& str) for convenience. The problem is, the preprocessor doesn't know or care whether you are calling SetString or defining a SetString overload. It just sees "SetString" and replaces it with the macro definition. Which of course doesn't compile when defining a new SetString overload.
I could potentially reorder the #includes in stdafx.h to include FormTrackingFramework.h after LegacyPCHIncludes.h, however that would mean that none of the code in the LegacyPCHIncludes.h include tree would be tracked.
So I guess I have two questions at this point:
1: how do I solve the API overload problem?
2: Is there some other method of doing what I want to do that works better?
Note: I am using Visual Studio 2008 w/SP1.
| Well, for the cases you need overloads, you could use a class instance that overloads operater() for a number of parameters.
#define GetAmount GetAmountFunctor(FormTrackingFramework::GetCurrent(), __FILE__, __LINE__)
then, make a GetAmountFunctor:
class GetAmountFunctor
{
public:
GetAmountFunctor(....) // capture relevant debug info for logging
{}
void operator() (short idx, std::string str)
{
// logging here
api_ns::GetAmount(idx, str);
}
void operator() (short idx)
{
/// logging here
api_ns::GetAmount(Idx);
}
};
This is very much pseudocode but I think you get the idea. Whereever in your legacy code the particular function name is mentioned, it is replaced by a functor object, and the function is actually called on the functor. Do consider you only need to do this for functions where overloads are a problem. To reduce the amount of glue code, you can create a single struct for the parameters __FILE__, __LINE__, and pass it into the constructor as one argument.
|
2,313,894 | 2,314,082 | Visual Studio C++ exception... weirdness | I have a Qt application that I compile in release configuration, run, and then perform operation X in the program. Everything runs fine.
I then compile it in debug configuration, run without debugging (so CTRL+F5), perform operation X in the program. Everything still runs dandy fine.
But when I try to run the debug configuration with debugging (so just F5) and then perform operation X, Visual Studio breaks in with a message that an exception has been thrown... in a completely unrelated part of the program (code being executed is far from the site where VS breaks, in the QHash template)... and then VS hangs and I have to kill it with the Task Manager. I can repeat this ad infinitum, and it always freaks out the same way.
Boost::exception is used for the exceptions. VS is 2008, SP1. Qt is 4.6.2, using the precompiled VS binaries from the Qt site.
Does anyone have a clue what is going on?
| Visual Studio has a feature called "first chance exception handling" where, when running attached to the debugger, you can have the debugger break when exceptions of certain types are thrown.
You can change these settings by going to Debug -> Exceptions (Ctrl+Alt+E) and (un)checking the appropriate checkboxes.
When it breaks you should get a message in the Output window indicating what exception was thrown.
If you have _HAS_ITERATOR_DEBUGGING enabled (it is enabled by default in debug builds), it can cause a lot of iterator errors to throw exceptions instead of performing operations that would cause access violations. That's the only thing I can think of off the top of my head that would cause an exception to occur "randomly."
|
2,314,005 | 2,314,347 | How do I convert my program to use C++ namespaces? | My code was working fine, until I tried to wrap all of my class definitions in a namespace.
// "Player.h"
#include "PhysicsObject.h"
namespace MaelstromII
{
class Player : public MaelstromII::PhysicsObject
{
// ...
};
}
// "PhysicsObject.h"
#include "GameObject.h"
namespace MaelstromII
{
class PhysicsObject : public MaelstromII::GameObject
{
// ...
};
}
// "GameObject.h"
namespace MaelstromII
{
class GameObject
{
// ...
};
}
When I compile in Visual Studio, I get a bunch of these errors:
error C2039: 'PhysicsObject' : is not a member of 'MaelstromII'
It complains about GameObject, too.
Does anyone know why this is?
| Turns out the trouble was caused by a circular dependency in my code somewhere else. After fixing that problem, my code compiled fine.
Evidently, there is no difference between this:
namespace Foo {
class Bar {}
class Bar2 : public Bar {}
}
And this:
namespace Foo {
class Bar {}
class Bar2 : public Foo::Bar {}
}
The compiler resolves them the same way.
|
2,314,008 | 2,314,024 | C++ in template initialization | Given the following piece of code:
template<typename T>
class MyContainer
{
typedef T value_type;
typedef unsigned int size_type;
...
};
How one should initialize variables using size_type (like loop indexes)?
Should it be:
for(size_type currentIndex = size_type(0);currentIndex < bound;++currentIndex)
or
for(size_type currentIndex = static_cast<size_type>(0);currentIndex < bound;++currentIndex)
The rationale for the question is to produce code that will still work when type underlying size_type is changed or added to template parameters.
Thanks...
| There are four possibilities I see:
size_type();
size_type(0);
static_cast<size_type>(0);
0;
I would prefer the last one. It's concise, and has the same effect as the rest.
You're probably worried that if the type change this won't work, or something. The thing is, size_type's are, by convention, unsigned integers. 0 is always going to be a valid value as long as size_type is a sensible & correct size-measuring type.
|
2,314,066 | 2,314,089 | do {...} while(false) | I was looking at some code by an individual and noticed he seems to have a pattern in his functions:
<return-type> function(<params>)
{
<initialization>
do
{
<main code for function>
}
while(false);
<tidy-up & return>
}
It's not bad, more peculiar (the actual code is fairly neat and unsurprising). It's not something I've seen before and I wondered if anyone can think of any logic behind it - background in a different language perhaps?
| You can break out of do{...}while(false).
|
2,314,078 | 2,314,646 | Passing data around with QMimeData in Qt drag and drop | I'm trying to understand how data gets passed around when using drag and drop in Qt. From what I understood from the examples I've been studying, you first define a widget as draggable by overriding methods inherited through QWidget.
In the implementation of the overridden method, the examples I've been looking at instantiate a pointer to a QMimeData object, and store information in it by calling setText(const QString &text) and setData(const QByteArray &data). They store information in the QByteArray object with the << operator:
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
dataStream << labelText << QPoint(ev->pos() - rect().topLeft());
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-fridgemagnet", itemData);
mimeData->setText(labelText);
In the definition of the dropEvent() method in the widget that accepts the drops, both of those variables were retrieved with the >> operator:
QString text;
QPoint offset;
dataStream >> text >> offset;
In the setData() method, application/x-fridgemagnet was passed as a MIME type argument. Was that defined somewhere else or its just something you can make up?
How can I store and retrieve a custom object inside the QMimeData object? I tried this:
dataStream << labelText << QPoint(ev->pos() - rect().topLeft()) << myObject;
and tried to retrieve it like this:
myClass myObject;
dataStream >> text >> offset >> myObject;
But it didn't work, says theres "no match for 'operator >>'". Any tips on what should I do?
|
In the setData() method, application/x-fridgemagnet was passed as a MIME type argument. Was that defined somewhere else or its just something you can make up?
If the data is in your own proprietary format, then you can make it up. If, however, it's something standardized, like images, you'll probably want to use a known mime-type.
If you already support serialization to XML, then it would be easy to create your own mime-type, serialize to XML, and then de-serialize on the receiving end.
How can I store and retrieve a custom object inside the QMimeData object?
You'll need to create non-member operators (<< and >>) that write out MyObject's member data in a way supported by QDataStream. See the QDataStream documentation under the heading "Reading and Writing other Qt Class."
That will involve creating the following two methods:
QDataStream &operator<<(QDataStream &, const MyObject &);
QDataStream &operator>>(QDataStream &, MyObject &);
Since these are non-member operators, they will be defined outside your class:
class MyObject { /* ... */ };
QDataStream &operator<<(QDataStream &stream, const MyObject &obj) {
/* as long as first_member and second_member are types supported
by QDataStream, I can serialize them directly. If they're not
supported, I'd need an operator for them as well unless I can
convert them to a QString or something else supported by Qt /
QDataStream */
stream << obj.first_member;
stream << obj.second_member;
/* and so on and so forth */
return stream;
}
/* and similarly for operator>> */
|
2,314,196 | 2,314,270 | push_back to a Vector | I have a weird problem. I have a vector that I would like to push objects on to like so:
vector<DEMData>* dems = new vector<DEMData>();
DEMData* demData = new DEMData();
// Build DEMDATA
dems->push_back(*demData);
There will be a few hundred DEMData objects in the vector. The problem is when this code is finished, all items are equal to the last item "pushed back" to the vector?
Why are the other objects being overridden in the vector?
edit:
The DemData class is simple, just a data structure with setters and getters:
class DEMData
{
private:
int bitFldPos;
int bytFldPos;
const char* byteOrder;
const char* desS;
const char* engUnit;
const char* oTag;
const char* valType;
int index;
public:
void SetIndex(int index);
int GetIndex() const;
void SetValType(const char* valType);
const char* GetValType() const;
void SetOTag(const char* oTag);
const char* GetOTag() const;
void SetEngUnit(const char* engUnit);
const char* GetEngUnit() const;
void SetDesS(const char* desS);
const char* GetDesS() const;
void SetByteOrder(const char* byteOrder);
const char* GetByteOrder() const;
void SetBytFldPos(int bytFldPos);
int GetBytFldPos() const;
void SetBitFldPos(int bitFldPos);
int GetBitFldPos() const;
friend std::ostream &operator<<(std::ostream &stream, DEMData d);
};
EDIT:
I am reading an XML file and building DEMData objects based on the attributes of each xml element:
DEMData demData;
for (i = 0; attr[i]; i += 2)
{
if(strcmp(attr[i],"BitFldPos") == 0)
{
demData.SetBitFldPos(*attr[i + 1] - '0');
}
else if(strcmp(attr[i],"BytFldPos") == 0)
{
char* pEnd;
int tmp = strtol(attr[i + 1],&pEnd,10);
demData.SetBytFldPos(tmp);
}
else if(strcmp(attr[i],"ByteOrder") == 0)
{
demData.SetByteOrder(attr[i + 1]);
}
else if(strcmp(attr[i],"DesS") == 0)
{
demData.SetDesS(attr[i + 1]);
}
else if(strcmp(attr[i],"EngUnit") == 0)
{
demData.SetEngUnit(attr[i + 1]);
}
else if(strcmp(attr[i],"OTag") == 0)
{
demData.SetOTag(attr[i + 1]);
}
else if(strcmp(attr[i],"ValTyp") == 0)
{
demData.SetValType(attr[i + 1]);
}
else if(strcmp(attr[i],"idx") == 0)
{
char* pEnd;
int tmp = strtol(attr[i + 1],&pEnd,10);
demData.SetIndex(tmp);
}
//printf(" %s='%s'", attr[i], attr[i + 1]);
}
// Insert the data in the vector.
dems.push_back(demData);
| Why are you allocating the vector with new? Why are you allocating your temporary DEMData object with new?
A vector stores a copy of what you pass to it, not that data itself, so unless you're deleting the DEMData object you allocated with new, you're leaking memory ever time you push an item onto the vector. Likewise, you're setting yourself up for memory leak problems by allocating the vector dynamically.
As to why the objects in the vector all seem to contain the same data, chances are pretty good that you have more of the same -- probably use of pointers combined with an incorrect copy ctor that ends up doing shallow copies a few places it shouldn't -- but since you haven't shown us that code, that's only a guess.
Edit: Now that you've added the code for your DEMData class, it looks very much like the guess above was correct -- you have pointers and no user-defined copy ctor, so you're getting a shallow copy.
As a first step, I'd get rid of all the pointer char members, and replace them with std::strings. The int members should be all right -- copying them will copy the values.
Edit2: Given what you're doing with these member variables, it looks a lot like you should consider using two std::maps -- one for the std::string variables, and one for the int variables.
|
2,314,419 | 2,318,689 | Script for changing C++ class names | I have moved my classes from a global namespace into a specific namespace. I have also changed the class names. I want to convert all my source files that use these classes to the new format. I was thinking either a bash script using a sed file on Cygwin or executing a perl script. I'm having troubles with the bash script.
Here's the process I'm trying to perform:
For each source file, *.cpp and
*.hpp, recursively:
If the file contains an old class
name, then convert the file.
End for.
My problem in Bash script is detecting if the file contains an old class name. I was thinking of one grep statement for each class name:
for f in `find . -iname \*.[ch]pp`;
do
if [ grep "Field_Blob_Medium" $f -eq 0 || grep "Field_Boolean" ]; then
sed -f conversion.sed $f
fi
done
An issue is that only one command can be in Bash if statement, using this syntax:
if grep "Field_Unsigned_Short" $f;
so I can't do a logical OR of greps.
I could perform a nested loop, but I don't know how to break out of a Bash for loop:
OLD_CLASS_NAMES="Field_Blob_Medium Field_Boolean Field_Unsigned_Int"
for f in `find . -iname \*.[ch]pp`;
do
for c_name in $OLD_CLASS_NAMES;
do
if grep $c_name $f then
sed -f convert.sed $f # <-- Need to break out of inner loop after this execution.
fi
done
done
So I'm looking for suggestions on how to process every source file that contains old class names and convert them to new ones. A Cygwin Bash script example is preferred, although a Perl script would also be acceptable. Also, the script should make a backup copy of the original source file before writing the converted contents out to the new file.
I'm running Cygwin on Windows XP and Windows Vista.
| Don't shy away from Perl: it makes this sort of task easy!
#! /usr/bin/perl -i.bak
use warnings;
use strict;
my $old = join "|" => qw(
Field_Blob_Medium
Field_Boolean
Field_Unsigned_Int
);
chomp(@ARGV = `find . -iname \*.[ch]pp -print0 |
xargs -0 grep -lE '($old)'`);
unless (@ARGV) {
warn "$0: nothing to do!\n";
exit 0;
}
while (<>) {
s[Field_Blob_Medium] [my::ns::MediumBlob]g ||
s[Field_Boolean] [my::ns::Bool]g ||
s[Field_Unsigned_Int] [my::ns::UInt]g;
print;
}
The -i switch is for in-place editing. It automatically creates backups and writes the transformed results to the original locations.
Setting @ARGV makes it as though you had invoked the program with only those *.cpp and *.hpp files that contain the old class names. The -E switch to grep enables extended regular expressions so unescaped (, ), and | are metacharacters.
If there were no hits (i.e., if @ARGV is empty), then there's nothing to do.
Otherwise, for each line of each file that has the old names (the mechanics of which Perl handles for you!), try to rename Field_Blob_Medium to my::ns::MediumBlob and so on. Note that these substitution attempts cease after the first success, so if a line contains two different old names, one will be replaced and the other will remain the same.
Usually the substitution operator is written s///, but you may use bracketing delimiters as above. I did so to left-justify the new names.
Of course this is a stand-in for your actual substitution.
Finally, print the possibly-modified line, which because of -i writes it to the updated source file.
|
2,314,664 | 2,314,723 | Why numeric_limits<int>::min() is differently defined? | To retrieve the smallest value i have to use numeric_limits<int>::min()
I suppose the smallest int is -2147483648, and tests on my machine showed this result.
But some C++ references like Open Group Base Specifications and
cplusplus.com define it with the value -2147483647.
I ask this question because in my implementation of the negaMax Framework (Game Tree Search)
the value minimal integer * (-1) has to be well defined.
Yes, with minimal int = (numeric_limits::min() + 2) i am on the safe side in any case,
thus my question is more theoretically but i think nevertheless quite interesting.
| If a value is represented as sign-and-magnitude instead of two's complement, the sign bit being one with all other bits as zero is equivalent to -0. In sign-and-magnitude the maximum positive integer and negative integer are the same magnitude. Two's complement is able to represent one more negative value because it doesn't have the same symmetry.
|
2,314,816 | 2,327,724 | Remove all handlers from a boost::asio::io_service without calling them | I want to remove all handlers from an IO_service right before I reuse it. Is this possible?
I'm writing unit tests that involve an asio::io_service. In between each test case I want to clear the handlers from the global io_service. I thought that io_service::reset would to that but it doesn't. reset() only allows the io_service to be resumed. All of the handlers from the last test case are still queued up.
I only need to do this for unit testing so any crazy hack would work.
More info:
The io_service is from a deadline_timer member variable. The deadline_timer is part of the code I'm testing so I can't change how it's constructed. I get a hold of its io_service via the deadline_timer's get_io_service method.
| Well, I racked my brain on this for a few days and came up with a workable solution. It's the mother of all hacks.
void clear( boost::asio::io_service& service )
{
service.stop();
service.~io_service();
new( &service ) boost::asio::io_service;
}
I'm not sure how safe this would be for productions code. But so far it seems to work (no segfaults, no weird behavior).
|
2,315,095 | 2,315,134 | Do people still write their own data structures and algorithms? | Instead of the STL and similar libraries in other languages?
As a newbie, how much should I delve into this part of software development? Breadth first or depth?
Is only a conceptual understanding necessary these days? Or should I be able to implement a doubly linked list blindfolded?
| While no one really rolls their own stacks or queues anymore, it -is- very important to understand how and why they are different. So no, to use simple data structures effectively, it's not 100% necessary to be able to do all the proper error checking for loops/null tail/concurrency/etc in a linked list while blindfolded.
However, while the simplest data structures aren't rewritten over and over, trees and graphs are often still custom rolled, and you probably won't be able to do anything with those without understanding more basic data structures.
Also, these often fall under 'interview questions', so they're worth knowing how to do even if you don't actually rewrite a doubly linked list in live code.
|
2,315,311 | 2,315,333 | What is a long pointer? | I am reading a book and it mentions certain data type as being long pointer. Just curious about what that meant. Thanks.
| Some processors have two types of pointers, a near pointer and a far pointer. The near pointer is narrower (thus has a limited range) than a far pointer. A far pointer may also be a long pointer.
Some processors offer relative addressing for things nearby. A long pointer may indicate that the item is not close by and relative addressing cannot be used.
In any case, long pointers are a platform specific issue and may not be portable to other OSes or platforms.
Edit: (further explanation and usage of relative addressing)
Address distances are less of a high level concept and more of an assembly language concept. The distance is measured from the program counter (either the current address or the next address) and the start of the object (function or data). If the location is greater than the limit for a small, relative pointer, a longer pointer will be necessary.
Example: Given a system with 32 bit "long" addressing and 8-bit relative addressing. The relative distance would allow for at least 127 bytes in the forward (positive value) or previous (negative) direction. If the target is 1024 bytes away, a full 32-bit pointer must be used.
This is an optimization feature based on the concept that most instructions and data are near by. The majority of loops have a small distance between the start of the loop and end of the loop. These employ relative addressing for execution.
Most data is nearby, whether a data constant or a variable. In more detail, the data is near a frame or reference point. Local variables are placed on the stack, relative to a frame or base address. This base address is the start of the stack before the function is executed. Thus the data can be accessed using addressing relative to the stack frame start.
The processors allow compilers to use specialized instructions for relative (near) addressing. On many processors, the instructions to use relative addressing are smaller than instructions using long address. Thus the processor requires less fetching from the instruction cache and the instruction cache can hold more instructions.
Long and short, near and far, addressing may depend on the scope of the data or function. There are other factors involved, such a PIC (position indepent code), virtual memory and paging.
|
2,315,398 | 2,315,418 | Reference initialization in C++ | Can anybody explain to me why there is a difference between these two statements?
class A{};
const A& a = A(); // correct
A& b = A(); // wrong
It says
invalid initialization of non-const reference of type A& from a temporary of type A
Why does const matter here?
| Non-const references must be initialised with l-values. If you could initialise them with temporaries, then what would the following do?
int& foo = 5;
foo = 6; // ?!
const references have the special property that they extend the life of the referee, and since they are const, there is no possibility that you'll try to modify something that doesn't sit in memory. For example:
const int& foo = 5;
foo = 6; // not allowed, because foo is const.
Remember that references actually have to refer to something, not just temporary variables. For example, the following is valid:
int foo = 5;
int& bar = foo;
bar = 6;
assert(foo == 6);
|
2,315,423 | 2,316,337 | 3DS model loading - tree/hierarchies | I am using the 3DS loader here:
http://www.flipcode.com/archives/Another_3DS_LoaderViewer_Class.shtml
It does a good job of loading and rendering the model, however it lacks any sense of heirarchy. As a result, all the objects in the model render at the origin.
In the code under: void Model_3DS::MainChunkProcessor(long length, long findex) is the line:
// I left this in case anyone gets very ambitious
case KEYF3DS :
//KeyFrameChunkProcessor(h.len, ftell(bin3ds));
break;
Nobody has implemented this anywhere, and I don't see any other 3DS loaders that implement it too. People seem to only post up and until they reach this point having been satisfied with anything rendering on to the screen at all.
What would KeyFrameChunkProcessor look like?
| Google led me here:
Keyframer chunk
---------------
id Description
---- -----------
B00A unknown
7001 See first description of this chunk
B008 Frames
B009 unknown
B002 Start object description
* B008 - Frame information
simple structure describing frame info
start end size type name
0 3 4 unsigned long start frame
4 7 4 unsigned long end frame
*B002 - Start of Object info
Subhunks
id Description
---- -----------
B010 Name & Hierarchy
B011* Name Dummy Object
B013 unknown
B014* unknown
B015 unknown
B020 Objects pivot point ?
B021 unknown
B022 unknown
B030 unknown
* B010 - Name & Hierarchy descriptor
start end size type name
0 ? ? ASCIIZ Object name
? ? ? unsigned int unknown
? ? ? unsigned int unknown
? ? ? unsigned int Hierarchy of Object
The object hierarchy is a bit complex but works like this.
Each Object in the scene is given a number to identify its
order in the tree. Also each object is orddered in the 3ds
file as it would appear in the tree.
The root object is given the number -1 ( FFFF ).
As the file is read a counter of the object number is kept.
Is the counter increments the object are children of the
previous objects.But when the pattern is broken by a number
what will be less than the current counter the hierarchy returns
to that level.
for example.
object hierarchy
name
A -1
B 0 This example is taken
C 1 from 50pman.3ds
D 2
E 1 I would really reccomend
F 4 having a look at one of the
G 5 examples with the hierarchy
H 1 numbers to help work it out.
I 7
J 8
K 0
L 10
M 11
N 0
O 13
P 14
A
+-----------------+----------------+
B K N
+----+----+ + +
C E H L O
+ + + + +
D F I M P
+ +
G J
Still not done with this chunk yet !
If the object name is $$$DUMMY then it is a dummy object
and therefore you should expect a few extra chunks.
|
2,315,453 | 2,315,480 | C++: Operator matches across classes | I'm trying to do the following operation:
R3MeshHalfEdge *tmp_edge = half_edge;
R3Vector *tmp_vector = new R3Vector(R3zero_vector);
do
{
**tmp_vector += tmp_edge->face->plane.Normal();**
tmp_edge = tmp_edge->opposite->next;
}while(tmp_edge != half_edge);
However, the compiler gives me the following error:
R3Mesh.cpp: In member function ‘void R3MeshVertex::UpdateNormal()’:
R3Mesh.cpp:1291: error: no match for ‘operator+=’ in ‘tmp_vector += tmp_edge->R3MeshHalfEdge::face->R3MeshFace::plane.R3Plane::Normal()’
HalfEdge has the following structure:
class R3MeshHalfEdge {
public:
// Constructors
R3MeshHalfEdge(R3MeshVertex* vertex, R3MeshFace* face);
R3MeshVertex *vertex;
R3MeshFace *face;
R3MeshHalfEdge *opposite;
R3MeshHalfEdge *next;
int id;
};
Face has the following structure:
class R3MeshFace {
public:
// Constructors
R3MeshFace(void);
R3MeshFace(const R3MeshFace& face);
R3MeshFace(const vector <R3MeshVertex *>& vertices);
// Property functions
double Area(void) const;
// Data
vector<R3MeshVertex *> vertices;
R3Plane plane;
R3MeshHalfEdge *half_edge;
int id;
};
Vector has the following public operation defined in the class:
class R3Vector {
public:
R3Vector& operator+=(const R3Vector& vector);
}
It is implemented as such:
R3Vector& R3Vector::
operator+=(const R3Vector& vector)
{
// Add vector to this
v[0] += vector.v[0];
v[1] += vector.v[1];
v[2] += vector.v[2];
return *this;
}
I don't understand why the compiler is giving the error.
Edit:
I forgot to include the Normal() definition for R3Plane:
class R3Plane{
public:
const R3Vector& Normal(void) const;
}
| Looks like you added two asterisks before and after the offending line.
R3Vector *tmp_vector = new R3Vector(R3zero_vector);
do
{
**tmp_vector += tmp_edge->face->plane.Normal();**
Supposing you added two, and not one, at the beginning of the line, you had
tmp_vector += tmp_edge->face->plane.Normal();
and tmp_vector is a pointer so you want
*tmp_vector += tmp_edge->face->plane.Normal();
|
2,315,728 | 2,315,816 | QImage from datastream | I'm using the Qt library, creating QImages.
I'm able to use this constructor:
QImage image("example.jpg");
But I'm having trouble with this static function:
char buffer[sizeOfFile];
ifstream inFile("example.jpg");
inFile.read(buffer, sizeOfFile);
QImage image = QImage::fromData(buffer); // error here
// but there's nothing wrong with the buffer
ofstream outFile("bufferOut.jpg");
outFile.write(buffer, sizeOfFile);
Where Qt spits out to console:
Corrupt JPEG data: 1 extraneous bytes before marker 0xd9
JPEG datastream contains no image
The above isn't exactly what I have, but it's the only important difference. (I need to be able to read from a buffer because I'm opening images that are inside a zip archive.)
| Tnx to peppe from #qt on irc.freenode.net:
The solution is to explicitly include the buffer length. Ignoring a few unsigned char to char typecasting and other details, what I should have used is something akin to:
QImage image = QImage::fromData(buffer, sizeOfFile);
|
2,315,729 | 2,315,822 | intellisense for previously declared variables and constants | I am using MSVS C++ Express 2008. Right now my intellisense only works for objects that have methods or arguments in a method. Is it possible to set it where it detects declared constants and varibles that are within scope. Thanks
| It should work when you hover over a constant, or any variable for that matter. It should show you the definition. I'm not sure if there are any feature differences between the Express and "real" versions, but I don't believe so.
Some things to try:
Do a rebuild of the solution.
Restart VS.
There is a file in your solution root directory with an ".ncb" extension. Delete it and restart VS. This forces VS to rebuild the Intellisense database.
Intellisense is notoriously flakey...
|
2,315,760 | 2,315,865 | Any memory usage paradigm besides Stack and Heap? | As I have learned data structure, I know there are plenty of other data stuctures besides Stack and Heap, why the processes nowadays only contain these 2 paradigm as the "standard equipment" in their address space? Could there be any brand new paradigm for memory usage?
Thanks for your replies. Yes, I realized that something is wrong with my statement. The heap data structure is not the same as the heap in a process' address space. But what I am wondering is besides Stack area and Heap area in the proecss address space, is there any new paradigm to use memory? It seems that other ways of memory usage is built upon these two basic paradigms. And these 2 paradigms are kind of some meta-paradigms?
| Let's think for a moment. We have two fundamental storage disciplines. Contiguous and Fragmented.
Contiguous.
Stack is constrained by order. Last in First Out. The nesting contexts of function calls demand this.
We can easily invert this pattern to define a Queue. First in First Out.
We can add a bound to the queue to make a Circular Queue. Input-output processing demands this.
We can combine both constraints into a Dequeue.
We can add a key and ordering to a queue to create a Priority Queue. The OS Scheduler demands this.
So. That's a bunch of variations on contiguous structures constrained by entry order. And there are multiple implementations of these.
You can have contiguous storage unconstrained by entry order: Array and Hash. An array is indexed by "position", a hash is indexed by a hash function of a Key.
Fragmented:
The bare "heap" is fragmented storage with no relationships. This is the usual approach.
You can have heap storage using handles to allow relocation. The old Mac OS used to do this.
You can have fragmented storage with relationships -- lists and trees and the like.
Linked Lists. Single-linked and doubly-linked lists are implementation choices.
Binary Trees have 0, 1 or 2 children.
Higher-order trees. Tries and the like.
What are we up to? A dozen?
You can also look at this as "collections" which exist irrespective of the storage. In this case you mix storage discipline (heapish or array-ish)
Bags: unordered collections with duplicates allowed. You can have a bag built on a number of storage disciplines: LinkedBag, TreeBag, ArrayBag, HashBag. The link and tree use fragmented storage, the array and hash use contiguous storage.
Sets: unordered collections with no duplicates. No indexing. Again: LinkedSet, TreeSet, ArraySet, HashSet.
Lists: ordered collections. Indexed by position. Again: LinkedList, TreeList, ArrayList, HashList.
Mapping: key-value association collections. Indexed by key. LinkedMap, TreeMap, ArrayMap, HashMap.
|
2,315,768 | 2,337,781 | how do i send keystrokes to only one program? | i have been having a hard time to find anything that is usefull but i found someone asked how to do that,(How to send keystrokes to a window?)
if used the code and i can set notepad's text but i want to send keys but sets the text, i
want to send keys like keybd_event i have been using it but i want to only have it send to one program.
keybd_event('a', NULL, NULL, NULL);
keybd_event('a', NULL, KEYEVENTF_KEYUP, NULL);
how could i do that?
| Sounds like you're trying to make a window have the focus before sending your keys. Look at FindWindow and SetForegroundWindow.
Something like this should work:
SetForegroundWindow(FindWindow(0,"Untitled - Notepad"));
keybd_event(....);
If instead you're talking about changing a window's text directly, look at GetWindow to navigate the window tree and SendMessage with a WM_SETTEXT parameter.
|
2,315,819 | 2,315,835 | How can I slow down a TCP connection on Windows? | I am developing a Windows proxy program where two TCP sockets, connected through different adapters are bridged by my program. That is, my program reads from one socket and writes to the other, and vice versa. Each socket is handled by its own thread. When one socket reads data it is queued for the other socket to write it. The problem I have is the case when one link runs at 100Mb and the other runs at 10Mb. I read data from the 100Mb link faster than I can write it to the 10Mb link. How can I "slow down" the faster connection so that it is essentially running at the slower link speed? Changing the faster link to a slower speed is not an option. --Thanks
| Create a fixed length queue between reading and writing threads. Block on the enqueue when queue is full and on dequeue when it's empty. Regular semaphore or mutex/condition variable should work. Play with the queue size so the slower thread is always busy.
|
2,315,886 | 2,315,894 | return value of prefix and postfix in C++ | Why in C++ the prefix return a reference but the postfix return a value?
| Because with prefix you modify the object and then return it (so it can be lvalue), and with postfix you return the unchanged object (i.e. a copy) and only then update it (this is of course done by first storing the copy in a temporary, updating the original object, and then returning the temporary by value.)
|
2,315,971 | 2,559,024 | XPCOM C++: Does it support RegExps? | I'm developing a XPCOM C++ component that have to use some RegExps functions
Does XPCOM C++ have build-in support for RegExps?
| It was planned for Firefox 1.0 but after a long thread there was a decision not to add it to core XPCOM.
|
2,316,148 | 2,316,208 | What are real-world examples of C++ multiple inheritance? | Besides textbook examples -- in the real world -- does it ever make sense to use multiple inheritance (where more than one of the base classes are not pure interfaces) in C++?
| It's very common when using Policy-based design, for example.
|
2,316,230 | 2,322,981 | Is There any Following C++ Blocking Condition Variable | I would like the have the following Blocking Condition Variable
Once the blocking condition variable had been signaled, all threads will not wait on the particular condition variable
The condition variable can be unsignaled anytime.
Once condition variable had been unsignaled, all threads will be waiting on the variable
I look at http://www.boost.org/doc/libs/1_34_0/doc/html/boost/condition.html
However, it doesn't work in (1)
As if there are no thread waiting on the condition variable, the notify_one/notify_all called, will make the signal lost
1) thread TA try wait on condition variable C
2) thread TB call `notify_all`
3) thread TA will continue execution
1) thread TB call `notify_all`
2) thread TA wait on condition variable C
3) thread TA will still continue waiting <-- How can I have condition variable C remains in
signaled state, and make no wait for thread TA
| The solution is to have a manual reset Event as follow :
CreateEvent(0, TRUE, TRUE, 0);
Once it had been signaled through SetEvent, it will always be in signaled state.
|
2,316,269 | 2,316,275 | Should I put global application details in a static class? | I'm currently maintaining a legacy C++ application which has put all the global application details in a static class, some of the variables stored are:
application name
registry path
version number
company name etc..
What is the recommended method for storing and accessing system application details?
| If it never changes then why not. However, if not I'd externalise it into data that's loaded at run time. This way it can change without rebuild.
And since you include version number, I'd suspect the latter is way to go.
From my C++ days I recall builds taking not inconsequential times.
|
2,316,285 | 2,318,057 | qtreewidgetitem addchild to already present item yields nothing | I have two QTreeWidgetItem that are top level. I want to make the second the parent of the first. Calling the first one's addChild(second item) shows no change. How would I accomplish this?
| You probably have to remove the item you want to reparent first using takeItem(), and subsequently add it as a child to the new parent item.
|
2,316,386 | 2,316,716 | Using SetKeyboardState along with GetKeyboardState in C++ | I don't know how to write a good question here, but, basically, does anyone know where I can possibly find some C++ source code using these to actually set keyboard state? For some reason using it the way MSDN does on Windows 7 doesn't do...anything at all.
Basic code:
PBYTE keyState;
GetKeyboardState(keyState);
...
// Later on when I need to set the keyboard state (key pressed etc) back to original:
SetKeyboardState(keyState);
and ... nothing happens :(
| From:
http://www.gamedev.net/community/forums/topic.asp?topic_id=43463
First off, GetKeyboardState() would be the wrong function to use because as Windows has a chance to process keyboard messages (whether you want it too or not) it updates the results of the keyboard's state for the next call to GetKeyboardState().
Here's a little function that I use to get the status of the keyboard's keys. Be carefull though, depending on how fast your main loop is, it may cause problems if you aren't expecting it.
You need to keep track of whether or not a specific key was pressed the last time you called the ReadKeyboard() function. If your loop polls the keyboard 30 times a second, then pressing a key once probably causes the key to be flagged 3 or 4 calls in a row. Rather confusing sometimes. Just thought I'd mention it.
void ReadKeyboard( char* keys )
{
for (int x = 0; x < 256; x++)
keys[x] = (char) (GetAsyncKeyState(x) >> 8);
}
|
2,316,425 | 2,316,829 | Directx9 Specular Mapping | How would I implement loading a texture to be used as a specular map for a piece of geometry and rendering it in Directx9 using C++?
Are there any tutorials or basic examples I can refer to?
| Use D3DXCreateTextureFromFile to load the file from disk. You then need to set up a shader that multiplies the specular value by the value stored in the texture. This gives you the specular colour.
So you're final pixel comes from
Final = ambient + (N.L * texture colour) + (N.H * texture specular)
You can do this easily in a shader.
Its also worth noting that it can be very useful to store the per texel specular in the alpha channel of the texture. This way you only need one texture around, though it does break per-pixel transparency.
|
2,316,470 | 2,316,488 | How do I fix this formula error? | I have this code in my program: (I included the cout statements for debugging purposes)
cout << "b: " << b << "\na: " << a;
constant[0] = (-b / (2 * a));
cout << "\nconstant: " << constant[0] << endl;
The output I get is:
b: -4
a: 3
constant: 0
Whereas I'm trying to make constant[0] equal to -(-4)/(2 * 3), or 0.6666...
What am I doing wrong with the formula I put there?
| Undoubtably you have a and b defined as integers, causing your whole formula to be done in integer math. Either define them as floating point numbers or do something like this:
constant[0] = (-b / (2.0 * a));
which forces the math to be done in floating point.
|
2,316,672 | 6,400,968 | Opening fstream with file with Unicode file name under Windows using non-MSVC compiler | I need to open a file as std::fstream (or actually any other std::ostream) when file name is "Unicode" file name.
Under MSVC I have non-standard extension std::fstream::open(wchar_t const *,...)? What can I do with other compilers like GCC (most important) and probably Borland compiler.
I know that CRTL provides _wfopen but it gives C FILE * interface instead of io-streams, maybe there is a non-standard way to create io-stream from FILE *? Is there any boost::ifstream with MSVC like extension for Windows?
| Currently there is no easy solution.
You need to create your own stream buffer that uses _wfopen under the hood. You can use for this for example boost::iostream
|
2,316,820 | 2,317,017 | MSVC Dependencies vs. References | I have always used the Visual Studio Dependencies option to ensure that, for example, when building my C++ projects, any dependent LIB or DLL projects are also built. However, I keep hearing people mention 'references' and wondered, with VS 2010 on the horizon, I should be changing how I do this.
Are there any benefits to using references to dependencies or is the former a .NET feature only? I am currently using VS2008.
| I prefer using references since these were introduced for unmanaged C++ in VS 2005. The difference (in unmanaged C++ developer's perspective) is that reference is stored in .vcproj file, while project dependencies are stored in .sln file.
This difference means that when you reuse your project in different solutions (and I often do) you don't need to redefine the inter-project relationships again.
Visual Studio is smart enough not to depend gravely on the paths of the projects when it establishes the reference relationship.
|
2,316,927 | 2,324,777 | How to convert UNC to local path | I'm looking for a method to get corresponding local path for a given UNC path. Microsoft provides a small library CheckLCL for this purpose. This library is not supported on all Windows versions. Does anybody know any open source method for this?
There is also MAPI function ScLocalPathFromUNC, but am not sure if it works on all platforms.
| After some googling and digging in MSDN i have the following solution:
#include <Crtdbg.h> // for debug stuff
#include "Winnetwk.h" // for WNetGetUniversalName()
#include "Lm.h" // for NetShareGetInfo()
#include "pystring.h" // from http://code.google.com/p/pystring
#pragma comment( lib, "Mpr.lib" ) // for WNetGetUniversalName()
#pragma comment( lib, "Netapi32.lib" ) // for NetShareGetInfo()
//-----------------------------------------------------------------------------
// converts x:\\folder -> \\\\server\\share\\folder
bool ConvertLocalPathToUNC(const char* szFilePath, std::string& strUNC)
{
// get size of the remote name buffer
DWORD dwBufferSize = 0;
char szBuff[2];
if (::WNetGetUniversalName(szFilePath, UNIVERSAL_NAME_INFO_LEVEL, szBuff, &dwBufferSize) == ERROR_MORE_DATA)
{
// get remote name of the share
char* buf = new char[dwBufferSize];
UNIVERSAL_NAME_INFO* puni = (UNIVERSAL_NAME_INFO*) buf;
if (::WNetGetUniversalName(szFilePath, UNIVERSAL_NAME_INFO_LEVEL, buf, &dwBufferSize) == NO_ERROR)
{
strUNC = puni->lpUniversalName;
delete [] buf;
return true;
}
delete [] buf;
}
return false;
}
//-----------------------------------------------------------------------------
// converts \\\\server\\share\\folder -> x:\\folder
bool ConvertUNCToLocalPath(const char* szUNC, std::string& strLocalPath)
{
// get share name from UNC
std::string strUNC(szUNC);
std::vector< std::string > vecTokens;
pystring::split(strUNC, vecTokens, _T("\\"));
if (vecTokens.size() < 4)
return false;
// we need wchar for NetShareGetInfo()
std::wstring strShare(vecTokens[3].length(), L' ');
std::copy(vecTokens[3].begin(), vecTokens[3].end(), strShare.begin());
PSHARE_INFO_502 BufPtr;
NET_API_STATUS res;
if ((res = NetShareGetInfo(NULL, const_cast<LPWSTR>(strShare.c_str()), 502, (LPBYTE*) &BufPtr)) == ERROR_SUCCESS)
{
// print the retrieved data.
_RPTF3(_CRT_WARN, _T("%ls\t%ls\t%u\n"), BufPtr->shi502_netname, BufPtr->shi502_path, BufPtr->shi502_current_uses);
std::wstring strPath(BufPtr->shi502_path);
strLocalPath.assign(strPath.begin(), strPath.end());
// build local path
for (size_t i = 4; i < vecTokens.size(); ++i)
{
if (!pystring::endswith(strLocalPath, _T("\\")))
strLocalPath += _T("\\");
strLocalPath += vecTokens[i];
}
// Validate the value of the shi502_security_descriptor member.
if (IsValidSecurityDescriptor(BufPtr->shi502_security_descriptor))
_RPTF0(_CRT_WARN, _T("It has a valid Security Descriptor.\n"));
else
_RPTF0(_CRT_WARN, _T("It does not have a valid Security Descriptor.\n"));
// Free the allocated memory.
NetApiBufferFree(BufPtr);
}
else
return false;
return true;
}
|
2,317,127 | 2,317,160 | Not able to read the contents in the file in MFC using the function Cfile? | I am not able to read the contents in the file if I manually write something in the file...If there are contents existing already am able to read the contents...but if I go and manually write something in the file and try to read I am not able to read the contents that I have edited..check the code below that I am using to read....
CFile file;
if(file.open("C:\\users\\rakesh\\Desktop\\myText.txt",CFile::modeRead))
{
return false;
}
TCHAR buffer[50];//say content is small
file.read(buffer,50);
file.close();
| Looks like an unicode-problem. My guess is that your project is set to use unicode, but your editor writes ascii.
|
2,317,502 | 2,317,566 | Unresolved external symbol when lib is linked, compiler adds the letter 'A' to the function name | I get this error when trying to link a win32 exe project. I have linked in the lib that contains the code for this method. But still gets an unresolved symbol error.
error LNK2001: unresolved external symbol "public: bool __thiscall SharedJobQueue::AddJobA(class boost::shared_ptr<class domain::Job>)" (?AddJobA@SharedJobQueue@@QAE_NV?$shared_ptr@VJob@domain@@@boost@@@Z)
Why does it say AddJobA with the 'A' at the end. The method is declared as AddJob.
I have looked in the output from 'dumpbin /symbols' and it only contains symbols for AddJob not AddJobA. Why do the compiler add an 'A' to the end of the function name?
| And here we see the problem with macros.
There is nothing wrong with your code per se, the problem is with the windows libraries. There is actually a function called AddJob in the Win32 headers, but not quite... The don't declare an Addjob function, but instead an AddJobA and an AddJobW function, which deal with non-unicode and unicode strings respectively.
The A at the end of your function name is due to a macro defined in the windows header that was defined to deal with unicode. Essentially they'll have something like:
#ifdef UNICODE
# define AddJob AddJobW
#else
# define AddJob AddJobA
#endif
This allows people to just use AddJob and the macros will point the function towards the correct unicode/non-unicode function. The problem of course is that the #define affects everything, which is what's happening to your function.
To fix this, you can either #undef AddJob or simply change the name of your function to something that isn't a Win32 function.
|
2,317,539 | 2,318,461 | Are there any XSLT to C++ compilers available? | I found only one attempt to create such compiler - http://sourceforge.net/projects/xsltc/.
But this project is dead for decade already. Are there any other examples? Opensource or commercial?
Are there any fundamental technical difficulties with building such software? With the whole approach of compiling XSLT natively?
I suppose there are good use cases for using it - places where we don't need to change XSLT but still would like to get higher performance (and probably, lower memory requirements).
Are there any other reasons this software may be not so efficient as it looks? - Are interpreting XSLT processors as efficient as compiled would probably be?
| From my understanding, XSLT isn't very popular anymore. Generally, it's easier and more powerful to use your favorite XML library for your language of choice, parse your XML data, and write code to format the output the way you want it.
On the other hand, it seems like you have had some success with it already. There are cases when it's useful. Check this SO question out for more details on the pros and cons of XSLT.
Anyway, software developers in general aren't big fans of XSLT, which would explain why there hasn't been a big movement to write an optimized XSLT parser in C++.
|
2,317,554 | 2,317,694 | How to Store a VARIANT | I need to store a VARIANT of type bstr in a stl vector. I'm not sure how should I store VARIANT type in vector.
vector<VARIANT> vec_MyVec;
VARIANT var_Temp;
VariantInit(&var_Temp);
var_Temp.vt = VT_BSTR
var_Temp.bstrVal = SysAllocString("Test");
vec_MyVec.push_back(var_Temp);
Is this implementation cause a memory leak ? What would be the best way to store VARIANTS ?
Thank you
| Yes, you're leaking memory.
Whenever you allocate memory with the SysAllocString family, you must either free it using SysFreeString or pass it to something that will take responsibility for freeing it. The VARIANT type does not clean up its own memory.
You have a couple of options for fixing it:
Use CComVariant or variant_t. It provides an operator=, copy constructors and a destructor that manage the memory for you. The drawback to storing them in a vector is that temporary copies will be created and destroyed (the same as if you'd stored std::string). This is the easiest, and my preferred, solution.
Call SysFreeString on every string in vec_MyVec when you're finished. This is more efficient but also much more error prone and difficult to do correctly, especially when considering exception safety.
Store a vector of std::tr1::shared_ptr<CComVariant>, this will prevent temporary copies being created, but you'll have the overhead of reference counting instead.
|
2,317,559 | 2,317,729 | overriden virtual function is not getting called | a more exact version of the code is:
class SomeParam;
class IBase
{
public:
virtual void Func(SomeParam* param = NULL)
{
cout << "Base func";
}
};
class DerivedA : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedA func";
IBase::Func();
}
};
class DerivedB : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedB func";
IBase::Func();
}
};
//at somewhere else
void FuncCaller(IBase *instance1, IBase *instance2)
{
IBase *i1 = instance1;
IBase *i2 = instance2;
i1->Func();
i2->Func();
}
DerivedA *a = new DerivedA;
DerivedB *b = new DerivedB;
FuncCaller(a,b);
This gives me:
"Base func"
"Base func"
| It looks like you have provided a simplified version of your code to make it more readable, but you have oversimplified inadvertently.
The most likely reasons for your behaviour are:
Slicing in FuncCaller() (see quamrana's answer for the details)
Wrong overriding, such as making the derived class function const, while the base class function is not const
EDIT: After reading the edited question, it is clearly the second reason. You are not overriding the base class function, but hiding it in the derived classes with a new definition. You need to keep exactly the same signature (covariance does not apply here, since the function returns void) in the derived classes. In code, you need to do either:
class SomeParam;
class IBase
{
public:
virtual void Func(SomeParam* param = NULL)
{
cout << "Base func";
}
};
class DerivedA : public IBase
{
public:
void Func(SomeParam* param = NULL)
{
//do some custom stuff
cout << "DerivedA func";
IBase::Func();
}
};
class DerivedB : public IBase
{
public:
void Func(SomeParam* param = NULL)
{
//do some custom stuff
cout << "DerivedB func";
IBase::Func();
}
};
//at somewhere else
void FuncCaller(IBase *instance1, IBase *instance2)
{
IBase *i1 = instance1;
IBase *i2 = instance2;
i1->Func();
i2->Func();
}
DerivedA *a = new DerivedA;
DerivedB *b = new DerivedB;
FuncCaller(a,b);
or
class SomeParam;
class IBase
{
public:
virtual void Func()
{
cout << "Base func";
}
};
class DerivedA : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedA func";
IBase::Func();
}
};
class DerivedB : public IBase
{
public:
void Func()
{
//do some custom stuff
cout << "DerivedB func";
IBase::Func();
}
};
//at somewhere else
void FuncCaller(IBase *instance1, IBase *instance2)
{
IBase *i1 = instance1;
IBase *i2 = instance2;
i1->Func();
i2->Func();
}
DerivedA *a = new DerivedA;
DerivedB *b = new DerivedB;
FuncCaller(a,b);
|
2,317,588 | 2,317,759 | Deploying a Custom Program to a Hosting Service | I am a total newbie in servers/hosting etc, although I have some experience in programming in C,Java,etc. So excuse me if the question is 'absurd'.
I recently bought service from a hosting site,namely this(hostmds). I have some code I've written in C++ and I want to run it in the hosting site. So my question is:
Is this possible, or will I have to rewrite everything in a new language?
What should my approach be?
Edit: I have a Shared-Hosting account.
| You will have to get a "virtual private server" account from your host in order to do this. This will enable you to compile your program on your host machine and run it essentially as if it were a separate machine under your control.
This means you will also be responsible for maintaining your own HTTP server program (such as Apache, if running on a Linux/Unix host), and your own database servers and other support.
If you have a "shared hosting" account (the most common low cost option) with SSH support, you may be able to compile your program, and even run it, but you will be subject to the whims (capricious or otherwise) of the administrators of your system (that it, you may find that libraries you need are removed or moved around)
|
2,317,616 | 2,317,655 | Best way of organising load/save functions in terms of static/non-static | I have a class which defines a historical extraction on a database:
class ExtractionConfiguration
{
string ExtractionName;
time ExtractionStartTime;
time ExtractionEndTime;
// Should these functions be static/non-static?
// The load/save path is a function of ExtractionName
void SaveConfigruation();
void LoadConfiguration();
}
These ExtractionConfigurations need to be saved to/loaded from disk. What is the best way of organising the save/load functions in terms of static/non-static? To me, it is clear that SaveConfiguration() should be a member function. However with LoadConfiguration(), does it make more sense to call
ExtractionConfiguration newExtraction;
newExtraction.LoadConfiguration();
and have a temporary empty instance or make the load function static
static ExtractionConfiguration LoadConfiguration(string filename);
and just call
ExtractionConfiguration newExtraction = ExtractionConfiguration::LoadConfiguration(filename);
which feels neater to me, but breaks the 'symmetry' of the load/save mechanism (is this even a meaningful/worthwhile consideration?).
I suppose asking for the 'best' answer is somewhat naive. I am really trying to get a better understanding of the issues involved here.
P.S. This is my first question on SO, so if I have not presented it correctly, please let me know and I will try and make the problem clearer.
| You should consider using Boost.Serialization style serialization function that avoids having separate functions for saving and loading (even if you don't use the library itself).
In this approach you can pass the function any type of object that has operator&, to perform an operation on all the member variables. One such object might save the data to a file, another might load from a file, third might print the data on console (for debugging, etc).
If you wish to keep separate functions, having them as non-static members might be a better option. For the saving function this is obvious, but loading is a different matter because there you need to construct the object. However, quite commonly loading is done by default-constructing and then calling the load non-static member function, for symmetry reasons, I guess.
Having the loading as a function that returns a new object seems better in some ways, but then you need to decide how it returns the object. Is it allocated by new, or simply returned by value? Returning by value requires the object to be copyable and returning a pointer mandates the resource management scheme (cannot just store the object on stack).
|
2,317,972 | 2,318,060 | graceful thread termination with pthread_cond_signal proving problematic | I need to fire of a bunch of threads and would like to bring them down gracefully.
I'm trying to use pthread_cond_signal/pthread_cond_wait to achieve this but am running into a problem.
Here's my code. firstly the thread_main
static void *thrmain( void * arg )
{
// acquire references to the cond var, mutex, finished flag and
// message queue
.....
while( true )
{
pthread_mutex_lock( &lock );
if ( msq.empty() )
{
// no messages so wait for one.
pthread_cond_wait( &cnd, &lock );
}
// are we finished.
if ( finished )
{
// finished so unlock the mutex and get out of here
pthread_mutex_unlock( &lock );
break;
}
if ( !msg.empty() )
{
// retrieve msg
....
// finished with lock
pthread_mutex_unlock( &lock );
// perform action based on msg
// outside of lock to avoid deadlock
}
else
{
// nothing to do so we're
// finished with the lock.
pthread_mutex_unlock( &lock );
}
}
return 0;
}
Now, this all looks fine and dandy (to me anyway).
So to tear down the threads I have this method
void teardown()
{
// set the global finished var
pthread_mutex_lock( &lock );
finished = true;
pthread_mutex_unlock( &lock );
// loop over the threads, signalling them
for ( int i = 0 ; i < threads.size() ; ++i )
{
// send a signal per thread to wake it up
// and get it to check it's finished flag
pthread_cond_signal( &cnd );
}
// need to loop over the threads and join them.
for ( int i = 0 ; i < threads.size() ; ++i )
{
pthread_join( threads[ i ].tid, NULL );
}
}
Now I know that pthread_cond_signal doesn't guarantee which thread it wakes up so I can't signal and join in the same loop. However, this is where it's all going wrong. pthread_cond_signal does nothing if there is no thread waiting so potentially some of the threads won't have been signalled and therefore won't know to exit.
How do I over come this.
M.
***** UPDATE *******
Please don't post that I should use pthread_cond_broadcast as this exhibits EXACTLY THE SAME BEHAVIOUR. it will only wake up a thread which is actually waiting on the cond var. Any thread that is processing during this time and comes back to wait later will have missed the signal and will be oblivious
| Firstly, you have to change your predicate from
if ( msq.empty() ) {
// no messages so wait for one.
pthread_cond_wait( &cnd, &lock );
}
to
while ( msq.empty() ) {
// no messages so wait for one.
pthread_cond_wait( &cnd, &lock );
}
That's a pthreads thing, you have to guard yourself against spurious wakeups.
Now you can change that to
while ( msq.empty() && !finished) {
// no messages so wait for one.
pthread_cond_wait( &cnd, &lock );
}
Since after that check, you already test whether finished is set and exits if so,
all you have to do is signal all the threads.
So, in your teardown function, replace the loop with:
pthread_cond_broadcast(&cond);
That should ensure all threads wake up, and will see finished set to true and exit.
This is safe even if your threads are not stuck in pthread_cond_wait. If the threads are processing a message, they will not get the wakeup signal, however they will finish that processing, enter the loop again and see that finished == false and exit.
Another common pattern for this is to inject a poison message. A poison message is simply a special message your thread could recognise that would mean "STOP", you would place as many of those messages in your queue as you have threads.
|
2,318,028 | 2,318,232 | Is it possible to use HTTPS certificates for licensing? | I am working on an application with multiple clients and a server running various web-services for the clients. To implement licensing I am thinking about using HTTPS as a protocol for the web-services using certificates that are issued by our company. By influencing the expiration date of a certificate for a client we can prevent them from using our software after their license term.
It this possible and does it make sense to you?
Additional information: I am planning on using Qt/C++ for the clients, and the Twisted framework for the web-services.
| It should work. I don't know Twisted well, but you can place an Apache proxy in front of the web service, and have that handle certificate based authentication.
As for the client side, watch this bug. libcurl should provide you with an escape route if Qt gives problems.
You'll need to think through the procedures around the CA, to make sure this works operationally: Are your sales and billing departments comfortable with issuing a hard cut-off date to each customer? Will the certificate be issued on purchase order, or payment of invoice?
|
2,318,122 | 2,318,174 | Double Quoted Strings in C++ | How to converted string with space in double quoted string.
For Example:
I get string
c:\program files\abc.bat
I want to convert this string to "c:\program files\abc.bat" but only if there is space in the string.
| Assuming the STL string s contains the string you want to check for a space:
if (s.find(' ') != std::string::npos)
{
s = '"' + s + '"';
}
|
2,318,306 | 2,318,316 | Is alloca part of the C++ standard? | Is alloca part of the C++ standard?
| No. The answer says it all.
|
2,318,454 | 2,318,592 | Some basic questions on constructors (and multiple-inheritance) in C++? | (I’m sorry if this has been asked before; the search feature seems to be broken: the results area is completely blank, even though it says there are a few pages of results… in Chrome, FireFox, and Safari)
So, I’m just learning C++… and the book I’m moving through is doing a really bad job of explaining constructors in a way that I can grasp them. I’ve pretty much grokked everything else so far, but I can’t figure out how the syntax for constructors actually works.
For instance, I am told that the following will cause the constructor to call the designated superclass’s constructor:
class something : something_else {
something(int foo, double bar) : something_else(int foo) {}
};
On the other hand, that same syntax was utilized later on in the book, when describing how to initialize const members:
class something : something_else {
private: const int constant_member;
public: something(int foo, double bar) : constant_member(42) {}
};
So… uh… what the hell is going on there? What does the syntax rv signature(param) : something_else(what); actually mean? I can’t figure out what that something_else(what) is, with relation to the code around it. It seems to take on multiple meanings; I’m sure there must be some underlying element of the language that it corresponds to, I just can’t figure out what.
Edit: Also, I should mention, it’s very confusing that the what in the previous example is sometimes a parameter list (so something_else(what) looks like a function signature)… and sometimes a constant-value expression (so something_else(what) looks like a function call).
Now, moving on: What about multiple-inheritance and constructors? How can I specify what constructors from which parent classes are called… and which ones are called by default? I’m aware that, by default, the following two are the same… but I’m not sure what the equivalent is when multiple-inheritance is involved:
class something : something_else {
//something(int foo, double bar) : something_else() {}
something(int foo, double bar) {}
};
Any help in grokking these topics would be very appreciated; I don’t like this feeling that I’m failing to understand something basic. I don’t like it at all.
Edit 2: Okay, the answers below as of now are all really helpful. They raise one more portion of this question though: How do the arguments of base-class-constructor-calls in ‘initialization lists’ relate to the constructor you’re defining? Do they have to match… do there have to be defaults? How much do they have to match? In other words, which of the following are illegal:
class something_else {
something_else(int foo, double bar = 0.0) {}
something_else(double gaz) {}
};
class something : something_else {
something(int foo, double bar) : something_else(int foo, double bar) {} };
class something : something_else {
something(int foo) : something_else(int foo, double bar) {} };
class something : something_else {
something(double bar, int foo) : something_else(double gaz) {} };
| The syntax for a constructor definition is:
Type( parameter-list ) : initialization-list
{
constructor-body
};
Where the 'initialization-list' is a comma separated list of calls to constructors for the bases and/or member attributes. It is required to initialize any subobject (base or member) for which there is no default constructor, constant subobjects and reference attributes, and should be preferred over assignment in the constructor block in all other cases.
struct base {
base( int ) {};
};
struct base2 {
base2( int ) {};
};
struct type : base, base2
{
type( int x )
: member2(x),
base2(5),
base(1),
member1(x*2)
{ f(); }
int member1;
int member2;
};
The order in which the initialization list is executed is defined in the class declaration: bases in the order in which they are declared, member attributes in the order in which they are declared. In the example above before executing f() in the constructor body the class will initialize its base classes and attributes in the following sequence:
call base(int) constructor with parameter 1
call base2(int) constructor with parameter 5
initialize member1 with value x*2
initialize member2 with value x
When you throw in virtual inheritance, the virtual base is initialized in the most derived class of the virtual inheritance hierachy, and as such it can (or must if there is no default constructor) appear in that initialization list. In that case, the virtual base will be initialized right before the first subobject that inherits virtually from that base.
class unrelated {};
class base {};
class vd1 : virtual base {};
class vd2 : virtual base {};
struct derived : unrelated, vd1, vd2 {
derived() : unrelated(), base(), vd1(), vd2() {} // in actual order
};
On Edit 2
I think you are not reading the details in the answers. The elements in the initialization list are constructor calls, not declarations. The compiler will apply the usual conversion rules for the call if appropriate.
struct base {
base( int x, double y );
explicit base( char x );
};
struct derived : base {
derived() : base( 5, 1.3 ) {}
derived( int x ) : base( x, x ) {}
// will convert x into a double and call base(int,double)
derived( double d ) : base( 5 ) {}
// will convert 5 to char and call base(char)
// derived( base b ) {} // error, base has no default constructor
// derived( base b, int x ) : base( "Hi" ) {}
// error, no constructor of base takes a const char *
};
|
2,318,481 | 2,320,067 | UTF-8, CString and CFile? (C++, MFC) | I'm currently working on a MFC program that specifically has to work with UTF-8. At some point, I have to write UTF-8 data into a file; to do that, I'm using CFiles and CStrings.
When I get to write utf-8 (russian characters, to be more precise) data into a file, the output looks like
Ðàñïå÷àòàíî:
Ñèñòåìà
Ïðîèçâîäñòâî
and etc. This is assurely not utf-8. To read this data properly, I have to change my system settings; changing non ASCII characters to a russian encoding table does work, but then all my latin based non-ascii characters get to fail.
Anyway, that's how I do it.
CFile CSVFile( m_sCible, CFile::modeCreate|CFile::modeWrite);
CString sWorkingLine;
//Add stuff into sWorkingline
CSVFile.Write(sWorkingLine,sWorkingLine.GetLength());
//Clean sWorkingline and start over
Am I missing something? Shall I use something else instead? Is there some kind of catch I've missed?
I'll be tuned in for your wisdom and experience, fellow programmers.
EDIT:
Of course, as I just asked a question, I finally find something which might be interesting, that can be found here. Thought I might share it.
EDIT 2:
Okay, so I added the BOM to my file, which now contains chineese character, probably because I didn't convert my line to UTF-8. To add the bom I did...
char BOM[3]={0xEF, 0xBB, 0xBF};
CSVFile.Write(BOM,3);
And after that, I added...
TCHAR TestLine;
//Convert the line to UTF-8 multibyte.
WideCharToMultiByte (CP_UTF8,0,sWorkingLine,sWorkingLine.GetLength(),TestLine,strlen(TestLine)+1,NULL,NULL);
//Add the line to file.
CSVFile.Write(TestLine,strlen(TestLine)+1);
But then I cannot compile, as I don't really know how to get the length of TestLine. strlen doesn't seem to accept TCHAR.
Fixed, used a static lenght of 1000 instead.
EDIT 3:
So, I added this code...
wchar_t NewLine[1000];
wcscpy( NewLine, CT2CW( (LPCTSTR) sWorkingLine ));
TCHAR* TCHARBuf = new TCHAR[1000];
//Convert the line to UTF-8 multibyte.
WideCharToMultiByte (CP_UTF8,0,NewLine,1000,TCHARBuf,1000,NULL,NULL);
//Find how many characters we have to add
size_t size = 0;
HRESULT hr = StringCchLength(TCHARBuf, MAX_PATH, &size);
//Add the line to the file
CSVFile.Write(TCHARBuf,size);
It compiles fine, but when I go look at my new file, it's exactly the same as when I didn't have all this new code (ex : Ðàñïå÷àòàíî:). It feels like I didn't do a step forward, although I guess only a small thing is what separates me from victory.
EDIT 4:
I removed previously added code, as Nate asked, and I decided to use his code instead, meaning that now, when I get to add my line, I have...
CT2CA outputString(sWorkingLine, CP_UTF8);
//Add line to file.
CSVFile.Write(outputString,::strlen(outputString));
Everything compiles fine, but the russian characters are shown as ???????. Getting closer, but still not that.
Btw, I'd like to thank everyone who tried/tries to help me, it is MUCH appreciated. I've been stuck on this for a while now, I can't wait for this problem to be gone.
FINAL EDIT (I hope)
By changing the way I first got my UTF-8 characters (I reencoded without really knowing), which was erroneous with my new way of outputting the text, I got acceptable results. By adding the UTF-8 BOM char at the beginning of my file, it could be read as Unicode in other programs, like Excel.
Hurray! Thank you everyone!
| When you output data you need to do (this assumes you are compiling in Unicode mode, which is highly recommended):
CString russianText = L"Привет мир";
CFile yourFile(_T("yourfile.txt"), CFile::modeWrite | CFile::modeCreate);
CT2CA outputString(russianText, CP_UTF8);
yourFile.Write(outputString, ::strlen(outputString));
If _UNICODE is not defined (you are working in multi-byte mode instead), you need to know what code page your input text is in and convert it to something you can use. This example shows working with Russian text that is in UTF-16 format, saving it to UTF-8:
// Example 1: convert from Russian text in UTF-16 (note the "L"
// in front of the string), into UTF-8.
CW2A russianTextAsUtf8(L"Привет мир", CP_UTF8);
yourFile.Write(russianTextAsUtf8, ::strlen(russianTextAsUtf8));
More likely, your Russian text is in some other code page, such as KOI-8R. In that case, you need to convert from the other code page into UTF-16. Then convert the UTF-16 into UTF-8. You cannot convert directly from KOI-8R to UTF-8 using the conversion macros because they always try to convert narrow text to the system code page. So the easy way is to do this:
// Example 2: convert from Russian text in KOI-8R (code page 20866)
// to UTF-16, and then to UTF-8. Conversions between UTFs are
// lossless.
CA2W russianTextAsUtf16("\xf0\xd2\xc9\xd7\xc5\xd4 \xcd\xc9\xd2", 20866);
CW2A russianTextAsUtf8(russianTextAsUtf16, CP_UTF8);
yourFile.Write(russianTextAsUtf8, ::strlen(russianTextAsUtf8));
You don't need a BOM (it's optional; I wouldn't use it unless there was a specific reason to do so).
Make sure you read this: http://msdn.microsoft.com/en-us/library/87zae4a3(VS.80).aspx. If you incorrectly use CT2CA (for example, using the assignment operator) you will run into trouble. The linked documentation page shows examples of how to use and how not to use it.
Further information:
The C in CT2CA indicates const. I use it when possible, but some conversions only support the non-const version (e.g. CW2A).
The T in CT2CA indicates that you are converting from an LPCTSTR. Thus it will work whether your code is compiled with the _UNICODE flag or not. You could also use CW2A (where W indicates wide characters).
The A in CT2CA indicates that you are converting to an "ANSI" (8-bit char) string.
Finally, the second parameter to CT2CA indicates the code page you are converting to.
To do the reverse conversion (from UTF-8 to LPCTSTR), you could do:
CString myString(CA2CT(russianText, CP_UTF8));
In this case, we are converting from an "ANSI" string in UTF-8 format, to an LPCTSTR. The LPCTSTR is always assumed to be UTF-16 (if _UNICODE is defined) or the current system code page (if _UNICODE is not defined).
|
2,318,650 | 2,318,669 | A most vexing parse error: constructor with no arguments | I was compiling a C++ program in Cygwin using g++ and I had a class whose constructor had no arguments. I had the lines:
MyClass myObj();
myObj.function1();
And when trying to compile it, I got the message:
error: request for member 'function1' in 'myObj', which is of non-class type 'MyClass ()()'
After a little research, I found that the fix was to change that first line to
MyClass myObj;
I could swear I've done empty constructor declarations with parentheses in C++ before. Is this probably a limitation of the compiler I'm using or does the language standard really say don't use parentheses for a constructor without arguments?
| Although MyClass myObj(); could be parsed as an object definition with an empty initializer or a function declaration the language standard specifies that the ambiguity is always resolved in favour of the function declaration. An empty parentheses initializer is allowed in other contexts e.g. in a new expression or constructing a value-initialized temporary.
|
2,318,788 | 2,331,468 | How to format date in SQLite according to current locale format settings? | I need to match on a date using the LIKE operator. The date should be in current user's local format, not in the general format.
So I use the strftime function like this:
WHERE strftime('%d.%m.%Y %H:%M', createdDate, 'localtime') LIKE '%{searchTerm}%'
Unfortunately this works only for fixed format '%d.%m.%Y %H:%M'. But I want to use the user's current locale format.
So I need to either:
1) Get the strftime format string from a C++ locale object
2) Make SQLite format the date using current locale itself
Spent already several hours on this to no avail.
Would be grateful if anyone would point me in the right direction on how to tackle this problem.
Example:
Given current locale is German I want to get something like "%d.%m.%Y %H:%m".
For an US locale I want to get "%m/%d/%Y %H:%m"
| Normally the local date format can be obtained with the Windows GetDateFormat API (or GetDateFormatEx API for Vista). Your program could interrogate the API then transform the date accordingly. Following that, the date can be recorded in SQLite.
However, once can question the validity of storing timestamps in a specific format. That basically means a lot of code to manipulate each date, or no date manipulation at all. May I suggest, if it is possible, storing in a plain format (say ISO or UNIX timestamp) and working from that, outputing with whichever flavour of GetDateFormat is required?
|
2,319,105 | 2,322,954 | Qt::Tool window diasappears when application become inactive | I have problem with keeping Qt::Tool window visible when the application becomes inactive. The application is running and there are 2 windows opened - main and additional with Qt::Tool flag set. When I open/switch to other app e.g Konosole the main window remains visible but second disappears - so if I want to e.g. rewrite some data from the tool window to a document I need to keep switching between them.
There is no such problem with Qt::ToolTip but it looks different.
I've also tried setAttribute(Qt::WA_MacAlwaysShowToolWindow,true) but since I'm running Linux with KDE4 it doesn't help. Also Qt::WindowStaysOnTopHint is not what I'm trying to get.
Is there any way to keep it visible?
Thanks in advance.
| I ran into this problem as well, but wasn't able to fix it by modifying code since it seems to be a window manager setting, which you should be able to tweak in KDE Control Center.
I don't have KDE 4 installed so I'm not sure where the setting is there, but in the KDE 3.5 Control Center, if you look under Desktop->Window Behavior and then click on the Advanced tab, you can un-check a box called Hide utility windows for inactive applications to keep your tool window visible. Hopefully, there's a similar setting in the KDE 4 Control Center.
|
2,319,224 | 2,324,279 | Dynamic array of COM objects | I have an ATL COM object which needs to expose a collection of other COM objects, so clients can find out how many objects are in the collection (via a simple Count property which I can provide) and access the objects using its index. This collection of objects is dynamic - the count is not fixed - and I don't know how many there will be when my main (parent) object is constructed (so I can't create these objects in my FinalConstruct for example). The objects I want to expose only have read-only properties.
What I want to do is somehow create a std::vector of these objects the first time they are required. I want to use ATL smart COM pointers where possible so I don't need to manually manage reference counts, etc. but I'm not sure whether I should be using CComPtr, 'CComQIPtr', etc.
Assuming the objects I want to return are called IChild, I was hoping I could do something like this:
std::vector<CComPtr<IChild> > children;
...
CComPtr<IChild> child;
// Somehow instantiate an IChild?
...
children.push_back(child);
STDMETHODIMP Parent::GetAt(LONG index, IChild** pRet)
{
*pRet = children[index];
}
If anyone has any pointers on how I can achieve this, I would be very welcome. There is an excellent article on exposing a static object, but I can't find anything on the particular problem in hand.
| Yes, std::vector< CComPtr<IChild> > is the way to do it - you will get a dynamic array of IChild* that manages the lifetime of IChild-derived objects. Once you want to convert the IChild* to a derived interface you'll have to use QueryInterface() the same way as you would use dynamic_cast with C++ objects.
There's no point to use CComQIPtr for the array. The primary use of CComQIPtr is to have a convenient way to call QueryInterface() on a pointer to an object that maybe implements the interface of interest. Instead of calling QueryInterface() and checking the result you invoke the CComQIPtr constructor and check whether the resulting object contains a non-null pointer. You could use CComQIPtr in the code that uses your array, but there's no point in using it for the array itself.
|
2,319,270 | 2,326,057 | DsMakeSpn Always Fails on Windows Server 2008 | What could be the reason for consistent failure when calling DsMakeSpn?
The error code is 87.
Thanks in advance!!
| The problem has been pinpointed:
The SPN in ADSI was written in upper case letters, when the function parameters (ServiceName) were written in lower case.
Anyway - does someone know what can cause ADSI to be case sensitive?
Thanks.
|
2,319,334 | 2,344,414 | Deleting a regular expression match | I have a program that I need to be able to search a file with regex epressions and delete what regex has found. Here is the code I have been working on:
#include <boost/regex.hpp>
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include "time.h"
using namespace std;
class application{
private:
//Variables
boost::regex expression;
boost::smatch matches;
string line;
string pat;
int lineNumber;
string replace;
char time[9];
char date[9];
//Functions
void getExpression(){
cout << "Expression: ";
cin >> pat;
try{
expression = pat;
}
catch(boost::bad_expression){
cout << pat << " is not a valid regular expression\n";
exit(1);
}
}
void boostMatch(){
//Files to open
//Input Files
ifstream in("files/trff292010.csv");
if(!in) cerr << "no file\n";
//Output Files
ofstream out("files/ORIGtrff292010.csv");
ofstream newFile("files/NEWtrff292010.csv");
ofstream record("files/record.dat");
//time
_strdate_s(date);
_strtime_s(time);
lineNumber = 0;
while(in.peek() != EOF){
getline(in, line, '\n');
lineNumber++;
out << line << "\n";
if (regex_search(line, matches, expression)){
for (int i = 0; i<matches.size(); ++i){
record << "Date: "<< date << "Time: " << time << "\tmatches[" << i << "]: " << matches[i] << "\n\tLine Number: "<< lineNumber<< '\n\t\t' << line << '\n';
boost::regex_replace(line, expression, "");
newFile << line << "\n";
}
}else{
newFile << line << "\n";
}
}
}
public:
void run(){
replace = "";
getExpression();
boostMatch();
}
};
As you can see I was trying to use boost::regex_replace to just replace what was found with a blank space, but this did not work. The test I have been running is using [*] to find all the asterisks before some names in a list. Example *alice. The program does find the star but does not remove is to just alice
| It seems like boost::regex_replace is returning a string instead of modifying the input. See the documentation for this method.
Try this instead:
newFile << boost::regex_replace(line, expression, "") << "\n";
|
2,319,343 | 2,320,491 | Linking additional dependencies with XCode | I'm trying to compile a game I made with the Allegro library. The library has .a files which I need to tell XCode to use because right now my code has no errors but it as unreferenced function errors which means it needs the .a files to do the static linking. How do I provide these to XCode? (sort of like the XCode equivalent of MSVC's additional dependencies Thanks
| Add the .a files to your project in the same way that you would add source files and everything should just work.
|
2,319,381 | 2,319,509 | How to use C macro's (#define) to alter calls but not prototypes | Older code in our application contains calls to malloc, realloc and free. With our updated code, our own implementations are called instead of the standard runtime ones. Examples are shown below,
#define malloc(s) OurMalloc(s)
#define free(p) OurFree(p)
This works fine for the updated code and for the newer C++ code we simply implement global new and delete operators, so the C++ solution is 'cleaner'.
The problem is that we now have to include a 3rd party library, which has classes that contain methods that have names like malloc and free, e.g.
class ABC
{
public:
...
void free (char *p);
};
If the free method of the class has the same number of arguments, the C/C++ preprocessor simply replaces all occurrences of free by ourFree, even in the class definition, even when calling the method free of the class ABC.
So the class definition above and the following call:
ABC abc;
abc.free(p);
are replaced by,
class ABC
{
public:
...
void OurFree (char *p);
};
ABC abc;
abc.OurFree(p);
Which may compile, but which doesn't link of course.
If ABC::free has a different number of arguments than the standard free, the compiler still gives a warning. we would like to avoid them.
Some alternative solutions are:
undefining our defines in the beginning of the 3rd party include file and redefining it later
make sure that the 3rd party include file is always included before our own define's
But even then, if our code is required to call these malloc or free methods of the 3rd party classes, the preprocessor will still alter the calls, unless we write all calls like this:
(abc::free)(p)
Is there a way to tell a C/C++ preprocessor define that?
only pure C-calls must be replaced
prototypes MUST NOT be replaced
methods in classes MUST NOT be replaced
| Preprocessor know nothing about about scope and semantic. So short answer - no, you can't do that.
But, you can use #undef free in library modules. On other side - this will not help, if you call methods abc.free() from your code.
|
2,319,544 | 2,363,927 | Comparing address of std::endl | I am inspecting a piece of existing code and found out it behaves differently when compiled with Visual C++ 9 and MinGW:
inline LogMsg& LogMsg::operator<<(std::ostream& (*p_manip)(std::ostream&) )
{
if ( p_manip == static_cast< std::ostream& (*)(std::ostream&) > ( &std::endl<char, std::char_traits<char> >) )
{
msg(m_output.str());
m_output.str( "" );
}
else
{
(*p_manip) (m_output); // or // output << p_manip;
}
return *this;
}
As the name suggests, this is a log class and it overloads operator<<() to strip endls from the stream.
I found out why it behaves differently: the test p_manip == static_cast... succeeds with MinGW while it fails with Visual C++ 9.
MinGW "ignores" the cast and returns the real address of std::endl;
Visual C++ 9 actually casts the pointer-to-endl and returns a different address.
I changed the test to if ( p_manip == std::endl ) and now it behaves as expected.
My question is: what is the rationale behind such a complicated (and, as a matter of fact, wrong) test?
For the sake of completness:
class LogStream
{
public:
LogStream() {}
protected:
std::ostringstream m_output;
};
class LogMsg : public LogStream
{
friend LogMsg& msg() ;
static LogMsg s_stream;
public:
LogMsg() {}
template <typename T>
inline LogMsg& operator<<(T p_data);
inline LogMsg& operator<<(std::ostream& (*p_manip)(std::ostream&) );
};
| For information:
The statement if ( p_manip == std::endl ) does not compile on the original compiler (gcc 3.4.5, the compiler on which the code was originally developed).
That means the test was not wrong as I stated in my question.
|
2,319,663 | 2,319,692 | Why does C++ code missing a formal argument name in a function definition compile without warnings? | While getting started with some VS2005-generated MFC code, I noticed it overrode a method with something like this:
void OnDraw(CDC* /*pDC*/)
{
...
// TODO: Add your code here
}
So of course, as soon as I added something I realized I needed to un-comment the pDC formal argument in order to compile, but I'm confused as to how/why a C++ function can compile (with no warnings) when the formal argument only has a type and not a name:
void foo(int)
{
int x = 3;
}
int main()
{
foo(5);
return 0;
}
Shouldn't this generate at least a warning (with -Wall or /W4)? It doesn't seem to. Am I missing something? Is there a case where this is useful or is it just because the compiler can't tell the difference between a function declaration (only types required) and a definition (fully specified) until after the line has been processed?
| Because sometimes you have a parameter that's required by an interface but the function doesn't use it. Maybe the parameter is no longer necessary, is only necessary in other functions that must use the same signature (especially so they can be called through pointers) or the functionality hasn't been implemented yet. Having parameters that aren't used can be particularly common in generated or framework code for this reason (and that's probably why the MFC generated code has the name commented out).
As to why there's no warning - I guess it's because whether this is a problem is a subjective thing and other people (particularly compiler implementers) don't see it as a problem. Once you actually go to use the parameter, you'll get the compiler to complain if you forget to uncomment the name so you get the compiler complaining only when you really need it to (the compiler's version of the agile YAGNI: "You Aren’t Gonna Neet It" philosophy).
The opposite does seem to generally occur when you crank up warnings - named parameters that aren't used generate warnings - again that's probably why the generated function has the name commented out.
|
2,319,688 | 2,825,599 | Random Complete System Unresponsiveness Running Mathematical Functions | I have a program that loads a file (anywhere from 10MB to 5GB) a chunk at a time (ReadFile), and for each chunk performs a set of mathematical operations (basically calculates the hash).
After calculating the hash, it stores info about the chunk in an STL map (basically <chunkID, hash>) and then writes the chunk itself to another file (WriteFile).
That's all it does. This program will cause certain PCs to choke and die. The mouse begins to stutter, the task manager takes > 2 min to show, ctrl+alt+del is unresponsive, running programs are slow.... the works.
I've done literally everything I can think of to optimize the program, and have triple-checked all objects.
What I've done:
Tried different (less intensive) hashing algorithms.
Switched all allocations to nedmalloc instead of the default new operator
Switched from stl::map to unordered_set, found the performance to still be abysmal, so I switched again to Google's dense_hash_map.
Converted all objects to store pointers to objects instead of the objects themselves.
Caching all Read and Write operations. Instead of reading a 16k chunk of the file and performing the math on it, I read 4MB into a buffer and read 16k chunks from there instead. Same for all write operations - they are coalesced into 4MB blocks before being written to disk.
Run extensive profiling with Visual Studio 2010, AMD Code Analyst, and perfmon.
Set the thread priority to THREAD_MODE_BACKGROUND_BEGIN
Set the thread priority to THREAD_PRIORITY_IDLE
Added a Sleep(100) call after every loop.
Even after all this, the application still results in a system-wide hang on certain machines under certain circumstances.
Perfmon and Process Explorer show minimal CPU usage (with the sleep), no constant reads/writes from disk, few hard pagefaults (and only ~30k pagefaults in the lifetime of the application on a 5GB input file), little virtual memory (never more than 150MB), no leaked handles, no memory leaks.
The machines I've tested it on run Windows XP - Windows 7, x86 and x64 versions included. None have less than 2GB RAM, though the problem is always exacerbated under lower memory conditions.
I'm at a loss as to what to do next. I don't know what's causing it - I'm torn between CPU or Memory as the culprit. CPU because without the sleep and under different thread priorities the system performances changes noticeably. Memory because there's a huge difference in how often the issue occurs when using unordered_set vs Google's dense_hash_map.
What's really weird? Obviously, the NT kernel design is supposed to prevent this sort of behavior from ever occurring (a user-mode application driving the system to this sort of extreme poor performance!?)..... but when I compile the code and run it on OS X or Linux (it's fairly standard C++ throughout) it performs excellently even on poor machines with little RAM and weaker CPUs.
What am I supposed to do next? How do I know what the hell it is that Windows is doing behind the scenes that's killing system performance, when all the indicators are that the application itself isn't doing anything extreme?
Any advice would be most welcome.
| It turns out that this is a bug in the Visual Studio compiler. Using a different compiler resolves the issue entirely.
In my case, I installed and used the Intel C++ Compiler and even with all optimizations disabled I did not see the fully-system hang that I was experiencing w/ the Visual Studio 2005 - 2010 compilers on this library.
I'm not certain as to what is causing the compiler to generate such broken code, but it looks like we'll be buying a copy of the Intel compiler.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.