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;
unsigne... | 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 ... | 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 sev... | 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... |
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... |
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 ... | 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 ... |
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 keyb... | 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... |
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... | 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 inst... |
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 m... | 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.
y... |
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 comprise... |
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... | 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 getpointe... |
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 dev... |
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
... | 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:\\De... | 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,... | 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 P... |
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 t... | 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 ... | 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.DrawT... |
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 nul... | 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 ha... | 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; // ARG... | 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. T... |
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). L... | 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... |
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... | 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.
S... | 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 ... |
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())
{
... | 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... |
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 ... | 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 fro... |
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... | 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... | 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... | 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> ... | 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 ... |
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 valu... |
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*&, R3MeshHa... | 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, ... |
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:
inl... | 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>::all... | 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... |
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 ... | 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-... |
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... | 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,
... | 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 cou... | 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 int... |
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(OL... | 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 activ... | 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 obvi... |
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... | 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(....) //... |
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 con... | 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 i... |
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 ... | 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... |
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... | 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 ... |
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 ... | 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 inst... |
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 k... |
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, ... | 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,... |
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... | 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... |
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 implementat... | 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 do... |
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 t... | 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. B... |
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 blindfol... |
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 ... |
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... |
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... | 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 fr... |
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 ... | 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();
an... |
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 no... | 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 s... |
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 som... | 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 q... |
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 sen... | 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 GetWind... |
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 w... | 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 varia... | 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);
...... | 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().
He... |
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 ea... |
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.... | 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 _wfope... | 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 benefit... | 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 (an... |
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 wo... | 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" ) ... |
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 usin... | 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@SharedJo... | 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-un... |
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... | 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 a... |
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 c... | 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 va... |
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();
... | 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... |
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 th... | 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 ... |
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 SaveCon... | 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 s... |
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, finish... | 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... |
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... | 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 aroun... |
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 ... | 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... |
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
Ðàñïå÷àòàíî:
Ñèñòåìà
Ïðîèçâîäñòâî... | 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... |
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 res... | 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 con... |
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'. Bu... | 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 specifi... |
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. rew... | 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->Wind... |
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 ho... | 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 p... |
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{
priv... | 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 eq... | 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... | 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> >) )
{
... | 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 con... | 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. ... |
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 itsel... | 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.