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,589,474
6,689,589
Service a live OpenCV H.264 stream through Live555 on Windows
Totally new to this! As the title says, I'm trying to serve a stream from OpenCV through Live555 using H.264 that is captured from a webcam. I've tried something like: #define LOCALADDRESS "rtsp://localhost:8081" // Address media is served #define FOURCCCODEC CV_FOURCC('H','2','6','4') // H.264 codec #define FPS 2...
There really isn't a straight-forward way I know of; certainly nothing that will happen in anything less than a few hundred lines of code. I'm assuming you want to use an on-demand RTSP server (this is where the server's just sitting there, waiting for a client to connect, and then it starts streaming when the client e...
6,589,878
6,604,030
2 Identical Programs; Only 1 asks for elevation
I am having an interesting problem when compiling my programs on win32 (mingw). I have 2 identical projects, both created in C::B. When compiling one, it runs just fine without requiring elevated permissions, but the other prompts the user with the "Allow program to make changes to computer etc.." dialog. I would like ...
It turns out Win7 marks files with "update" (not case sensitive) in the name as needing elevated permissions. So yea, worth knowing for future
6,589,946
6,590,027
What does the C++ standard say about stack overflow?
I took a look at the draft C++0x standard, and as far as I can tell there is nothing about stack overflow in there. Searching for "stack overflow" yields no results, and searching for "stack" I've only gotten references to stack unwinding and std::stack. Does that mean that there cannot be a conforming implementation o...
I'm not sure if this is what you're looking for, but in Appendix B of the C++03 ISO standard there's the following notice: Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where k...
6,590,178
6,590,358
Google Mock: "no appropriate default constructor available"?
Using Visual Studio 2010 C++ with googlemock. I'm trying to use a mock I created and I'm getting the compiler error on the line: EmployeeFake employeeStub; The error is: 1>c:\someclasstests.cpp(22): error C2512: 'MyNamespace::EmployeeFake' : no appropriate default constructor available EmployeeFake: class EmployeeFa...
You can just add a constructor to your mock that delegates to the Employee constructor: class MockEmployee : public Employee { public: MockEmployee(PensionPlan* pension_plan, const char* full_name) : Employee(pension_plan, full_name) {} // ... }; Then construct MockEmployee like you w...
6,590,215
6,590,351
accessing static members using boost lambda
I am trying to write some simple predicate using boost::lambda and I am getting tons of errors. I checked the documentation and I have some doubt on accessing the static variable std::string::npos in a lambda expression. Below my code. #include <boost/lambda/lambda.hpp> #include <boost/lambda/core.hpp> #inc...
Accessing a static variable can be done using simply one of the following boost::constant( std::string::npos ) boost::var( std::string::npos ) Depending on the input parameter signature also boost::constant_ref.
6,590,426
6,590,457
Do I pay for default construction here and if so can I avoid it
In the case where T is expensive to construct I'd like to know if I pay for default construction in the following case (I think I do) std::function< T() > make_t; std::vector< T > t( 100000 ); std::generate( t.begin(), t.end(), make_T ); If I do have to pay for it can I avoid it? I wanted to write something like std:...
std::function< T() > make_t; std::vector< T > t; int const count = 100000; t.reserve( count ); std::generate_n( std::back_inserter(t), count, make_T ); std::back_inserter is in <iterator>.
6,590,463
6,592,103
How to move an element without removing and re-inserting it into a boost::multi_index_container?
I'm using a boost::multi_index_container to provide a random access and a hash-based access to a collection of elements. I wanted to change the random access index of an element, without changing the hash-based index. Here is a piece of code : # include <string> # include <boost/multi_index_container.hpp> # include <bo...
Use relocate: http://www.boost.org/libs/multi_index/doc/reference/rnd_indices.html#rearrange_operations
6,590,581
6,590,615
member function alternative names
I am trying to create alternative names for the function call numberedFunction when it has certain values as below template< typename T > class X { public: X() : single( std::bind( &X::numberedFunction, *this, 1 ) ), halfDozen( std::bind( &X::numberedFunction, *this, 6 ) ) { ... } T numberedFu...
const std::function< T() >& single; const std::function< T() >& halfDozen; Your members are references to const, but you are initializing them from a temporary in the constructor (assuming the bind expressions in your real code aren't nonsensical). As soon as the construction is done they are invalid. Is this really w...
6,590,683
6,591,428
boost::asio UDP how to receive messages on Windows?
I have two classes UDPSender and UDPReceiver. Senarios: (1)It works when I run UDPSender in QNX and UDPReceiver in Linux. (2)It doesn't work when I run UDPSender in QNX and UDPReceiver in WindowsXP.(But I see UDP datagrams using Wireshark, meaning Sender is working as in Senario(1)) (3)It partially works in Windows. ...
It's probably being blocked by the Windows Firewall.
6,590,686
6,590,769
Strong Pointer causing a heap corruption on application closing when std::vector is present
I am getting a strange heap corruption error during the application close where if a "std::vector" is present in my code, AND I am deleted my "ref_count" variable. If I don't have an std::vector, there is no crash. If there is a std::vector and I don't delete the ref_count (causing a memory leak), then there is a heap ...
This line: strong_ref<int> reg1; sets *ref_count to 0 (because ptr == NULL), then this line: strong_ref<int> copy1(reg1); increments *ref_count to 1. On exit, the destructor is called twice (once for reg1, once for copy1). The first time, *ref_count is decremented to 0 and ref_count is deallocated, leaving a dangling...
6,590,778
6,590,856
timer outside of a class
I have the following code and I wanted to create a class that encapsulates the timer but the trouble I'm having is using the timer after declaring the class. I posted another block of code to show an example of how I want to use the timer. double diffclock(clock_t clock1,clock_t clock2) { double diffticks=clock1-c...
The way you have your class set up doesn't really make sense. I have a simple timer class that works like this: Timer MyTimer; // Do stuff... std::cout << "Execution took " << MyTimer.Seconds() << " seconds." << std::endl; Is this what you're looking for? If so, my class is set up like the following: class Timer {...
6,590,820
6,590,878
Making sense of where "const" goes in a declaration
I am having trouble finding an intuitive pattern for the way const is used in declarations in the C and C++ languages. Here are some examples: const int a; //Const integer int const a; //Const integer const int * a; //Pointer to constant integer int * const a; //Const pointer to an integer int const * a const;...
The compiler generally reads the type from right-to-left, so: T const& const Would be read as: const (a constant) & (to a reference) const (to a constant) T (of type T) So, basically the keyword "const" modifies everything that precedes it. However, there is an exception in the case where "const" comes first, in ...
6,590,832
6,658,892
Set background color of entire window in PDCurses
wattron and a color pair only sets the background color of text when it is printed inside a window. What is the best way to set the background color of the entire window without filling it with spaces (i.e. a title or status bar)?
A call to wbkgd with a pointer to a WINDOW object and a color pair sets the background color of the window.
6,590,939
6,619,994
How to set Display Settings to EXTEND mode in Windows 7 using C++?
In my C++ Win32 program I want to set the current Display Settings to "Extend" mode. I Googled and found out that SetDisplayConfig() is the way to go forward in Windows 7 (I'm on Windows 7) but now I am kind of stuck how to proceed as the MSDN explanation (link here) is pretty confusing. I am very much new to C++ and A...
Okay so I figured out the answer. To identify the current configuration: UINT32 PathArraySize = 0; UINT32 ModeArraySize = 0; DISPLAYCONFIG_PATH_INFO* PathArray; DISPLAYCONFIG_MODE_INFO* ModeArray; DISPLAYCONFIG_TOPOLOGY_ID CurrentTopology; GetDisplayConfigBufferSizes(QDC_ALL_PATHS, &PathArraySize, &ModeArraySize); Pa...
6,591,096
6,591,884
Anderson tree problem
Thought I'd use an Anderson tree for something. So I started porting to C++ the Julienne Walker version found here: http://www.eternallyconfuzzled.com/tuts/datastructures/jsw_tut_andersson.aspx Now I have insertions working. But the problem is if I compile with optimisations it crashes. Even -O1 crashes it. template...
Your make_node function claims to return a value, but contains no return statement.
6,591,130
6,591,274
Building custom boost librares
Isn't there an easy way to select the source files and build them with all multithreading options (/MT, /MTd, /MD, /MDd) for MSVC v.8? I've seen this command, C:\Program Files\boost\boost_1_46_1> bjam ^ More? --build-dir="C:\Documents and Settings\dave\build-boost" ^ More? --build-type=complete msvc stage from MSVC Co...
Further down on the page you quote from: In particular, to limit the amount of time spent building, you may be interested in: reviewing the list of library names with --show-libraries limiting which libraries get built with the --with-library-name or --without-library-name options choosing a specific build varia...
6,591,306
6,591,467
Qt push button event using Qt Designer not working: "No such slot QApplication"
I've read several articles about push button events in Qt but none seem to solve my problem. I have a simple GUI built with Qt Designer which only contains one button. The run-time error I get is the following: Object::connect: No such slot QApplication::FullSizeR() in CameraWindow.h:25 Object::connect: (sender name: ...
connect(widget.FullSize,SIGNAL(clicked()), qApp, SLOT(FullSizeR())); The error message says it all: qApp doesn't have the slot. You need this: connect(widget.FullSize, SIGNAL(clicked()), this, SLOT(FullSizeR()));
6,591,397
6,591,529
TCP between Windows .NET program in C# to Linux program in C++
I am new to the topic of computer networking and sending data to one computer to another. Currently I am tasked with integrating a C# Kinect SDK program with a Linux C++ Opengl/Covise program. The C++ program is to then receive and make use of the output generated by the Kinect. Is it possible to have them communicate ...
I new to the topic of computer networking and sending data to one computer to another. Currently I am tasked with integrating a C# Kinect SDK program with a Linux C++ Opengl/Covise program. Cool, congrats on learning new stuff. Is it possible to have them communicate to one another via TCP, UDP, or anything despite...
6,591,859
6,591,952
When does the vptr (pointing to vtable) get initialized for a polymorphic class?
This is not about "When VTABLE is created?". Rather, when the VPTR should be initialized? Is it at the beginning/end of the constructor or before/after the constructor? A::A () : i(0), j(0) -->> here ? { -->> here ? //... -->> here ? }
The machinery for virtual calls (usually a v-table, but doesn't need to be) is set up during the ctor-initializer, after construction of base subobjects and before construction of members. Section [class.base.init] decrees: Member functions (including virtual member functions, 10.3) can be called for an object under ...
6,591,996
6,592,026
Freelibrary using remote thread
In the book Windows via C/C++, Part IV , Chapter 22 - Injecting a Dll Using Remote Thread. In the function BOOL WINAPI EjectLibW(DWORD dwProcessId, PCWSTR pszLibFile), the code: hThread = CreateRemoteThread(hProcess, NULL, 0, pfnThreadRtn, me.modBaseAddr, 0, NULL); My Question: Why the 5th param is not me.hMod...
This is a typo, but still works because HINSTANCEs/HMODULEs are now simply a pointer to the address where the DLL is mapped in the process's VA space. Also, please don't inject threads into arbitrary processes, it is very tricky to get right in the general case.
6,592,287
6,592,379
Volatile and multithreading: is the following thread-safe?
Assume there are two threads running Thread1() and Thread2() respectively. The thread 1 just sets a global flag to tell thread 2 to quit and thread 2 periodically checks if it should quit. volatile bool is_terminate = false; void Thread1() { is_terminate = true; } void Thread2() { while (!is_terminate) { ...
It is probably sort of thread-safe. Thread safety tends to depend on context. Updating a bool is always thread safe, if you never read from it. And if you do read from it, then the answer depends on when you read from it, and what that read signifies. On some CPUs, but not all, writes to an object of type bool will b...
6,592,665
6,592,702
vector< pair<aStruct*,int> > not possible?
So I tried to make a vector which elements are pairs of a struct pointer and an int, and I'm beginning to think that this may be impossible.. Suppose I have the following struct: struct node{ string str; int size; node *child[3]; node(string str1):str(str1){ size = 0;} }; and a vector: vector< pair<node*,int> ...
nodevector.push_back(pair<node*,int>(nod1, 3));
6,592,835
6,593,511
Can new throws in a case of heap corruption?
In a case of a heap corruption, can new throw? If I understand it correctly, in a case of a heap corruption, all bets are off, and anything can happen. Is this correct?
( Moved from a comment to an answer at Als' suggestion, and extended for better or worse :-) ) A corrupted heap invalidates any behavioural expectations you may have of the program. Crucially, throwing an exception implies some reliable programmatic handling is possible, but no implementation detecting heap corruption ...
6,593,003
6,594,063
How can I reliably check whether one Windows process is the parent of another in C++?
I'm working on a function which gets me the PID of the parent process for a given PID. The prototype of the function is DWORD getParentPid( DWORD pid ); To do so, I'm using the CreateToolhelp32Snapshot function (and related functions) to get the PROCESSENTRY32 structure for my given PID pid. I can then use the th32Par...
The sample here: http://msdn.microsoft.com/en-us/library/ms686701(v=vs.85).aspx Shows calling CreateToolhelp32Snapshot with a parameter of 0 for the processId and it uses the option TH32CS_SNAPPROCESS which says it captures all processes. Then, once you've got the snapshot, as in the sample you can walk the processes a...
6,593,117
6,593,139
How could I prohibit use of "new" in certain parts of C++ code?
Is it possible to prevent new from being used at certain points in the code? The legacy code that I am developing with has a requirement that there is no dynamic memory allocation after the bootstrap has completed. We now want to test this. If I was starting the development from scratch then I could write my own wrappe...
No, you can't "overload" global new - only replace it. However in your replacement you can check for a global flag meaning "new allowed" (and throw an exception if that flag is not set) and change that flag from inside calling code. This won't help against overloaded operator new in classes unless you change each overl...
6,593,390
6,593,413
How can i update QMenu and sub menu title text ‘s dynamically
i have QMenu that holds sub menu i like to be able to update each menu title string dynamccly for example i have this menu [main menu ] Groups 2 [sub menu] group_X 3 [sub menu] group_Y 1 i like to be able to change only the numbers part of the string in each menu entry from my application which appr...
Set the title menu -> setTitle (tr ("Number %1") .arg (123));
6,593,392
6,594,946
C++ Libraries on iPhone/Android: Generation of Wrapper classes
I have the following question: Let's assume I have many different C++ libraries(algorithms), which are written in the same style . (They need some inputs and give back some outputs). I've done some research and wanted to ask if its possible to auto-generate Wrapper classes (by using an algorithm which are given the inp...
You'll want to look at SWIG. This generates bindings for other languages from a C based API. Objective-C support is in there as is Java. I'm not sure what happened to objective-C support in the later versions, but its in v1.1 and you can see the branch where it was added.
6,593,658
6,594,107
C++ Templating vs Inheritance
I just realize how hard asking questions can be... Hopefully I can give examples that are both, sufficiently precise to demonstrate my problem and short enough not to mess everything up... At least there's the possibility to edit. So this is kind of my situation at the moment. Of course I altered it a bit in terms of l...
It's better to go with the first option. It's cleaner and maintainable. Because from your comments, I am making out that you are making a wrong assumption for the 2nd option: // The ExtractorBase has a virtual method // template<T> void extract(const string& source, vector<T>* myType) = 0; NO. That's not possible; a t...
6,593,770
54,381,239
Creating a non-thread safe shared_ptr
I'm working on a mult-threaded program, but have a UI component that makes extensive use of std::shared_ptr to manage elements. I can guarantee that only one thread will ever use these shared_ptrs. Is there a way to define a shared_ptr that doesn't incur the overhead of thread safe reference counting? It could be based...
Now adding this as the accepted answer. Boost local_shared_ptr is a single thread reference counted smart pointer that uses non-atomic operations for speed: https://www.boost.org/doc/libs/1_65_0/libs/smart_ptr/doc/html/smart_ptr.html#local_shared_ptr
6,593,821
6,594,440
Type inference for `T::some_typredef` in Templated Function
Given a template function, that does not use the template parameter for input directly. How would C++ type inference work? For instance given template<typename T> void f(T::value_type){} when (if at all) will type inference work for this function? Is there any other place except of template<typename T1,...>void f(T1,T...
I think here's your answer: 14.8.2.4 - Deducing template arguments from a type [temp.deduct.type] [...] -3- [...] In most cases, the types, templates, and non-type values that are used to compose P participate in template argument deduction. That is, they may be used to determine the value of a template argument, and ...
6,594,146
6,595,247
How to create main.cpp when using Qt designer?
I am new to Qt, and I use QT 4.4.3 on Linux. When I design a new Qt GUI with Qt Designer, is there a way to make it create main.cpp automatically, or do I have to manually create a file and manually add it to the Makefile created by qmake?
The output of QT Designer is a GUI element, essentially a subclass of QWidget. It will not generate a main function for you (the entry point for the C runtime to locate). You'll have to write your own where you create a QApplication, and then instantiate and show the main window widget. For example, when using Qt Creat...
6,594,214
6,594,519
glGetIntegerv returning garbage value
#include<iostream> #include"Glew\glew.h" #include"freeGlut\freeglut.h" using namespace std; int main(int argc, char* argv[]) { GLint ExtensionCount; glGetIntegerv(GL_NUM_EXTENSIONS, &ExtensionCount); cout << ExtensionCount << endl; return 0; } The output of this program is, -858993460. Why? It shoul...
@mario & @Banthar yes, thanks. I have to create a context first to use the any Opengl functionality.(yes, even for Opengl 1.1 which comes default with windows.) glGetIntegerv is not returning garbage. glGetIntegerv returns either a good value, or it does not touch the pointed to address at all. The reason why you see g...
6,594,556
6,594,623
ostream operator overloading for unsigned char in C++
Given: typedef struct { char val[SOME_FIXED_SIZE]; } AString; typedef struct { unsigned char val[SOME_FIXED_SIZE]; } BString; I want to add ostream operator << available for AString and BString. std::ostream & operator<<(std::ostream &out, const AString &str) { out.write(str.val, SOME_FIXED_SIZE); return out; ...
The simplest and cleanest solution is to create an std::string, e.g.: out << std::string(str.val, str.val + sizeof(str.val)); However, the question is: do you want formatted or unformatted output? For unformatted output, as ugly as it is, I'd just use a reinterpret_cast.
6,594,796
6,595,001
How do I make CMake output into a 'bin' dir?
I'm currently constructing a project with a plugin structure. I'm using CMake to compile the project. The plugins are compiled in separate directories. My problem is that CMake compiles and saves the binaries and plugins, dynamic libraries, in the directory structure of the source. How do I make CMake save the files in...
As in Oleg's answer, I believe the correct variable to set is CMAKE_RUNTIME_OUTPUT_DIRECTORY. We use the following in our root CMakeLists.txt: set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bi...
6,595,004
6,595,219
stringstream conversion error
I had ever used the following code snippet in one class. Today, I copied it to another class. When compiling, I got the following errors. It is strange that such a thing has actually happened! Would you please tell what's the matter? Thank you. I've just been using the following snippet code to do a test in a demo proj...
What compiler are you using? Your code snippet compiles fine with VC10 on my box. Did you forget to include all the proper header files? For this piece of code you need these 3 headers: #include <string> #include <sstream> #include <iterator> Since VC10, <iterator> is not implicitly included by others. You need to inc...
6,595,132
6,597,184
Best way to convert/port other platform games developed in other languages like C++ etc in iphone?
In order to port games in to iphone, I dont thing complete Objective C coding is required. As I have seen most popular games which were on other devices or on other platform. Now converting exactly to iphone. Is it there any tool for it ?
There are a few different tools out there that allow you to develop once and deploy to multiple platforms. Some of these are full engines, like UDK, Torque, and the aforementioned Unity. There are also tools like PhoneGap and Adobe Air, which allow you to develop using web technologies, and then convert to mobile app...
6,595,163
6,595,198
C++ STL wrong keys types
can't understand this: g++ compiler is angry on: lengths.insert(pair<Deux,long>(d,one)); where struct Deux {long big; long small}; map<Deux, long> lengths; Deux d; long one; so, g++ said, that i miss operator<. after making overloaded operator< for struct Deux, i saw new interesting, but the same error: map <long, No...
The compiler complains that there is no operator < for Deux (I guess). The key must be a comparable class with operator < or you must pass a third template parameter to map - the comparator. You see, the map keeps its keys in an ordered way. In order to order them, it needs a predicate. By default it tries to use opera...
6,595,238
7,417,820
static_assert not working in Visual C++ 10
I was under impression Visual C++ 10 had built-in static_assert. However when I compile the following void test() { static_assert( sizeof( char ) == 1, "" ); } I get error C3861: 'static_assert': identifier not found What am I doing wrong and how do I use static_assert in Visual C++ 10?
The reason was Visual Studio was set up to use Visual C++ 9 compiler (the one which is shipped with Visual Studio 2008). I don't know how it happened, perhaps the wizard configuring Visual Studio imported paths to the previous version. The settings is changed in project properties - on "VC++ Directories" pane. The easy...
6,595,272
8,129,374
Is there a downloadable distribution of Thrift for Windows?
I've been reading quite a bit about Thrift and it looks like a technology I'd really like to use. I'm having all sorts of trouble building the Windows distribution. I know a patch exists to build a Windows version, however I have not had much luck with this either. Does anyone know of a pre-built distribution for Windo...
Thrift 0.8 now has VS projects for both the compiler and C++ library. Get the snapshot release or the latest off of SVN http://thrift.apache.org/download/ Edit: 0.8 has been officially released and the source is available as a tarball on the download page. Edit2: The SVN trunk now has a cross-platform sample project u...
6,595,323
6,595,488
Tell windows to process all but one message
I have a function triggered by a message(WM_ONDATA defined by me) the function will execute this code : MSG msg; while(::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if( !AfxGetApp()->PumpMessage() ) { ::PostQuitMessage(0); return 0; } } return 1; The problem is that there could be o...
You could get the window proc to ignore the message or to queue it's execution. If you're just looking to avoid recursion, have a reentrance lock class MyDlg : ... { MyDlg(...) : m_inOnData(false), ... { .... } ... private: BOOL m_inOnData; }; .... void MyDlg::OnOnData(...) { if...
6,595,341
6,595,411
C++ passing a pointer to static function changes value during execution
Here is my code Node* Node::createNode(int n) { Node newNode(n); Node *temp = &newNode; return temp; } void Node::printNode(Node* node) { cout << node->data << "\t" << node->next << endl; system("pause"); } Here is the main function int main(int argc, char* argv[]) { Node *head = Node::create...
You're returning a pointer to a local variable. When you later use that pointer in the main function, the variable it pointed to is long gone and you enter the realm of undefined behavior. You could just return the node by value: Node Node::createNode(int n) { Node newNode(n); return newNode; } Or you could al...
6,595,523
6,595,668
C++ screen partition
I want to partition the output screen into two parts (just like frames do it in HTML). So that one part may remain fixed and display some content which is updated based on input received from the other part. I do not wish to venture into GUI stuff therefore OpenGL, SDL etc are ruled out (I wish to do it in command line...
You may want to take a look at curses-like libraries like PDCurses. Other than that, you may use ANSI terminal escape sequences to control the cursor on a text window, this may be quicker if what you are doing is simple, otherwise use PDCurses and it will handle the escape sequences for you.
6,595,580
6,595,674
Debug features on libstdc++ in Linux?
I was running my code under debug mode in VS2010 and it catched a nice error about invalid operator< which wasn't a strict weak ordering. Is there a way to catch these errors in libstdc++ on Linux or such conservative checks are only a feature of visual studio 2010?
Defining _GLIBCXX_DEBUG should do the trick. :) http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt03ch17s03.html#debug_mode.using.mode
6,596,093
6,596,457
multiple threads with Vector iterator
I 've declared a vector as typedef std::vector< unsigned int > SampleList; and declared Samplist type member variable in a class. I am accessing this vector from another class with multiple threads. I am adding , deleting , Reading values values from different threads. I am reading this value frequently like the f...
As soon as somebody adds or deletes a member of the vector, you iterator becomes invalid. Especially if elements are added, the internal buffer might have to be reallocated. But also if objects are deleted, the end() is moving and you might miss it. You must have a lock to protect the vector while iterating over it.
6,596,097
6,596,134
NaN handled differently in different g++ versions
Consider the following program, which is obviously buggy: #include <cstdio> double test(int n) { if (n % 2 == 0) return 0.0; // warning: control reaches end of non-void function } int main() { printf("%.9lf\n", test(0)); printf("%.9lf\n", test(1)); printf("%.9lf\n", test(2)); printf("%...
The code you show has undefined behavior, by failing to return a value in test from all control paths. There is nothing to expect, and nothing you can do to control it, except by writing a correct program in the first place. EDIT: I maintain that you shouldn't rely on what the compiler seems to do. Even if you think yo...
6,596,242
6,596,400
.NET System::String to UTF8-bytes stored in char*
I am wrapping some unmanaged C++ code inside a .NET project. For this I need to convert System::String to UTF8-bytes stored in char*. I am unsure if this is the best or even a correct way to do this and I'd appreciate if someone could take a look and provide feedback. Thanks, /David // Copy into blank VisualStudio C++/...
You don't need to create an encoder instance, you can use the static instances. If the called function doesn't expect a pointer to the HGlobal heap you can just use plain C/C++ memory allocation (new or malloc) for the buffer. In your example the function doesn't take ownership so you don't need a copy at all, just pi...
6,596,364
6,652,570
Tracking C++ lib public API changes
I'm currently working on large C++ Qt based project which is a about to go under a major re-factor of its public API and it would be nice to have a tool that can generate a report on which methods have been added or removed from build to build. I know there is a tool for Java to do this and I think there might be one f...
If you use Doxygen or some similar tool to document your API then you can diff the table-of-contents. This is something you should be doing anyway. (You can also tell Doxygen to find undocumented functions.) You can apply it easily to ancient checkins without changing anything. The Doxygen and its ilk know enough ab...
6,596,543
6,596,940
Problem with double precision and smartpointer in ITK
The problem I have is that I open an Image from a GUI using Qt (through the class I created ImageFrame, this class has defined the PixelType as follows: typedef double PixelType; typedef itk::Image<PixelType,2> ImageType; and after the extraction of the image, I would lie to make a FFT which input is real data. The e...
This is because image.Pointer() is a smart pointer object, a wrapper around the read pointer to your data. You must pass image.Pointer().GetPointer() to fftw.
6,596,575
6,596,730
C++ custom allocator that utilizes a underlying memory pool
I'm using a memory pool class which reuses allocated memory addresses and a custom allocator which wraps that class. The following code snippet gives you a basic idea of the interface. template<class alloc> class memory_pool : boost::noncopyable, public allocator_traits<void> { public: memory_pool(typenam...
C++0x has better support for scoped allocators such as memory pools. Profile your code., it's very hard to predict what advantages this will confer unless your algorithm performs very regular allocation/deallocation patterns such as LIFO. It's dead easy to write a very fast allocator when all the allocated objects are ...
6,596,578
6,596,615
sending e-mail from c++ code
I am making a console app that needs to send e-mail when asked so.How could i do that ? Though i tried this link it was not successful, because you need additional software for it. AND there is a delay of about 10 minutes when i actually get the email.what could be the problem ? This is the dialog box displayed when yo...
Give VMime a try! (Sending mail is not a language built-in feature, you will have to use some sort of library.)
6,596,737
6,596,896
When should I use C++ instead of SQL?
I am a C++ programmer who occasionally uses MySQL to work with databases, but my SQL knowledge is rather limited. However I am surely willing to change that. At the moment I am trying to do analysis(!) on the data I have in my database solely with SQL queries. But I am about to give up, and instead import the data to C...
SQL excels at analyzing large sets of relational data. The place to draw the line is the scale of your analysis. If you analyze individual records one at a time, do it in your application. If you analyze large sets of records as a unit, SQL is definitely the best tool for that job. Row-by-row analysis is not something...
6,596,847
6,597,677
how to find the maximum size of ostream class in c++
I am assigning std::ostream *pout_ = output_.get(); where output_ is scoped_ptr<std::stringstream> output_; after assigning i am filling *pout_ <<"large strings"; appx 1172528 characters. But after some extent i am not able to insert charcters inside *pout_. I tried surfing on the net whats the maximum size of this cla...
There are several possible causes for output to an ostream to fail. The most obvious is that the underlying supporting media (memory, in the case of an std::ostringstream) is full. Another is that you've reached some internal limit: a lot of systems have (or had) file size limits which would hit you long before the di...
6,597,030
6,599,291
Floating point operations in interrupt handler (PowerPC, VxWorks)
I haven't found any resources that exactly answer what I am trying to understand with an issue I saw in a piece of software I am working on, so I'll ask the geniuses here! For starters, I'm running with VxWorks on a PowerPC processor. In trying to debug a separate issue, I tried throwing some quick and dirty debug code...
In VxWorks, each task that utilises floating point has to be specified as such in the task creation so that the FP registers are saved during context switches, but only when switching from tasks that use floating point. This allows non-floating point tasks to have faster context switch times. When an interrupt pre-emp...
6,597,080
6,597,147
Boost shared memory. How many processes are currently using the shared memory?
I am sharing some memory between processes, using the boost library; boost::interprocess::managed_shared_memory managed_shm(boost::interprocess::open_or_create, "shm", 1024); is there a way to find out how many processes are currently accessing this memory?
If you can get the underlying SHM ID, you can use shmctl function to get the number of processes having the segment attached.
6,597,369
6,597,521
how to get function name and line number when project crashed in release mode
i have a project in C++/MFC when i run its in debug mode and project crashed i can get function and line number of code with SetUnhandledExceptionFilter function but in release mode i can not get it i am test this function and source _set_invalid_parameter_handler msdn.microsoft.com/en-us/library/a9yf33zb(v=vs.80).aspx...
PDB files are meant to provide you this information; the flaw is that don't you want a PDB file. I can understand not wanting to release the PDB to end users, but in that case why would you want them to see stack trace information? To me your goal is conflicting with itself. The best solution for gathering debug info f...
6,597,491
7,046,695
SQLAPI++ Library use
Has anyone have good experience using SQLAPI++ Library? (connecting C++ and SQL) What do you recommend, I have a local server, SQL server 2008 and Windows XP. Do you have a funcional example to connect c++ and sql server?, just to do a simple SELECt * FROM mytable; in C++?
My first impression is that SQLApi++ is great. Here is a bit of background. I have been using ADO for a long time, but it's starting to give some COM errors for some users, without any helpful information. Also, msado??.tlb is not backwards-compatible so you have to be careful about all your users being on the same ver...
6,597,654
6,597,911
Output and Input at Same Line using IOSTREAM
I want to use the iostream input and output operators in the same statement, not to be nicer to the user but the look I was trying not successfully obtained. Code fragment: int value = 0; std::cout << "Number 1: " << std::cin >> value << std::endl; Is there any way to do this using only cin cout?
struct IO { template <typename T> const IO & operator << (const T & t) const { std :: cout << t; return *this; } template <typename T> const IO & operator >> (T & t) const { std :: cin >> t; return *this; } }; IO () << "Number 1: " >> value;
6,597,719
6,621,175
UpdateData works, then data changes?
Language: C++ Development Environment: Microsoft Visual C++ Libraries Used: MFC Background: So I've created an application that is basically a large preference dialog where the user can configure a number of pages, each with a bunch of different settings. When the user is finished, he/she has three options for saving t...
Jon, Very hard to understand your code. What i understood is you have a member variable m_pages in CSAPrefsDialog dialog class which you are updating by calling UpdateData. And then you are creating a local variable CSaveThese m_sT and calling DoModal. Do you expect CSaveThese class should hold the values of m_Pages?...
6,597,760
6,597,815
boost.random buggy warning - what does it mean?
The documentation for the uniform distribution of boost.random says Note: The current implementation is buggy, because it may not fill all of the mantissa with random bits. I'm unsure how to fill a (to-be-invented) boost::bigfloat class with random bits efficiently. It's probably time for a traits class. ...
It's a warning that the current boost::random implementation doesn't fill all of the bits with the same distribution, so the numbers are "slightly less random" (have fun quantifying that statement) than they could have been. Chances are, however, that you won't be able to tell anyway.
6,598,002
6,598,114
Toggle dynamically created objects using dynamically created QRadioButtons
I'm working on a QT application. In it the user can create several objects, each one will be added to a list. In the next step the user shall position the objects. The choice which one of the objects shall be positioned, shall be made by clicking QRadioButtons (seems logical as QRadioButtons added to a QGroupbox ensure...
QObject::sender is a bit too abstract. Try QButtonGroup::buttonClicked
6,598,019
6,608,579
Asynchronous keyboard input on win32
I'm creating a simple 3D game on Windows 7 in C++ using the free version of the Havok physics engine. I want to use the WASD keys to move the character. The structure of the code is such that I need to capture this input asychronously; there is a function called in every frame of the scene to update the character's pos...
It appears that my problem wasn't GetAsyncKeyState() after all, but my use of FindWindow() and GetWindowRect(). It wasn't recognizing that the current window was the visual debugger. Fixed.
6,598,047
6,598,545
std::bind and std::function usage in callbacks
I was trying to understand c++0x std::bind and std::function usage in event handling / callbacks. So I was examining some code snippets and encountered some interesting places which I can't fully understand. Let's say we have: class EventHandler { public: template<typename Event, typename Listener> bool bindEve...
Listener will be inferred by the compiler to be the type of function pointer that you pass it, in this case void(const KeyboardEvent&). And your test fails because it's the wrong way around: you want if (!std::is_convertible<Listener, std::function<void (Event&)>>::value) instead (note the negation). By the way, both ...
6,598,244
6,598,350
private static member function or free function in anonymous namespace?
I've recently made a change stylistically and wanted to see how other c++ programmers felt about it and if there were any downsides to it. Essentially, when I needed a utility function which doesn't need access to a given class member, what I used to do was something like this: file.h class A { public: // public in...
If the function is only used in one source file, it makes perfect sense to define it there. If nobody else is using it, it doesn't belong in the header. As you say, it reduces dependencies and can potentially save some recompiles.
6,598,265
6,602,880
Convert uint64 to GMP/MPIR number
I am using MPIR 2.4.0 on Windows (MSVC 2010) and I was trying to add an unsigned 64bit integer to a mpz_t number. However it seems that MPIR/GMP does not support direct conversion between 64bit Integers and mpz_t. Does this mean I have to convert my uint64 to a string and read this via mpz_init_set_str? Neither is this...
As suggested by Banthar use mpz_import, but I'd suggest the following which does not rely on the platform endianness: mpz_import(b, 1, 1, sizeof(a), 0, 0, &a);
6,598,648
6,621,478
How to use the latest openssl update?
I have openssl 0.9.8g installed on my computer... It seems that it has a known bug which I ran into. I wanted to install the current version 1.0.0d which seems to have fixed the bug. so, basic install : $ ./config $ make $ sudo make install However even after recompiled my software I still get the same error, and it ...
Let's assume you installed your downloaded version of OpenSSL to /home/yourname/openssl. Then you need to tell your software to use that custom install instead of the pre-packaged 0.9.8 that already resides on your file system. There's no need to uninstall that, you can have several installations on your machine. "Tell...
6,598,830
6,599,125
Compilation error when using class template parameter in lambda
I'm trying to recreate some of the behavior of C#'s delegate types in C++, and I'm running in to a particular error when compiling- here is the relevant code: struct Nil { }; // Represents a C# Func template <typename returnType = void, typename T1 = Nil, typename T2 = Nil, typename T3 = ...
I think you still have the 0x syntax slightly messed up. auto myFunc = [&] ( returnType (*functionPointerToAdd)(T1) ) -> returnType (*)(T1, T2, T3) { functionPointerToAdd(T1); }; This line is the problem. Let's pull it apart: auto myFunc = [&] This creates a local variable of undefined type that receives a lambda (wh...
6,598,894
6,599,255
Is it possible to conditionally compile / run code based on a macro OR a variable?
We have several projects in development sharing the same codebase. Certain pieces of code are only relevant to one or other of those projects. We have a couple of requirements: The first requirement is that we want our final releases not to compile in code from the other projects. One solution (the one we like) is to u...
If the condition in the test is a compile-time constant, any half-decent optimizing compiler will remove the dead code completely from the object file. So something as simple as this should work fine: #ifdef REMOVECODE #ifdef PROJECT1 #define CONDITION1 1 #else #define CONDITION1 0 #endif #else #define CONDITION1 pro...
6,598,907
6,599,025
Does Internet Explorer offer a function to BHOs for downloading files over HTTP?
A Browser Helper Plugin I'm writing at the moment (C++) needs a list of domains for its work. This list must be updated weekly and is available as textfile over HTTP. Does Internet Explorer offer a method to download this file or do I have to use libcurl? I searched MSDN but didn't find anything helpful.
See URLDownloadToFile function.
6,599,124
6,599,289
g++ "declaration of "operator<<" as non-function"
We have a custom Logging class which compiles fine in VisualStudio 2010, but throws errors when being compiled with g++ on Linux. The error message we receive are the following: Logger.hpp:84: error: declaration of "operator<<" as non-function Logger.hpp:84: error: expected ";" before "(" token Logger.hpp:91: error: ex...
_Smanip is a Microsoft extension, and not part of the standard library. That's why your code compiles under Visual C++. Here's an MSDN article on the use of _Smanip, and here's another one of how to avoid using it and write portable code instead. EDIT: Found another link that explains manipulators with parameters in g...
6,599,132
6,599,240
Cost of a virtual function in a tight loop
I am in a situation where I have game objects that have a virtual function Update(). There are a lot of game objects (currently a little over 7000) and the loop calls update for all of them (amongst other things). My colleague suggested that we should remove the virtual function altogether. As you can imagine, this wil...
If you can't profile, have a look at the assembler code to get an idea how expensive the lookup really is. It might be a simple indirect jump which costs almost nothing. If you need to refactor, here is a suggestion: Create lots of "UpdateXxx" classes which know how to call the new non-virtual update() method. Collect ...
6,599,246
6,600,928
A C++ covariance/overriding/circularity problem
I am writing a backend of a compiler of a subset of Java. The backend writes C++ code. There is some hypothetical Java code, though, that I do not known how to translate to C++. An example problem is shown in the following code. A is extended by B, B is extended by C, and here are respective three header files A.h, B.h...
You can implement covariance yourself, cleanly, without relying on the compiler and without any casts. Here's a header with some circular dependencies: class A { public: A* get() { return get_A(); } private: virtual A* get_A(); }; class B : public A { public: C* get() { return get_C(); } private: ...
6,599,436
6,612,097
As of 2011: Netbeans 7 or Eclipse Indigo for C++?
This is basically a duplicate of: Netbeans or Eclipse for C++? But, that question as 3+ years old, and a lot has changed since then. I have a large code base with a custom (but Makefile based) build system. The areas I am specifically wondering about include: Syntax highlighting Code navigation. Code hints. "ReSharpe...
I cannot comment on Netbeans, but I can offer you information on Eclipse. I work with C++ on UNIX systems, and I have started to use Eclipse when exploring large code bases that I know little about. I don't use it to build, but it would be easy to integrate our build system with it as one only needs commands. Eclipse...
6,599,458
6,599,531
How do you remove directory qualifiers to simplify pathname using the Win32 API?
If you have a path like "C:\foo\.\bar\.." is there an easy way using the Win32 API to remove the directory qualifiers in order to simplify it to "C:\foo" ? Update: It seems to be a more complicated issue. On this simple example of "C:\foo\.\bar\..", it works with both PathCanonicalize() and GetFullPathName() to get "C...
Take a look at shlwapi's PathCanonicalize()
6,599,632
6,599,712
Calculate estimated time in a program
I'm making a program and I want to give to the user information about the estimated times every 1000 elements processed. I'm calculating time in this way: C = elements processed so far MAX = Max elements to process Tp = time elapsed Te = time estimated In theory, the relation between elements processed and elapsed ti...
I think your initial equation is slightly off, rather than what you have it should be (C/Tp) = (MAX - C)/Te since we're estimating the time required to process each item, and this should be constant and equal in the past and the future. This will give you a final equation Te = (MAX - C)*(Tp/C) which tends to zero as ...
6,599,960
6,600,239
Error 3699, creating GUID for objects
I'm trying to use CoCreateGuid(GUID* guid) to create a guid for objects in my application. I am getting a few errors trying to use this function. error C3699: '*' : cannot use this indirection on type 'IServiceProvider' in servprov.h error C2872: 'IServiceProvider' : ambiguous symbol in servprov.h error C2371: 'IServic...
A using directive (using namespace System;) in one of your headers (probably AutomationCPP.h) is causing the problem. You're indirectly including servprov.h, which has a definition for ::IServiceProvider, and you've got the using directive which is bringing System::IServiceProvider into the global scope. This causes am...
6,600,064
6,600,157
merge vector into existing vector
In C++, given vector<T> src, dst, both already sorted, is there a more efficient way to merge the contents of src into dst than size_t n = dst.size(); dst.insert(dst.end(), src.begin(), src.end()); std::inplace_merge(dst.begin(), dst.begin() + n, dst.end()); ? In the case I care about, T is a small (12-16 bytes, depe...
I would at least try: std::vector<T> tmp; tmp.reserve(src.size() + dst.size()); // commenters are probably right about this std::merge(src.begin(), src.end(), dst.begin(), dst.end(), std::back_inserter(tmp)); src.swap(tmp); But I suspect that much depends on the nature of T, the size of src and dst, and why we need to...
6,600,222
6,603,748
Implement COM interface C++ / VC++ 6.0 / MFC
Entry level programmer here trying to implement a COM interface. I am working on a program that interfaces with the Aloha point of sale system. Aloha uses COM to work with external programs. I am trying to intercept card data from the mag card reader, which is an OPOS reader, not a keyboard wedge. The documentation I h...
It probably means there is a license you have to install before their custom class factory will create an instance of the class. Did you try running your program on a fully working POS system with the magnetic card swipe licensed for use? Maybe there is some other license that you need to do this type of thing? If it...
6,600,229
6,600,356
A few memory management questions involving class destructors and delete operator?
After reading some tutorials I am still unclear on some points about memory management in C++. 1. when a class declared with the new operator goes out of scope is its destructor called and memory freed? Is it necessary to call the delete operator to free the class' memory and have its destructor called? class Test{}; ...
It sounds like you may come from a Java background, so things with new work a bit differently in C++. The memory allocated with new must be explicitly destroyed with delete. This example has a memory leak. Similar to question 1, you must delete the memory in the class destructor to reclaim it. In this case the vector ...
6,600,507
6,600,572
c++ try-except statement
I came across this article about detecting VMWare or Virtual PC http://www.codeproject.com/KB/system/VmDetect.aspx and I saw that they use some kind of try-except statement. So I looked it up in the MSDN: http://msdn.microsoft.com/en-us/library/s58ftw19%28v=vs.80%29.aspx and I don't understand why would I use a try-ex...
__try/__except is a try/catch, for a different kind of exception. You can catch hardware exceptions like floating point violation, bad pointer de-reference, etc, and not C++ exceptions. This is referred to as Structured Exception Handling, or SEH, and MSDN has quite a bit on it if you know where to look. In this case, ...
6,600,725
6,600,765
Pass std::string to a function f(**char)
Is it possible to pass the pointer of a std::string to a function which expects a **char? The function expects a **char in order to write a value to it. Currently I am doing the following: char *s1; f(&s1); std::string s2 = s1; Is there no shorter way? It is obvious, that s2.c_str() does not work, since it returns con...
That's the appropriate way to handle that sort of function. You cannot pass in the std::string directly because, while you can convert it to a C string, it is laid out in memory differently and so the called function would not know where to put its result. If possible, however, you should rewrite the function so it tak...
6,600,916
6,601,013
Is there a hoist-free version of BOOST_FOREACH?
I'm aware of the "hoisting" pitfall of BOOST_FOREACH where it caches the end iterator. However it seems that: Modifying sequences mid loop is fairly common (especially push_back) It wouldn't be hard to provide a version of BOOST_FOREACH that was didn't hoist so was immune to modification problems. Clearly people ofte...
"Modifying sequences mid loop is fairly common" Avoiding the hoist would not make the macro immune to modification problems, since BOOST_FOREACH is also using a moving iterator under the covers that might be invalidated by push_back (for example you're using a vector and it reallocates) or other structural modification...
6,601,041
6,601,158
Linking cURL in Makefile
I need link cURL in Ubuntu 11.04 after installed cURL by source code. . Correction of the PROBLEM First I discovered that the -l must come before the -L and then discovered that I was not entering a variable in the makefile. . Get cURL Configs: On my termial: # curl-config --libs -L/usr/local/lib -lcurl # curl-config ...
This should do the job. You didn't really link to cURL before. build: $(SOURCES) $(CXX) -o $(OUT) $(INCLUDE) $(CFLAGS) $(LDFLAGS) $(LDLIBS) $(SOURCES) Notice the added $(LDLIBS). Oh, I should add that basically what happens is that you throw overboard the built-in rules of GNU make (see output of make -np) and def...
6,601,124
6,601,177
Proper idiom for std::string assignment
When constructing a std::string from a const char*, I often use the following pattern: const char* p = GetString(); std::string s(p); I suppose I could use the similar pattern: const char* p = GetString(); std::string s = p; But, when I want to assign, rather than construct, to a std::string from a const char*, I hav...
Go for readability, and just use the idiomatic operator= for assignment. Also, directly construct the std::string from the const char*. std::string s(GetString()); s = GetString();
6,601,141
6,601,198
compiling Lua source with host C++ application
I'll be quick: I have a C++ application that embeds Lua. Until now I have just used a pre-compiled lib that I link to the app. I would like to make a new approach by including the Lua source code and compile from scratch. What all would I need to do? I'm running gcc v 4.4.3 in ubuntu 11.4 Thanks!
Include the lua source code as included in the library - leave out the .c files which contain a main() Make the proper #define for your operating system (see the Lua makefile for which ones to use) Compile.
6,601,296
6,602,767
boost::fusion::result_of::as_set (or as_vector) converted from complex (nested) mpl sequences
#include <iostream> #include <boost/fusion/mpl.hpp> #include <boost/fusion/include/mpl.hpp> #include <boost/fusion/container/set.hpp> #include <boost/fusion/include/at_key.hpp> #include <boost/fusion/include/as_set.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/set.hpp> #include <boost/mpl/front.hpp> #include...
the solution is a lot simpler than it first appears! :) You've missed out something critical: typedef ::boost::fusion::result_of::as_set<restored_set_type> restored_fusion_set; Is incorrect, what you need is: typedef ::boost::fusion::result_of::as_set<restored_set_type>::type restored_fusion_set; You simply missed ::...
6,601,355
6,602,395
Passing an fstream (or equivalent) from C# to C++ through CLI
How can I pass an fstream or equivalent from C# through CLI to an unmanaged C++ DLL? Rough application outline: C# application reads a binary file from a database Unmanaged C++ dll is used to "decode" this file and return the information contained therein I can modify any of the C# code. The CLI wrapper is the only p...
You can pass a managed binary array to the C++/CLI DLL. Pin the array. This can then be converted to an STL string object. You can then pass the STL string into an STL stringstream object, which inherits from iostream. Think of stringstream as a .NET MemoryBuffer object. Pass stringstream to your unmanaged C++. T...
6,601,542
6,601,857
Overloaded functions and size of executable / library
While studying the Qt framework, I've noticed that it's littered with hundreds of overloaded functions scattered among all its classes. This makes me wonder how much these functions contribute to the size of the libraries. Without going through a tedious process of eliminating each overloaded function, is it possible t...
In GCC the options to use are -ffunction-sections and -fdata-sections when compiling and --gc-sections when linking. This causes it to essentially create a graph of your program and drop any function, variable and so on that isn't referenced. For shared libraries, the shared lib takes all the code - they're all in the...
6,601,592
6,601,633
Counting digits using while loop
I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code: int x; cout << "Enter a number: "; cin >> x; x /= 10; while(x > 0) { count++; x = x/10; } From what I can tell (even with my limited experience) is that it seems c...
In your particular example you could read the number as a string and count the number of characters. But for the general case, you can do it your way or you can use a base-10 logarithm. Here is the logarithm example: #include <iostream> #include <cmath> using namespace std; int main() { double n; cout << "Ent...
6,601,725
6,602,074
Map causing Seg Fault. How to increase memory?
I have a simple question. I have a few files, one file is around ~20000 lines. It has 5 fields, have some other adt (vectors and lists), but those do not cause a segfault. The map itself will store a key value, equivalent to about 1 per line. When I added a map to my code, I would instantly get a segfault, I copied 50...
Be careful erasing elements from a container while you are iterating over the container. for (pos = ava_bw.begin(); pos != ava_bw.end(); ++pos) { if (pos->second == INIT){ ava_bw.erase(pos); } } I believe this will have pos pointing to the next value but then ++pos will advance it yet again. If erase(p...
6,601,874
6,601,921
Matching Start / End Profiling Calls
I'm currently implementing a profiling system into an application. I have a two macro functions which are defined based on a compiler flag (NDEBUG). When NDEBUG is not defined, these two functions (profilingStart / profilingEnd) generate profiling reports which show the time when profilingStart was called, vs the time ...
In C++, one solution is to use the "RAII" idiom. Something like this: class Profiler { public: Profiler() { profilingStart(); } ~Profiler() { profilingEnd(); } } Then you use it like this: { // start of block you want to profile Profiler prof; ... } This will ensure that profilingEnd gets called ev...
6,601,930
6,603,301
C++11 lambda as member variable?
Can lambda's be defined as class members? For example, would it be possible to rewrite the code sample below using a lambda instead of a function object? struct Foo { std::function<void()> bar; }; The reason I wonder is because the following lambda's can be passed as arguments: template<typename Lambda> void call_...
Templates make it possible without type erasure, but that's it: template<typename T> struct foo { T t; }; template<typename T> foo<typename std::decay<T>::type> make_foo(T&& t) { return { std::forward<T>(t) }; } // ... auto f = make_foo([] { return 42; }); Repeating the arguments that everyone has already ex...
6,602,117
6,602,280
Fencepost conditions and portability for using of snprintf()?
Given the following code: const int size = 20; char buffer[size]; // From the Linux man page for snprintf(): // // The 'res' is the number of bytes that would be written to buffer had size been // sufficiently large excluding the terminating null byte. Output bytes beyond // the size-1st are discarded instead of bein...
snprintf isn't strictly speaking portable, as it's not part of the C/C++ standards. Windows has it as _snprintf - but otherwise identical. The fencepost conditions are all fine. Your printf's aren't entirely fine, in the equals case it's going to print The buffer was not large enough, we needed 215 but only had 215.
6,602,209
6,602,607
Automatic variables in C++
Possible Duplicate: In C++, why should new be used as little as possible? Where are automatic variables allocated in C++? On the stack or the heap? Also, I read in 7.9 — The stack and the heap that all memory allocated on the stack is known at compile time. Is it true? Does it mean that only static memory allocation...
C++ does not have the concept of a stack or heap, it is an implementation detail as far as the language is concerned. That being said, every implementation I know of uses the stack to manage the lifetime of local variables. However, many local variables may end up living entirely within registers and never touch the st...
6,602,391
6,605,437
Common game controls/ User interface libraries or source code?
Sorry for the ackward title, but i don't know what to call it exactly. I'm looking for code or libraries that allow easy creation of commonly used user input devices, and code/libs that make gaming controls easy to set up (i'm using SFML and Box2D at the moment) I don't want to re-invent things like buttons, arrows be...
I think CEGUI is the type of thing you are looking for: http://www.cegui.org.uk/wiki/index.php/Main_Page It is a GUI framework to work with OpenGL. Some others can be found in this list. Still, if I were you, I would just use a major toolkit, such as GTK, Qt, or wxWidgets combined with SFML instead of dealing with CEG...
6,602,511
6,602,752
What will happen in this situation?
Say I have base class A. it has method void foo(A* a); It also has method void foo(B* b); B inherits from A. Say I now have a B instance but it is an A* ex: A* a = new B(); If I were to call someA.foo(a); Would this call the A* implementation or B* implementation of the method? I'm providing an A* to the method, ...
Well, two things will happen. First of all the determination of which function to call: A* a = new B(); foo(a); Here you pass a variable of type A* (C++ = static typed, remember) to foo, this will as usual call foo(A* a), nothing different from any other function overloading. If you were to call foo(new B()) it would ...
6,602,543
6,602,695
C++ What might cause unresolved external errors in he link process when using static members of a class?
I made a program that has a class with static-only members in it in its own dedicated cpp/h file combo. The probably is that when I try to use these static members in my code, I'm getting "unresolved external" errors at the linker stage. I am remembering to include the h file in my cpp file that is getting the errors. ...
Are you remembering to actually define the variable somewhere, instead of just declaring it in the header? Foo.hpp: #ifndef FOO_HPP #define FOO_HPP class Foo { public: static int bar; }; #endif Foo.cpp: #include "Foo.hpp" int Foo::bar; // <-- This being the critical line.
6,602,614
6,602,741
How do I use C Headers in a C++ Program?
I am working on a project in Visual Studio 2010 which is to produce a win 32 dll file. The examples I have are C files and the compile and work well. I would like to incorporate some functionality from C++ function I've written but I have hit a bit of a wall. If I attempt to link the C++ functions to the C program, i...
error LNK2001: unresolved external symbol "void (__cdecl* b_evnt) (unsigned short,short *,union I_EVNT_T *,union O_EVNT_T *)" (?b_evnt@@3P6AXGPAFPATI_EVNT_T@@PATO_EVNT_T@@@ZA) That means, the C++ mangled variable b_evnt can't be found. That's true, because it should've been C mangled (just an _ prefix). To fix that,...
6,602,967
6,631,049
Handle C++ functions with clang API to insert code
I need to preprocess some C++ files to automatically insert code for testing and profiling, and I need to do it with the clang API. For now, I want to be able to do the following: If there is a function: int SomeFn(int a, int b, int c) { doStuff(); } I want to preprocess it, that it looks like this: int SomeFn(in...
Are there any settings to switch between C and C++ ? Finally I found out how to handle this: I extended from ASTConsumer and RecursiveASTVisitor<MyConsumer> to traverse the AST and implemented VisitCXXRecordDecl(CXXRecordDecl* D). Then I had to set the LangOptions parameter for the preprocessor, so it parses C++. lan...
6,603,166
6,604,314
How to write into an array from a dispatch_apply (GCD) loop?
I have written code to calculate the dynamics of a large set of coupled master equation using the Runge-Kutta-method. The code contains a lot of for-loops, where each step is independent. I intend to use Grand Central Dispatch to speed up the program. I based my attempt on an example I found at http://www.macresearch.o...
error: cannot refer to declaration with an array type inside block Under the blocks implementation, it is not allowed to access to an C array from blocks. (I can't find the documentation about it...) There is an easy fix :-) double valuesArray[SpaceSize], k1Array[SpaceSize]; double *values = valuesArray, *k1 = k1...
6,603,307
6,603,439
Namespace alias scoping issues
I have a header file in which I wish to use a namespace alias while defining a class. However I don't want to expose this alias to anything that includes the header file. // foo.h namespace qux = boost::std::bar::baz::qux; // ! exposed to the world class foo { // can't put a namespace alias here // stuff usin...
namespace MyClassSpace { namespace qux = boost::std::bar::baz::qux; class foo { // use qux:: }; } using MyClassSpace::foo; // lift 'foo' into the enclosing namespace This is also how most Boost libraries do it, put all their stuff in a seperate namespace and lift the important identifiers into the boost namespace...