question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,837,434 | 1,837,595 | mySql Connector exception (C++ library for mysql) when inserting row into non-empty table | I have not done much database programming at all. I am working from some example code for using MySQL Connector/C++.
When I run the following code I get a crash on the last line in some std::string code - but it ONLY crashes when the table is not empty. If the table is empty, it inserts the row and works fine. If th... | I suspect it's either your zero-filled INT or the DATETIME column (not sure which is column 3).
Try creating your table with something like:
`val3` INT(10) ZEROFILL ,
where 10 is the number of positions to zero-fill. I'm also not sure the NULL is necessary, so I excluded it above.
Also, can you post the date string yo... |
1,837,559 | 1,837,598 | passing Temporary variables to reference arg in Constructor works. but not for functions in general. Why? | Consider the following code.
Here, A a(B()) compiles even though the constructor is A(B& b);
But print(B()) does not work. But print is also declared as print(B& b);
Why this inconsistency?
#include <iostream>
using namespace std;
class B{
public:
char b;
};
class A {
public:
B b;
... | It compiles because it's not creating an instance of A. It's declaring a function named a that returns an A and receives one unnamed parameter of type pointer-to-function-returning-B. Since it's just a declaration, it compiles. If you're referred to a elsewhere in the code, you'd have seen additional problems. For why ... |
1,837,656 | 1,837,986 | Jump Table Switch Case question | I am trying to understand some things about jump tables and its relationship between a switch case statement.
I was told that a jump table is a O(1) structure that the compiler generates which makes lookup of values essentially about as fast as you can get. However in some cases a Hashtable/Dictionary might be faster. ... | A jump table is an abstract structure used to transfer control to another location. Goto, continue, and break are similar, except they always transfer to a specific location instead of one possibility from many. In particular, this control flow is not the same as a function call. (Wikipedia's article on branch table... |
1,837,815 | 1,838,657 | Is it possible to use separate threads for reading and writing with Boost.Asio? | According to the Boost Documentation, having multiple threads call io_service::run() sets up a pool of threads that the IO service can use for performing asynchronous tasks. It explicitly states that all threads that have joined the pool are considered equivalent.
Does this imply that it is not possible to have a separ... | Any thread that calls io_service::run() can be used to invoke asynchronous handlers. But you can't specifically specify which thread executes which type of operation. For example, if you call io_service::run() in 2 background threads, and you were to call socket::async_send and socket::async_receive in a main thread,... |
1,837,867 | 1,855,842 | problem parsing a xml file with MSXML4 in C++ | Here is my parsing code:
MSXML2::IXMLDOMNodePtr pNode = m_pXmlDoc->selectSingleNode(kNameOfChild.c_str());
MSXML2::IXMLDOMNodeListPtr pIDOMNodeList = NULL;
MSXML2::IXMLDOMNodePtr pIDOMNode = NULL;
long numOfChildNodes= 0;
BSTR bstrItemText;
HRESULT hr;
MSXML2::IXMLDOMElementPtr pChildNode = m_pXmlDoc->getElementsByTa... | Try /GovTalkMessage/Header/MessageDetails/Qualifier for the XPath query.
|
1,837,979 | 1,838,088 | Handling touch detection in iPhone with C++? | I'm working on a game for the iPhone, for several reasons most of the code is in C++. I need to write a TouchesManager for my Game, I know about the methods touchesBegan: touchesEnded: and touchesMoved:
I would really like to make a manager in C++ so I can subscribe some classes to this manager, so they can handle touc... | At a higher level, I would create a C++ base class with the exact arguments/names (maybe even self and _cmd). Someplace, you would need to create these, and establish connections from the manager to the objects queried.
The objc objects could either hold a pointer to their C++ implementation/receiver, or you could use... |
1,838,271 | 1,838,310 | Types in a public c++ API | I'm writing a library and wonder what's the best practice for datatypes used in a public API.
Given the function
void foo (int bar)
which expects an index to some internal array/container. What type should that be? Because an index can never be negative I could use unsigned int or size_t. Or should I stick with a plai... | If the array/container you are talking about is just a generic abstract application-independent array, then the most appropriate type would be size_t. You can, of course, provide a typedef name for the type in your interface. Again, this is only appropriate when you are working with abstract arrays, like in a generic c... |
1,838,308 | 1,838,330 | What's C++ Really Doing When I Accidently Use a Variables to Declare Array Length? | I was helping a friend with some C++ homework. I warned said friend that the kind of programming I do (PHP, Perl, Python) is pretty different from C++, and there were no guarantees I wouldn't tell horrible lies.
I was able to answer his questions, but not without stumbling over my own dynamic background. While I was ... | Update:
Neil pointed out in his comment to the question that you will get error if you compile this with -Wall and -pedantic flags in g++.
error: ISO C++ forbids variable-size array
You are getting ABC???? because it prints the contents of the array (ABC) and continues to print until it encounters a \0.
Had the array... |
1,838,368 | 1,838,732 | Calculating the Amount of Combinations | Cheers,
I know you can get the amount of combinations with the following formula (without repetition and order is not important):
// Choose r from n
n! / r!(n - r)!
However, I don't know how to implement this in C++, since for instance with
n = 52
n! = 8,0658175170943878571660636856404e+67
the number gets way too big... | Here's an ancient algorithm which is exact and doesn't overflow unless the result is to big for a long long
unsigned long long
choose(unsigned long long n, unsigned long long k) {
if (k > n) {
return 0;
}
unsigned long long r = 1;
for (unsigned long long d = 1; d <= k; ++d) {
r *= n--;
... |
1,838,730 | 1,838,792 | Template with static functions vs object with non-static functions in overloaded operator | Which approach is the better one and why?
template<typename T>
struct assistant {
T sum(const T& x, const T& y) const { ... }
};
template<typename T>
T operator+ (const T& x, const T& y) {
assistant<T> t;
return t.sum(x, y);
}
Or
template<typename T>
struct assistant {
static T sum(const T& x, const ... | It is usually not a question of run-time performance, but one of readability. The former version communicates to a potential maintainer that some form of object initialization is performed. The latter makes the intent much clearer and should be (in my opinion) preferred.
By the way, what you've created is basically a t... |
1,838,992 | 1,839,200 | Converting existing C++ web service to a load balanced server? | We have a C++ (SOAP-based) web service deployed Using Systinet C++ Server, that has a single port for all the incoming connections from Java front-end.
However recently in production environment when it was tested with around 150 connections, the service went down and hence I wonder how to achieve load-balancing in a C... | The service is accessed as SOAP/HTTP?
Then you create several instances of you services and put some kind of router between your clients and the web service to distribute the requests across the instances. Often people use dedicated hardware routers for that purpose.
Note that this is often not truly load "balancing", ... |
1,839,093 | 1,839,696 | msgStore was not declared in this scope (XCode) | I'm implementing callback routines for external static C++ library to be used in Objective-C project. Now I have trouble moving data between callback and normal routines. As you can see below my "msgStore" is defined as part of MyMessage class and can be used within class routines such as init(). However attempting sam... | You cannot call msgStore from the function because it is not in the scope of the function.
There are a few ways to get to it in the function.
One is to use a singleton class. If you plan on only using one message store, then you can make that class a singleton. That means you can get the object instance of that class b... |
1,839,128 | 1,839,258 | Why is my glutWireCube not placed in origin? | I have the following OpenGL code in the display function:
glLoadIdentity();
gluLookAt(eyex, eyey, eyez, atx, aty, atz, upx, upy, upz);
// called as: gluLookAt(20, 5, 5, -20, 5, 5, 0, 1, 0);
axis();
glutWireCube (1.);
glFlush ();
axis() draws lines from (0,0,0) to (10,0,0), (0,10,0) and (0,10,0), plus a line from (1,... | Are you sure axis does not mess with the view matrix ?
What happens if you call it after the drawing of the cube ?
Edit to add:
Actually... Looking at the picture closer, it looks like it might be centered at the origin.
The center of the cube seems to align exactly with the intersection of the 3 axes. The only thing t... |
1,839,221 | 1,851,914 | Audio Device, change Speaker setup | I want to change from my program the speaker setup, which is under speaker settings / advanced... section.
I tried to find maybe there is some sort of registry entry but no luck till now :|
Any Ideas ?
Thanks a lot !
| Ok, here is the code for what I wanted
var
ds:IDirectSound;
begin
if DirectSoundCreate(nil, ds, nil) <> DS_OK then
raise Exception.Create('Failed to create IDirectSound object');
ds.SetSpeakerConfig(1);
|
1,839,224 | 1,839,237 | Why does compiler generate error? | Why does compiler generate error?
template<class T>
void ignore (const T &) {}
void f() {
ignore(std::endl);
}
Compiler VS2008 gives the following error: cannot deduce template argument as function argument is ambiguous.
| I think that problem is that std::endl is a template function and compiler cannot deduce template argument for ignore function.
template <class charT, class traits>
basic_ostream<charT,traits>& endl ( basic_ostream<charT,traits>& os );
To fix a problem you could write something like as follows:
void f() {
ignore(... |
1,839,225 | 1,839,283 | Float addition promoted to double? | I had a small WTF moment this morning. Ths WTF can be summarized with this:
float x = 0.2f;
float y = 0.1f;
float z = x + y;
assert(z == x + y); //This assert is triggered! (Atleast with visual studio 2008)
The reason seems to be that the expression x + y is promoted to double and compared with the truncated version i... | You can't generally assume that == will work as expected for floating point types. Compare rounded values or use constructs like abs(a-b) < tolerance instead.
Promotion is entirely at the compiler's discretion (and will depend on target hardware, optimisation level, etc).
What's going on in this particular case is al... |
1,839,422 | 1,839,437 | strange output in comparison of float with float literal | float f = 0.7;
if( f == 0.7 )
printf("equal");
else
printf("not equal");
Why is the output not equal ?
Why does this happen?
| This happens because in your statement
if(f == 0.7)
the 0.7 is treated as a double. Try 0.7f to ensure the value is treated as a float:
if(f == 0.7f)
But as Michael suggested in the comments below you should never test for exact equality of floating-point values.
|
1,839,821 | 1,840,366 | Unique id of files and monitoring file system changes | Do files or folders on S60 have some unique id value that can identify them?
I would like to have an id that can be later used to extract full path of a file or folder. Is this achievable?
If not, what would be the best way to keep track of files of interest?
E.g. if I have a pdf reader, and I want to have a menu opti... | I can't quite see anything in the Symbian OS C++ API that would do exactly what you want.
Using RFs::NotifyChange() is probably your best bet.
|
1,839,844 | 1,840,477 | is pwrite after dup race safe? | On Linux pwrite operation (which is seek+write) is atomic, meaning doing pwrite-s in multiple threads with one file descriptor is safe.
I want to create file descriptor duplicate, using dup(). Now, having fd1 and fd2 - will pwrite-s work as expected, or there's danger of race condition?
| I think pwrite is an atomic operation if the number of bytes you're writing is less than PIPE_BUF of the pipe you're writing to (from the POSIX programmer's manual).
|
1,840,012 | 1,840,048 | Do non const internal members of class become const when I have const ref to an object of that class? | Well, I think my problem originates in a lake of knowledge of basic C++ concepts. The problem is, in my code (below) I have the classes Header and Register. For both, I pass a reference to a ifstrem file already opened. The Header reads some bytes from it. Register has a method to return a reference of Header (which is... | Yes, when GetHeader() returns a const reference to the Header object, you can only call const methods on it.
In this case if you declare Field_1as a const method by writing:
unsigned long Header::Field_1(void) const
(note the const on the end)
The trouble is if you do this then within the const method all other members... |
1,840,029 | 1,841,344 | passing functor as function pointer | I'm trying to use a C library in a C++ app and have found my self in the following situation (I know my C, but I'm fairly new to C++). On the C side I have a collection of functions that takes a function pointer as their argument. On the C++ side I have objects with a functor which has the same signature as the functi... | You cannot directly pass a pointer to a C++ functor object as a function pointer to C code
(or even to C++ code).
Additionally, to portably pass a callback to C code it needs to be at least declared
as an extern "C" non-member function.
At least, because some APIs require specific function call conventions and thus
add... |
1,840,121 | 1,840,131 | Which type of sorting is used in the std::sort()? | Can anyone please tell me that which type of sorting technique (bubble, insertion, selection, quick, merge, count...) is implemented in the std::sort() function defined in the <algorithm> header file?
| Most implementations of std::sort use quicksort, (or usually a hybrid algorithm like introsort, which combines quicksort, heapsort and insertion sort).
The only thing the standard requires is that std::sort somehow sort the data according to the specified ordering with a complexity of approximately O(N log(N)); it is n... |
1,840,241 | 1,840,278 | What's the difference between Boost.MPI and Boost.Interprocess? | I suppose Boost.MPI and Boost.Interprocess are different, right?
From a performance perspective, which is faster? Has anyone ever done benchmarking?
Can I use them to pass data within the same process (i.e. among different threads)?
Thanks!
| They are totally different. Boost MPI is for parallel/distributed computing (like massively-parallel super-computers). It requires an existing installation of MPI (Message Passing Interface), such as OpenMPI. MPI is usually used with high-performance clusters of networked computers, or with super computers. The Boo... |
1,840,253 | 1,840,318 | template member function of template class called from template function | This doesn't compile:
template<class X> struct A {
template<int I> void f() {}
};
template<class T> void g()
{
A<T> a;
a.f<3>(); // Compilation fails here (Line 18)
}
int main(int argc, char *argv[])
{
g<int>(); // Line 23
}
The compiler (gcc) says:
hhh.cpp: In function 'void g()':
hhh.cpp:18: error: ... | Try the following code:
template<class T> void g()
{
A<T> a;
a.template f<3>(); // add `template` keyword here
}
According to C++'03 Standard 14.2/4:
When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfi... |
1,840,343 | 1,840,491 | C++ SmartPointers leak on self assign? | i have small problem understanding why my smart pointer class is leaking on self assing.
If i do something like this
SmartPtr sp1(new CSine());//CSine is a class that implements IFunction iterface
sp1=sp1;
my colleagues told me that my smart pointer leaks. I added some log messages in my smart pointer to track what is... | My impression is that there is no memory leak.
To be sure:
test with valgrind or the VS-alternative
use std::tr1::shared_ptr (if this is more than educational)
|
1,840,348 | 1,840,367 | What is this for loop doing? | What is the for loop doing? I just can't understand it.
list<pair<int, double> > nabors;
list<pair<int, double> >::iterator i;
for (i = nabors.begin(); i != nabors.end() && dist >= i->second; i++);
| It's finding the first element in nabors that satisfies the condition
dist < i->second
If no element satisfies that condition, the iterator i points to nabors.end().
|
1,840,497 | 1,840,540 | Reason for peculiar ordering of division and multiplication in C++ | I'm in the middle of porting some c++ code to java, and I keep running across instances where whoever wrote it kept doing the following:
double c = (1.0/(a+1.0)*pow(b, a+1.0));
double d = (1./(integral(gamma, dmax)-integral(gamma, dmin)))*(integral(gamma+1, dmax)-integral(gamma+1, dmin));
Instead of:
double c = pow(b,... | Yes, they're the same. The only reason I can think of is mathematical clarity: sometimes when you're normalizing a quantity, you often write:
answer = (1/total) * (some of it)
For example, Cauchy's integral theorem is often written
f(a) = (1/(2*pi*i)) * integral(f(z)/(z-a), dz)
|
1,841,149 | 1,841,201 | c++, get phone number from txt file | I'm trying input a phone number in the format: 555-555-5555 into a struct with three int's. I've tried using getline with a delimiter of "-", but I keep getting the error: "cannot convert parameter 1 from 'int' to 'char *'".
I tried creating a temp char* variable to store the number in and then type casting it to int,... | Since you are posting this as a c++ question, and not a c question, Use istringstream
http://www.cplusplus.com/reference/iostream/istringstream/
From my head it your code would become something like:
std::string sPhoneNum("555-555-5555");
struct
{
int p1;
int p2;
int p3;
} phone;
char dummy;
std::istringstrea... |
1,841,689 | 1,842,043 | Rendering multiple different textures with 1 image? (such as fonts) | Let's say I have a texture which is one file with separate 20 px by 20 px blocks. Within each of these blocks is a new character and I'd like to render different characters on screen as textures using these blocks. How can I use directx to render separate pieces of a texture file?
| You will need to render a quad (two triangles) with the UV coordinates mapped to the correct location in this texture for each letter you are rendering.
So if you had a quad like this:
|\ |
| \|
and you wanted to draw the entire texture you would assign the vertices UV coordinates of:
TopLeft: 0,0
TopRight: 1,0
Bottom... |
1,841,721 | 1,868,334 | Why can't a "procedure entry point could not be located in dll" when I definitely put it in? | I have a really vague problem, but I hope someone can help with it. I was modifying a C++ project and yesterday it was still working, but today it's not. I'm pretty sure I didn't change anything, but to be completely sure I checked the project out from SVN again and I even reverted to a previous system restore point (b... | I feel a bit stupid, but I found the answer. The application (exe) I was using apparently loaded a second, different dll which had a dependency on the one mentioned in my original post. This second dll was still expecting the old functions and also needed to be recompiled against the updated dll.
Many thanks to the peo... |
1,842,050 | 1,842,099 | Explanation for return value casting that is going on | #include <Fl/Enumerations.H>
class Color
{
public:
static Color amber () {return fl_rgb_color (255, 204, 0);}
static Color lighter_gray () {return fl_rgb_color (40, 40, 40); }
static Color light_gray () {return fl_rgb_color (179, 179, 179);}
static Color gray () {return fl_rgb_color ... | The static methods returning a Color all return the result of a call to fl_rgb_color.
fl_rgb_color returns a Fl_Color and Color has a single parameter constructor which is not marked explicit and takes a reference to a const Fl_Color so this is a valid implict conversion.
The return value of fl_rgb_color is a temporary... |
1,842,187 | 1,842,199 | How is each byte in an integer stored in CPU / memory? | i have tried this
char c[4];
int i=89;
memcpy(&c[0],&i,4);
cout<<(int)c[0]<<endl;
cout<<(int)c[1]<<endl;
cout<<(int)c[2]<<endl;
cout<<(int)c[3]<<endl;
the output is like:
89
0
0
0
which pretty trains my stomache cuz i thought the number would be saved in memory like
0x00000059 so how come c[0] is 89 ? i thought it is... | Because the processor you are running on is little-endian. The byte order, of a multi-byte fundamental type, is swapped. On a big-endian machine it would be as you expect.
|
1,842,377 | 1,867,649 | Double buffer common controls | Is there a way to double-buffer the common controls? Currently when they resize they flicker. A lot.....
EDIT: If it helps, it is a bunch of button controls and a few edit controls, all sitting on top of a tab control. The Tab control redraws itself, then the buttons redraw themselves. When the buttons redraw, they fli... | Look at using WS_EX_COMPOSITEDand WS_EX_TRANSPARENT styles. They provide doublebuffering, altough WM_PAINT will be called when the underlying bitmap is finished drawing, since it draws child controls from bottom to top, so you can paint only in your window procedure. I've used it in the past and work pretty well.
Set ... |
1,842,418 | 1,842,450 | c++ / object-oriented quick review? | I am looking for quick reference guide(s) for both OO and C++. I have a few technical interviews coming up and I just want a quick reference that gives the basic overview of the fundamentals. (Nothing too in depth, as I've learned it all once before)
| Have a look at this C++ tutorial online.
There is also Bruce Eckel's Thinking In C++ freely available book.
C++ FAQ Lite is searchable and Herb Sutter's Guru Of The Week series feature many tricky puzzles.
|
1,842,444 | 1,842,477 | Clarification on a header without #includes | I was reading some code from the Doom 3 SDK ( in a VS solution ) when I found a header like this:
#ifndef __PLAYERICON_H__
#define __PLAYERICON_H__
class idPlayerIcon {
public:
idPlayerIcon();
~idPlayerIcon();
...... // omitted
public:
playerIconType_t ... | Because every time it is included, the needed entities are forward declared/included right before it, so everything is defined at the point of inclusion. As you correctly say, it will not work any other way.
|
1,842,445 | 1,843,116 | How to convert std::wstring to a TCHAR*? | How to convert a std::wstring to a TCHAR*? std::wstring.c_str() does not work since it returns a wchar_t*.
How do I get from wchar_t* to TCHAR*, or from std::wstring to TCHAR*?
| #include <atlconv.h>
TCHAR *dst = W2T(src.c_str());
Will do the right thing in ANSI or Unicode builds.
|
1,842,481 | 1,844,717 | How do I update a value in a row in MySQL using Connector/C++ | I have a simple database and want to update an int value. I initially do a query and get back a ResultSet (sql::ResultSet). For each of the entries in the result set I want to modify a value that is in one particular column of a table, then write it back out to the database/update that entry in that row.
It is not c... | From a quick scan of the docs it appears Connector/C++ is a partial implementation of the Java JDBC API for C++. I didn't find any reference to updateable result sets so this might not be possible. In Java JDBC the ResultSet interface includes support for updating the current row if the statement was created with Res... |
1,842,626 | 1,842,648 | Location of const in a function | A similar question was previously asked, but none of the answers really provided what I was looking for.
I am having trouble deciding where consts should be located in a function. I know a lot of people put them at the top, but if you put them as close as possible to where they are used, you'll reduce code span. I.e.
v... | At the lowest scope possible, and directly before their first use.
As a matter of style, exceptions can be made for clarity/asthetics, e.g., grouping conceptually similar constants.
|
1,842,678 | 1,842,691 | C++: newbie initializer list question | Newbie here. I am looking at company code.
It appears that there are NO member variables in class A yet in A's constructor it initializes an object B even though class A does not contain any member variable of type B (or any member variable at all!).
I guess I don't understand it enough to even ask a question...so... | Class A (publicly) inherits from class B:
class A: public B
The only way to initialize a base class with parameters is through the initializer list.
|
1,842,732 | 1,843,692 | writing to GUI issue | So i have a setup where two imacs, imac_1 and imac_2, are connected through firewire. imac_1 sends some debugging information to imac_2 and on imac_2 i have a program in c++ that captures debugging information.(see illustration below)
Now the problem is that if i write the debugging info to the GUI (created using QT) ... | It sounds like your problem has nothing to do with the two computers communicating, but may instead be your GUI application.
I would suggest you try the file approach you mention, if only to isolate the network component from the discussion. Then work on making your GUI faster.
If you are adding the lines of text one ... |
1,842,941 | 1,842,976 | Translating python dictionary to C++ | I have python code that contains the following code.
d = {}
d[(0,0)] = 0
d[(1,2)] = 1
d[(2,1)] = 2
d[(2,3)] = 3
d[(3,2)] = 4
for (i,j) in d:
print d[(i,j)], d[(j,i)]
Unfortunately looping over all the keys in python isn't really fast enough for my purpose, and I would like to translate this code to C++. What is... | A dictionary would be a std::map in c++, and a tuple with two elements would be a std::pair.
The python code provided would translate to:
#include <iostream>
#include <map>
typedef std::map<std::pair<int, int>, int> Dict;
typedef Dict::const_iterator It;
int main()
{
Dict d;
d[std::make_pair(0, 0)] = 0;
d[s... |
1,842,979 | 1,843,094 | Cost of using std::map with std::string keys vs int keys? | I know that the individual map queries take a maximum of log(N) time. However I was wondering, I have seen a lot of examples that use strings as map keys. What is the performance cost of associating a std::string as a key to a map instead of an int for example ?
std::map<std::string, aClass*> someMap; vs std::map<int, ... | In addition to the time complexity from comparing strings already mentioned, a string key will also cause an additional memory allocation each time an item is added to the container. In certain cases, e.g. highly parallel systems, a global allocator mutex can be a source of performance problems.
In general, you should... |
1,843,181 | 1,843,445 | Is there a C++/win32 library function to convert a file path to a file:// URL? | I have an LPTSTR for a file path, i.e. C:\Program Files\Ahoy. I would like to convert it to a file:// URL that I can pass to ShellExecute in order to start the system's default browser pointing at the file. I don't want to give the path to ShellExecute directly since file associations may result in it being opened by... | There's the UrlCreateFromPath API:
http://msdn.microsoft.com/en-us/library/bb773773%28VS.85%29.aspx
|
1,843,221 | 1,843,242 | Restrict method access to a specific class in C++ | I have two closely related classes which I'll call Widget and Sprocket. Sprocket has a set of methods which I want to be callable from Widget but not from any other class. I also don't want to just declare Widget a friend of Spocket because that would give Widget access to ALL protected and private members. I want to r... | If you have two tightly coupled classes, then it's really not worth trying to make friend access any more granular than it is. You control the implementation of both, and you should trust yourself enough to not abuse the ability to call some methods that you don't, strictly speaking, need to call.
If you want to make i... |
1,843,314 | 1,843,333 | Embedded Visual C++/Why is my Symbol Undefined? | I am new to this platform, and I am trying to resolve an issue with existing code that was developed by a contractor many years ago.
In Resource.h, I have something that looks like this, where the last two items I have added.
#define IDC_HOSPITAL_NAME_LABEL 1069
#define IDC_REASON_LABEL 1070
#def... | Sounds to me like its just "one of those things". You will notice plenty. Try not to get too wound up by them. In the end ... if it compiles ... don't worry about it :)
|
1,843,369 | 1,843,404 | How to create a file in a different directory in C++? | #include <iostream>
#include <fstream>
#include <cstdlib>
int main() {
std::fstream f1("/tmp/test");
if (!f1) {
std::cerr << "f1 failed\n";
} else {
std::cerr << "f1 success\n";
}
FILE *f2 = fopen("/tmp/test", "w+");
if (!f2) {
std::cerr << "f2 failed\n";
} else {
... | You have to tell the fstream you are opening the file for output, like this
std::fstream fs("/tmp/test", std::ios::out);
Or use ofstream instead of fstream, that opens the file for output by default:
std::ofstream fs("/tmp/test");
|
1,843,410 | 1,854,085 | OpenCV C++ error in Xcode | I have built the OpenCV libraries using the cmake build system as described here and have added the header, '.a' and '.dylib' files to my terminal c++ project. However when I run the code below (got it from http://iphone-cocoa-objectivec.blogspot.com/2009/01/using-opencv-for-mac-os-in-xcode.html), it gives me the error... | Avoid using Xcode with OpenCV 2.0. If using OpenCV use Windows and also use OpenCV 1.1. It will save a lot of headache. When 2.0/Mac are better documented then transition onto Mac platform/2.0 version. The book (O'Reilly) is good - covers v1.1. The next installment for 2.0 should follow soon. 1.
|
1,843,567 | 1,843,594 | std::list threading push_back, front, pop_front | Is std::list thread safe? I'm assuming its not so I added my own synchronization mechanisms (I think i have the right term). But I am still running into problems
Each function is called by a separate thread. Thread1 can not wait, it has to be as fast as possible
std::list<CFoo> g_buffer;
bool g_buffer_lock;
void t... |
Is std::list thread safe?
The current C++ standard doesn't even acknowledge the existence of threads, so std::list certainly isn't. Different implementations, however, might provide (different levels of) thread safety.
As for your code: If you need a lock, use a lock. That bool variable might not help when the threa... |
1,843,581 | 1,844,056 | Generate diagnostic message for HRESULT codes? | I'd like to be able to do the equivalent of FormatMessage - generate a text message for debug and even runtime builds that can report some of the common HRESULTs, or even spit out things like what the severity is, what facility it was, and possibly a description of the error code.
I found this simple function, but its ... | As you muse, _com_error::ErrorMessage() should do the trick.
If you are getting "Unknown Error", then the HRESULTs you are getting are probably not known to windows. For those messages, try dumping the HRESULT value and figuring out if they actually map to win32 error codes.
There are some com macros available to help... |
1,843,716 | 1,843,767 | Is there a difference between a "child control", a "child window" and a "child window control"? | Or are these terms used to refer to the same thing?
I'm trying to implement some custom buttons showing a bitmap image, into my Win32 app. One tutorial indicates I should be creating child windows using CreateWindow().
However, I have downloaded a bunch of source code from another tutorial on creating "child controls"... | Every control is a window, but not every window is a control. Controls have a parent and are usually one of the window classes that are appropriate in that context, such as a Button.
|
1,843,747 | 1,843,839 | Why would buffer overruns cause segmentation faults when accessing an integer? | During a call to function B() from function A(), B() allocates a 100-char array and fills it several times, including once with a 101-character string and once with a 110 character string. This is an obvious mistake.
Later, function A() tries to access completely unrelated int variable i, and a segmentation fault occu... | When A() calls B(), B's preamble instructions save A's frame pointer—the location on the stack where A keeps local variables, before replacing it with B's own frame pointer. It looks like this:
When B overruns its local variables, it messes up the value which will be reloaded into the frame pointer. This is garbage ... |
1,843,915 | 1,844,984 | Variable number of arguments (va_list) with a function callback? | I am working on implementing a function that would execute another function a few seconds in the future, depending upon the user's input. I have a priority queue of a class (which I am calling TimedEvent) that contains a function pointer to the action I want it to execute at the end of the interval. Say for instance ... | I'm inferring here that these functions are API calls that you have no control over. I hacked up something that I think does more or less what you're looking for; it's kind of a rough Command pattern.
#include <iostream>
#include <string>
using namespace std;
//these are the various function types you're calling; opt... |
1,844,162 | 1,844,175 | Assisting in avoiding assert... always! | In C and C++ assert is a very heavyweight routine, writing an error to stdout and terminating the program. In our application we have implemented a much more robust replacement for assert and given it its own macro. Every effort has been made to replace assert with our macro, however there are still many ways assert ca... | I'm not sure I really understand the problem, actually. Asserts are only expensive if they go off, which is fine anyway, since you're now in an exception situation.
assert is only enabled in debug builds, so use the release build of a third-party library. But really, asserts shouldn't be going off every moment.
|
1,844,213 | 1,844,479 | Building game logic with events | I'm making a game engine in C++. It is supposed to read all its game-level logic from XML files, so I'm in need of a simple, but rock solid way of creating and handling events. So far all i have done is to use an Action class. It's practically equivalent to throwing callbacks around.
An example could be an object (a ma... | It sounds like you want to use a signal library, such as boost::signals or sigc.
Either of those libraries will allow any of your objects to know when an event such as a click happens.
They can also automate the cleanup when either the signaling object or a listening object is destroyed.
Good luck!
|
1,844,223 | 1,844,227 | #include iostream in C? | In C++ we always put the following at the top of the program
#include <iostream>
What about for C?
| Well, this is called the standard I/O header. In C you have:
#include <stdio.h>
It's not an analog to <iostream>. There is no analog to iostream in C -- it lacks objects and types. If you're using C++, it's the analog to <cstdio>.
stdio man page
GNU documentation on Input/Output on Streams
See also this fantastic qu... |
1,844,336 | 1,844,385 | Compilers for DOS32? | Where can I get BASIC and C/C++ Compilers for MS-DOS?
| There's DJGPP for C/C++.
http://www.delorie.com/djgpp/
|
1,844,404 | 1,844,414 | PeekMessage() Resetting the Mouse Cursor | Im currently messing around with changing the mouse cursor within a game like C++ application for Windows XP.
To change the cursor I am using SetCursor() and passing in the desired cursor, which is working. However during the while loop in which PeekMessage() is called the cursor keep getting reset back to the default... | How did you debug that? Unless you use SoftIce or some other application which doesn't share the windows mouse pointer, it would be hard to isolate the debugger from the application.
|
1,844,736 | 1,846,363 | Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++ | How to access elements by row, col in OpenCV 2.0's new "Mat" class? The documentation is linked below, but I have not been able to make any sense of it.
http://opencv.willowgarage.com/documentation/cpp/basic_structures.html#mat
| On the documentation:
http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat
It says:
(...) if you know the matrix element
type, e.g. it is float, then you can
use at<>() method
That is, you can use:
Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);
Maybe it is easier to use the Mat_ class. It i... |
1,844,887 | 1,844,904 | How do you call the copy constructor within a member function of a class? | Here's what I've got:
void set::operator =(const set& source)
{
if (&source == this)
return;
clear();
set(source);
}
And here's the error I get:
vset.cxx:33: error: declaration of 'source' shadows a parameter
How do I properly do this?
| I believe with set(source); you are trying to call copy ctor. You can not do that in C++ i.e. you can not explicitly invoke the ctor. What you can do is write a private clone
method and call it in both copy ctor and assignment operator.
|
1,845,474 | 1,845,609 | Concatenate null-terminated strings recursively | I'm inventing interview questions that require analysis of C++ code that does something simple with pointers and recursion. I tried to write strcat() in recursive manner:
size_t mystrlen( const char* str )
{
if( *str == 0 ) {
return 0;
}
return 1 + mystrlen( str + 1 );
}
void mystrcpy( char* to, co... | here's my example (the advantage is it has only one recursive call):
char * mystrcat(char *dest, const char *src){
if(*dest == 0){
if(*src == 0) // end of recursion cond
return dest;
*dest = *src++; // actual copy
dest[1]=0; // zero out dest buf
}
mystrcat(dest+1,s... |
1,845,482 | 1,845,491 | What is the uintptr_t data type? | What is uintptr_t and what can it be used for?
| uintptr_t is an unsigned integer type that is capable of storing a data pointer (whether it can hold a function pointer is unspecified). Which typically means that it's the same size as a pointer.
It is optionally defined in C++11 and later standards.
A common reason to want an integer type that can hold an architectu... |
1,845,734 | 1,845,766 | Program option library for portable code | I have a portable code running on Visual C++ 2008 and RHEL 5.3 (gcc 4.x.x).
My program should accept command line arguments. I consider using some library for that task.
My candidats are:
Boost program options
ACE has this capability too
(1) is not in standard and as for (2) we already using it heavily for other tas... | I like a lot boost::PO, but I never used ACE, so I can't compare.
You're saying that boost is not a standard, but is it really a problem? Many people consider it as almost a standard. At least it isn't any exotic library.
|
1,845,869 | 1,845,924 | Converting operator in enum | I wrote class like this:
#pragma once
#include "stdafx.h"
struct Date
{
private:
int day;
int year;
enum Month {jan = 1,feb,mar,apr,may,jun,jul,aug,sep,oct,nov,dec};
Month* month;
enum date_state
{
good,err_flag, bad_day, bad_month, bad_year,
};
//I would like to define converting operator from enum to char
Date:... | You can't declare member functions for enum date_state, because it is an enum, but you could do so for class Date:
class Date {
...
enum date_state
{
good, bad_day, bad_month, bad_year,
} err_flag;
operator char() {
return err_flag;
}
}
But would rather recommend using a normal me... |
1,845,870 | 1,845,898 | why project dependency affect linker settings | any idea why project dependency (Visual Studio) affects linker settings (C++)? I thought that it's enough to chceck linker settings (Additional depend...) or pragma in source code. It's not a big problem, I'm just curious. Thanks.
| If I understand correctly, you are referring to the feature that, when you check project B as dependency of project A, B gets linked into A. This is just for usablility. In that case, Visual Studio knows that it has to check B for changes (and rebuild if necessary) if A gets build. It's really just convenience.
|
1,845,908 | 1,846,005 | Checking for intersection points between two rectangles? | If I have two rectangles whose positions are deifned using two 2D vectors (i.e. top left, bottom right) how can I check for the points they are intersecting?
| I assume you actually want the result of the intersection, not only the test if both rectangles intersect.
The intersection of rect1 = (l1, t1, r1, b1) and rect2 = (l2, t2, r2, b2) is again a rectangle:
rectIntersection = ( max(l1, l2), max(t1, t2), min(r1, r2), min(b1, b2) )
rectIntersection is of course empty if l... |
1,846,032 | 1,846,253 | What is the easiest way to convert a char array to a WCHAR array? | In my code, I receive a const char array like the following:
const char * myString = someFunction();
Now I want to postprocess it as a wchar array since the functions I use afterwards don't handle narrow strings.
What is the easiest way to accomplish this goal?
Eventually MultiByteToWideChar? (However, since it is a ... | const char * myString = someFunction();
const int len = strlen(myString);
std::vector<wchar_t> myWString (len);
std::copy(myString, myString + len, myWString.begin());
const wchar_t * result = &myWString[0];
|
1,846,144 | 1,846,409 | Pattern name for create in constructor, delete in destructor (C++) | Traditionally, in C++, you would create any dependencies in the constructor and delete them in the destructor.
class A
{
public:
A() { m_b = new B(); }
~A() { delete m_b; }
private:
B* m_b;
};
This technique/pattern of resource acquisition, does it have a common name?
I'm quite sure I've read it somewher... | The answer to your question is RAII (Resource Acquisition Is Initialization).
But your example is dangerous:
Solution 1 use a smart pointer:
class A
{
public:
A(): m_b(new B) {}
private:
boost::shared_ptr<B> m_b;
};
Solution 2: Remember the rule of 4:
If your class contains an "Owned RAW pointer" then ... |
1,846,178 | 1,846,187 | Crosscompiling C++; from Linux to Windows, does it really work? | I have the source code for some very simple command line programs. I was considering the option of compiling them on a Linux machine (they were deveoped here) so they can be used on Windows. If I am not wrong this is called Cross-compiling. I have never tried it, but reading yesterday some information, it seems to be k... | Look into mingw, a suite of tools for building Win32 applications in Linux. If the programs don't depend on any Linux-specific functionality not supported by mingw, you should be fine.
|
1,846,186 | 1,846,198 | Thread safety of std::map for read-only operations | I have a std::map that I use to map values (field ID's) to a human readable string. This map is initialised once when my program starts before any other threads are started, and after that it is never modified again. Right now, I give every thread its own copy of this (rather large) map but this is obviously inefficien... | This will work from multiple threads as long as your map remains the same. The map you use is immutable de facto so any find will actually do a find in a map which does not change.
Here is a relevant link: http://www.sgi.com/tech/stl/thread_safety.html
The SGI implementation of STL is
thread-safe only in the sense t... |
1,846,385 | 1,846,447 | Running a Windows program and detect when it ends with C++ | Suppose I run an application, after some time this app will get closed by user. Is it possible to find out when the program exits? Can I get it's process id when I run that application?
| This is a quote from here:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <conio.h>
void _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
STARTUPINFO sj;
PROCESS_INFORMATION pj;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
ZeroMemor... |
1,846,392 | 1,846,402 | Passing string as an argument in C | I am having a function:
int getparam(char *gotstring)
and i am passing a string argument to it, like char *sendstring = "benjamin"
Instead of the above declaration I can use,
int getparam(char gotstring[])
Question: Which one is better? And if I have to use int getparam(char gotstring[]) what are all the other change... | int getparam(char gotstring[]) and int getparam(char* gotstring) are identical. Personally, I would recommend the latter syntax, because it better describes what is actually going on. The getparam function only has a pointer to the string; it has no knowledge about the actual array size. However, that is just my opi... |
1,846,450 | 1,847,867 | Cross-platform library for manipulating Windows paths? | I am writing a cross-platform application that needs to inspect and manipulate Windows-paths.
Specifically, for the particular problem I am having now, I need to know if a path is absolute or relative.
The current code uses boost::filesystem::path which of course works like a charm on Windows:
boost::filesystem::path t... | It seems to be difficult to find a library for this. One possibility is PathIsRelative in Winelib, but I don't want to use Winelib.
I ended up doing a very specific solution just for deciding this small thing. Assuming that the path is correct (a fair assumption in my case), an absolute path will contain :\, while a re... |
1,846,656 | 1,846,845 | Cast boost::shared_array<char> to boost::shared_array<const char> | How can I cast a boost::shared_array<char> to boost::shared_array<const char>?
| Since shared_array has no add_ref method you could emulate it as follows:
struct MagicDeleter {
MagicDeleter( boost::shared_array<char> ptr ) : ptr(ptr) {};
template<typename T> void operator()(T*) {}
protected:
boost::shared_array<char> ptr;
};
...
boost::shared_array<char> orig_ptr( some_val );
boost::shared... |
1,846,684 | 1,867,534 | .NET COM Library is not unloaded from C++ host process | We have a plugin system here, written in c++. Now that this has to have an ability to upgrade plugins(which are COM) we need to unload the plugin, install the plugin and then load it again. Now the problem is that this has to happen without closing an app. c++ COM dlls get unloaded pretty good but .NET ones not. Here's... | Resolved via this thread
|
1,846,856 | 1,846,879 | How do I determine if an indexed mode SDL_Surface has transparency or not? | I've got code I've been working with to load and convert SDL_Surfaces to OpenGL textures, however I've realized that they only work with RGB(A) surfaces. I need to extend the support onto indexed mode images (with or without transparency).
Initially, I was looking into ::SDL_SetColorKey(), however it seems to only work... | The typical way it's done for indexed mode is either to have a full 32-bit RGBA palette, so you have 8 bits of alpha per indexed color slot. Or, you can just define a certain (range of) palette index as being transparent.
OpenGL supports the latter, through the GL_PIXEL_MAP_I_TO_A table accessed through glPixelMap(). S... |
1,846,979 | 1,848,315 | force a bit field read to 32 bits | I am trying to perform a less-than-32bit read over the PCI bus to a VME-bridge chip (Tundra Universe II), which will then go onto the VME bus and picked up by the target.
The target VME application only accepts D32 (a data width read of 32bits) and will ignore anything else.
If I use bit field structure mapped over a V... | As an example, the Linux kernel has inline functions that explicitly handle memory-mapped IO reads and writes. In newer kernels it's a big macro wrapper that boils down to an inline assembly movl instruction, but it older kernels it was defined like this:
#define readl(addr) (*(volatile unsigned int *) (addr))
#define... |
1,847,032 | 1,910,190 | Upgradeable read/write lock Win32 | I am in search of an upgradeable read write lock for win32 with the behaviour of pthreads rwlock, where a read lock can be up- and downgraded.
What I want:
pthread_rwlock_rdlock( &lock );
...read...
if( some condition ) {
pthread_rwlock_wrlock( &lock );
...write...
pthread_rwlock_unlock( &lock );
}
...read.... | The boost shared_mutex class supports reader (shared) and writer (unique) locks and temporary upgrades from shared to unique locks.
Example for boost shared_mutex (multiple reads/one write)?
I don't recommend writing your own, it's a tricky thing to get right and difficult to test thoroughly.
|
1,847,038 | 1,847,074 | Illegal call to non-static member function (C++)? | I'm developing a game which is based around the user controlling a ball which moves between areas on the screen. The 'map' for the screen is defined in the file ThreeDCubeGame.cpp:
char m_acMapData[MAP_WIDTH][MAP_HEIGHT];
The ThreeDCubeGame.cpp handles most of the stuff to do with the map, but the player (and keyboard... | class A {
int i;
public:
A(): i(0) {}
int get() const { return i; }
};
int main() {
A a;
a.get(); // works
A::get(); // error C2352
}
There's no object to call the function with.
|
1,847,131 | 1,847,229 | How many digits in this base? | The problem is to derive a formula for determining number of digits a given decimal number could have in a given base.
For example: The decimal number 100006 can be represented by 17,11,9,8,7,6,8 digits in bases 2,3,4,5,6,7,8 respectively.
Well the formula I derived so far is like this : (log10(num) /log10(base)) + 1... | There are fast floating operations in your compiler settings. You need precise floation operations. The thing is that log10(8)/log10(2) is always 3 in math. But may be your result is 2.99999, for expample. It is bad. You must add small additive, but not 0.5. It should be about .00001 or something like that.
Almost true... |
1,847,196 | 1,847,218 | Efficient switch statement | In the following two versions of switch case, I am wondering which version is efficient.
1:
string* convertToString(int i)
{
switch(i)
{
case 1:
return new string("one");
case 2:
return new string("two");
case 3:
return new string("three");
.
.
default:
... | This is a premature optimization worry.
The former form is clearer and has fewer source lines, that is a compelling reason to chose it (in my opinion), of course.
You should (as usual) profile your program to determine if this function is even on the "hot list" for optimization. This will tell you if there is a perform... |
1,847,410 | 3,039,857 | crypto++ RSA and "invalid ciphertext" | Well, I've been going through my personal hell these days
I am having some trouble decrypting a message that was encrypted using
RSA and I'm always failing with a "RSA/OAEP-MGF1(SHA-1): invalid
ciphertext"
I have a private key encoded in base64 and I load it:
RSA::PrivateKey private_key;
StringSource file_pk(P... | If the key was actually corrupted, the Load function should have failed. However you can ask the key to self-test itself, which should detect any corruption, by calling Validate, like:
bool key_ok = private_key.Validate(rng, 3);
The second parameter (here, 3) specifies how much checking to be done. For RSA, this will ... |
1,847,478 | 1,847,540 | Protecting class from getting instantiated before main() | I want to ensure that my C++ class is never instantiated before main() is entered. Is there any way to achieve this?
--
Some clarification:
I am writing an embedded application. My class must be static (reside in the BSS), but at instantiation it requires some resources that aren't available before certain things has ... | One thing you can do is have a static method like MyClass::enableConstruction() which turns on a static flag in the class. If the c'tor is called when this flag is false then it throws an exception. This way you'll alteast have some run-time indication that someone is breaking the rules.
Notice that you should be care... |
1,847,640 | 1,849,152 | COleDataSource - setting drag & drop data between applications | Some code I am working on uses COleDataSource::CacheGlobalData, passing as CF_TEXT an HGLOBAL pointing to some memory allocated for the text. I want to also add a numeric value, so ythe drop-target can access either the text or numeric values.
How can this easily be done? Can a 2nd CacheGlobalData call be made with a d... | You can call CacheGlobalData multiple times. For each clipboard format, the clipboard stores the last value set by CacheGlobalData. For example, IE stores data in CF_UNICODETEXT, CF_TEXT and CF_HTML formats when you drag a paragraph of text. Generally an application should provide data in as many formats as possible so... |
1,847,661 | 1,847,697 | Calling a Child class' method when processing a list of Parent class objects | This question seems like it might be somewhat common, but I didn't find anything when scowering StackOverflow or the interwebs.
I came across a method in a C++ class that takes a list of (for example) Parent objects. For this example, assume that there are two classes that derive from Parent: Child1 and Child2.
For e... | If your IsOfType() test passes, you can cast the (pointer to the) parent object to a Child2 object and access its specific member functions.
EDIT:
This depends on your design and on how strict you ensure the IsOfType() implementation will give correct answers (i.e. it also works when you add new subclasses in a week). ... |
1,847,717 | 1,847,770 | Does CAtlList::RemoveAt invalidate existing POSITIONS? | I'm looking at this, where m_Rows is a CAtlList:
void CData::RemoveAll()
{
size_t cItems = m_Rows.GetCount();
POSITION Pos = m_Rows.GetHeadPosition();
while(Pos != 0)
{
CItem* pItem = m_Rows.GetAt(Pos);
if (pItem != 0)
delete pItem;
POSITION RemoveablePos = Pos;
... | According to the documentation, CAtlList behaves like a double linked list, so removing one list item should not invalidate the pointers to other items. The POSITION type references the memory location of a list item directly:
Most of the CAtlList methods make use of a position value. This value is used by the methods... |
1,847,822 | 1,848,418 | name collision in C++ | While writing some code i came across this issue:
#include <iostream>
class random
{
public:
random(){ std::cout << "yay!! i am called \n" ;}
};
random r1 ;
int main()
{
std::cout << "entry!!\n" ;
static random r2;
std::cout << "done!!\n" ;
return 0 ;
}
When i try to compile this code i get the error
error: ... | Why does your using namespace... not work, while your using ... works? First i want to show you another way to solve it by use of an elaborated type specifier:
int main() {
// ...
static class random r2; // notice "class" here
// ...
}
That works because "class some_class" is an elaborated type specifier, which ... |
1,847,846 | 1,849,280 | Pass by value or reference, to a C++ constructor that needs to store a copy? | Should a C++ (implicit or explicit) value constructor accept its parameter(s) by value or reference-to-const, when it needs to store a copy of the argument(s) in its object either way?
Here is the shortest example I can think of:
struct foo {
bar _b;
foo(bar [const&] b) // pass by value or reference-to-const?
... | In C++98 and C++03, you should pass const& bar and then copy. In C++0x, you should pass bar and then do a move (provided bar has a move constructor).
#include <utility>
struct foo
{
bar _b;
foo(bar b) : _b(std::move(b)) {}
};
If you construct foo with an lvalue parameter, the copy constructor will be called ... |
1,847,860 | 1,847,949 | Why is there a performance warning on casting pointer to bool? | This question extends Why use !! when converting int to bool?.
I thought I was being cool when I did something like:
bool hasParent() {
return this->parentNode;
}
Where this->parentNode is NULL when there is no parent node.
But I'm getting:
warning C4800: 'Node *' : forcing value to bool 'true' or 'false' (perfor... | There's a discussion on Microsoft Connect about this (What is the performance implication of converting to bool in C++?). The example given to Microsoft is:
$ cat -n t.cpp && cl -c -W3 -O2 -nologo -Fa t.cpp
1 bool f1 (int i)
2 {
3 return i & 2;
4 }
5
6 bool f2 (int i)
7 {
8 const bool b = i & 2;
9 return b;
10 }
11
12... |
1,848,136 | 1,848,248 | What is the reason for not allowing in C++ a default value for a variable to be a non-static method or member of a class? | I wanted to know why the default value for a variable for a method of a class, cannot be a non-static method or member of the same class.
Is there a reason for that ? Could not the compiler provide to the method the position in the class of the non-static default value ?
I tried to google quickly for an answer but I co... | Default arguments are evaluated in the context of the caller (which is why they are usually called "arguments", not "parameters"), not in the context of the class method. This means that in order to evaluate these non-static arguments the compiler would need to know the specific class instance from which to take these ... |
1,848,286 | 1,848,301 | Why does `include <iostream>` end up including so *many* files? | Follow up of this question:
When I do include <iostream>.
It happens that it includes many files from /usr/include .A grep "\usr\include" over g++ -E prog.cpp counted to about 1260 entries ;).
Is their a way to control including various files?
Platform: Linux
G++ version: 4.2.4
| No, <iostream> includes them because it depends on them directly, or it's dependancies depend on them.
Ain't nothing you can do about it.
You can (depending on your compiler) limit the effect this has on compilation times by using Precompiled Headers
|
1,848,479 | 1,849,327 | In windbg, How to set breakpoint on all functions in kernel32.dll? | I want figure out the call sequence and functions to kernel32.dll
in a function example() in example.DLL.
In windbg, how to set breakpoint on all functions in kernel32.dll?
I tried bm kernel32!* , but seems not work.
| I would not do just as stated. Of course it is possible, but if done with bm /a kernel32!* you inadvertently set bps also on data symbols (as opposed to actual functions). In your case wt - trace and watch data (you can look it up in the debugger.chm provided with your windbg package) might be what you're after.
|
1,848,585 | 1,848,598 | What is the best way for two programs on the same machine to communicate with each other | I need to pass some data (integers) from one (C++) program to another (C#). What is the fastest way to do this?
P.S.: OS: Windows XP
| My personal preference for this, given that you're using C++ and C# both, and it's on the same system, would be to use Pipes.
They work very well from native code (C++) as well as from C# via NamedPipeClientStream and NamedPipeServerStream.
However, there are other options for Interprocess Communication, any of which w... |
1,848,730 | 1,848,769 | c++ read from file redirection and also keyboard | My program reads a list of integers from user input [ keyboard] and calculates some statistics
The user enters 'x' to terminate the input process.
So for example,
Enter integers separated by space ( enter x to quit) : 1 2 3 4 5 x
But now I want to include the inputs to be read from file redirection also. So if the nu... | use isatty for your file descriptor
(0 for standard input)
example:
#include <unistd.h>
main(){
if(isatty(0))
puts("tty"); // print some prompt
else
puts("pipe"); // not really needed in your case
}
|
1,849,447 | 1,849,487 | How can you detect if two regular expressions overlap in the strings they can match? | I have a container of regular expressions. I'd like to analyze them to determine if it's possible to generate a string that matches more than 1 of them. Short of writing my own regex engine with this use case in mind, is there an easy way in C++ or Python to solve this problem?
| There's no easy way.
As long as your regular expressions use only standard features (Perl lets you embed arbitrary code in matching, I think), you can produce from each one a nondeterministic finite-state automaton (NFA) that compactly encodes all the strings that the RE matches.
Given any pair of NFA, it's decidable w... |
1,849,490 | 1,849,508 | C++ - Arguments for Exceptions over Return Codes | I'm having a discussion about which way to go in a new C++ project. I favor exceptions over return codes (for exceptional cases only) for the following reasons -
Constructors can't give a return code
Decouples the failure path (which should be very rare) from the logical code which is cleaner
Faster in the non-excepti... | I think this article sums it up.
Arguments for Using Exceptions
Exceptions separate error-handling code from the normal program flow and thus make the code more readable, robust and extensible.
Throwing an exception is the only clean way to report an error from a constructor.
Exceptions are hard to ignore, unlike erro... |
1,849,558 | 1,850,059 | How do I use QTextBlock? | I'm completely new to C++ and Qt.
I want to populate a QTextEdit object with QTextBlocks, how do I do that?
e.g. If I have the sentence "the fish are coming" how would I put each word into its own QTextBlock and add that block to QTextEdit, or have I misunderstood how QTextBlock actually works?
| QTextEdit will let you add your contents via a QString:
QTextEdit myEdit("the fish are coming");
It also allows you to use a QTextDocument, which holds blocks of text.
The QTextDocument itself also can accept a QString:
QTextEdit myEdit;
QTextDocument* myDocument = new QTextDocument("the fish are coming", &myEdit);
my... |
1,849,571 | 1,849,629 | Calling pointer-to-member function in call for a function passed to a template function | This is the provided function template I'm trying to use:
template <class Process, class BTNode>
void postorder(Process f, BTNode* node_ptr)
{
if (node_ptr != 0)
{
postorder( f, node_ptr->left() );
postorder( f, node_ptr->right() );
f( node_ptr->data() );
}
}
This is my call, and the functio... | Your problem is that postorder accepts a function object that must be called this way:
f(arg);
You are passing in a pointer to member function. You should first call mem_fun to make a function object from the pointer to member:
std::mem_fun(&city_db::print)
The returned function object takes two arguments: the pointe... |
1,849,608 | 1,849,648 | Unix C++ simple server question: sending data back to browser | I am creating a simple Unix server written in C++ that simply waits for incoming connections, and then when a connection is established, it sends the requested data back to the client's browser to be displayed. I have everything working except for the sending of the data to the client. This is how it should work:
I st... | When you say:
int writeInt = write(recvInt, buffer, strlen(buffer));
the first parameter of write() should be the socket to write to - you are passing it the count of characters returned by recv()
|
1,849,738 | 1,849,769 | including .h file from a different application/directory | I have some .h files as follows (on Linux)
Source/Server/connect.h
Source/Server/message.h
...
I am developing another application that needs the two .h files but is in a different directory
Source/App2/..
How can I include the connect.h file in the App2 application, considering that I use perforce and everyone else ... | You can #include a relative path to the files:
#include "../Server/connect.h"
or you can add a flag to tell the compiler to look in the other directory. For gcc you can use -I../Server; for Visual C++ you can use /I"../Server"; other compilers, I'm sure, have their own flags for this purpose.
I think the second is be... |
1,849,918 | 1,851,489 | Pipe communication C++ | I´m writing two litle c++ apps that must communicate. First one will be a service which, every once in a while, must alert the user for something. Since a service cannot create windows I designed the app to be two separate executables.
The service will use a notifier to communicate.
The service needs only to send text ... | Some simple snippets from the client (your service) & the server (the notifier)
[Note: This is adapted from a project I've done a while ago which in turn was heavily "influenced" by the MSDN samples from CreateNamedPipe & co]:
Server side:
HANDLE hPipe = INVALID_HANDLE_VALUE;
bool bConnected = false;
hPipe = CreateNa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.