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 |
|---|---|---|---|---|
778,085 | 778,124 | How to name a thread in Linux? | I have a multithreaded Linux application written in C/C++. I have chosen names for my threads. To aid debugging, I would like these names to be visible in GDB, "top", etc. Is this possible, and if so how?
(There are plenty of reasons to know the thread name. Right now I want to know which thread is taking up 50% CP... | Posix Threads?
This evidently won't compile, but it will give you an idea of where to go hunting. I'm not even sure its the right PR_ command, but i think it is. It's been a while...
#include <sys/prctl.h>
prctl(PR_SET_NAME,"<null> terminated string",0,0,0)
|
778,378 | 778,397 | How to write bitset data to a file? | I have a std::bitset that I'd like to write to a file, bit for bit, but of course fstream's write function doesn't support this. I can't think of another way besides converting each 8-bit group to a char using string and writing that...
Anyone know of a good way?
| Try:
#include <bitset>
#include <fstream>
int main() {
using namespace std;
const bitset<12> x(2730ul);
cout << "x = " << x << endl;
ofstream ofs("C:\\test.txt"); // write as txt
if (ofs) {
// easy way, use the stream insertion operator
ofs << x << endl;
// using fst... |
778,431 | 778,531 | How do I use C++ in flex and bison? | I have a project for school where we need to use flex and bison. I want to use C++ so that I have access to STL and my own classes that I wrote. We were provided with the following Makefile:
CC = gcc
CFLAGS = -g
OBJs = parse.tab.o symtab.o attr.o lex.yy.o
default: parser
parser: ${OBJs}
${CC} ${CFLAGS} ${OBJs... | You don't need to do anything with flex or bison to use C++, I have done it many times. You just have to make sure you use g++, not gcc.
Your problems are with the Makefile, not the code.
|
778,475 | 778,605 | PInvoke an Array of a Byte Arrays | I have the following C code:
const BYTE* Items[3];
Items[0] = item1;
Items[1] = item2;
Items[2] = item3;
int result = Generalize(3, Items);
with Generalize having a signature of
int __stdcall Generalize(INT count, const BYTE * const * items);
What is the best way to make that call with PInvoke?
| I can't guarantee this is the best way, but it's the first way I'd try.
[DllImport("<unknown>",
EntryPoint="Generalize",
CallingConvention=CallingConvention.StdCall)]
public static extern int Generalize(int count, IntPtr[] items);
public static void CallGeneralize()
{
v... |
778,802 | 778,870 | C++ Header file that declares a class and methods but not members? | Is it possible to make a C++ header file (.h) that declares a class, and its public methods, but does not define the private members in that class? I found a few pages that say you should declare the class and all its members in the header file, then define the methods separately in you cpp file. I ask because I want... | I think what you are looking for is something called the "pimpl idiom". To understand how this works, you need to understand that in C++ you can forward declare something like so.
class CWidget; // Widget will exist sometime in the future
CWidget* aWidget; // An address (integer) to something that
... |
779,185 | 779,299 | Conflict with DrawText function | I am developing a multi-platform application and in one component I have a class method called DrawText. Unfortunately, I get a linker error (on windows only) saying that there is an unresolved external symbol for a DrawTextW method of this class.
I've seen this before with other methods ending in "Text" where it is lo... | Yes, this is a real problem with using Windows, and there's no way to turn it off since the headers all look like this:
#ifdef UNICODE
#define GetDlgItemText GetDlgItemTextW
#else
#define GetDlgItemText GetDlgItemTextA
#endif
So you're going to get the symbol defined either way. It would be very nice if you could #de... |
779,282 | 779,297 | How far does recursion execute into your function in C++? | I've written recursive functions with the guidance of a friend who is teaching me C++ (as a first language). However, I don't really understand what is going on. He helped me (and the SO community, as well) write a merge sort function.
std::vector<int> mergeSort(std::vector<int> original)
//code here to create two vec... | Each time you call a function recursively, it effectively makes a new copy of the information it needs, and goes on.
You could have a program that recurs "infinitely", ie, until it runs out of resources, usually stack space — the space in which those copies are going. That would look like
void recur(){
recur();
}
... |
779,338 | 779,353 | Suggestions of excellent examples of real C/C++ code | I'd like to study some good C/C++ code. The code should:
be good in style and structure, presenting best practices
be a real life program (not an example or toy)
not too big so it doesn't takes ages to analyse it
Windows and/or Unix
I know there are 1000s of open source projects out there. But I'd like to hear y... | I would specifically mention memcached. It's a great example of fairly short, readable code with a clear purpose.
Second, I would recommend the Apache web server. It's a fantastically well-run open source project that you'll learn a lot from, both about the language, as well as general design practices and networking/... |
779,448 | 779,475 | C or C++ compiler for the Tandy 1000 PC SX? | I have my dad's old PC from the 1980's. It's a Tandy 1000 PC SX:
This computer doesn't have a modem, but I have another PC that has Windows XP on it and it also has a 5 3/4 inch floppy drive. So where can I find a C/C++ compiler for this old PC?
| Oh my God, I haven't seen one of those in forever. Okay, that's running a version of MS/DOS, no later than about MS/DOS 3 as I recall.
First thing is to make sure you can read and write a floppy on the XP computer that the Tandy will read.
You'll need to look for a fairly old version of Turbo C, even, I'd guess. You ... |
779,580 | 779,611 | Equivalent of CppUnit protectors for boost::test? | I've used both CppUnit and boost::test for C++ unittesting. Generally I prefer boost::test, mainly because the auto-test macros minimise the effort to setup tests. But there's one thing I really miss from CppUnit: the ability to register your own "protectors", instances of which automatically wrap all the run tests. ... | I've never used CppUnit, so not sure how protectors work. Are you looking for something that wraps individual tests, or the entire test suite?
For the former, you could use fixtures as you mention, but as I understand it, fixtures should be considered "outside" the test. They set up whatever the test needs, and cleans ... |
779,791 | 779,882 | Performance: vector of classes or a class containing vectors | I have a class containing a number of double values. This is stored in a vector where the indices for the classes are important (they are referenced from elsewhere). The class looks something like this:
Vector of classes
class A
{
double count;
double val;
double sumA;
double sumB;
vector<double> sumVectorC;... | As lothar says, you really should test it out. But to answer your last question, yes, cache misses will be a major concern here.
Also, it seems that your first implementation would run into load-hit-store stalls as coded, but I'm not sure how much of a problem that is on x86 (it's a big problem on XBox 360 and PS3).
|
780,027 | 780,097 | Why are many VMs written in C when they look like they have C++ features? | I noticed some not so old VM languages like Lua, NekoVM, and Potion written in C.
It looked like they were reimplementing many C++ features.
Is there a benefit to writing them in C rather than C++?
| I know something about Lua.
Lua is written in pure ANSI Standard C and compiles on any ANSI platform with no errors and no warnings. Thus Lua runs on almost any platform in the world, including things like Canon PowerShot cameras. It's a lot harder to get C++ to run on weird little embedded platforms.
Lua is a high-... |
780,041 | 780,044 | Confusion about UDP/IP and sendto/recvfrom return values | I'm working with UDP sockets in C++ for the first time, and I'm not sure I understand how they work. I know that sendto/recvfrom and send/recv normally return the number of bytes actually sent or received. I've heard this value can be arbitrarily small (but at least 1), and depends on how much data is in the socket's b... | It's a little stronger than that. UDP does deliver a full package; the buffer size can be arbitrarily small, but it has to include all the data sent in the packet. But there's also a size limit: if you want to send a lot of data, you have to break it into packets and be able to reassemble them yourself. It's also no... |
780,156 | 780,230 | Cross-platform memory allocator sbrk/virtualalloc | I am wondering if there is a cross-platform allocator that is one step lower than malloc/free.
For example, I want something that would simply call sbrk in Linux and VirtualAlloc in Windows (There might be two more similar syscalls, but its just an example).
| I'm not familiar with the functions in question but:
#if defined (__WIN32__)
#define F(X) VirtualAlloc(X)
#elif defined (__LINUX__) /* or whatever linux's define is */
#define F(X) sbrk(X)
#endif
Not sure if the syntax is 100% (I'm new to macros & c), but the general idea should work.
|
780,283 | 780,293 | Is Int32^ i = gcnew Int32() allocated on managed heap? | Basically I would like to know the difference between
Int32^ i = gcnew Int32();
and
Int32* i2 = new Int32();
I have written the following code:
#include <stdio.h>
#using <mscorlib.dll>
using namespace System;
int main(void) {
Int32^ i = gcnew Int32();
Int32* i2 = new Int32();
printf("%p %d\n", i2, *i... | In managed C++ new allocates on unmanaged heap, gcnew - on managed heap. Objects in the managed heap are eligible for garbage collection, while objects in the unmanaged heap are not. Pointers with ^ work like C# references - the runtime tracks them and uses for garbage collection, pointers with * work like normal C++ p... |
780,349 | 780,383 | Runtime optimization of static languages: JIT for C++? | Is anyone using JIT tricks to improve the runtime performance of statically compiled languages such as C++? It seems like hotspot analysis and branch prediction based on observations made during runtime could improve the performance of any code, but maybe there's some fundamental strategic reason why making such obser... | Profile guided optimization is different than runtime optimization. The optimization is still done offline, based on profiling information, but once the binary is shipped there is no ongoing optimization, so if the usage patterns of the profile-guided optimization phase don't accurately reflect real-world usage then th... |
780,448 | 784,814 | Debugging embedded Lua | How do you debug lua code embedded in a c++ application?
From what I gather, either I need to buy a special IDE and link in their special lua runtime (ugh). Or I need to build a debug console in to the game engine, using the lua debug API calls.
I am leaning toward writing my own debug console, but it seems like a lot ... | There are several tools floating around that can do at least parts of what you want. I have seen references to a VS plugin, there is a SciTE debugger extension in Lua for Windows, and there is the Kepler project's RemDebug, as well as their LuaEclipse.
RemDebug may be on the track of what you need, as it was built to ... |
780,580 | 780,608 | Why this sample works? | typedef pair<double, double> dd;
const double epsilon = 1e-6;
struct sort_by_polar_angle {
dd center;
// Constuctor of any type
// Just find and store the center
template<typename T> sort_by_polar_angle(T b, T e) {
int count = 0;
center = dd(0,0);
while(b != e) {
... | When you call sort_by_polar_angle() in the sort() function, you are creating a temporary object of type sort_by_polar_angle (i.e. its constructor is called). Inside the sort algorithm, the functor object you passed is used something like functor() which will be translated into functor.operator().
|
780,730 | 780,733 | C/C++: Static function in header file, what does it mean? | I know what it means when static function is declared in source file. I am reading some code, found that static function in header files could be invoke in other files.
| Is the function defined in the header file? So that the actual code is given directly in the function, like this:
static int addTwo(int x)
{
return x + 2;
}
Then that's just a way of providing a useful function to many different C files. Each C file that includes the header will get its own definition that it can ca... |
780,805 | 780,818 | Populate a static member container in c++ | I've got a static class member which is some container, like
(Foo.h)
class Foo
{
...
private:
static list<string> s_List;
}
I need to populate the list with a number of specific values. Actually it should be also const, but that might overcomplicate the problem further.
All the class member functions are static,... | a common solution is to do something like this:
// header
class Foo
{
...
private:
static list<string> s_List;
}
// cpp
list<string> init()
{
list<string> tmp;
... fill tmp with strings
return tmp;
}
list<string> Foo::s_List(init());
the other method is like Neil Butterworth suggested.
|
781,001 | 781,383 | What is the typical usage of boost any library? | What are the advantages of using boost.any library ? Could you please give me some real life examples ? Why the same functionality couldn't be achieved by having some generic type in the root of object's hierarchy and creating containers with that base type ?
| I consider that Boost.Variant should always be preferred as it's non-intrusive and still calls for very structured programming.
But i guess the main idea behind boost.any is to provide the equivalent of java and c# object types. It's a way of saying "yes we can" ! :-)
|
781,246 | 781,615 | Wrapping a 3rd party DLL | I have a 3rd party DLL that needs to be loaded dynamically using LoadLibrary() and which uses the __cdecl calling convention. I need to be able to use the dll from VB6 so I've created a wrapper DLL of my own that uses the __stdcall calling convention and exports the functions that are needed.
An additional requirement... | I suggest that you dump the COM server idea and go with copies of the original DLL. I have used this approach myself to get multiple instances of libraries that aren't threadsafe and don't support multiple instances.
Since the files are different, Windows will load them all into separate address spaces and thus keep t... |
781,256 | 781,375 | Implementing zoom controls in MFC | I am working on a 'print preview' facility to show an overview of a slide with rectangular arrays of sample spots on it.
The slides typically measure 25 x 75 mm and the spot samples are typically 0.1 mm in diameter. There is usually a 2mm gap around the perimeter of the slide where no spots are printed.
The distance b... | Let's start from the beginning:
why aren't you using ::AFXPrintPreview() and the rest of the print preview facilities of MFC?
'slides' and 'spots' are specific to your industry I think - are they relevant to the question or is it just for illustration?
StretchBlt() isn't going to do you much good because it will only ... |
781,494 | 783,729 | How do a specify a library file dependency for qmake in Qt? | Have a SomeLib.pro file that contains:
CONFIG += debug
TEMPLATE = lib
TARGET = SomeLib
..
Then in a dependent SomeApp.pro:
..
debug:LIBS += -lSomeLib_debug
..
How can I force SomeApp to build if I touched SomeLib in qmake?
| It's ugly because you need to give the exact library file name, but this should work:
TARGETDEPS += libfoo.a
|
781,533 | 781,649 | Weird linker error on Borland C++ Builder 6 | I've been trying to compile a Borland C++ Builder 6 project, but linker dies with exact following error:
[Linker Fatal Error] Fatal: Unable to open file '.OBJ'
Strange thing about it is that it doesn't give any file name except the extension. It looks like an internal bug, though googling for it didn't give any result... | Check for illegal whitespace characters in your Linker command line.
If you don't find any, post your linker command line here (Off the top of my head found in Project -> Options -> Linker -> Command Line).
|
781,760 | 781,785 | Copy constructor with pointers | I have recently discovered that when I have pointers within a class, I need to specify a Copy constructor.
To learn that, I have made the following simple code. It compiles, but gives me runtime error when performing the copy constructor.
I am trying to copy just the value from the pointer of the copied object, but avo... | With the statement int* pointer you have just defined a pointer but has not allocated any memory. First you should make it point to a proper memory location by allocating some memory like this: int* pointer = new int. Then in the copy constructor again you have to allocate the memory for the copied object. Also, don't... |
781,792 | 781,851 | How do I debug a single .cpp file in Visual Studio? | Is there any way to debug a single file in Visual Studio.NET?
I'm still a noob with C++, but I want to start learning how to get comfortable with the debugger, and as of right now I am writing really small files.
It seems if there is only one source file, it won't let me debug, but the moment I add another one, I can.... | It doesn't want another source file, it wants a project file.
Visual Studio needs a bunch of information to know how to compile and debug your source code. Things like which optimization settings to use, where to look for the boost headers, that sort of thing.
Try this: go to File->New->Project... and pick a win32 cons... |
781,907 | 781,924 | Generating object file to separate directory using g++ compiler - C++ | I use the following code to compile a cpp file to object file.
g++ -c main.cpp
Above code generates the .o fles in same directory where main.cpp resides.
Suppose I have a folder named obj and need to generate the object files there, how could I write it?
How can I see the compiler switches supported by g++ and it's ... |
Suppose I have a folder named obj and need to generate the object files there, how do I write?
Use:
g++ -c main.cpp -o obj/main.o
How can I see the compiler switches supported by g++ and it's usages?
If you are on a *nix system use:
man g++
or use info g++
|
782,316 | 782,369 | C++ HTML generation classes | A question prompted by jbar's question.
In scripting languages like Python, Ruby, and Perl, there are libraries that simplify generating dynamic HTML. (For example, the cgi module in Ruby.)
Are there any similar packages for C++? I don't know of one, and at least some desultory googling didn't reveal one.
| http://www.webtoolkit.eu/wt#/
I don't know anything about it, but their web-page is clean and the introduction sounds like exactly what you're looking for...
Wt (pronounced 'witty') is a C++ library and application server for developing and deploying web applications. It is not a 'framework', which enforces a way of p... |
782,955 | 782,983 | getting XML data from Xerces (c++) | I am a latecomer to XML - have to parse an XML file. Our company is using xerces already so I managed to cobble together a sample app (SAX) that displays all the data in a file. However, after parsing is complete I was expecting to be able to call the parser or some other entity that had an internal representation of... | Xerces provides both SAX and DOM processing. SAX parsing doesn't construct a model, so once parsing is finished there is nothing to examine or iterate through. DOM processing produces a tree-structured model which gives you what you want.
|
783,018 | 783,953 | Howto elegantly extract a 2D rectangular region from a C++ vector | The problem is pretty basic.
(I am puzzled why the search didn't find anything)
I have a rectangular "picture" that stores it's pixel color line
after line in a std::vector
I want to copy a rectangular region out of that picture.
How would I elegantly code this in c++?
My first try:
template <class T> std::vector... | Your question asks for a C++ way of copying a rectangular field of elements in some container. You have a fairly close example of doing so and will get more in the answers. Let's generalize, though:
You want an iterator that travels a rectangular range of elements over some range of elements. So, how about write a sort... |
783,073 | 783,095 | Processing messages is too slow, resulting in a jerky, unresponsive UI - how can I use multiple threads to alleviate this? | I'm having trouble keeping my app responsive to user actions. Therefore, I'd like to split message processing between multiple threads.
Can I simply create several threads, reading from the same message queue in all of them, and letting which ever one is able process each message?
If so, how can this be accomplished?... | You cannot have more than one thread which interacts with the message pump or any UI elements. That way lies madness.
If there are long processing tasks which can be farmed out to worker threads, you can do it that way, but you'll have to use another thread-safe queue to manage them.
|
783,212 | 783,242 | Find QWidget of single instance Qt application | I'm trying to create a single instance Qt application and I'm at the point this works, but now I want to focus the already started instance when a second is started.
QWidget::find(g_hWnd) should return the widget but it fails and crashes on w->show();
Any thoughts?
#pragma data_seg("Shared")
HWND g_hWnd = NULL;
#pragma... | You should use the qtsingleapplication API
edit- It's a separate download see here for both LGPL and Commercial editions
|
783,260 | 787,833 | How can I use a User Defined Type (UDT) in a COM server? | I have a COM server with a method currently returning an integer:
[
object,
uuid("..."),
dual,
helpstring("IMyCOMServer Interface"),
pointer_default(unique)
]
__interface IMyCOMServer : IDispatch
{
[id(1), helpstring("method MyQuery")]
HRESULT MyQuery([in] BSTR instr, [out,retval] int* outin... | (This is adapted from an actual IDL, so I know it works)
[uuid(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX), v1_enum, helpstring("Enum")]
enum MyEnum {
value_a,
value_b,
value_c
} ;
Plus, in your Library section you must include the enum as well, or the enum won't be exported to the type library:
library MyLib
{
... |
783,310 | 783,314 | Are there any tools to detect buffer overflow on Visual C++ 6.0? | I've been having crash problems due to heap problems, so I guess a buffer overflow is happening somewhere. How do I detect it?
| I use Compuware BoundsChecker as a tool for error detection in VC6. It can pick up buffer overruns.
You can also try PageHeap, a tool for windows.
|
783,354 | 783,664 | Windows forms control library; Managed and Unamanaged | The windows forms control library project (C++) I writes uses an unmanaged dll. The unmanaged dll has a header file (a Cheshire cat). And I just include it in the control library project. And calls functions in the unmanaged dll (of course with proper marshaling). This compiles and builds. The problem is when I go ahea... | Maybe it's because VS2005 does not find your native .DLL. This .DLL is searched in the "normal" manner for native .DLLs:
Current directory (I think it is mostly the start-up dir of VS)
App direcotry (somewhere in %ProgramFiles%\Microsoft Visual Studio...)
%PATH% dirs.
You could try to put your native DLL somewhere in... |
783,592 | 783,616 | SQLite3 object not understood? | Now I'm geting an error:
1>c:\development\document_manager\document_manager\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3'
with
#pragma once
#include "sqlite3.h"
class storage_manager
{
sqlite3 db;
sqlite3** db_pp;
public:
void open()
{
sqlite3_open("... | It looks like you might be trying to compile a C program using a C++ compiler. While there is a lot of C code which is also valid C++, they are different languages.
Your compiler may have some switch or setting to compile C code. Check your compiler documentation.
|
783,623 | 1,121,397 | Boost, Shared Memory and Vectors | I need to share a stack of strings between processes (possibly more complex objects in the future). I've decided to use boost::interprocess but I can't get it to work. I'm sure it's because I'm not understanding something. I followed their example, but I would really appreciate it if someone with experience with usi... | There are several things that leaped out at me about your implementation. One was the use of a pointer to the named mutex object, whereas the documentation of most boost libraries tends to bend over backwards to not use a pointer. This leads me to ask for a reference to the program snippet you worked from in building y... |
783,864 | 783,889 | std::map<tstring<std::map<tstring, unsigned int>> assignment fail | basically i have (state, state code) pairs, that are subsets of country
[USA] -> [VT] -> 32
so i'm using std::map<tstring<std::map<tstring, unsigned int>> but i'm having trouble with assignment of the state code
for(std::map<tstring, std::map<tstring, unsigned int>>::const_iterator it = countrylist.begin(); it != count... | operator[] on std::map is non-const, because it creates the entry if it doesn't already exist. So you can't use a const_iterator in this way. You can use find() on const maps, but that still won't let you modify their values.
And Smashery is right, you're doing the first lookup in a strange way considering that you hav... |
783,944 | 784,328 | How do I allocate a std::string on the stack using glibc's string implementation? | int main(void)
{
std::string foo("foo");
}
My understanding is that the above code uses the default allocator to call new. So even though the std::string foo is allocated on the stack the internal buffer inside of foo is allocated on the heap.
How can I create a string that is allocated entirely on the stack?
| I wanted to do just this myself recently and found the following code illuminating:
Chronium's stack_container.h
It defines a new std::allocator which can provide stack-based allocation for the initial allocation of storage for STL containers. I wound up finding a different way to solve my particular problem, so I did... |
784,247 | 784,278 | How can I make my mouse control the camera like a FPS using OpenGL/SDL? | I've created this basic 3D Demo using OpenGL/SDL. I handled the keyboard callback so I can "strafe" left and right using 'a' and 's' and move forward and backward using 's' and 'w'.
However, I would like to now make it so I can control the direction my camera is "looking" based off my mouse movements. Just like in a ... | Mouse moving up/down -> pitch, Mouse moving right/left -> yaw.
I do not believe having your 'a' and 'd' keys be yaw is accurate.
Actually, your whole setup is a bit odd to me, since from a geometric standpoint, I view the coordinate as (x, y, z). You set s and w to go "up" and "down" (z), instead of "forward" and "back... |
784,330 | 784,342 | RAII and uninitalized values | Just a simple question:
if I had a simple vector class:
class Vector
{
public:
float x;
float y;
float z;
};
Doesnt the RAII concept apply here as well? i.e. to provide a constructor to initialize all values to some values (to prevent uninitialized value being used).
EDIT or to provide a constructor that explic... | The "R" in RAII stands for Resource. Not everything is a resource.
Many classes, such as std::vector, are self-initializing. You don't need to worry about those.
POD types are not self initializing, so it makes sense to initialize them to some useful value.
|
784,379 | 789,805 | Why does gcov report 0% coverage on a header file for a well used class? | I'm attempting to measure test coverage for the first time using gcov. Now that I'm past the initial learning curve, things seem to be going well, except for one little snag. I expect that it boils down to a lack of understanding on my part, so I'm hoping someone familiar with gcov can explain what's going on.
The i... | It looks like I've sorted out the problem. As I expected, it's more of a lack-of-experience issue, than anything.
As it turns out, gcov was only finding a subset of the available tracefiles, and was therefore reporting only part of the total results. Finding and adding the rest of the tracefiles resolved the issue.
F... |
784,445 | 784,477 | How could simply calling Pitch() and Yaw() cause the camera to eventually Roll()? | I'm coding a basic OpenGL game and I've got some code that handles the mouse in terms of moving the camera.
I'm using the following method:
int windowWidth = 640;
int windowHeight = 480;
int oldMouseX = -1;
int oldMouseY = -1;
void mousePassiveHandler(int x, int y)
{
int snapThreshold = 50;
if (oldMouseX != ... | Congratulations -- you have discovered Lie group theory!
Yes, it's possible. The outcome of a series of transformations
depends on the order in which they're executed. Doing a pitch
followed by a yaw is not the same as a doing a yaw, followed
by a pitch. In fact, in the limit of infinitesimally small yaws
and pitches,... |
784,469 | 784,489 | makefile not building updated part of the program - C++ | I am new to makefiles and facing some issue with it. I have created the following makefile. It works correctly. But when I modify the main.cpp and run make, it says "everything is up to date". I need to do a make clean and run make again, everything will work.
Looks like there is some issue with this makefile and I ca... | Normally the .o file needs to have a dependency on the corresponding .cpp file. I think this is the syntax, but not 100% sure:
%.o : %.cpp
$(CC) ...
main.o : main.cpp
$(CC) ...
|
784,533 | 784,540 | Reverse that Math function | I need to reverse a function with hard Math operations, I'm asking here to check if it's even possible, eventually for help.
public static UInt32 Func_4(UInt32 P, UInt32 X, UInt32 G)
{
UInt64 result = 1;
UInt64 mult = G;
if (X == 0)
return 1;
while (X != 0)
{
... | It looks like your Func_4() function calculates GX mod P. What you're asking for is a solution to the discrete logarithm problem, but no efficient algorithm is known.
|
784,781 | 784,789 | Static libraries, dynamic libraries, DLLs, entry points, headers ... how to get out of this alive? | I recently had to program C++ under Windows for an University project, and I'm pretty confused about static and dynamic libraries system, what the compiler needs, what the linker needs, how to build a library ... is there any good document about this out there? I'm pretty confused about the *nix library system as well ... | Start with Wikipedia - plenty of information there, and lots of links to other useful resources.
P.S. But perhaps it would be better to just ask a specific question about the problem you're currently having. Learning how to solve it may go a long way to teaching you the general concepts.
|
784,997 | 892,607 | Launching email application (MAPI) from C# (with attachment) | In the past I have used MAPISendMail to launch Outlook (or whatever the desired MAPI email application was) from a C++ application with a file attachment. (Similar to say Microsoft Word's Send Email functionality).
I need to do the equivalent from a C# application and to have it work when running on XP, Vista, Server 2... | At work we have successfully done this using VSTO.
Here is a snippet of some lines we have running on VISTA with Outlook 2007: (the code is in VB.net).
Note that the usage is security locked when doing certain things to the outlook object. (to address, body and other properties marked as security risks). We use a 3rd ... |
785,097 | 785,129 | How do I implement a Bézier curve in C++? | I'd like to implement a Bézier curve. I've done this in C# before, but I'm totally unfamiliar with the C++ libraries. How should I go about creating a quadratic curve?
void printQuadCurve(float delta, Vector2f p0, Vector2f p1, Vector2f p2);
Clearly we'd need to use linear interpolation, but does this exist in the stan... | Did you use a C# library earlier?
In C++, no standard library function for Bezier curves is available (yet). You can of course roll your own (CodeProject sample) or look for a math library.
This blogpost explains the idea nicely but in Actionscript. Translation should not be much of a problem.
|
785,480 | 785,514 | Good patterns for a C/C++ plugin-based system? | When developing a C/C++ (=2?) plugin based framework with shared objects/dynamic libraries that need to support live swapping what examples would be helpful to look at for implementation details?
Thanks.
Note: live swapping is the key point here, no need to restart the system is a requirement
| If you are on POSIX, dlopen(), dlsym() and dlclose() are all you need.
See man dlsym for details and examples.
There is a good article about loading dynamic libraries, and plugin infrastructure is an example.
EDIT OP added Windows as requirement so this approach won't help since Windows isn't POSIX-compliant. However t... |
785,503 | 799,517 | COM MFC application don't show window | I have a MFC application with ATL support, the idea is when someone creates an instance of my interface declared in the mfc application, this instantiation creates and displays a window.
This all works fine if the com client is the cmd.exe, i made a quick com client that instance the interface and when this instances ... | In general a service cannot create windows. Pre-Vista you can enable a service to interact with the desktop (for example, open a window) via the "Allow service to interact with desktop" check-box on the "Log On" tag of the given services properties. If you're targetting Vista, this isn't an option.
However, given thi... |
785,581 | 785,610 | How to ensure that a program is running and restart it if needed? | I developed a software (in C++) which needs to be continuously running. That basically means that it has to be restarted each time it stops.
I was thinking about using cron jobs to check every minutes if it is still alive, but there might be a cleaner way or standard way of doing this.
Thanks in advance
| Fedora and Ubuntu use upstart, which has a the ability to automatically restart your deamon if it exits.
|
785,598 | 785,635 | How to send a link to an application, like Spotify does | When we save a level in our editor, we create a log file of any errors it contains. These consist basically of an error message and a path that allows the user to find the erronous item in a tree view.
What I want is to make that path a link, something like
< a href="editor://path/to/gameobject" > Click to see object i... | If you need the link to work in any viewer, yes, registering a protocol handler is the best way.
As for launching the editor, you could implement it as an out-of-process COM server, but if you've already got command line parsing sorted, you might as well use a window message or named pipe to pass that to the editor. I... |
785,686 | 785,695 | Semicolon after class declaration braces | In C++ classes, why the semi-colon after the closing brace? I regularly forget it and get compiler errors, and hence lost time. Seems somewhat superfluous to me, which is unlikely to be the case. Do people really do things like:
class MyClass
{
.
.
.
} MyInstance;
I get it from a C compatibility point of view for stru... | The semi-colon after the closing brace in a type declaration is required by the language. It's been that way since the earliest versions of C.
And yes, people do indeed do the declaration you just put up there. It's useful for creating scoped types inside of methods.
void Example() {
struct { int x; } s1;
s1.... |
785,814 | 786,485 | Boost serialization in Qt: is it a proper way? | I'm thinking about serializing data in an application which is Qt-based.
Essentially what I'm going to serialize is my hierarchical model, which is composed of different classes that derive from, say, TreeModelItem:
class TreeModelItem
{
protected:
QList<TreeModelItem *> m_children;
//...
};
Should I study boost::... | QDataStream supports (de)serialization of some popular Qt objects. You can check which ones here.
The "Qt" way would be to use that.
However, there's nothing preventing you from using boost, but you will have to implement the serialization for basic objects such as QList all over again, which can be tiresome.
Note that... |
786,093 | 786,114 | Does using SecureZeroMemory() really help to make the application more secure? | There's a SecureZeroMemory() function in WinAPI that is designed for erasing the memory used for storing passwords/encryption keys/similar stuff when the buffer is no longer needed. It differs from ZeroMemory() in that its call will not be optimized out by the compiler.
Is it really so necessary to erase the memory use... | It does. Hibernation file is not encrypted, for example. And if you don't securely clear the memory, you might end up with trouble. It's just a single example, though. You should always hold secret stuff in memory only as long as needed.
|
786,131 | 786,162 | How to maintain a list of functions in C++/STL? | Before asking you my question directly, I'm going to describe the nature of my prolem.
I'm coding a 2D simulation using C++/OpenGL with the GLFW library. And I need to manage a lot of threads properly. In GLFW we have to call the function:
thread = glfwCreateThread(ThreadFunc, NULL); (the first parameter is the functio... | You need to create threads in each simulation cycle? That sounds suspicious. Create your threads once, and reuse them.
Thread creation isn't a cheap operation. You definitely don't want to do that in every iteration step.
If possible, I'd recommend you use Boost.Thread for threads instead, to give you type safety and o... |
786,182 | 786,760 | How should I link a data Class to my GUI code (to display attributes of object, in C++)? | I have a class (in C++), call it Data, that has thousands of instances (objects) when the code is run. I have a widget (in Qt), call it DataWidget that displays attributes of the objects. To rapidly build the widget I simply wrote the object attributes to a file and had the widget parse the file for the attributes - th... | I see you're using Qt. This is good because Qt 4.0 and later includes a powerful model/view framework. And I think this is what you want.
Model/View
Basically, have your Data class inherit and implement QAbstractItemModel, or a different Qt Model class, depending on the kind of model you want. Then set your view ... |
786,417 | 786,553 | Is there an ORM (Object Relational Mapper) framework that supports C++ and C# | I'm looking for an ORM that will allow me to write a C# user interface and a C++ service. Both need to access data from the same database. Ideally I want C# and C++ classes to be generated from the database schema that I can then program against.
The database will probably be SQLServer, but that hasn't been decided yet... | Unfortunately this may not be of any help to you, but if you give up on trying to find a pre-build solution, it's not that terribly difficult to develop an in-house version that only supports what you need.
We have an in-house data definition language that we use to generate the SQL schema for our data, and ORM classes... |
786,547 | 786,586 | What is a good way to recover from a fread() failure? | If a call to fread() returns 0 and ferror() indicates an error (vs. EOF), is it OK to retry the read or is it better to close and reopen the file?
I can't start over entirely -- the input file has been partially processed in a way that can't be undone (say I'm writing out a chunk at a time to a socket and, due to exist... | There's no "one size fits all" solution, since different errors can require different handling. Errors from fread() are unusual; if you're calling it correctly, an error may indicate a situation that has left the FILE* in a weird error state. In that case you're best off calling fclose(), fopen(), fseek() to get things... |
786,555 | 786,567 | C++ stream to memory | how can I create std::ostream and std::istream objects to point to a piece of memory I allocated and manage (I don't want the stream to free my memory).
I was looking at using rdbuf()->pubsetbuf() to modify one of the other streams - say sstringstream. However I think streambuf used by stringstream will free the buffe... | Take a look at the bufferstream class in the Boost.Interprocess library:
The bufferstream classes offer
iostream interface with direct
formatting in a fixed size memory
buffer with protection against buffer
overflows.
|
786,558 | 786,572 | How to get round VC++ Runtime requirement in a dll? | I wrote a dll in VS2008 that I use in my C# application,but my users don't like the fact they need both .NET framework and VC++ Runtime.
Is there a way I could avoid the 'must-have' VC++ Runtime in my C++ dll?
| You can build your dll with the runtime linked statically (/MT instead of /MD - Under properties->Configuration Properties->C/C++->Code Generation->Runtime Library).
|
786,566 | 787,115 | Adding an item to Internet Explorer's right-click context menu | I'm trying to add a new entry into Internet Explorer's right-click context menu. I understand that this can be achieved by creating an HTML file containing JavaScript, and then linking to this from a location in the registry. I have also read that you can also add the HTML to a resource file and compile it into a DLL... | Have you tried having the ID be TEST.html? My guess is that IE doesn't know how to handle the file because it doesn't have an extension listed, but this is totally a guess based off the fact that's how certain MS .dlls identify them (i.e. res://c:\windows\system32\shdoclc.dll/navcancl.htm)
The only other thing I can t... |
786,951 | 787,843 | stringstream unsigned conversion broken? | Consider this program:
#include <iostream>
#include <string>
#include <sstream>
#include <cassert>
int main()
{
std::istringstream stream( "-1" );
unsigned short n = 0;
stream >> n;
assert( stream.fail() && n == 0 );
std::cout << "can't convert -1 to unsigned short" << std::endl;
return 0;
}
I... | The behaviour claimed by GCC in Max Lybbert's post is based on the tables om the C++ Standard that map iostream behaviour onto printf/scanf converters (or at least that;'s my reading). However, the scanf behaviour of g++ seems to be different from the istream behavior:
#include <iostream>
#include <cstdio>
using namesp... |
786,984 | 786,991 | How can I control my PC's fan speed using C++ in Vista? | How can I use C++ to control CPU fan speed in Windows Vista Ultimate?
I would like to use ACPI.
| ACPI:
You need to learn about and use the WMI - Windows system management interface. Here are a few resources that will give you clues on where to start:
SetSpeed Method of the CIM_Fan Class
WMI C++ Application Examples
Example: Calling a Provider Method
Note that some motherboards don't support fan speed changes, a... |
787,164 | 787,231 | Boost Regex - Where are the matching strings stored? | I`m writing a web spider and want to use boost regex library instead of crafting some complicated parsing functions.
I took a look at this example:
#include <string>
#include <map>
#include <boost/regex.hpp>
// purpose:
// takes the contents of a file in the form of a string
// and searches for all the C++ class ... | as the comments in the code suggest, what[0] contains the entire string.
so what[0].first will point to the beginning of the match in every iteration of the loop.
and in general to get the i'th group you could use:
string s(what[i].first, what[i].second);
to read more about the class match_results, check this link.
|
787,288 | 789,367 | Problem when disabling checked iterators in vs2008 SP1 (_HAS_ITERATOR_DEBUGGING=0) | I've been having some trouble with vs2008 SP1 running in debug mode when I try to disable checked iterators. The following program reproduces the problem (a crash in the string destructor):
#define _HAS_ITERATOR_DEBUGGING 0
#include <sstream>
int do_stuff(std::string const& text)
{
std::string::const_iterator i(... | I've just tried this in VS2008 on Windows XP and got a warning regarding a buffer overflow, both on a pre- and a post-SP1 VS2008.
Interestingly enough the problem seems to be centred around passing the string into do_stuff either by reference or by value - if I use the original code, it complains about the buffer overf... |
787,375 | 787,395 | Why would you want to use C# if its slower than C++? | I'm looking for a new language to learn after C++ and Java. I was going to try C#, but a bunch of people say its really slow because its a high level language. So why would anybody use C#? Isn't C++ much faster? Does it make development easier, but just have a slower final product?
Also, what can C# be used for? You u... | Who exactly is this "bunch of people"? What are they comparing it against?
For the vast majority of things, C++ is not "much faster" than C#. It certainly has benefits in various situations, particularly where you want more deterministic memory handling, but in my experience the bottleneck in most applications isn't in... |
787,417 | 793,385 | Why would you write something like this? (intentionally not using delete [] on an array) | I came across this kind of code once in a while - I suspect the creator is/was afraid that table delete would iterate over the table and "cost performance" (which imho will not be done either way)... is there any real benefit one might get/consider/imagine from not using the the table delete here?
myClass** table = new... | There's really no reason to write like that and a serious reason to never do so.
It's true that for types with trivial destructors (like raw pointers in your case) there's no need to know the actual number of elements in the array and so the compiler might decide to map new[] and delete[] onto new and delete to reduce ... |
787,448 | 787,467 | Marshalling reference-types from C++ to C# | I want to invoke the following C++ function (exported by a DLL) from C#:
void createVm(
const jace::VmLoader& loader,
const jace::OptionList& options,
bool ignoreUnrecognized = true );
I've found documentation for marshaling primitives from C++ to C# but I'm not sure how to handle reference-types or non-pritm... | AFAIK, PInvoking into a function with C++ constructs is not a supported operation. You could probably get it to work but I think you'll find problems.
What is supported is writing a simple C wrapper function which calls into your C++ function. PInvoke into the wrapper function instead and that will do the trick.
|
787,481 | 787,508 | SQLite3 trouble under VC9 | I imported sqlite3.c sqlite3.h into my project - and I'm having trouble compiling it.
Errors:
1>c:\...\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sqlite3'
1>storage_manager.cpp
1>c:\...\storage_manager.h(7) : error C2079: 'storage_manager::db' uses undefined struct 'sql... | I just noticed you try to create a stack variable of type sqlite3 called db. That won't work, as sqlite3 is a handle and you can only have a pointer variable. You need then to pass the address of that pointer variable to sqlite3_open.
@Neil Butterworth spotted it a bit earlier than me :-)
|
787,533 | 787,539 | Is #pragma once a safe include guard? | I've read that there is some compiler optimization when using #pragma once which can result in faster compilation. I recognize that is non-standard, and thus could pose a cross-platform compatibility issue.
Is this something that is supported by most modern compilers on non-windows platforms (gcc)?
I want to avoid pla... | Using #pragma once should work on any modern compiler, but I don't see any reason not to use a standard #ifndef include guard. It works just fine. The one caveat is that GCC didn't support #pragma once before version 3.4.
I also found that, at least on GCC, it recognizes the standard #ifndef include guard and optimizes... |
787,598 | 787,694 | How to perform atomic 64b read on x86 (Pentium and above)? | I would like to perform and atomic read of 64b aligned 64b data on x86 platform (Pentium or above guaranteed).
Is there a way to do this? (And no, I do not want to use a critical section or a mutex for this, I want this to be lock-free).
| Use the Interlocked operations, here's some sample code:
LONGLONG AtomicRead(LONGLONG* p)
{
return InterlockedCompareExchange64(p, 0, 0);
}
This does the compare exchange against zero and sets p to zero if it's already equal to zero -ie, it's a noop. InterlockedCompareExchange returns the original 64 bit value po... |
787,809 | 788,973 | How to clean up a complex QList? | I'm using a rather complex QList in a derivation of QAbstractTableModel to store data:
class MyTableModel : public QAbstractTableModel {
Q_OBJECT
QList<QHash<int, QHash<int, QVariant> *> *> m_data;
/*...*/
};
MyTableModel::~TMusicTableModel() {
/* Should I deallocate QList items? */
}
MyTableMo... | Because you're creating the sub items with "new", you do have to deallocate them yourself. See the qDeleteAll function for a quick way of doing so.
Is there a reason why you're using new to create these hashs? (Your code is obviously just a snippet, so the pointers could be used and passed around elsewhere.) Generally,... |
787,906 | 787,939 | C++ operator overloading resolution ambiguity | Am trying to move an antique C++ code base from gcc 3.2 to gcc 4.1, as I have run into a few issues. Of all the issues, the following is left me clueless (I guess I spent too much time with Java or I might have forgotten the basics of C++ :-P ).
I have a template class
template < class T > class XVector < T >
{
...
... | The second operand type is long [int]. The first is TypeValue, I expect, but there is no operator* that takes those two exact types. There are lots of other type combinations for that operator, though, which the compiler can select by doing an implicit conversion on the first operand. The language allows the compiler t... |
788,080 | 788,161 | Automatically sorting on insert in QTreeWidget | I have a QTreeWidget that I insert items in, and the user can select a column to sort it. As the items are being inserted, they just get appended to the end instead of having the sort being done automatically. If I click the header to switch between ascending/descending it will sort the current items.
I figured I could... | If your tree widget is called treeWidget, you should be able to call the header() method, which is from QTreeWidget's parent QTreeView, then sortIndicatorOrder() from the QHeaderView class:
treeWidget->header()->sortIndicatorOrder()
With this, you know the user's current sort order, and you can apply your sort on inse... |
788,482 | 788,497 | delete[] supplied a modified new-ed pointer. Undefined Behaviour? | I saw some code as below during a peer-code-review session:
char *s = new char[3];
*s++ = 'a';
*s++ = 'b';
*s++='\0';
delete []s; // this may or may not crash on some or any day !!
Firstly, I know that in Standard C++, pointing to one-past the array-size is O.K. though accessing it results in undefined behaviour. So I... | From the C++ Standard, section 5.3.5/2:
the value of the operand of delete shall be the pointer value
which resulted from a previous array
new-expression. If not, the behaviour
is undefined
|
788,703 | 788,745 | Initializing a vector before main() in C++ | I want to be able to initialize a vector of a size 'SIZE' before main. Normally I would do
static vector<int> myVector(4,100);
int main() {
// Here I have a vector of size 4 with all the entries equal to 100
}
But the problem is that I would like to initialize the first item of the vector to be of a certain va... | Here's alternative solution:
#include <vector>
static std::vector<int> myVector(4,100);
bool init()
{
myVector[0] = 42;
return true;
}
bool initresult = init();
int main()
{
;
}
|
788,814 | 788,825 | Writing a simple parser | I need to write a simple parser to a sort of Domain Specific Language.
It needs to have basic arithmatics with proper operators evaluation order and a syntax to call functions of the underlying environment which can be overloaded.
What is the simplest way to write such a parser? Is there something I can adapt or use ou... | Take a look at Boost Spirit.
|
788,940 | 788,946 | How to synchronize SVN revision and version ressources of EXE/DLL files? | Say I have some C++ project which builds an exe or dll file. The project is checked into a SVN repository. I want to automatically synchronize the revision from SVN with the version resource embedded in my exe/dll file, i.e. the version should be something like $major.$minor.$svn_revision.
Any ideas on how to achieve t... | If you have TortoiseSVN installed, then there is a program installed with it, SubWCRev.
If, in your file, you have this value:
$WCREV$
Then it'll be replaced with the highest committed revision number if you execute something like this:
SubWCRev .\ yourfile.txt.template yourfile.txt
This will copy from yourfile.txt.t... |
788,953 | 788,969 | What happens if my app is out of memory? | If my application is out of memory when i call new() i will get exception and malloc() i will get 0 pointer.
But what if i call a method with some local variables? They occupy memory too. Is there some way to reserve memory for "normal" variables? So that even though new() throws exception i can just catch it, fix stuf... | The compiler knows how much of memory per stack you need. However, sufficiently high number of stacks (caused due to recursion) will crash your program -- there probably isn't another way to fix this.
The standard has an interesting annexure called Implementation Quantities. This is non-normative (informative) and henc... |
789,061 | 789,442 | How to create separate library for include in C++/Eclipse | I've gotten some C++ code to work with the TinyXML parser. However, to do this I had to include the source code from TinyXML with my regular source code. I'd like to have TinyXML included as a separate library. I'm using Eclipse with the Cygwin C++ compiler. What's a good way to do this?
| I assume you want to separate the library from your own project's source code... but you don't know how to build when the library is not in the same folder.
Assuming your library has precompiled *.lib and *.h files:
Move the library source code to a separate directory
Menubar "project"
Menu "properties" will open a ... |
789,159 | 789,199 | How do I find the shortest path that covers all nodes in a directed cyclic graph? | I need an example of the shortest path of a directed cyclic graph from one node
(it should reach to all nodes of the graph from a node that will be the input).
Please if there is an example, I need it in C++, or the algorithm.
| EDIT: Oops, misread the question. Thanks @jfclavette for picking this up. Old answer is at the end.
The problem you're trying to solve is called the Travelling salesman problem. There are many potential solutions, but it's NP-complete so you won't be able to solve for large graphs.
Old answer:
What you're trying to fin... |
789,278 | 789,330 | Differences between UNIX and Windows development | I've been programming in C and C++ in Linux for around 3 years, and recently have been interested in developing commercial software for businesses. Let's say I've found a niche where I think I could be successful, but that they only use Windows. I have no experience whatsoever with the Windows API, however. I have a... | I faced exactly the same questions and I am so happy I tried .NET. I hope this info can help you:
Should I learn .NET?
I would highly recomment it.
Do I need to learn C# in order to use .NET, or can I stick with C++?
You can stick with C++ but I am sure you will love to learn C#, please try it. You will be able to mix... |
789,402 | 789,414 | typeid() returns extra characters in g++ | class foo
{
public:
void say_type_name()
{
std::cout << typeid(this).name() << std::endl;
}
};
int main()
{
foo f;;
f.say_type_name();
}
Above code prints P3foo on my ubuntu machine with g++. I am not getting why it is printing P3foo instead of just foo. If I change the code like
std::cout << typei... | Because it is a pointer to foo. And foo has 3 characters. So it becomes P3foo. The other one has type foo, so it becomes 3foo. Note that the text is implementation dependent, and in this case GCC just gives you the internal, mangled name.
Enter that mangled name into the program c++filt to get the unmangled name:
$ c+... |
789,421 | 789,433 | C++ static global objects workarounds? | I have a C++ program that crashed due to a bug. It would not even get to main as a NULL pointer was accessed in one of its static global object's contructor functions. To make matters worse the pointer was NULL but should have been set by another global static variable. I think I can wrap those globals in a function... | One way to control the instantiation of static objects is to use construct on first use idiom as explained in this FAQ
|
789,426 | 789,451 | Rotate a string in c++? | I'm looking for a way to rotate a string in c++. I spend all of my time in python, so my c++ is very rusty.
Here is what I want it to do: if I have a string 'abcde' I want it changed to 'bcdea' (first character moved to the end).
Here is how I did it in python:
def rotate(s):
return s[1:] + s[:1]
I'm not sure how ... | I recommend std::rotate:
std::rotate(s.begin(), s.begin() + 1, s.end());
|
789,448 | 789,458 | C++ Explicit Superclass Constructor Problem While Using Header Files | I seem to be having a very frustrating time with an inherited class calling an explicit superclass constructor. I just can't seem to get the syntax right!
All the examples I have seen on the matter so far do not separate out the header and in-line class definition (using {}'s) from forward-declarations with a header f... | You don't put the initializer list in the class declaration, but in the function defininition. Remove it from the header, and in your .cc file:
#include "serverconnection.h"
#include "connection.h"
ServerConnection::ServerConnection(string myOwnArg, string superClassArg) : Connection(superClassArg) {
//do my con... |
789,532 | 789,567 | QList and shared_ptr | What do you think? Is this correct or are there memory leaks?
Source:
#include <QList.h>
#include <boost/shared_ptr.hpp>
#include <iostream>
class A {
private:
int m_data;
public:
A(int value=0) { m_data = value; }
~A() { std::cout << "destroying A(" << m_data << ")" << std::endl; }
operator int() cons... | It seems correct. Boost's shared_ptr is a reference counting pointer. Reference counting is able to reclaim memory if there are no circular references between objects. In your case, objects of class A do not reference any other objects. Thus, you can use shared_ptr without worries. Also, the ownership semantics allow s... |
789,611 | 789,624 | Embedding data inside a c++ application | Is there a platform-independent method to embed file data into a c++ program? For instance, I am making a game, and the levels are stored in text format. But I don't want to distribute those text files with the game itself. What are my options?
| This has been asked here before. Basically, you just name the data with an accessible symbol. I like this method best:
You can always write a small program or script to convert your text file into a header > > file and run it as part of your build process.
|
789,656 | 799,451 | What's wrong with my KD-Tree? (K=2) | More specifically, there's something wrong with my nearest neighbor search. I've confirmed that the tree is built correctly, and that all the helper functions work as expected.
Note this differs slightly from standard KD-trees in that I'm looking for the closest 3 points.
struct Node
{
unsigned int axis;
Point* obj;
... | This line is wrong:
double searchToSplit = _distance(to, current->obj, current->axis);
You want axis, not current->axis.
|
789,659 | 789,680 | What is the best approach for a Java developer to learn C++ | I consider myself an experienced Java developer and am planning to get started with learning C++.
If you had same experience, i.e learn C++ after Java, I would like to hear your thoughts on what is the best approach at doing this.
[Update] "the best approach" was not well quantified. What I am looking for is to lever... | I've taught C++ to Java people, even though I learned them the other direction.
Are you comfortable with C? If not, read Kernighan and Ritchie. Many many peculiarities of C++ are explained by the desire for C++ to be a "Better C" with C's basic expression syntax.
You should get Stroustrup.
I think well of Thinking in... |
789,817 | 790,109 | How to use TinyXml to parse for a specific element | I would like to parse a group of elements out of a TinyXml output. Essentially, I need to pick out any port element's "portid" attribute of the port has a state of "open" (shown below for port 23).
What's the best way to do this? Here's the (simplified) listing for the output from TinyXml:
<?xml version="1.0" ?>
<nmapr... | This will roughly do it:
TiXmlHandle docHandle( &doc );
TiXmlElement* child = docHandle.FirstChild( "nmaprun" ).FirstChild( "host" ).FirstChild( "ports" ).FirstChild( "port" ).ToElement();
int port;
string state;
for( child; child; child=child->NextSiblingElement() )
{
port = atoi(chi... |
789,954 | 790,050 | boost::filter_iterator -- how would I do that with the STL? | I am passed an Iterator and I have to pass it on to another function -- but filtered so that certain elements are skipped (it's a range of pointers, and I want to filter out the NULL pointers).
I googled for "stl filter iterator" to see how to do this, and boost::filter_iterator came up.
That looks nice and I could u... | You are correct; you would essentially be recreating the filter iterator yourself.
My advice would be to use Boost's filter_iterator. Boost has special status as c++'s most used external library; many c++ committee members have helped write libraries for boost. Its ubiquity essentially makes it almost-stl as is; there'... |
790,239 | 876,160 | Getting File Version Information fails -- But not for me | I am trying to get version information from a file. My code works perfectly for me, but fails on several others' machines. Because I can't reproduce the bug, I'm having quite a time finding the issue.
Does anyone see anything majorly wrong with this?
LPBYTE versionInformationBlock;
struct LANGANDCODEPAGE {
WORD wLa... | nvm. Seems Stackoverflow beats the heck out of me if it isn't answered.....
Billy3
|
790,407 | 790,432 | Debugging using gdb - Best practices | I am a beginner in GDB and I got it working correctly. However, I am wondering how this is used in big projects. I have a project where build is done using makefile and g++. For GDB to work, we need to compile with debug symbols on, right (g++ -g files)?
Question
Do I need to create a new target in makefile something... |
Not needed, although you may want to consider always building with -g (sometimes, you may even need to try and debug optimized (-O1, -O2, etc) code; why not leave -g on? For releases, you can always just run strip on the binary.
Yes. Build just that file with -g .
|
790,494 | 790,531 | What's the most brilliant use of templates you've ever encountered? | We all know the usual use of templates to design containers and we all know that you can do things with templates that will make your head spin.
When I first encoutered static polymorphism I was really struck on what you can do with templates. It's obvious that templates are useful for more than for designing container... | boost's Spirit meta programming for creating a parser's grammar.
|
790,538 | 790,544 | Adding values from file to a hash type structure in C++ | I have a space separated file which contains some key->value pairs. These are to be loaded to a structure of the type given below:
#define FV_PARAM1 "A"
#define FV_PARAM2 "B"
parameter_t & parameterFeatureVector (
parameter_t & param,
int param1,
int param2,
) {
... | I take it you are asking how to translate a name "A" to a specific structure field? If So, C++ has no built-in way of doing that - you have to write a function:
void Add( parameter_t & p, const std::string & name, int value ) {
if ( name == "A" ) {
p.param1 = value;
}
else if ( name == "B" ) {
p.param... |
790,552 | 790,593 | Calling a function with different number of threads passed to the application | I have a function which needs to be invoked with a different number of threads each time (am doing some performance calculation, so need to know when the performance starts deteriorating). Example is given below:
getTime() {
return 0;
}
int main() {
boost::threadpool::thread_pool<> threads(nThreads);
for(... | If i understand correctly, what you really want to do is something like this :
int main()
{
int nbThreads = 20;
boost::threadpool::thread_pool<> threads(nbThreads);
for(int threadId = 0; threadId <= nbThreads ; ++threadId)
{
threads.schedule(getTime);
}
threads.wait();
}
If i am rig... |
790,553 | 790,704 | Thread-safe C++ stack | I'm new to C++ and am writing a multi-threaded app whereby different writers will be pushing objects onto a stack and readers pulling them off the stack (or at least pushing the pointer to an object)..
Are there any structures built-into C++ which can handle this without adding locking code etc.? If not, what about the... | Yep: Boost.Thread is great, and should fit your needs very well. (These days, many people say that you could almost count Boost as built-in functionality.)
There is still no class that you could use out-of-the-box, but once you have the synchronization primitives at hand, it really is quite simple to implement your own... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.