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,907,402
2,907,424
Noob boost::bind member function callback question
#include <boost/bind.hpp> #include <iostream> using namespace std; using boost::bind; class A { public: void print(string &s) { cout << s.c_str() << endl; } }; typedef void (*callback)(); class B { public: void set_callback(callback cb) { m_cb = cb; } void do_callback() { ...
replace typedef void (*callback)(); with typedef boost::function<void()> callback; A bound function doesn't produce an ordinary function, so you cannot just store it in a regular function pointer. However, boost::function is able to handle anything as long as it is callable with the correct signature, so that's what yo...
2,907,432
2,907,477
C++ friend class std::vector
Is it possible to do the following portably: struct structure { structure() {} private: // only allow container copy construct structure(const structure&) {} // in general, does not work because allocator (not vector) calls copy construct friend class std::vector<structure>; }; example message tryi...
No. vector (more precisely, the allocator passed into vector) can delegate the task of construction to a free function or another class, making the friendship useless. Even if you pass your own allocator, it may be rebound to a class internal to the implementation. Then the constructor for your class may be accessed fr...
2,907,473
2,907,480
A simple question about type coercion in C++
Given a function prototype, and a type definition: int my_function(unsigned short x); typedef unsigned short blatherskite; Is the following situation defined by standard: int main(int argc, char** argv) { int result; blatherskite b; b=3; result = my_function(b); } Do I get type coercion predictably via the f...
If your question is really about whether the types of the argument and the parameter match, then the answer is yes. typedef does not introduce a new type, it only creates alias for an existing one. Variable b has type unsigned int, just like the parameter, even though b is declared using typedef-name blatherskite. Your...
2,907,500
2,907,534
Can C++ and C# be used for applications for iPhone
Can I write applications for iPhone in C++ or C#? Where can I find simulators for iPhone for testing my apps. How to write them?
You need at least a small Objective C stub to hook into the system and deal with provided services (including getting input), but your program can be primarily in C++ if you would like. Apple seems to disallow C#; tools such as MonoTouch appear to be banned by the current developer agreement. With a Macintosh, you go ...
2,907,580
2,907,760
How do i return a template class from a template function?
How do i pull off something that would make the last commented line compile? How would i have to change this code to make it work? #include<iostream> using namespace std; template <int x> class someclass{ public: int size; int intarr[x]; someclass():size(x){} }; template<int x, int y> int somefunc(someclass<...
How is it supposed to know what x is from outside the function? (It can't look into the body, because in which body of which function it looks depends on what value x gets!). Also you cannot write that ?: because both your branches yield totally unrelated types that can't possibly get to a common type. But that operato...
2,907,797
2,907,817
Where does the compiler store methods for C++ classes?
This is more a curiosity than anything else... Suppose I have a C++ class Kitty as follows: class Kitty { void Meow() { //Do stuff } } Does the compiler place the code for Meow() in every instance of Kitty? Obviously repeating the same code everywhere requires more memory. But on the other hand, br...
I believe the standard way for instance methods is to be implemented like any static method, only once, but having the this pointer passed on a specific register or on the stack to perform the call.
2,907,859
2,909,575
Mingling C++ classes with Objective C classes
I am using the iphone SDK and coding primarily in C++ while using parts of the SDK in obj-c. Is it possible to designate a C++ class in situations where an obj-c class is needed? For instance: 1) when setting delegates to obj-c objects. I cannot make a C++ class derive from a Delegate protocol so this and possibly o...
The sad news is that you can't get completely around the adapters, but you can ease the job. By using the Objective-C runtime libraries you can reduce the clutter by generating the adapters for you with a declarative approach. The Objective-C runtime allows you to construct classes at runtime for which you can set the ...
2,907,929
2,907,973
How to solve this error that is shown on Windbg?
I've loaded a .exe and it gave this error: Microsoft (R) Windows Debugger Version 6.12.0002.633 X86 Copyright (c) Microsoft Corporation. All rights reserved. CommandLine: "C:\Users\Public\SoundLog\Code\Código Python\SoundLog\dist\SoundLog.exe" Symbol search path is: *** Invalid *** ************************************...
Your first issue is that you do not have a symbol path set. You can run ".symfix", as suggested in the message, to automatically select a symbol path using Microsoft's public symbol server. The second is an unhandled exception. You need to get proper symbols first, and then run "k" to get a stack trace that should g...
2,908,057
2,908,351
Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?
My project directory looks like this: /project Makefile main /src main.cpp foo.cpp foo.h bar.cpp bar.h /obj main.o foo.o bar.o What I would like my makefile to do would be to compile all .cpp files in the /src folder to .o files in the /ob...
Makefile part of the question This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++) SRC_DIR := .../src OBJ_DIR := .../obj SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp) OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES)...
2,908,076
8,379,375
How to fix this exception shown in windbg execution?
after running the .exe thought WinDBG, this was the exception information provided by pressing "k" when the exception occured: ChildEBP RetAddr 0012e2f4 6f9fbb1c KERNELBASE!RaiseException+0x58 0012e354 6fba88f4 mscorwks!RaiseTheExceptionInternalOnly+0x2a8 0012e36c 6fba8966 mscorwks!RaiseTheException+0x4e 0012e394 6fb...
If it is a 3.5 or lower .NET then you have to load sos by calling ".loadby sos mscorwks". If it is a 4.0 then you have to use ".loadby sos clr".
2,908,135
2,908,148
Compilation problem in the standard x86_64 libraries
I am having trouble compiling a program I have written. I have two different files with the same includes but only one generates the following error when compiled with g++ /usr/lib/gcc/x86_64-linux-gnu/4.4.1/../../../../lib/crt1.o: In function `_start': /build/buildd/eglibc-2.10.1/csu/../sysdeps/x86_64/elf/start.S:109:...
You need a main function and you don't have one. If you do have a main function, show more code please.
2,908,244
2,908,270
why no implicit conversion from pointer to reference to const pointer
I'll illustrate my question with code: #include <iostream> void PrintInt(const unsigned char*& ptr) { int data = 0; ::memcpy(&data, ptr, sizeof(data)); // advance the pointer reference. ptr += sizeof(data); std::cout << std::hex << data << " " << std::endl; } int main(int, char**) { unsigned c...
If the pointer gets converted to a const pointer, as you suggest, then the result of that conversion is a temporary value, an rvalue. You cannot attach a non-const reference to an rvalue - it is illegal in C++. For example, this code will not compile for a similar reason int i = 42; double &r = i; Even though type in...
2,908,275
2,908,314
Are reference attributes destroyed when class is destroyed in C++?
Suppose I have a C++ class with an attribute that is a reference: class ClassB { ClassA &ref; public: ClassB(ClassA &_ref); } Of course, the constructor is defined this way: ClassB::ClassB(ClassA &_ref) : ref(_ref) { /* ... */ } My question is: When an instance of class 'ClassB' is destroyed, is the object re...
A reference is nothing but an alias for a variable, the alias gets destructed, not the actual variable. You could consider it some kind of pointer, but there are reasons to refrain from this kind of (evil) thoughts :).
2,908,477
2,908,507
When do I need to deallocate memory?
I am using this code inside a class to make a webbrowser control visit a website: void myClass::visitWeb(const char *url) { WCHAR buffer[MAX_LEN]; ZeroMemory(buffer, sizeof(buffer)); MultiByteToWideChar(CP_ACP, MB_ERR_INVALID_CHARS, url, strlen(url), buffer, sizeof(buffer)-1); VARIANT vURL; vURL.vt...
I think you have some fundamental problems with your understanding of memory management. In this case, no, you don't need to explicitly free any memory. You didn't ever call new, so you don't need to call delete. buffer exists only on the stack, and will vanish when this method returns.
2,908,603
2,908,615
TerminateProcess and deadlocks
Is it real that the TerminateProcess function in Windows could hang because the threads inside the process were stuck in a deadlock? Example: Process A is running under Process B's control, now Process A gets into a deadlock and Process B detects this and decides to 'Kill' process A using TerminateProcess. Would it be...
Yes, all kernel objects held by the process will be released, including locks. The main problem with TerminateProcess is that the process has no say in the matter: if it's holding on to any global state (files, shared memory, etc) then you have no guarantee those things are in a consistent state after the process is te...
2,908,607
2,908,707
Fun with casting and inheritance
NOTE: This question is written in a C# like pseudo code, but I am really going to ask which languages have a solution. Please don't get hung up on syntax. Say I have two classes: class AngleLabel: CustomLabel { public bool Bold; // Just upping the visibility to public // code to allow the label to be on a...
It would work in Delphi. Code in the same unit as the classes it uses have implicit access to protected (but not strict protected) members, even those members declared in another unit. You'de declare the property protected in CustomLabel: type CustomLabel = class private FBold: Boolean; protected property...
2,908,632
2,908,695
Why does DestroyWindow close my application?
I'v created a window after creating my main one but calling DestroyWindow on its handle closes the entire application, how can I simply get rid of it? it looks like this: BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; HWND fakehandle; hInst = hInstance; // Store instance handle in our glob...
I've just found this comment: If the specified window is a parent or owner window, DestroyWindow automatically destroys the associated child or owned windows when it destroys the parent or owner window. The function first destroys child or owned windows, and then it destroys the parent or owner window. on the Destroy...
2,908,673
2,914,595
Is it possible to load a file full of binary data into GDB when GDB is debugging a core file?
I am debugging a crash using GDB and a core file. A large portion of the memory space is mmapped into the process. That portion of the memory is not saved into the core file. I have a file that contains all the data in that mmapped memory. I would like to find a way to load the data from that file into GDB at a ce...
The only way that I was able to get this to work was to modify the core file itself to have an additional program header/section that contained the new data. In theory, I believe that objcopy should be able to do this, but after a lot of testing I was unable to get it to work. Instead, I resorted to writing a perl scr...
2,908,834
2,908,853
Why was the definition of a variable changed during the development of C++11?
n3035 says: A variable is introduced by the declaration of an object. The variable's name denotes the object. n3090 says: A variable is introduced by the declaration of a reference other than a non-static data member or of an object. The variable's name denotes the reference or object. I wonder what motivated this ...
The change was in response to CWG defect 633. The list of changes related to this can be found in n2993: The goal of these changes is to expand the meaning of "variable" to encompass both named objects and references, and to apply the term consistently wherever feasible.
2,908,928
2,909,107
Coupling an MFC CListCtrl and CTreeCtrl to get a view of the whole tree, not just one node at a time
Consider Windows Explorer (or regedit or similar). To the left side, there is a tree view, and to the right, a list view. In all cases I know of, the contents of the right view reflect the attributes of the selected node from the left pane. This is all well and good... but just not what I want. The nodes of the tree I ...
You are probably looking for Coumn Tree Control
2,909,213
2,909,236
How to add custom line endings in text file (e.g. I want to add a line ending after all periods)
I have a bunch of text files where I want to add a line ending after each period. I'm wondering if there is a way to do this by doing replacing all periods with a \n\n, assuming I have the right encoding (unix). Anyone know how I would do this? Replace .'s with .\n\n and then save as a different file? Thanks!
perl -pne 's/\./\.\n/g' < input_file > output_file
2,909,250
2,976,254
Disable MSBuild output of "Processing /ORDER options..."
The output file from our project build has gone from 6MB to over 75MB in text. Diff'ing the last good build and the first time it blew up, there's a section in the output file like this in the latest: Processing /ORDER options External code objects not listed in the /ORDER file: ?onCallDisconnected@CallStateConnect...
I turned of VERBOSE linking and set it to none. Now I have zip spitting out.
2,909,427
2,909,445
C++ floating point precision
Possible Duplicate: Floating point inaccuracy examples double a = 0.3; std::cout.precision(20); std::cout << a << std::endl; result: 0.2999999999999999889 double a, b; a = 0.3; b = 0; for (char i = 1; i <= 50; i++) { b = b + a; }; std::cout.precision(20); std::cout << b << std::endl; result: 15.00000000000001421...
To get the correct results, don't set precision greater than available for this numeric type: #include <iostream> #include <limits> int main() { double a = 0.3; std::cout.precision(std::numeric_limits<double>::digits10); std::cout << a << std::endl; double b = 0; for (char i = 1;...
2,909,515
2,909,699
Access cost of dynamically created objects with dynamically allocated members
I'm building an application which will have dynamic allocated objects of type A each with a dynamically allocated member (v) similar to the below class class A { int a; int b; int* v; }; where: The memory for v will be allocated in the constructor. v will be allocated once when an object of type A is created and w...
If you have a good reason to care about performance... Could having v dynamically allocated could mean that an instance of A and its member v are not located together in memory? If they are both allocated with 'new', then it is likely that they will be near one another. However, the current state of memory can dra...
2,909,590
2,909,672
Strange error with CreateCompatibleDC
Maybe this is a foolish question, I can't see why I can not get a DC created in the following code : HBITMAP COcrDlg::LoadClippedBitmap(LPCTSTR pathName,UINT maxWidth,UINT maxHeight) { HBITMAP hBmp = (HBITMAP)::LoadImage(NULL, pathName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREA...
You are improperly casting the result of GetDC() to an HDC. GetDC() returns a pointer to a CDC object. To do what you want you can do either of the following. The first choice fits more into how MFC likes to do things, but both work just fine: CDC *pDC = GetDC(); // Option 1 CDC memDC; memDC.CreateCompatibleDC(pDC);...
2,909,604
2,909,748
Bona fide transiant windows with WinAPI?
I want to create a Window like when a context menu pops up or clicking the menubar. I want a Window that will be like this and that I can take over its paint event. Sort of like what is created when you select a sub tool in Photoshop. EDIT:I want to know how to create controls like the one that comes when you select a...
But how do they get a nice shadow around it, and how does it still stay with the main window without a parent? That's your real question. There are several ways of getting the shadow. One is that the window is actually two windows, the "shadow" plus the "main" window. When you create the flyout window (that's wh...
2,909,746
2,909,806
weird performance in C++ (VC 2010)
I have this loop written in C++, that compiled with MSVC2010 takes a long time to run. (300ms) for (int i=0; i<h; i++) { for (int j=0; j<w; j++) { if (buf[i*w+j] > 0) { const int sy = max(0, i - hr); const int ey = min(h, i + hr + 1); const int sx = max(0, j - hr); ...
I suggest you try different floating-point calculation models supported by the compiler - precise, strict or fast (see /fp option) - with your original code before making any conclusions. I suspect that your original code was compiled with some overly restrictive floating-point model (not followed by your assembly in t...
2,909,953
2,909,959
Is there any way to use VC++ 2010 without including stdafx.h?
I've successfully installed M$ VC2010 and start writing simple programs using it. I am very annoyed from the #include<stdafx.h>, So is there any way to compile and run programs without it???
It's for pre-compiled headers. Don't use pre-compiled headers, don't include it.
2,909,957
2,915,522
Why this base64 function stop working when increasing max length?
I am using this class to encode/decode text to base64. It works fine with MAX_LEN up to 512 but if I increase it to 1024 the decode function returns and empty var. This is the function: char* Base64::decode(char *src) { unsigned six, dix; unsigned int d_len = MAX_LEN; memset(dst,'\0', MAX_LEN); unsig...
Odds are dst is not sized correctly to hold all 1024 bytes. Without seeing dst's declaration there is no way to be sure.
2,909,991
2,910,102
Compiling cpp code in netbeans produce errors, how to solve it?
i use the netbeans with MinGW and MYSY make /debugger but when i compile a basic cpp code in it and run it it produces two erorrs this is the code runned and the output![alt text][1] box #include <iostream> void main() { cout << "Hello World!" << endl; cout << "Welcome to C++ Programming" << endl; } output is ...
I can see three things here, the first two have been pointed out by Xavier and jwismar, but to consolidate: Both D:/Users/Home/Documents/NetBeansProjects/newApp/newfile.cpp and D:/Users/Home/Documents/NetBeansProjects/newApp/main.cpp define a main(). You'll need to remove one of these from your project. You'll need to...
2,910,157
2,910,180
Can't inherit from auto_ptr without problems
What I want to do is this: #include <memory> class autostr : public std::auto_ptr<char> { public: autostr(char *a) : std::auto_ptr<char>(a) {} autostr(autostr &a) : std::auto_ptr<char>(a) {} // define a bunch of string utils here... }; autostr test(char a) { return autostr(new char(a)); } void main(i...
The autostr that is returned from the function is a temporary. Temporary values can only be bound to references-to-const (const autostr&), but your reference is non-const. (And "rightly so".) This is a terrible idea, almost none of the standard library is intended to be inherited from. I already see a bug in your code:...
2,910,318
2,910,749
Global variable not stable after platform changed
Our embedded system is built on a hw/sw platform made by enea. After the platform updated recently, we found some operations on the global variable keep crashing the system. For example, we have a global map structure holding some data. We can insert/iterate the map once or twice, then the address of the elements in t...
A known issue with globals is order of initialization. This order is generally not defined. As a result, you may see crashes if the ctor of one global tries to use another global. In your case, the problem may be that GCC has decided to initialize the map later, after the point where you're using it. A quick solution c...
2,910,377
2,910,392
Get home directory in Linux
I need a way to get user home directory in C++ program running on Linux. If the same code works on Unix, it would be nice. I don't want to use HOME environment value. AFAIK, root home directory is /root. Is it OK to create some files/folders in this directory, in the case my program is running by root user?
You need getuid to get the user id of the current user and then getpwuid to get the password entry (which includes the home directory) of that user: #include <unistd.h> #include <sys/types.h> #include <pwd.h> struct passwd *pw = getpwuid(getuid()); const char *homedir = pw->pw_dir; Note: if you need this in a thread...
2,910,428
2,910,438
Switch/Case statements in C++
Regarding the switch/case statement in the C++ code below: "Case 1" is obviously false, so how/why does it enter the do-while loop? #include <iostream> using namespace std; int main() { int test = 4; switch(test) { case 1: do { case 2: test++; case 3: test++; ca...
This is Duff's Device, which is an old, clever technique for jumping into the middle of a loop.
2,910,557
2,911,355
Eliminating inherited overlong MACRO
I have inherited a very long set of macros from some C algorithm code.They basically call free on a number of structures as the function exits either abnormally or normally. I would like to replace these with something more debuggable and readable. A snippet is shown below #define FREE_ALL_VECS {FREE_VEC_COND(kernel);F...
If they are broken then fix them by converting to functions. If they're aren't broken then leave them be. If you are determined to change them, write unit-tests to check you don't inadvertently break something.
2,910,587
2,910,694
delete vs NULL vs free in c++
what is the difference between deleting a pointer, setting it to null, and freeing it. delete ptr; vs. ptr=NULL; vs. free(ptr);
Your question suggests that you come from a language that has garbage collection. C++ does not have garbage collection. If you set a pointer to NULL, this does not cause the memory to return to the pool of available memory. If no other pointers point to this block of memory, you now simply have an "orphaned" block of...
2,910,836
2,911,350
How do I read long lines from a text file in C++?
I am using the following code for reading lines from a text-file. What is the best method for handling the case where the line is greater than the limit SIZE_MAX_LINE? void TextFileReader::read(string inFilename) { ifstream xInFile(inFilename.c_str()); if(!xInFile){ return; } char acLine[SIZE_M...
Don't use istream::getline(). It deals with naked character buffers and is therefor prone to errors. Better use std::getline(std::istream&,std::string&, char='\n') from the <string> header: std::string line; while(std::getline(xInFile, line)) { m_sStream.append(line); m_sStream.append('\n'); // getline() cons...
2,910,979
2,913,870
How does `is_base_of` work?
How does the following code work? typedef char (&yes)[1]; typedef char (&no)[2]; template <typename B, typename D> struct Host { operator B*() const; operator D*(); }; template <typename B, typename D> struct is_base_of { template <typename T> static yes check(D*, T); static no check(B*, int); static co...
If they are related Let's for a moment assume that B is actually a base of D. Then for the call to check, both versions are viable because Host can be converted to D* and B*. It's a user defined conversion sequence as described by 13.3.3.1.2 from Host<B, D> to D* and B* respectively. For finding conversion functions th...
2,911,154
2,911,438
Custom (pool) allocator with boost shared_ptr
I want objects managed by a shared_ptr to be allocated from a pool, say Boost's Pool interface, how can this be achieved?
Here's the code to do what you want (probably won't compile as I don't have boost on hand and I'm writing it from memory): class YourClass; // your data type, defined somewhere else boost::object_pool<YourClass> allocator; void destroy(YourClass* pointer) { allocator.destroy(pointer); } boost::shared_ptr<YourCla...
2,911,318
2,911,329
Find the "name" of a library (-L -l switches)
Being fairly new to C++ I have a question bascially concerning the g++ compiler and especially the inclusion of libraries. Consider the following makefile: CPPFLAGS= -I libraries/boost_1_43_0-bin/include/ -I libraries/jpeg-8b-bin/include/ LDLIBS= libraries/jpeg-8b-bin/lib/libjpeg.a # LDLIBS= -L libraries/jpeg-8b-bin/li...
You don't need the lib part if you use the -l switch. LDLIBS=-Llibraries/jpeg-8b-bin/lib -ljpeg # ^^^^ Whenever you write -lxxx, the linker will look for a library with filename libxxx.<ext> in all supplied library paths. This is the standard convention of ld, and should be true for...
2,911,442
2,911,504
Access variable value using string representing variable's name in C++
If the title was not clear, I will try to clarify what I am asking: Imagine I have a variable called counter, I know I can see its current value by doing something like: std::cout << counter << std::endl; However, assume I have lots of variables and I don't know which I'm going to want to look at until runtime. Does ...
As has been mentioned, you are looking for reflection in C++. It doesn't have that, and this answer explains why.
2,911,448
2,914,348
structures, inheritance and definition
i need to help with structures, inheritance and definition. //define struct struct tStruct1{ int a; }; //definition tStruct1 struct1{1}; and inheritance struct tStruct2:tStruct1{ int b; }; How can I define it in declaration line? tStruct2 struct2{ ????? }; One more question, how can i use inheritance for st...
First off, the typedef for a structure doesn't change anything, it only introduces an alternative name for the type. You can still inherit from it as usual. The Type identifier{params} syntax for definitions is C++0x syntax for the new uniform initialization. In pre-C++0x you have two choices for initialization of user...
2,911,482
2,911,520
Better name needed for applying a function on elements of a container
I have a container class (containing a multi-index container) for which I have a public "foreach" member-function, so users can pass a functor to apply on all elements. While implementing, I had a case where the functor should only be applied to some elements of a range in the container, so I overloaded the foreach, to...
Based on your description, i'd go for apply_until().
2,911,639
2,911,669
Interrupt mechanism in C,C++
Hey I was writing a udp client server in which a client waits for packets from server.But I want to limit this wait for certain time.After client don't get response for a certain moment in raise an alarm,basically it comes out and start taking remedy steps.So what are the possible solution for it.I think writing a wrap...
If you want to do socket communications with timeouts, then select is the way to go. You basically set up arrays of file descriptors for various events such as read-ready or write-able, then call select with a timeout. If one of the events is valid, you will be notified and you can perform your actions. If none of the ...
2,911,703
2,919,167
crash when using stl vector at instead of operator[]
I have a method as follows (from a class than implements TBB task interface - not currently multithreading though) My problem is that two ways of accessing a vector are causing quite different behaviour - one works and the other causes the entire program to bomb out quite spectacularly (this is a plugin and normally a ...
I hate answering my own questions but this seems to be a situation where it is required. As it says in the update, I downloaded and installed the latest intel c++ compiler and recompiled from scratch which seems to have fixed the problem. I've also rebuilt the entire project from scratch using the 11.0.074 compiler to ...
2,911,798
5,995,994
FFMpeg encoding RGB images to H264
I'm developing a DirectShow filter which has 2 input pins (1 for audio, 1 for video). I'm using libavcodec/libavformat/libavutil of FFMpeg for encoding the video to H264, audio to AAC and mux it/stream using RTP. So far I was able to encode video and audio correctly using libavcodec but now I see that FFMpeg seems to s...
Try checking out the code in HandBrake. Specifically, this file muxmp4.c, which was a jem I found working with FFMpeg / RTP. Be sure and use av_interleaved_write_frame() and the extradata fields correctly. Those were some key differences I remember for RTP. Still, I had some stability issues with RTP/RTSP with FFMpe...
2,911,932
2,928,803
CRXIR2 doesn't work with VS2010 on Windows 7 nor on Vista
We're upgrading from VS2005 to VS2010. We are almost there but there is a problem with Crystal Reports. We use the RDC (COM-based) component within our C++ application. On Windows 7 or on VISTA, I can't get the viewer nor the designer controls working. I get Access Violations when the control is activated: // from atlh...
it looks like it has something to do with DEP. If we turn off the DEP completely on the system with bcdedit /set Nx AlwaysOff and then reboot of course, the Viewer works! Unfortunately this is a system global turn off. We tried to turn off DEP for our exe alone before, but then we got a message from Windows that we we...
2,912,037
2,912,108
Strange realloc behaviour
i'm developing an array structure just for fun. This structure, generalized by a template parameter, pre allocates a given number of items at startup, then, if "busy" items are more than available ones, a function will realloc the inner buffer . The testing code is : #include <stdio.h> #include <stdlib.h> #include <str...
realloc does not automatically grow the piece of memory - you'll have to do that. Do e.g.: da->data=(T*)realloc(da->data, sizeof(T)*(da->items+DARRAY_REALLOC_ITEMS_STEP)); (and you should handle realloc returning NULL)
2,912,266
2,912,524
What does this C++ code mean
I was trying to understand how webkit parses urls, and I'm having a hard time making heads or tails of this: Vector<char, 4096> buffer(fragmentEnd * 3 + 1); This line is on line 1214 (you can see it here: http://trac.webkit.org/browser/trunk/WebCore/platform/KURL.cpp#L1214). I get that it's making a vector of type ch...
The buffer variable is constructed exactly on that line: Vector<char, 4096> buffer(fragmentEnd * 3 + 1); Walking through the steps that the compiler takes, it first ensures that there are sizeof(Vector<char, 4096>) bytes of space on the stack into which it can construct the Vector<char, 4096> buffer object. It then ca...
2,912,404
2,912,453
How does py2exe actually -and simply explained- work? :)
I have a c++ app that calls another python one (bundled into an exe with py2exe) So I have 2 apps. So I was wondering: What if my c++ did what py2exe does? i.e. embed the python app in the c++ one. This way I won't depend on py2exe and its configurations nighmares (yes, it has some) Hence my questions: how does ...
http://www.py2exe.org/index.cgi/FAQ Basically, it packages up your python install and redistributes it. It still runs your Python as Python on a Python interpreter. The exe it creates just kicks everything off. The Python website has some methods on integrating with C++.
2,912,445
2,912,454
How to discard const in c++
This is what I'm trying to do and I can't: #include <string> using namespace std; class A { public: bool has() const { return get().length(); } string& get() { /* huge code here */ return s; } private: string s; }; The error I'm getting is: passing ‘const A’ as ‘this’ argument of ‘std::string& A::get()’ discards...
Add a second overload of get(): string const & get() const { return s; } That will be called on a const typed object of class A. In practice, I prefer adding only const-typed accessors, and then keeping modifications entirely internal to the class or even avoid them entirely. For example, that means having a method D...
2,912,481
2,912,536
How should I compile boost library in a small project?
I have a small project where I need just part of boost library, boost::regex in particular. This is what I've done so far: /include /boost /regex /math .. 189 dirs, files, etc. /lib /boost-regex c_regex_traits.cpp cpp_regex_traits.cpp .. ~20 .cpp files myprog.cpp In my Makefile I compile al...
Why not build regex library as a static lib and use it's features in your code by writing #include <boost/regex.hpp>? This shouldn't affect the final size of your application, because compiler will take only those functions that are actually used in your app. Also, precompiled boost libraries for different platforms ca...
2,912,520
2,912,614
Read file-contents into a string in C++
Possible Duplicate: What is the best way to slurp a file into a std::string in c++? In scripting languages like Perl, it is possible to read a file into a variable in one shot. open(FILEHANDLE,$file); $content=<FILEHANDLE>; What would be the most efficient way to do this in C++?
Like this: #include <fstream> #include <string> int main(int argc, char** argv) { std::ifstream ifs("myfile.txt"); std::string content( (std::istreambuf_iterator<char>(ifs) ), (std::istreambuf_iterator<char>() ) ); return 0; } The statement std::string content( (std::istreambuf_ite...
2,912,588
2,955,316
Generating XML Documents from XML Schemas in C++
Is there any easy way to create at least a template XML file using XML Schema? My main interest is bounded by C++, but discussions of other programming languages are also welcome.By the way I also use QT framework.
You may have to write this yourself. There is no one way of getting an XML file from a Schema. If you can make domain-specific assumptions (e.g. how to populate data items, which items to choose in case of a choice, how often to insert domain-specific elements) then you will get a better instance document. If you are w...
2,912,658
2,912,945
C++0x: memory ordering
The current C++0x draft states on section 29.3.9 and 29.3.10, pages 1111-1112 that in the following example: // Thread 1 r1 = y.load(memory_order_relaxed); x.store(1, memory_order_relaxed); // Thread 2 r2 = x.load(memory_order_relaxed); y.store(1, memory_order_relaxed); The outcome r1 = r2 = 1 is possible since the o...
If we take time (or, instruction sequences if you like) to flow downward, just like reading code, then my understanding is that An acquire fence allows other memory accesses to move downwards past the fence, but not upwards past the fence A release fence allows other memory accesses to move upwards past the fence, but...
2,912,683
2,912,783
SysRc enum values in c c++
i am working on a project where i am using SysRc values as return values from some function like SUCCESS and FAILURE ond sum enums . Now i want to know how to get them print?
Building on top of Neil's post: A switch statement is usually the way to go with enum values in C++. You could save some writing work by using #define-macros, but I personally avoid them. enum E { foo, bar }; const char * ToStr( E e ) { switch(e) { case foo: return "foo"; case bar: return "bar"; }; ...
2,912,759
2,914,299
How to design properly a hierarchy of classes using pointers in C++
I am trying to improve my knowledge on program architecture and recently arised a question to me which is related with this pointers issues I posted recently. The thing is that in a simple hierarchy in which you have Class A with a pointers to Class B and the last to Class C. Do not confuse the with the inheritage prop...
Instead of making class A aware of every class C, consider using the Composite Pattern: #include <boost/ptr_container/ptr_vector.hpp> #include <boost/foreach.hpp> #include <iostream> #include <stdexcept> //------------------------------------------------------------------------------ class Component { public: type...
2,912,767
2,912,905
Is it possible to cast object of class to void *?
I am trying to use qsort from STL to sort array of edge: struct edge { int w,v,weight; }; by weight. What I am trying is: int compare_e(const void *a, const void *b) { return ( *(edge *)a->weight - *(edge *)b->weight ); }; But I get: `const void*' is not a pointer-to-object type EDIT: Ok thx, now my cod...
struct less_by_weight { bool operator()(const edge& lhs, const edge& rhs) const { return lhs.weight < rhs.weight; } }; int main() { const std::size_t size = 100; edge *tab = new edge[size]; for(int i = 0; i < size; ++i) { tab[i].weight = rand() % size; std::cout << i << " ...
2,912,958
2,913,014
c++ inheritance not recognized
Is there some solution or I have to keep exactly class types? //header file Class Car { public: Car(); virtual ~Car(); }; class Bmw:Car { public: Bmw(); virtual ~Bmw(); }; void Start(Car& mycar) {}; //cpp file Car::Car(){} Car::~Car() {} Bmw::Bmw() :Car::Car(){} Bmw::~Bmw() {} int main() { ...
C++ defaults to private inheritance, so, you need to declare Bmw as: class Bmw:public Car Also, to be completely accurate, you should really have Start as a virtual method of Car and override it as needed in descendant classes. :)
2,912,979
2,913,239
Even lighter than SQLite
I've been looking for a C++ SQL library implementation that is simple to hook in like SQLite, but faster and smaller. My projects are in games development and there's definitely a cutoff point between needing to pass the ACID test and wanting some extreme performance. I'm willing to move away from SQL string style quer...
Are you sure that you have obtained the maximum speed available from SQLITE? Out of the box, SQLITE is extremely safe, but quite slow. If you know what you are doing, and are willing to risk db corruption on a disk crash, then there are several optimizations you can do that provide spectacular speed improvements. In ...
2,913,006
2,917,613
How can I keep an event from being delivered to the GUI until my code finished running?
I installed a global mouse hook function like this: mouseEventHook = ::SetWindowsHookEx( WH_MOUSE_LL, mouseEventHookFn, thisModule, 0 ); The hook function looks like this: RESULT CALLBACK mouseEventHookFn( int code, WPARAM wParam, LPARAM lParam ) { if ( code == HC_ACTION ) { PMSLLHOOKSTRUCT mi = (PMSLLHOOK...
assume it's not safe to call CallNextHookEx from outside a hook function, is this true? I believe this is true. Since there is a finite number of operations that you can receive through your low-level mouse hook, you could just put them onto a queue to be re-posted to the receiving window once your long-running opera...
2,913,206
2,913,269
A follow up on type coercion in C++, as it may be construed by type conversion
This is a follow up to my previous question. Consider that I write a function with the following prototype: int a_function(Foo val); Where foo is believed to be a type defined unsigned int. This is unfortunately not verifiable for lack of documentation. So, someone comes along and uses a_function, but calls it with a...
In case when Foo has a constructor for unsigned int implicit conversion will take place unless Foo is not declared explicit. The first case: class Foo { public: Foo(unsigned int) {} }; // ... a_function( 1 ); // OK Second case: class Foo { public: explicit Foo(unsigned int) {} }; // .. a_function( 1 ); // error Accor...
2,913,386
2,913,604
Quicksort / vector / partition issue
I have an issue with the following code : class quicksort { private: void _sort(double_it begin, double_it end) { if ( begin == end ) { return ; } double_it it = partition(begin, end, bind2nd(less<double>(), *begin)) ; iter_swap(begin, it-1); _sort(begin, it-1); _sort(it, end); } public: qui...
I see a couple of problems. I wouldn't include the pivot in your partitioning so I would use this line instead: double_it it = partition(begin + 1, end, bind2nd(less<double>(), *begin)) ; Also, I wouldn't continue to include the pivot in your future sorts so I would do _sort(begin, it - 2); instead, but you need to b...
2,913,562
2,913,826
How to get only first words from several C++ strings?
I have several C++ strings with some words. I need to get the first word from every string. Then I have to put all of them into a char array. How can I do it?
Here is one way of doing it... // SO2913562.cpp // #include <iostream> #include <sstream> using namespace std; void getHeadWords(const char *input[] , unsigned numStrings , char *outBuf , unsigned outBufSize) { string outStr = ""; for(unsigned i...
2,914,027
2,914,244
Multi-process builds in Visual Studio 2010: Worth it?
I've started testing our C++ software with VS2010 and the build times are really bad (30-45 minutes, about double the VS2005 times). I've been reading about the /MP switch for multi-process compilation. Unfortunately, it is incompatible with some features that we use quite a bit like #import, incremental compilation, a...
Definitely YES. I worked on a large application which took around 35 minutes to build when something was modified (In Visual Studio). We used IncrediBuild for that (to speed up the compilation process, from 35 minutes to 5 minutes) - to be truly distributed. In your case it is possible that /MP switch will make some di...
2,914,081
6,448,225
C++ member function template in derived class, how to call it from base class?
As my prveious question sounded confusing, I think it's best to clearly state what I want to achieve. I have (ignore the inheritance for now and focus on X): class Base {}; class X : public Base { private: double m_double; public: template<class A> friend void state( A& a, const X& x ) { data( a, ...
You could use the vistor pattern for this: class IVisitor { public: virtual void on_data( double, const char * )=0; virtual void on_data( std::string, const char * )=0; }; class Base { public: virtual void visit( IVisitor * v )=0; }; class X : public Base { private: double m_double; std::...
2,914,090
2,914,103
What's the benefit of declaring class functions separately from their actual functionality?
In C++, what's the benefit of having a class with functions... say class someClass{ public: void someFunc(int arg1); }; then having the function's actual functionality declared after int main int main() { return 0; } void someClass::someFunc(int arg1) { cout<<arg1; } Furthermore, what's the benefit of...
Dependency management. Users of the class only need to include the header file, so they don't depend on the implementation. Another use is breaking circular dependencies. Both issues may look like a waste of time with toy programs, but they start to grow into a really bad problem as the program grows.
2,914,150
2,914,294
Implement a multithreading environment
I want to implement a multithreading environment using Qt4. The idea is as follows in c++-alike pseudo-code: class Thread : public QThread { QList<SubThread*> threads_; public: void run() { foreach(SubThread* thread : threads) { thread.start(); } foreach(SubThread* thread :...
You probably want to use a condition variable instead of a mutex for this situation. A condition variable is a way for one thread to signal another. QT's implementation appears to be the QTWaitCondition: I might have the child thread's periodically check the state of the condition variable. This can be done with QTWait...
2,914,202
2,914,421
How to concatenate 2 LPOLESTR
i want to concatenate 2 strings in c++, i can't use char*. I tried the following but doesn't work: #define url L"http://domain.com" wstring s1 = url; wstring s2 = L"/page.html"; wstring s = s1 + s2; LPOLESTR o = OLESTR(s); I need a string with s1 and s2 concatenated. Any info or website that explain more about this ? ...
OLESTR("s") is the same as L"s" (and OLESTR(s) is Ls), which is obviously not what you want. Use this: #define url L"http://domain.com" wstring s1 = url; wstring s2 = L"/page.html"; wstring s = s1 + s2; LPCOLESTR o = s.c_str(); This gives you a LPCOLESTR (ie. a const LPOLESTR). If you really need it to be non-const, ...
2,914,209
2,914,255
What happens to class members when malloc is used instead of new?
I'm studying for a final exam and I stumbled upon a curious question that was part of the exam our teacher gave last year to some poor souls. The question goes something like this: Is the following program correct, or not? If it is, write down what the program outputs. If it's not, write down why. The program: #inclu...
Is this behavior (p2->x being 0 after malloc) the default? Should I have expected this? No, p2->x can be anything after the call to malloc. It just happens to be 0 in your test environment. What would your answer to my teacher's question be? (besides forgetting to #include for malloc :P) What everyone has told you...
2,914,356
2,914,719
Problem with boost::find_format_all, boost::regex_finder and custom regex formatter (bug boost 1.42)
I have a code that has been working for almost 4 years (since boost 1.33) and today I went from boost 1.36 to boost 1.42 and now I have a problem. I'm calling a custom formatter on a string to format parts of the string that match a REGEX. For instance, a string like: "abc;def:" will be changed to "abc\2Cdef\3B" if the...
The struct find_regexF seems to be the culprit. As you can see, it returns an empty result with a uninitialized match_results(). Looking through SO found me the following solution: struct custom_formatter() { template< typename T > std::string operator()( const T & s ) const { std::string matchStr; f...
2,914,597
2,914,618
Seeking References To MSVC 9.0's C++ Standards Compliance
I "know" (hopefully) that MSVC 9.0 Implements C++ 2003 (ISO/IEC 14882:2003). I am looking for a reference to this fact, and I am also looking for any research that has been done in to how compliant MSVC 9.0 is with that version of the Standard. I have searched for and not been able to find a specific reference from Mi...
Nonstandard Behavior . Short summary Compiler Limits 10.3 (Paragraph 5) Covariant Return Types 14 export Keyword on a Template 14.6.2 Dependent Names 15.4 Function Exception Specifiers 16.3.2 The # Operator 21.1.1 Character Traits Requirements Storage Location of Objects
2,914,631
2,914,788
How do I use foreach with QDomNodeList in Qt?
I'm new to Qt and I'm learning something new every day. Currently, I'm developing a small application for my Nokia N900 in my free time. Everything is fine, I am able to compile and run Maemo applications on the device. I've just learned about the foreach keyword in Qt. (I know it is not in C++, so I didn't think about...
foreach only supports the container classes, so you cannot use it with a QDomNodeList. I'm not sure of you actual goal, but I find the QXmlSimpleReader and QXmlStreamReader to be the easiest way to deal with XML. Edit to match question edit: What you are trying to do looks like a prime candidate for XPath or XQuery. T...
2,914,651
2,914,714
have you and how do you do C++ autotest?
As far as autotest is concerned, how do you do autotest for C++ programs? are there any autotest framework that can be utilized to do unit test and integration test?
You can use NUnit to achieve this, but there may be better ways. With NUnit you are writing test classes in managed C++/CLI which is calling your C++ code, which presumably runs as unmanaged. So for this option, some of your C++ code now runs as managed just for the sake of using NUnit. One may debate the "purity" o...
2,914,666
3,612,613
Boost.Thread throws bad_alloc exception in VS2010
Upon including <boost/thread.hpp> I get this exception: First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception: boost::exception_detail::clone_impl<boost::exception_detail::bad_alloc_> at memory location 0x0012fc3c.. First-chance exception at 0x7c812afb in CSF.exe: Microsoft C++ exception: [rethrow...
This was by design in boost 1.43 but has been since fixed. See this thread for the details.
2,914,856
2,914,898
Thread-local storage segfaults on NetBSD only?
Trying to run a C++ program, I get segmentation faults which appear to be specific to NetBSD. Bert Hubert wrote the simple test program (at the end of this message) and, indeed, it crashes only on NetBSD. % uname -a NetBSD golgoth 5.0.1 NetBSD 5.0.1 (GENERIC) #0: Thu Oct 1 15:46:16 CEST 2009 +stephane@golgoth:/usr/obj...
NetBSD does not support thread-local storage. Most of the other BSDs do however.
2,914,932
2,914,975
Boost test: catch user defined exceptions
If I have user defined exceptions in my code, I can't get Boost test to consider them as failures. For example, BOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(MyTest,1) BOOST_AUTO_TEST_CASE(MyTest) { // code which throws user defined exception, not derived from std::exception. } I get a generic message: Caught exception: ......
The EXPECTED_FAILURES are referring to failures against BOOST_REQUIRE or other assertions. The documentation clearly states: The feature is not intended to be used to check for expected functionality failures. To check that a particular input is causing an exception to be thrown use BOOST_CHECK_THROW family of testin...
2,914,971
2,932,390
Image/"most resembling pixel" search optimization?
The situation: Let's say I have an image A, say, 512x512 pixels, and image B, 5x5 or 7x7 pixels. Both images are 24bit rgb, and B have 1bit alpha mask (so each pixel is either completely transparent or completely solid). I need to find within image A a pixel which (with its' neighbors) most closely resembles image B, ...
Answering to my own question. Short answer: I was able to drop alpha channel, so I've decided to use image pyramids (see pyramid and gaussian pyramid on the net). It gave huge speed improvement. Long answer: My initial goal was texture synthesis. Alpha was used to generating pixels that weren't filled yet, and B repre...
2,914,986
2,919,948
Boost Mersenne Twister: how to seed with more than one value?
I'm using the boost mt19937 implementation for a simulation. The simulation needs to be reproducible, and that means storing and potentially reusing the RNG seeds later. I'm using the windows crypto api to generate the seed values because I need an external source for the seeds and not because of any particular guaran...
Your assumptions are mistaken. For a simulation, you don't need cryptographically strong seeds. In fact, using seeds 1,2,3,4, etcetera is often a better idea. The output values of the Mersenne Twister will be uncorrelated, yet nobody will question whether you cherry-picked your seeds to get desired simulation outputs. ...
2,915,049
2,915,096
better understanding of getline() and cin
Trying to get some basic understanding of console functionalities. I am having issues so consider the following... #include "stdafx.h" #include<iostream> #include<conio.h> using namespace std; /* This is a template Project */ void MultiplicationTable(int x); int main() { int value = 0; printf("Please ente...
The function getline() is declared in the string header. So, you have to add #include <string>. It is defined as istream& getline ( istream& is, string& str );, but you call it with an int instead of a string object. About your second question: When I execute this line of code the console window opens and immediately ...
2,915,071
2,915,210
Set clipping rectangle for OpenGL?
I'm making a drawing application with WINAPI and OpenGL. To make things more efficient I only redraw the region needed so I invalidateRect(hwnd,myRect,false). I know OpenGL does self clipping but I want to do that for my rect. I want it to clip itself for the region I invalidated to make things even more efficient. Tha...
If I understood correctly, what you want is the scissor test. Enable it with glEnable(GL_SCISSOR_TEST); and set the scissor rectangle with glScissor(x, y, width, height);
2,915,075
2,915,107
Derived template override return type of member function C++
I am writing matrix classes. Take a look at this definition: template <typename T, unsigned int dimension_x, unsigned int dimension_y> class generic_matrix { ... generic_matrix<T, dimension_x - 1, dimension_y - 1> minor(unsigned int x, unsigned int y) const { ... } ... } template <typename T, unsigned int ...
You could just implement the function in the derived class without making it virtual. This will "hide" the base class implementation and may be desirable for your use despite the general aversion to hiding member functions. A better method might be to just use a different name, although that may upset the "purity" of ...
2,915,332
2,951,546
Detect aborted connection during Boost.Asio request
Possible Duplicate: How to check if socket is closed in Boost.Asio? Is there an established way to determine whether the other end of a TCP connection is closed in the asio framework without sending any data? Using Boost.asio for a server process, if the client times out or otherwise disconnects before the server ha...
The key to this problem is to avoid doing request processing in the receive handler. Previously, I was doing something like this: async_receive(..., recv_handler) void recv_handler(error) { if (!error) { parse input process input async_send(response, ...) Instead, the appropriate pattern ...
2,915,363
2,915,401
How to build boost foreach cycle
I have some abstract class called IClass (has pure virtual function). There are some classes which inherit IClass: CFirst, CSecond. I want to add objects of classes which inherit into boost::ptr_vector: class IClass { virtual void someFunc() = 0; }; class CFirst : public IClass { }; class CSecond : public IClass { }; ...
Use a reference to IClass instead: foreach(IClass& tempObj, objectsList) { tempObj.someFunc(); }
2,915,483
2,915,523
Can I use a static var to "cache" the result? C++
I am using a function that returns a char*, and right now I am getting the compiler warning "returning address of local variable or temporary", so I guess I will have to use a static var for the return, my question is can I make something like if(var already set) return var else do function and return var? This is my f...
The reason you're getting a warning is because the memory allocated within your function for buf is going to be popped off the stack once the function exits. If you return a pointer to that memory address, you have a pointer to undefined memory. It may work, it may not - it's not safe regardless. Typically the pattern ...
2,915,546
2,918,987
Is learncpp.com good for beginners?
In my search for a good, freely available resource that will teach me C++ I stumbled on http://www.learncpp.com/. My question is for intermediate to experienced C++ programmers... Does this site seem to be a good resource for a beginner to learn C++ from? I've gone through the first few section of the site, and I feel ...
The site does not look too bad. However it really is a tutorial, in that it just explains the very basic concepts of C++. Notably, it completely misses an introduction to the STL and the proper use of it. You barely see std::cout and std::string. There's no mention of <algorithm> that I could see of and no mention of t...
2,915,614
2,916,272
Looking for a variety of Windows Form tutorials for visual studio.NET C++
Looking for a variety of Windows Form (winforms) tutorials for visual studio.NET C++ I found a few basic ones: How to: Create a Windows Forms Application Walkthrough: Retrieving Dialog Box Information Collectively Using Objects Any others? Thank You.
There are many excellent books available. Maybe you are looking for videos? Start at the bottom. You are not going to find anything at all that will be specific to C++/CLI, just about nobody uses that language to create WF projects.
2,915,791
2,915,802
Why is dereferencing a pointer called dereferencing?
Why is dereferencing called dereferencing? I'm just learning pointers properly, and I'd like to know why dereferencing is called that. It confused me as it sounds like you are removing a reference, rather than going via the pointer to the destination. Can anyone explain why it is called this? To me something like desti...
A pointer refers to an object. Ergo, we dereference the pointer (or, get the referent of the pointer) to get the object pointed-to. The de- prefix most likely comes from the Latin preposition meaning from; I suppose you could think of dereference as meaning "to obtain the referent (or object) from the reference."
2,915,825
2,925,828
how to excute a simple query use sqlapi++ with oracle
here is the code: cmd1.setCommandText("select * from lp.human_tb_meta_sex"); cmd1.Execute(); while (cmd1.FetchNext()) { SAString sas=cmd1.Field("id").asString(); cout<<"sas id:"< it gave me ORA-00932 error...I dont know why..?
Presumably "id" is the primary key. If it is defined as a NUMBER in the database, that could include fractions (eg 3.5). If you define it as NUMBER(10,0) then it will always be an integer. Since you are trying to pull it out as a String [.asString()] there could be a conversion issue.
2,915,972
2,916,361
Equvalent c++0x program withought using boost threads
I have the below simple program using boost threads, what would be the changes needed to do the same in c++0X #include<iostream> #include<boost/thread/thread.hpp> boost::mutex mutex; struct count { count(int i): id(i){} void operator()() { boost::mutex::scoped_lock lk(mutex); for(int i = ...
No changes to speak of... #include <iostream> #include <thread> std::mutex mutex; struct count { count(int i): id(i){} void operator()() { std::lock_guard<std::mutex> lk(mutex); // this seems rather silly... for(int i = 0 ; i < 10000 ; ++i) std::cout << "Thread " << id << "has ...
2,915,992
2,916,158
Qt Creator / QMake Linker Libraries
I'm using SFML, and I want to use Qt Creator in conjunction with it. When I'm compiling manually, I supply the following arguments to the linker -lsfmlsystem -lsfmlwindow. How do I do this if I'm using Qt Creator and (I think) QMake?
Just add LIBS += -L/path/to/sfml -lsfmlsystem -lsfmlwindow to the .pro file. You can open project files with QtCreator from the Projects view of the sidebar or searching for it via Ctrl-K. (BTW, the sidebar is not the list of icons down the left, it's the pane to the right of that which can be shown/hidden with Alt-0....
2,916,008
2,916,060
C++: Syntax for map where Data type is function?
In C#, what I want would look something like this: IDictionary<string, action()> dict = new Dictionary<string, action()>(); How do I do this in C++? This gives compiler errors: map<string, void()> exercises;
Use boost::function, a polymorphous wrapper for any object that can be called with your signature (including functions, function objects etc). map<string, function<void()>> ...; Note that the new C++ standard has already included function in <functional>. To explain the backgrounds: The only builtin mechanism of this...
2,916,061
2,916,541
Detecting regular expression in content during parse
I am writing a simple parser for C. I was just running it with some other language files (for fun - to see the extent of C-likeness and laziness - don't wanna really write separate parsers for each language if I can avoid it). However the parser seems to break down for JavaScript if the code being parsed contains reg...
It is impossible. Take this, for example: m =~ s/a/b/g; Could be both C or perl. One minute's thinking reveals, that the number of perl style regular expressions that are also sntyctically valid C expressions is infinite. Another example: m+foo *bar[index]+i The best you can get is some extreme vague guesswork. The d...
2,916,117
2,916,418
OpenGL Nothing will Display
Why can't I get anything to display with this code? #include <iostream> #include "GL/glfw.h" #ifndef MAIN #define MAIN #include "GL/gl.h" #include "GL/glu.h" #endif using namespace std; void display(); int main() { int running = GL_TRUE; glfwInit(); if( !glfwOpenWindow( 640,480, 0,0,0,0,0,0, GLFW_WINDOW...
I think the issue is that when you don't specify a coordinate system eg void glOrtho(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal); or void glFrustum(GLdouble left, GLdouble...
2,916,191
2,916,250
C/C++ - Convert 24-bit signed integer to float
I'm programming in C++. I need to convert a 24-bit signed integer (stored in a 3-byte array) to float (normalizing to [-1.0,1.0]). The platform is MSVC++ on x86 (which means the input is little-endian). I tried this: float convert(const unsigned char* src) { int i = src[2]; i = (i << 8) | src[1]; i = (i << ...
You are not sign extending the 24 bits into an integer; the upper bits will always be zero. This code will work no matter what your int size is: if (i & 0x800000) i |= ~0xffffff; Edit: Problem 2 is your scaling constant. In simple terms, you want to multiply by the new maximum and divide by the old maximum, assum...
2,916,201
2,916,225
Why function is weightless?
Why having function in my class doesn't change size of this class? This info must be stored somewhere, but where?
You can think of a member function as being just like any other function, except that it has an extra, hidden parameter that takes a pointer to the instance on which the member function was called. For example, this: class C { void f(int i) { } }; might be implemented (at least conceptually) as: void C_f(C* thi...
2,916,243
2,916,632
Detect When Network Cable Unplugged
Windows knows when you have removed the network cable from your NIC. Is there a programmatic way to determine this via API in C++? Note: I am not using .NET and this is for a closed LAN (not connected to Internet ever)
Raymond Chen blogged about something similar recently. Here is the relevant documentation. I think the MIB_IPADDR_DISCONNECTED flag is what you are looking for.
2,916,279
2,916,408
STLifying C++ classes
I'm trying to write a class which contains several std::vectors as data members, and provides a subset of vector's interface to access them: class Mesh { public: private: std::vector<Vector3> positions; std::vector<Vector3> normals; // Several other members along the same lines }; The main thing you can do with ...
these methods will have to be defined in the header file They have to be defined in a header file, so that if they're used then they're available in the translation unit where the template function is instantiated. If you're worried about too many templates in header files, slowing down compilation of translation units...
2,916,285
2,921,644
handling pointer to member functions within hierachy in C++
I'm trying to code the following situation: I have a base class providing a framework for handling events. I'm trying to use an array of pointer-to-member-functions for that. It goes as following: class EH { // EventHandler virtual void something(); // just to make sure we get RTTI public: typedef void (EH::*func_...
Instead of creating a wrapper for each handler in all derived classes (not even remotely a viable approach, of course), you can simply use static_cast to convert DEH::func_t to EH::func_t. Member pointers are contravariant: they convert naturally down the hierarchy and they can be manually converted up the hierarchy us...
2,916,358
2,916,394
immutable strings vs std::string
I've recent been reading about immutable strings Why can't strings be mutable in Java and .NET? and Why .NET String is immutable? as well some stuff about why D chose immutable strings. There seem to be many advantages. trivially thread safe more secure more memory efficient in most use cases. cheap substrings (token...
As an opinion: Yes, I'd quite like an immutable string library for C++. No, I would not like std::string to be immutable. Is it really worth doing (as a standard library feature)? I would say not. The use of const gives you locally immutable strings, and the basic nature of systems programming languages means that y...