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
6,307,458
6,307,588
Is there a generally accepted alternative to GMP for arbitrary precision?
In my quest for looking for a BigInt library, I came across this post: C or C++ BigInt library on Microsoft Windows The accepted answer mentions the GMP library, but one of the commenters claim that library does not error out very gracefully and would not be good for production code. Has anybody done any long term dev...
Well, as a large project like GCC uses this for its printf and compile-time calculations (correct me if I'm wrong here), I think it's stable enough. I would think there are ways to limit the out-of-memory errors the commenter worries about, but I haven't used it personally, so I can't help you there. All I'm saying is ...
6,307,526
6,307,791
C++0x const RValue reference as function parameter
I am trying to understand why someone would write a function that takes a const rvalue reference. In the code example below what purpose is the const rvalue reference function (returning "3"). And why does overload resolution preference the const Rvalue above the const LValue reference function (returning "2"). #inclu...
Lvalues strongly prefer binding to lvalue references, and similarly rvalue references strongly prefer binding to rvalue references. Modifiable expressions weakly prefer binding to a non-const reference. So when your compiler is doing overload resolution, it checks if there's an overload that takes an rvalue reference, ...
6,307,566
6,307,647
Method pointer casting
I'm writing a delegate class for educational purposes and have run into a little problem. The delegate must be able to call not only functions but also member methods of objects, which means that I need to store a pointer to a method: void (classname::*methodPtr)(...); And I need to store pointers to methods from diff...
You don't. You use run-time inheritance, if you need abstraction, and create a derived class which is templated on the necessities, or preferably, just create a plain old functor via the use of a function. Check out boost::bind and boost::function (both in the Standard for C++0x) as to how it should be done- if you can...
6,307,686
6,307,757
Handle object in c++
I've been told that a handle is a sort of "void" pointer. But what exactly does "void pointer" mean and what is its purpose. Also, what does "somehandle = GetStdHandle(STD_INPUT_HANDLE); do?
A handle in the general sense is an opaque value that uniquely identifies an object. In this context, "opaque" means that the entity distributing the handle (e.g. the window manager) knows how handles map to objects but the entities which use the handle (e.g. your code) do not. This is done so that they cannot get at t...
6,307,801
6,307,853
Passing parameters from managed to unmanaged code
I have to use a method from a library that has the following signature in the header file: NKREMOTELIB_API int __stdcall GetEvfFrame( const unsigned char*& buffer, size_t& size, NKRemoteEvfDisplayInfo& displayInfo); I am calling these from c# using the following: [DllImport("NKRemoteLib.dll")] public stati...
This has nothing to do with C++/C# interop. It's actually about C++. C++ has the concept of references. When you pass an object by reference, you are actually passing the object itself, and not just a copy. That means any modification to the object in the callee will appear in the caller. C# has a similar concept with ...
6,307,954
6,308,447
How to expose a property from a fluent interface with boost::python?
I have a C++ class which presents a fluent interface, something like: class Foo { public: int bar() const { return m_bar; }; Foo& bar(int value) { m_bar = value; return *this; }; private: int m_bar; }; I'd like to wrap the bar() functions as a property in my Python class. So I wrote: class_<Foo>("Foo"...
I ended up writting the following template function: template <class BaseClass, typename T, BaseClass& (BaseClass::*method)(T)> void make_nonfluent_setter(BaseClass& self, T value) { (self.*method)(value); } And now I can type: class_<Foo>("Foo") .add_property( "bar", (int (Foo::*)())&Foo::bar, make_...
6,307,984
6,308,030
"Simulating" a 64-bit integer with two 32-bit integers
I'm writing a very computationally intense procedure for a mobile device and I'm limited to 32-bit CPUs. In essence, I'm performing dot products of huge sets of data (>12k signed 16-bit integers). Floating point operations are just too slow, so I've been looking for a way to perform the same computation with integer ty...
I'm pretty sure that the JVM must support a 64-bit arithmetic long type, and if the platform doesn't support it, then the VM must emulate it. However, if you can't afford to use float for performance problems, then a JVM will probably destroy you. Most C and C++ implementations will provide 64-bit arithmetic emulated f...
6,307,997
6,309,740
Use numerical IDs of text boxes to initialize DoDataExchange?
So I have close to 300 variables (just right now), and I have numerically ordered their IDs in Resource.h so it's: #define IDC_BOX1 1 #define IDC_BOX2 2 #define IDC_BOX3 3 #define IDC_BOX4 4 etc. My question involves the DoDataExchange that I'm performing for each different dialog that I have that cont...
@Mark Ransom's answer is great. I do exactly what he suggests, but I have one other thing I do as well. During my app's startup (guarded by an #ifdef DEBUG), I have some code that verifies that all of my IDs are in consecutive numerical order. That way, I can be sure that someone (likely me in the future) doesn't co...
6,308,025
7,838,362
problem with <afxcontrolbars.h> in VS 2010
I cant figure out why my program refuse to build. it throws the error message - stdafx.h(36): fatal error C1083: Cannot open include file: 'afxcontrolbars.h': No such file or directory I am using windows xp and vs2010, can you help me with that? thank you on advance.
If you migrate a project from VC2008 to VC2010, make sure to change 'Platform Toolset' (in 'Configuration Properties' -> 'General') from 'V90' to 'V100'.
6,308,135
6,309,206
Accessing Light userdata in Lua
I may be misunderstanding their use or misread the documentation, but how do I access members of a struct or class passed to Lua as light userdata? For example if a vector using the following struct typedef struct Foo { int x; int y; } Foo; was declared as 'test' and defined as something like x = 413 and y = 612, ...
Light userdata in Lua is just a pointer. Lua has no understanding of how to read the contents of the object referenced by the pointer. The purpose of this data is to allow one C API call to pass a reference to another API call. If you want to work with data in Lua, you need to push it onto the stack, and in your case...
6,308,649
6,309,635
Testing a C++ library with Python
I have a libfoo.so library built from C++ code (compiled with gcc), and I would like to quickly test some of its exported classes (basically, instantiating a class then calling its methods to check the output). While I could do that in C/C++ with a main file that links to the library in question and build my tests, but...
I agree with Chris answer. However, I want to point out that Cython supports C++ (with some limitations).
6,308,653
6,308,695
Why is the base class method called if the derived class overrides the method?
consider the following program: class Base { public: virtual void foo() const { cout << "Base::foo()" << endl; } }; class Derived : public Base { public: virtual void foo() { cout << "Derived::foo()" << endl; } }; void func(Base& obj) { obj.foo(); } void main() { Derived d; ...
In the derived class, the function signature is this: virtual void foo(); //Derived::foo which doesn't mention const. Its a non-const member function, while the Base::foo is a const member function. They're two different functions, because const is a part of the function signature. virtual void foo() const; //Base::f...
6,308,675
6,308,879
How to track which network ports any program is trying to use?
I want to see what kind of connections any program is doing, which port and see the program exe path etc. I'm trying to achieve some sort of firewall notification system, it would pop up a window for me to tell that this and that port needs to be opened in order the program could work properly. How do i get started on ...
You'll need to hook the socket API for each process you're willing to provide this functionality, or write a filter using WFP and a client application that receive the informations from your filter and shows a notification window.
6,308,714
6,309,042
Windows LoadMenu error: "The specified resource name cannot be found in the image file."
I'm writing a program that, among other things, needs to display a context menu on right-click. I'm trapping WM_NOTIFY, the identifier of the control being clicked on, and NM_RCLICK. That all works great. The problem comes in when I'm processing that right-click: case NM_RCLICK: { HMENU Popup = LoadMenu(0, MAKEINTR...
The first parameter to LoadMenu must be a handle to your executable image where the resource resides. The handle is the first HINSTANCE that you get in WinMain. Alternatively you can obtain it by a call to GetModuleHandle(0).
6,308,915
6,308,938
Member fields, order of construction
In C++, when doing something like what you see below, is the order of construction guaranteed? Logger::Logger() : kFilePath_("../logs/runtime.log"), logFile_(kFilePath_) { // ... }
Yes, the order of construction is always guaranteed. It is not, however, guaranteed to be the same as the order in which the objects appear in the initializer list. Member variables are constructed in the order in which they are declared in the body of the class. For example: struct A { }; struct B { }; struct S { ...
6,309,105
6,309,134
Cross-OS distributed computing in C++, rand() issue
I'm working on a small distributed computing project. The server can't handle the calculations without crashing Apache in the process, so I'm giving these calculations to the users. The basic idea is that I run the calculations 3 times, and the results need to be exactly the same. However, the application will need to ...
Take a look at the Boost.Random facilities. They give you a broad choice of algorithms that are guaranteed to give the same results, always.
6,309,163
6,310,883
how to link the fmod library in visual studio
I am just a beginner at windows programming and was reading a tutorial about it. It said something about resources for menu creation. I am working in visual studio 2010 and would like to know how to create these resources (the turorial said something about adding them to the compiler which i could not understand) fo...
To actually use the additional functionality you have to include the header and specify the directory where it is contained so the project can find the file right click on project->properties C\C++->general tab the top element is Additional Include Directories - click the down arrow and specify the path to the header f...
6,309,237
6,309,485
How would you declare DLL import signature?
this is a follow-up post of Using pHash from .NET How would you declare following C++ declaration in .NET? int ph_dct_imagehash(const char* file,ulong64 &hash); So far i have [DllImport(@"pHash.dll")] public static extern int ph_dct_imagehash(string file, ref ulong hash); But I am now getting following error for ulo...
Stack imbalance indicates that the C++ code uses cdecl and your C# uses stdcall calling convention. Change your DLLImport to this: [DLLImport(@"pHash.dll", CallingConvention=CallingConvention.Cdecl)] The function signature in C# (return value and parameters) is otherwise correct.
6,309,506
6,309,572
How to run app from VC++ without debug?
I'm trying to learn to love Visual C++ 2010 Express, but it is difficult! I've just created a "Hello world" console app and compiled it - no problems. I now want to run it. It seems the only option open to me is to run it in the debugger - there is a "Run" button on the toolbar but it is disabled. I don't want to debug...
If you can't see the "Start Without Debugging" command in the toolbar, go to "Tools -> Settings -> Expert Settings". Basic Settings hides lots of stuff you probably want to see. Professional version of VC2010 doesn't seem to have this switch.
6,309,593
6,309,613
Is the copy CTOR required even if never called?
consider the following: class X { public: X(int i) { cout << "X(int i)" << endl; } X(const X& x) { cout << "X(const X& x)" << endl; } }; void main() { X x1(1); X x2 = X(1); X x3 = (X)1; } running this code produces this output: X(int i) X(int i) X(int i) I thought that all of the above three stat...
X x1(1); X x2 = X(1); X x3 = (X)1; The reason is that all of these are not exactly equivalent. First one is direct-initialization, while the second and third is copy-initialization. For copy-initialization, copy-constructor must be public, or else compiler will give error. Now the question is, if 2nd and 3rd requires ...
6,309,768
6,310,301
SWIG error: was declared 'extern' and later 'static'
I'm using swig to produce a python C++ interface such that I can make scripts in python to call my c++ functions. I've gotten as far as: swig -c++ python filename.i gcc -c filename.cpp filename_wrap.cxx -shared -Ic:\includepath Where the include path is my python27's include directory. Upon attempting to compile with...
The fact that they appear in a header as a prototype implicitly define them as an extern function. However you're ALSO declaring them as static. Given the C++ tag, I'm going to make an assumption here, so please pardon me if you already know this and it comes off as patronizing. static in C does something completely di...
6,309,977
6,312,502
Are there performance issues with CSocket::Send?
UPDATE 14 June 2011 A quick update... Most respondents have focused on the dodgy method for handling the queue of messages to be logged however while there is certainly a lack of optimisation there it's certainly not the root of the problem. We switched the Yield over to a short sleep (yes, the Yield did result in 100...
In my opinion, you're definitely not looking at the most efficient solution. You should definitely call Send() once. For all messages. Concatenate all the messages in the queue on the user side, send them all at once with Send(), then yield. In addition, this really isn't how you're meant to do it. The PPL contains con...
6,309,995
6,310,252
Writing first listening C++ application
I would like to write a "listening" background C++ application with which I can communicate from other programs, written in various languages, and don't quite know how to do it. What is the best (e.g. little development effort, portability across languages (C++,C#,R,vba,...), and works remotely between machines) way to...
Sockets are the way to go. Look at boost_asio for cross platform asynchronous networking in C++. Cheers
6,310,638
6,310,703
C++ vector::push_back using default copy constructor
I have a class (Uniform) that has a constructor with 2 parameters, and a default copy constructor (it only contains int, floats, a std::vector and a std::map). I created a std::vector<Uniform> uniforms that I want to fill using the uniforms.push_back() line. I use this code to do that (the 2nd line is just here to te...
When you say "default copy constructor" (which generally makes little sense), I assume you mean "implicitly-declared copy constructor" or "compiler-provided copy constructor" The exact signature of the compiler-provided copy constructor will depend on the contents of your Uniform class. It could be Uniform::Uniform(con...
6,310,720
6,310,959
Declare a member-function of a forward-declared class as friend
Is it possible to declare a member function of a forward-declared class as friend? I am trying to do the following: class BigComplicatedClass; class Storage { int data_; public: int data() { return data_; } // OK, but provides too broad access: friend class BigComplicatedClass; // ERROR "invalid use of...
As @Ben says, it's not possible, but you can give specific access just to that member function through a "passkey". It works a bit like the intermediate helper class, but is imho clearer: // Storage.h // forward declare the passkey class StorageDataKey; class Storage { int data_; public: int data() { return data...
6,310,746
6,321,963
Initializing pthread mutexes
According to the documentation a mutex can be initialized in two ways: Using the init function: pthread_mutex_t theMutex; pthread_mutex_init(&theMutex, NULL); Using an initializer macro: pthread_mutex_t result = PTHREAD_MUTEX_INITIALIZER; About the latter the documentation says: In cases where default mutex attribut...
Re "It turns out that three times the same mutex was created. What am I doing wrong here?" You are doing nothing wrong here. The same mutex was not created three times. It looks like you are interpreting that 0x32AAABA7 as an address. It isn't. It is essentially an enum value, but with a Hamming code protection to (a) ...
6,310,969
6,311,531
Convert 16bit QImage to 8bit unsigned char in QT
I am trying to figure out how to convert an image from uint16 to uint8. I am basically having to read the image in float, and I need to display it in unsigned char. I have the following: float two_eight = pow(2.0,8); float two_sixteen = pow(2.0,16); QImage *qi = new QImage(imwidth, imheight, QImage::Format_...
If I understand your question correctly, you got an image in RGB format where each color component is 16 bits, and you want to load this using QImage. You can do it like this : std::vector< unsigned short int > inData; // load the data into a vector std::vector< unsigned char > outData( inData.size(), 0 ); std::trans...
6,310,980
6,311,091
Condense 3 floats to a uint64_t
I'm working on a program that generates a lot of instances of a class (millions). The class is really simple, it just holds 3 floats. Now the range these floats can live in exists between 0 and 1 (color values) and most often they are pretty simple values (1, 0.5, 0.25, 0). In an interest to save memory, I thought mak...
You should just use a byte for each color value (24bit color). That would make each one of your classes take up 1/4(1/3 with padding) the space. That is the highest quality format each pixel of your screen is rendered in anyways. Edit: If you want to save even more space you could have the classes store 16bit color in...
6,311,011
6,311,064
Connecting to a database
I need to connect to an oracle database, what is the best way of doing so ODBC, ole db, or any others? speed is a bit of an issue and I will be running quite a few statements during runtime, however it would be nice if there's something fairly easy to program, also a tutorial would be helpful too
I am the original author of QOpenOCCI (QT, no longer maintained) and under the hood we used OCILIB. OCILIB did a good job of simplifying the base OCI libraries from Oracle and it was pretty dang fast. You're biggest overhead will likely be the DB processing layer or the connection to the DB, not the library of choice. ...
6,311,042
6,311,111
My ifstream doesn't seem to be working
This is a main file that I am using to test methods before I implement them. I am trying to get the list of all files in a directory, write them to a txt file (It works fine until here), then read the file names from that text file. using namespace std; string sysCall = "", location = "~/Documents/filenames.txt"; str...
ifstream allfiles("~/Documents/filenames.txt"); doesn't do what you think it does. The tilde ~ character is not part of the filename -- it is a special character interpreted by some shells. You need the entire path, with no ~ or $ characters in it. Try setting location to "/tmp/filenames.txt", or just "filenames.txt". ...
6,311,206
6,311,221
Malloc in constructors
I'm implementing a binary heap class. The heap is implemented as an array that is dynamically allocated. The heap class has members capacity, size and a pointer to an array, as: class Heap { private: Heap* H; int capacity; //Size of the array. int size; //Number of elements currently in the arr...
First of all, you do not need a Heap* member variable inside your Heap object, and you certainly should not be allocating memory for it in the Heap constructor - that's just asking for trouble. Nor should you be accessing your member variables as H->Elements, but rather simply as Elements. The only thing you need to al...
6,311,459
6,311,503
Why doesn't using boost::tuple's .get work in template functions in gcc?
While trying to port some code to compile in linux I get peculiar compilation errors. Searching through the codebase I finally manage to get it down to the following code. 5: // include and using statements 6: template<typename RT, typename T1> 7: RT func(tuple<T1> const& t) { 8: return t.get<0>(); 9: } 10: /...
You need some template love: return t.template get<0>(); Visual C++ does not parse templates correctly, which is why it incorrectly accepts the code without the template keyword. For more information on why the template is required here, see the Stack Overflow C++ FAQ "Where and why do I have to put “template” and “t...
6,311,671
6,311,735
Is it safe to modify data of pointer in vector from another thread?
Things seem to be working but I'm unsure if this is the best way to go about it. Basically I have an object which does asynchronous retrieval of data. This object has a vector of pointers which are allocated and de-allocated on the main thread. Using boost functions a process results callback is bound with one of the...
No, it isn't safe. ProcessResults operates on the data structure passed to it through DataObject. It indicates that you have shared state between different threads, and if both threads operate on the data structure concurrently you might have some trouble coming your way.
6,311,714
6,351,184
PCap library issue with receive
So I've been having an issue with the receive functionality with the PCap library. I set up an echo server (outside my PC) that just takes a packet and turns it around. So, in my application, I send a packet (that works fine) and I tried receiving the response packet (from the echo server) with pcap_next(). For some re...
Figured out the solution. I needed to have TX and RX on two separate threads. RX Thread does this forever: pcap_loop(handle, -1, got_packet, NULL); Then I call the TX thread whenever I want, which does this (and loops however many times I need): pcap_sendpacket(t, TxPacket, DataLen + 42); This solved the problem.
6,311,754
6,331,321
Program Built on Win7 won't run on WinXP
I have a project that I'm building on Windows 7 (32-bit) using Visual Studio 2005. The program builds fine, and I can move it to another Windows 7 machine and run it just fine. The problem comes when I try to move it to a Windows XP Pro machine. When I try to run the file, I get the following error: "This application h...
This is what ended up fixing the problem: Copy the following folder: "C:\Program Files\Microsoft Visual Studio 8\VC\redist\x86\Microsoft.VC80.CRT" (since this is the file mentioned in the event viewer) into the same directory as the .exe I was having trouble executing. This lets the program use the dependency it was bu...
6,311,759
6,375,260
David Lowe's SIFT -- Question about scale space and image coordinates (weird offset problem)
I realize this is a highly specialized question.. but here goes. I am using an implementation of SIFT to find matches on two images. With the current implementation that I have, when I match an image with is 90 or 180 degree version, I get matches that are off by around half a pixel consistently but its varies within a...
Contrary to Mikola's assertions, it is possible to get scale and orientation out of SIFT. SIFT attempts to find the scale with greatest DOG extrema (s) and also finds a dominant orientation (r). Each location vector for a SIFT feature returns (x, y, s, r) To see how scale space converts to pixels, try VLFeat's implemen...
6,311,796
6,311,933
unsigned shift template in C++
I'd like to do an unsigned shift in C++. Here's my example code. The problem with it is it isn't generic. This code is completely wrong. It will not work on longs and it wont work on smaller types like char. I tried (unsigned T) but that is a syntax error. How might i make this generic without specialization? #include ...
If you can use Boost, the type_traits library has the make_unsigned template that would fit your needs perfectly. #include <boost/type_traits/make_unsigned.hpp> template<class T> T unsigned_shift(const T&t, unsigned int s) { return ((make_unsigned<T>::type)t)>>s; } (I changed the type of s to unsigned int because...
6,312,151
6,312,370
_stricmp with mingw and c++0x not existent?
I'm currently trying to use googletest with MinGW and -std=c++0x but it complains that _stricmp is not declared in this scope which it doesn't when I do not use -std=c++0x. I have no idea what _stricmp is, I just found out that it is defined in cstring/string.h, so why is it gone in C++0x?
The -std=c++0x option causes g++ to go into 'strict ANSI' mode so it doesn't declare non-standard functions (and _stricmp() is non-standard - it's just a version of strcmp() that's case-insensitive). Use -std=gnu++0x instead.
6,312,190
6,313,622
Graphing with Cern ROOT
I am trying to create a graph and save it as an image. I am required to use ROOT. I created the graph with TGraph graph = TGraph(xvect, yvect); but now I'm stuck on how to get that saved as a png (or other image format). I'm using a linux machine if that makes a difference. Also, if anyone knows link to the docum...
TCanvas*c1 = new TCanvas(); graph->Draw(); c1->Print("name.png"); Will certainly work in the cint shell. It may need some fine-tuning to work in compiled code. You'll find all this basic stuff exhaustively covered in the on-line tutorials and HowTos. Also see the documentation in general.
6,312,265
6,312,302
reference vs variable in C++
In this article its says that references allow you to reduce the amount of copying behind the scenes. Does reference reduce any other operation compared to a variable?
Reference is a kind of a variable. You're asking about passing by reference instead of passing by value. Passing by value creates a copy of the value being passed, while passing by reference means that the receiver will be able to change that same variable whose value you passed. Both have its own benefits and shortcom...
6,312,282
6,313,589
Scientific and numeric simulation in android which way? ndk?
i want to write a scientific/numeric environment for android, i am collecting informations since i never developed anything for android or mobile. I've recently heard about the native development kit, which should allow me to write C++ code for my android app, but i have some questions: Would it bring portability issu...
From the website: If you write native code, your applications are still packaged into an .apk file and they still run inside of a virtual machine on the device. The fundamental Android application model does not change. Using native code does not result in an automatic performance increase, but always increases applic...
6,312,428
6,312,512
Template Compilation
Can someone pelase explain to me how I can avoid the error below? I think I am following all I have read on template compilation but still get an error. Sorry for asking this - it seems trivial but I am stuck! Thanks, Paolo 1>------ Build started: Project: BitsAndPieces, Configuration: Release Win32 ------ 1> NonTempl...
You can separate the file as long as you're including it inside the header file (templates must be fully defined within the same translation unit, lacking proper support for the export keyword). But you're not qualifying your function definition with the class Paolo<T>::
6,312,493
6,312,552
Does C++ already have some kind of reflection?
Consider this example: struct Nobody_Expects_The_Spanish_Inquisition{}; int main(){ throw Nobody_Expects_The_Spanish_Inquisition(); } Output shown on Ideone: terminate called after throwing an instance of Nobody_Expects_The_Spanish_Inquisition' Similar output for Windows: Unhandled exception at 0x760fb727 in T...
It's compiler dependant. Obviously, it's easy for the compiler to spot every throw, and encode the type of every thrown object into the executable. But there is no requirement that they should do this. And thinking about it, exceptions have to be copied into a weird implementation-dependent space when they are thrown. ...
6,312,718
6,312,804
Using templates in struct -- to make a generic linked list
In .NET I really liked System.Generic.List and wanted to replicate it as a way of learning the C++ language. The problem is that I want it to be generic, I want the elements to contain a value of a template type T. I know most of what to do, but the problem lies within the node. template<class T> struct node { T va...
There's nothing wrong with your code. Actually, I would probably write it as template<class T> struct node { T value; bool isFirst; node<T> *next; }; because it's not much more verbose and it's clearer that next points to a node of the same type, but nevertheless also your version is fine: in a template, w...
6,312,891
6,312,900
Using initializer lists with inherited variables
I've been fiddling with a program for about 20 minutes and I found that for some reason it won't let me use inherited variables in initialization lists. This program, for example: class A { protected: int i; }; class B : public A { public: B() : i(45) { } }; int main() { B b; } Will give the ...
An object can only be initialized once: when it first comes into existence. A initializes all of its member variables in its constructor (before the body of its constructor is executed). Thus, B cannot initialize a member variable of A because the member variable was already initialized by the constructor of A. (In...
6,312,983
6,313,303
Dump process memory to disk to analyze for memory leaks
I have a 32 bit msvc++ application running in a production environment that is leaking memory. It basically will run for a few hours until it consumes all 3 gb of addressable memory and terminates. I was thinking that if there was a way to suspend a process and dump it's memory to disk, I could analyze the memory to s...
This is extremely straightforward as long as you're confident that you have some means of finding something useful by analyzing the process' heap. The tools involved are all free and instructions are here: Dump Files That said, if you could just run a debug build for a while, the CRT will do all the work for you. See F...
6,312,998
6,313,037
Non-extern function with C linkage
Is it possible to declare a function with C linkage without it having external linkage? When trying to compile extern "C" static void f() {} I get f.cc:1: error: invalid use of 'static' in linkage specification which makes sense, in a way. In namespace { extern "C" void f() {} }, the extern specifier seems to overrid...
You can do extern "C" { static void f() {} } This will give the function f's type C linkage which in practice means that it uses the C calling convention on your platform. The function's name will still have C++/internal linkage, because a language linkage specification only applies to function names of external lin...
6,313,050
6,313,148
gcc: How to use __attribute((__may_alias__)) properly to avoid "derefencing type-punned pointer" warning
I've got some code that uses type-punning to avoid having to call a member "object"'s constructor and destructor unless/until it's actually necessary to use the object. It works fine, but under g++ 4.4.3, I get this dreaded compiler warning: jaf@jeremy-desktop:~$ g++ -O3 -Wall puns.cpp puns.cpp: In instantiation of ‘L...
I think the typedef is confusing GCC. These sorts of attributes seem to work best when applied directly to variable definitions. This version of your class works for me (GCC 4.6.0): template<class T> class Lightweight { private: // typedef T __attribute((__may_alias__)) T_may_alias; public: Lightweight() : _isOb...
6,313,286
6,313,495
Two conditions that don't work the same way and I can't understand why
I wrote a function that searches for a char in an array, and if found returns its successor, else returns -1. Then, if the word ends in a vowel, the algorithm adds a consonant, and vice-versa. This code works well, even with the last word of the file: changedChar = cipherChar(character, consonants, tConsonants); if (ch...
The only difference I see is that in the second piece of code if nothing is found then charType has the value 'o', whereas in the first piece of code if nothing is found then charType has whatever its initial value was before this code runs (which you haven't shown us). Other than that, these two pieces of code appear ...
6,313,304
6,315,714
CRTP sub-subclass and instances list
I'm trying to implement a kind of CRTP (if I well understand what it is) with multiple inheritance. My main goal is to have a unified way to access list of instances of each subclass. May problem seems to reside in the namespace utilization. Here is the code of the simplest version : http://ideone.com/rFab5 My real pro...
The problem is that you've tried to define the list variable wrong. You need to provide a definition for Base, in general- you don't just define it for the one part that happens to be Derived's subclass, unless it's an explicit specialization. template<typename T> std::list<T*> NS1::Base<T>::instances; http://ideone.c...
6,313,426
6,313,588
Compiling Sundance-4.73
I am compiling Sundance-4.37 using gcc 3.4.6. SUNDANCE (Sentence UNDerstanding ANd Concept Extraction) and autoannotate are software developed by the NLP laboratory at the University of Utah. Sundance comes prepackaged with OpinionFinder. It is compiled using an install script. During compilation, throws the following...
You don't use the class name as a prefix for the member functions inside the class, just if defining them outside. Just remove that prefix. protected:   Word* getWordhelper(unsigned int&, unsigned int) const; };
6,313,504
6,313,516
Vector of class objects
I have created a vector of class objects. The following program crashes with "Pointer being freed was not allocated". I have deep copied as well. I don't see where the double delete is happening. What am I missing ?. #include <iostream> #include <vector> using namespace std; enum MessageType { ...
I haven't looked at your code in detail, but if you think you need a copy constructor, you also need an assignment operator. And, why, why, why write this stuff anyway? Why not use std::string? Do you feel the need to write your own floating point types? No, I didn't think so.
6,313,600
6,313,612
where to find the definition of a external variable?
Where can I find the definition of end_of_list? I searched the whole project from eclipse, but can't find the definition. But when put end_of_list as an expression when debug, I can see it's value, just don't where from which file to find it. #pragma once #include <cstdlib> #include <cassert> #include <utility> #inclu...
I can see two immediate possibilities. The Eclipse search functionality is not up to scratch, either because it's buggy (unlikely) or the actual definition of that item is held somewhere outside its scope (say, for example, you're including a header that isn't in the project). The actual definition is not in a source ...
6,313,611
6,313,637
Which library/framework can be used for this specific project?
I have a project, but I don't know which library that I could use for this project: Project requirement Log into hotmail.com Click on each email individually and take a specific link out of the email. Copy and add the link i want into a txt file. I've used to try Watir with Ruby, however I would like to try C++ and...
Don't think of this in terms of logging into hotmail.com and clicking. Instead, think of it as retrieving email programmatically. Hotmail supports two standard protocols for this: POP3 and Exchange. If you're programming this on Windows, and since you tagged the question C#, I suggest using C# to access the Exchange...
6,313,669
6,313,679
Why is the i++ used in arrays
#include <iostream> int main() { int myArray[5]; // array of 5 integers lol int i; for (i=0; i<5; i++ ) // 0 - 4 { std::cout << "Value for myArray[" << i << " ]: "; std::cin >> myArray[i]; } for (i = 0; i<5; i++) std::cout << i << ": " << myArray[i] << std::endl; re...
Because if you don't execute i++ (or any other statement which increments i), i will remain 0, the condition i < 5 will always remain true and the loop will never end.
6,313,730
6,313,818
Does const-correctness give the compiler more room for optimization?
I know that it improves readability and makes the program less error-prone, but how much does it improve the performance? And on a side note, what's the major difference between a reference and a const pointer? I would assume they're stored in the memory differently, but how so?
[Edit: OK so this question is more subtle than I thought at first.] Declaring a pointer-to-const or reference-of-const never helps any compiler to optimize anything. (Although see the Update at the bottom of this answer.) The const declaration only indicates how an identifier will be used within the scope of its decla...
6,313,771
6,313,915
Why is there no <stlfwd> header and can the non-existence of it be considered a defect?
The standard library includes an <iosfwd> header, that (forward) declares all streams including any typedefs and defines the char_traits template, including the specializations. Sadly, there is no such <stlfwd> header that (forward) declares all the common STL datatypes and functions like vector, map, less, sort, etc. ...
What would be the purpose of forward declaring say less or sort or really any other algorithm? If you're passing a general purpose algorithm around it will almost certainly be as a template type and not need a forward declaration at all. That leaves us with the container types. There are definitely cases where forward ...
6,314,079
6,314,126
Why strange behavior with casting back pointer to the original class?
Assume that in my code I have to store a void* as data member and typecast it back to the original class pointer when needed. To test its reliability, I wrote a test program (linux ubuntu 4.4.1 g++ -04 -Wall) and I was shocked to see the behavior. struct A { int i; static int c; A () : i(c++) { cout<<"A() : i("<<...
Well, as the compiler warns you, you are violating the strict aliasing rule, which formally means that the results are undefined. You can eliminate the strict aliasing violation by using a function template for the increment: template<typename T> void advance_pointer_as(void*& p, int n = 1) { T* p_a(static_cast<T...
6,314,136
6,314,172
In C++, using luabind, call function defined in lua file?
Say I have a lua file: --functions.lua function testadd(a, b) return a+b end How would I use luabind to load that file, and call that function- something like: //test.cpp extern "C" { #include "lua.h" #include "lualib.h" #include "lauxlib.h" } #include <luabind/luabind.hpp> #include <luabind/function....
You probably want to call luaL_dofile instead of luaL_loadfile here.
6,314,320
6,314,382
Designing Javascript frontend <-> C++ backend communication
In my nearest future I will have to make a system with C++ backend and web frontend (requirements). At the moment, I don't know much more about it. I think that Frontend will be triggering data delivery, not backend - so no need for Comet-like things. Because of possibly little experience in this field, I'd really appr...
"All this asynchronization" is not something that Node.js works very hard to provide as an extra. It is a different view of Web serving that is easy as breathing once you understand how Node.js works. For example, my colleagues needed a way to wrap a C++ program as a web service, but the program had a significant start...
6,314,378
6,314,423
Want to run a program on some unknown system
I have been working on a VS 2005 project and have successfully generated an exe file which works fine on my system. However when I tried to run it on some other pc it didnt run. It throws up the error message "the system cannot run the specified program". Can someone tell me how to make my code immune to such message i...
I have seen before exe created on Windows Sp1 not working on SP2 and problems such as that. This should help you perhaps.
6,314,544
6,314,590
std::unordered_map undeclared identifier using Visual C++ 2008
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { unordered_map< int, string > m; m[1] = "one"; m[2] = "two"; m[4] = "four"; m[3] = "three"; m[2] = "TWO!"; cout << m[2] << endl; m.clear(); return 0; } I am learning and can't figu...
In Visual Studio 2008 the classes in Technical Report 1 (TR1) are in namespace std::tr1. Add: using namespace std::tr1; to your code.
6,314,718
6,314,743
How to get a vector iterator to point to a vector after vector.push_back() has caused reallocation?
I have a function void AddEntity(Entity* addtolist) that pushes elements back onto a vector but since the size and capacity are equal when the element is added to the vector, the vector reallocates and the iterator becomes invalid. Then when I try to increment the iterator I get a crash because of the invalid iterator,...
vector::push_back(const T& x); Adds a new element at the end of the vector, after its current last element. The content of this new element is initialized to a copy of x. This effectively increases the vector size by one, which causes a reallocation of the internal allocated storage if the vector size was equal to the...
6,314,830
6,314,881
Is STL a part of core of c++?
I have some confusing True and False questions I wish anyone answers them and prove the answer for me because I already did a search 1 - STL is a part of the core of c++ programming language 2 - std::string is a part of STL (I guess T) 3 - One purpose of the iterator is to connect containers and algorithms (I guess T)...
(1) and (2) both depend on your definitions. "The STL" is technically not part of standard C++, but sufficiently large portions of it were adapted into the original standard that the name stuck. But yes, the templated containers commonly reffered to as the STL are part of the official, standard C++ library. "Core" m...
6,315,040
6,315,115
Line-in jack sense with C/C++ in Ubuntu
This has probably been asked to death around here, but I could never get to a final solution (probably for good cause). Anyway, is there any way in Ubuntu (I use Ubuntu 11.04 with kernel 2.6.38-8) to detect if there is a headphone plugged in? Specifically, I'm searching for C/C++ solutions to poll my ALSA device to det...
The jack detection API is (here or here): snd_jack_new — Create a new jack snd_jack_set_parent — Set the parent device for a jack snd_jack_report — Report the current status of a jack
6,315,543
6,315,591
Build cpp application
I have a list of files (cpp, h, and also child-folders inside with cpp/h too). I'm not sure how to build it correctly because it doesn't have any makefile or smth like that (pure c++-files). So I decided to "catch" the right gcc arguments to build it. g++ *.cpp `wx-config --libs` `wx-config --cxxflags` -lGL -lglut -lfk...
The best thing to do would be to put in a little effort and actually create a set of Makefiles; a top-level one, and child Makefiles for the subdirectories. But if you want to use your same approach of just creating a command line, start by replacing your '*.cpp' with find . -name '*.cpp' so that it includes all the *....
6,315,551
6,315,798
Compiler error when creating a KeyBoard Hook
I am introducing myself to using Hooks in Win32 C++ (specifically KeyboardHooks) & I have an issue & a question. First off, I am trying to just create/declare a HHook object, but when I do Microsoft Visual C++ gives a compiler error saying: c:\users\soribo\desktop\c++ programming\visual c++ programming\testhhook\test...
You are using a case sensitive language. It is HHOOK, not HHook.
6,315,666
6,316,023
C++ get linux distribution name\version
According to the question " How to get Linux distribution name and version? ", to get the linux distro name and version, this works: lsb_release -a On my system, it shows the needed output: No LSB modules are available. Distributor ID: Ubuntu Description: Ubuntu 9.10 Release: 9.10 Codename: karmic Now, to get...
Got it from cplusplus.com forums, a simple call GetSystemOutput("/usr/bin/lsb_release -a") works. char* GetSystemOutput(char* cmd){ int buff_size = 32; char* buff = new char[buff_size]; char* ret = NULL; string str = ""; int fd[2]; int old_fd[3]; pipe(fd); old_fd[0] =...
6,315,863
6,315,907
Stack overflow (SIGSEGV) when calling static c++ class method
I've been looking into this problem for hours and tried all sorts of things, but everything results in the same - a SIGSEGV (from gdb; according to VC debug it's a stack overflow...) at the point when a static class method gets called. The culprit code: void LEHelper::copySinglePath (std::string from_path, std::string ...
You may well need to lower the size of your chunks, or alloc them on the heap. The call stack is very small, but the stack includes local variables. The Windows stack is, by default, only 1MB from memory whereas the Unix stack is 8MB. Allocating a 1MB array off this stack is instant overflow. You need to alter your lin...
6,315,923
6,316,202
OpenMP: nowait and reduction clauses on the same pragma
I am studying OpenMP, and came across the following example: #pragma omp parallel shared(n,a,b,c,d,sum) private(i) { #pragma omp for nowait for (i=0; i<n; i++) a[i] += b[i]; #pragma omp for nowait for (i=0; i<n; i++) c[i] += d[i]; #pragma omp barrier #pragma omp for nowait redu...
The nowaits in the second and last loop are somewhat redundant. The OpenMP spec mentions nowait before the end of the region so perhaps this can stay in. But the nowait before the second loop and the explicit barrier after it cancel each other out. Lastly, about the shared and private clauses. In your code, shared has...
6,316,007
6,321,199
how to use SSL in C++ gSOAP generated classes
i need to use gsoap library in C++ and i need to use https. documentation says how to work with HTTPS in C, but not in C++ (http://www.cs.fsu.edu/~engelen/soapdoc2.html#tth_sEc19.20). in particular, i have compulation error on soap_ssl_init(); function. i've looked /usr/lib/libgsoap* files and found ligsoapssl++.a file...
i've solved this trouble by myself. but it's quirky, very quirky way. gSOAP generates C++ classes inherited from struct soap, it contains following attrs: BIO *bio; SSL *ssl; SSL_CTX *ctx; unsigned short ssl_flags; const char *keyfile; const char *password; const char *dhfile; const char *cafile; const char *capath; co...
6,316,168
6,316,290
How ATL ActiveX control exposes a Boolean value to javascript
I am creating an ActiveX control using ATL and trying to expose a property taking a Boolean value. I implemented it as below: STDMETHOD(get_Visible)(VARIANT_BOOL *pVal); STDMETHOD(put_Visible)(VARIANT_BOOL newVal); In the JavaScript function, I call this by the following code: MyAxCtl.Visible = true; //MyAxCtl.Visible...
From the code you provider the STDMETHOD's are correct and the proper JavaScript call for a Boolean is to set it to true. While I don't see a case issue with the code you posted, make sure its "Visible" not "visisble". When you debug is the ActiveX call being entered?
6,316,329
6,316,702
Code for calculating the intersections between a line segment and a trimesh
I am looking for a good library (preferably in C/C++) that can calculate the intersections between a line segment (ray) and a trimesh. Thanks in advance for any answers!
CGAL is probably overkill, but I suggest it just for reference. The documentation is somewhat intimidating, but this chapter could be of interest for you.
6,316,407
6,316,479
FFMPEG reading keyframes
I am trying to write a c++ program that would read key frames from the video file using ffmpeg. So far I managed to get all the frames using av_read_frame where you sequentially read frame by frame. But I having some problems using av_seek_frame which (if I am correct) supposed to do the trick for keyframes. int av_s...
av_seek_frame has the ability to seek to a certain timestamp in a video file. It takes 4 parameters: a pointer to the AVFormatContext, a stream index, the timestamp to seek to and flags to select the direction and seeking mode. The function will then seek to the first key frame before the given timestamp. Check the doc...
6,316,661
6,318,321
typedef a template with all default arguments
I declare a templated class with all parameters having default arguments, for example: template<typename TYPE = int> class Foo {}; Then the following two are equivalent: Foo<int> one; Foo<> two; However, I'm not allowed to just do: Foo three; Is it possible to achieve that with a typedef to the same name but without...
If the declaration typedef Foo<> Foo; is allowed, thereafter the name Foo as a template cannot be specified. That is, the following becomes invalid. template< template< class > class > struct A {...}; A< Foo > a; // error Though the above typedef isn't allowed in practice, if you still need to write Foo as Foo<>, a ma...
6,316,697
6,960,525
gprof vs cachegrind profiles
While trying to optimize a code, I'm a bit puzzled by differences in profiles produced by kcachegrdind and gprof. Specifically, if I use gprof (compiling with the -pg switch, etc), I have this: Flat profile: Each sample counts as 0.01 seconds. % cumulative self self total time seco...
You are looking at the wrong column. You have to look at the second column in kcachegrind output, the one named "self". This is the time spent by the particular subroutine only without considering its children. The first column has the cumulative time (it is equal to 100% of machine time for the main) and it is not tha...
6,316,751
6,316,785
How to invoke pointer to member function when it's a class data member?
struct B { void (B::*pf)(int, int); // data member B () : pf(&B::foo) {} void foo (int i, int j) { cout<<"foo(int, int)\n"; } // target method }; int main () { B obj; // how to call foo() using obj.pf ? } In above test code, pf is a data member of B. What's the grammar rule to invoke it ? It should be stra...
Like this: (obj.*obj.pf)(0, 1); Member access (.) has a higher precedence than a pointer to member operator so this is equivalent to: (obj.*(obj.pf))(0, 1); Because function call also has higher precedence than a pointer to member operator, you can't do: obj.*obj.pf(0, 1) /* or */ obj.*(obj.pf)(0, 1) As that would b...
6,316,790
6,316,874
Virtual constructors
I was wondering what is the meaning of a virtual constructor and how would it be used. In addition I know that C++ does not allow for a virtual constructor, and I was wondering why.
C++ does not allow virtual constructors because you need an object to invoke a virtual method in the first place! The term virtual constructor is used for for idiom and a well-known design pattern. This idiom/pattern involves the definition of factory: an intermediate object with a virtual method who's role is to crea...
6,316,804
6,316,842
Unhandled exception in Visual Studio 2008
I finished writing the program in C++. I used 'cout' for debugging. Everything was working, I deleted the debug comments, but there is a problem with running the program. When I use comments, everything works well. But when I delete them, the program starts, allows me to write file name, but when I press 'enter', the e...
The value 0xcccccc70 looks like the program uses an offset from an uninitialized pointer. In debug mode memory is filled with 0xcccccccc to make this more visible.
6,316,955
6,316,988
C++ overload resolution
I want to use inheritance to have an object treated in a different way depending on where in the hierarchy it falls (similar to this C# question) Assume you build a hierarchy of Shape objects like: class Shape {} ; class Sphere : public Shape {} ; class Triangle : public Shape {} ; ... You then equip a Ray class with ...
You have to do it the other way around. Overload resolution takes place at compile-time, when the type of what you're calling it with is a Shape*.
6,317,058
6,317,360
How to design function interfaces that can deal with varied number of arguments or having any combination of argument types?
Occasionaly I find that I need a generic "pass through"-interface. For example for mix-in classes that forward their constructor arguments to the parent. Or for factory methods that forward their arguments to new: template<typename C> C * Create(); template<typename C, typename Arg0> C * Create(Arg0 & a); template<t...
It's no big deal, really. You pass by reference to const, and where a reference to non-const is to be passed you require the caller to write ref(x). And instead of definining umpteen versions you define a supporting ArgPack template once and for all. Or, use C++0x purrfect führwarding. Cheers & hth.,
6,317,309
6,317,444
Do I _have to_ use a pointer here?
I've run into this problem time & again, and I've always had to resolve it using a forward declaration and a pointer. It seems wrong that C++ requires a work around to get objects to co-operate. Is there any way to get this to compile WITHOUT making Mesh* a pointer in class Shape (or, the vector<Tri> into vector<Tri*>...
It works for me without a pointer (there are, naturally, pointers used inside std::vector). You just have to analyze your dependencies carefully. Triangle inherits Shape, therefore Shape's definition is above Triangle's. Shape contains a Mesh, therefore Mesh's definition precedes Shape's. This gives the order: Mesh...
6,317,395
6,317,434
Compiling and Running MFC Applications with Visual Studio 2008?
I was wondering if anyone can provide a detailed explanation on how I can compile and execute a C++ MFC application in Visual Studio 2008 given that I already have a .h and .cpp file only. I couldn't find a decent and up to date explanation anywhere and when I try to create a plain MFC project in VS08 I get a bunch of...
See here: Creating an MFC Application This tutorial may help you as well: Introduction to MFC Applications
6,317,515
6,317,525
c++ Function Argument Editing
i'm making a memory allocation/deallocation function it's simple inline void safedealloc ( void *mem ) { if ( mem ) { free( mem ); mem = NULL; } } it's working fine .. however after using it few times with a program i noticed that when calling it in something like safedealloc( (char *)name ); safedealloc( (...
It almost certainly is not working fine, it is pointless, and in C++ the way you allocate memory is with new and delete, not malloc and free. There is no need to check for a NULL pointer - free (NULL ) is well defined in both C and C++. And your assignment of NULL to the function parameter does nothing - it only modifi...
6,317,579
6,317,604
Visual Express vs. Visual Studio
I am planning to design a video game by myself as a hobby. I probably sound like some overconfident idiot, but I am a C++ programmer for a living, and I believe I have the patience, time, and skills to do this. However, my company does not allow us to use their license of Visual Studio for anything other than work, and...
VS Express is designed for the hobby developer. You can program the same software in Express the difference is in the tooling that makes you more productive and allows you to work as part of a team. For a comparison of the editions see: http://www.microsoft.com/visualstudio/en-us/products/2010-editions You should be fi...
6,317,683
6,317,731
C++ STL map: insert is storing null pointers
I have a simple class class symbol_entry { private: static unsigned long uid; public: std::string name; std::string filename; unsigned int line_number; unsigned int column_number; symbol_entry* parent_symbol; std::map<const char*,symbol_entry*> child_symbols; unsigned long type_flag...
child_symbols[child->name.c_str()] will always create and return a new map entry (a NULL one), and then child_symbols.insert(...) doesn't do anything (so the value in the map stays NULL). The correct way to check whether the key is already in the map is to use find: if (child_symbols.find(...) != child_symbols.end()) /...
6,317,748
6,317,766
improvements/changes in pointers with time?
perhaps, pointers have been on a course of modification regular pointers to auto_ptr to unique_ptr and shared_ptr I just wanted to know that the new types of pointers that have been developed completely overtake over the older versions(OR the versions of the pointers that you may consider having memory leak problems)...
Raw pointers are still useful if you don't own the object it points at. auto_ptr is officially deprecated (so yes, it's pretty much dead for new code). VS2008 provides shared_ptr though as part of TR1, and there's always Boost. I don't see any need for any other smart pointers in my C++ life right now.
6,317,796
6,317,837
ctor init not calling the global ctor instances in library
I'm developing an application and a library using SourceryGpp lite for arm. I'm not using standard libs or default start files. So to call the global ctrs i'm doing to following code: ldr r0,=__ctors_init__ ldr r0,[r0] mov lr,pc bx r0 So the problem is that I'm defining some global instances in the static library, but...
This is a well known problem with static libraries and global variables with runtime initialization. Most linkers will only include components of the static library that are needed to fulfill a dependency of the main program. If none of the objects in the compilation unit are used, the linker removes never adds the co...
6,317,917
6,323,133
What is the periodicity of the PRNG in GNU C Library?
Is there any literature available on the periodicity of the random number generator in gcc's g++ (if we don't re-seed the function)? I suppose I could run tests myself, but it would be better to have access to well-verified research. Thanks in advance for your help. // EDIT I just wanted to add that I have searched qu...
When searching in the rand(3) man page, I found this: The versions of rand() and srand() in the Linux C Library use the same random number generator as random() and srandom() so I had a look at the random(3) man page, and here is your answer: The period of this random number generator is very large, appr...
6,318,033
6,318,500
C++ Heterogenous Dictionary
I'm new to C++ and I recently found out that we can initialize a collection of strings by using the following code: map <string,string> myArray; myArray["key1"] = "value1"; myArray["key2"] = "value2"; cout<<myArray["key1"]<<endl; //result: value1 But what if I have to assign to key2 not a string but another collectio...
As the questioner seems to have accepted one of the answers, this is just a supplement. If Boost is allowed, Boost.Variant might meet the purpose. For example, the following code prints bar as in the question. #include <boost/variant.hpp> #include <map> #include <string> #include <iostream> int main() { using namesp...
6,318,051
6,318,089
boost and single-threaded event-driven model
Boost does not provide single-threaded event-driven model, such that was widespread on Unix before pthreads -- mainloop + "callbacks", does it ? For example, if I wanted to use boost::message_queue in single-threaded app, and mix it with timers and other asynchronous events (mainloop), then boost does not support it, a...
I'd look at Boost::Signals (you can use them precisely as you wish) Boost::Asio (most importantly: strands). Strands will let you have your cake and eat it too (by having single threaded semantics while still enabling parallel work, on another 'single thread apartment' if you allow my COM-infected pun). This is right...
6,318,077
6,318,282
Read perl script from c++
I've to read and parse HTML file and populate a data structure (in C++). I'm planning to do the parsing using perl (so I can use some other perl modules.). My requirement is this. Get the file from gui (C++ code) Pass it to perl. Parse file on perl side (perl script using some other perl modules), populate the C++ str...
In your reading did you find perlembed in Perl's documentation? That's the definitive resource for learning how to embed Perl in a C/C++ program. The author of the document was one of the original mod_perl developers, I believe. I don't think that embedding Perl for a trivial task would be the easiest solution when c...
6,318,435
6,318,470
problem in peterson's lock in shared memory
I have implemented peterson' algorithm for mutual exclusion in shared memory. I am using shared memory between a c++ and a java process(using jni) for communication. The problem is that I am still seeing a race condition somehow. If I try to debug it using printf/println, the code starts running fine, but as soon as I ...
To implement the algorithm properly you must use barriers to ensure that the memory is read/written in the order you specify in the code. Read the second paragraph from here: Most modern CPUs reorder memory accesses to improve execution efficiency (see memory ordering for types of reordering allowed). Such processors ...
6,318,447
6,318,458
How to view .dmp file on Windows 7?
I have created a "minidump" file using the Visual Studio 2008 C++ debugger (Debug menu -> Save dump as...). I am running on Windows 7, 64-bit. What program can I run to view the contents of the dump file in a meaningful way?
What information are you trying to get out of it? WinDbg is my tool of choice. It's part of the Windows SDK. You can get download links from here: http://www.windbg.org/ Note that there are three plaforms for it - x86, x64, and IA64. You want the version based on what the application is designed for, not your architect...
6,318,721
6,318,730
Make implementation of virtuals also virtual?
When implementing a pure virtual function in C++, is there a best-practices guideline that says the implementation should also be made virtual? What is the rationale? class Interface { public: virtual void foobar() = 0; }; class Concrete : public Interface { public: virtual void foobar(); };
It does not matter. void foobar() in Concrete is virtual regardless whether you declare it as such and it overrides the void foobar() in Interface.
6,318,765
6,318,801
Help with String Arrays C++
#include <iostream> #include <string.h> using namespace std; int main() { char firstname[] = "Alfred"; char middlename [] = "E"; char lastname[] = "Neuman"; char fullname [80]; int offset=0; strcpy(fullname,firstname); offset = strlen(firstname); strcpy(fullname+offset," "); offset +=1; strcpy(full...
That's because you're using the wrong tools. std::string firstname = "Alfred"; std::string middlename = "E"; std::string lastname = "Numan"; std::string fullname = firstname + " " + middlename + " . " + lastname; The offset is used to track the current position of the string in the array so that you can strcpy the new...
6,318,921
6,323,396
How to play sound at the same time as the program?
I want to play sound while the program is running in c++. I am using the code: void fighterplanesound() {PlaySound(TEXT("bombdrop.wav"), NULL, SND_FILENAME|SND_ASYNC);} I thought the SND_ASYNC flag would fix this problem but it did not. What is happening is the program will pause or control will not move on until th...
Ok. What I figured out was that you can't include the PlaySound method in the function because even though the ASYNC flag was there, control had to fully execute the PlaySound method before returning, so don't put it in the function unless there is more code in the function(in which case the sound will play while that ...
6,318,962
6,318,977
Why doesn't whitespace act as a delimiter when printing strings with ostream operator<<?
I know that when writing code like std::cin >> some_var; , where some_var is a string variable, only the first word that was inputted will be stored in some_var. But I do not understand why std::cout << "something here"; does not only output "something". Am I missing something?
When reading input using cin >> some_var, the delimiter is space by default (you can change this though), while when printing, cout prints till its find \0 which is end of the string. If you want to read till it finds \0 in the input stream, then you've to write this: std::getline(std::cin, some_var, '\0'); You can g...
6,319,149
6,319,304
Performance of Dijkstra's algorithm implementation
Below is an implementation of Dijkstra's algorithm I wrote from the pseudocode in the Wikipedia article. For a graph with about 40 000 nodes and 80 000 edges, it takes 3 or 4 minutes to run. Is that anything like the right order of magnitude? If not, what's wrong with my implementation? struct DijkstraVertex { int...
There are several things you can improve on this: implementing the priority queue with sort and erase adds a factor of |E| to the runtime - use the heap functions of the STL to get a log(N) insertion and removal into the queue. do not put all the nodes in the queue at once but only those where you have discovered a pa...
6,319,325
6,319,339
Where is the std equivalent of boost::shared_polymorphic_downcast in C++11?
boost::shared_polymorphic_downcast and the other boost::shared_ptr functions reside in <boost/shared_ptr.hpp> I recently enabled support for C++11 in GCC with -std=c++0x. In order to avoid confusion, I moved from boost::shared_ptr to std::shared_ptr which resides in #include <memory>. However it appears that shared_pol...
You either need std::static_pointer_cast or std::dynamic_pointer_cast, depending on whether you want static_cast or dynamic_cast behavior. Recent versions of Boost's Smart Pointers library include these functions for boost::shared_ptr too.