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
3,050,805
3,050,819
pointer to const member function typedef
I know it's possible to separate to create a pointer to member function like this struct K { void func() {} }; typedef void FuncType(); typedef FuncType K::* MemFuncType; MemFuncType pF = &K::func; Is there similar way to construct a pointer to a const function? I've tried adding const in various places with no succe...
You want this: typedef void (K::*MemFuncType)() const; If you want to still base MemFuncType on FuncType, you need to change FuncType: typedef void FuncType() const; typedef FuncType K::* MemFuncType;
3,050,811
3,050,911
Why should virtual functions not be used excessively?
I just read that we should not use virtual function excessively. People felt that less virtual functions tends to have fewer bugs and reduces maintenance. What kind of bugs and disadvantages can appear due to virtual functions? I'm interested in context of C++ or Java. One reason I can think of is virtual function may...
You've posted some blanket statements that I would think most pragmatic programmers would shrug off as being misinformed or misinterpreted. But, there do exist anti-virtual zealots, and their code can be just as bad for performance and maintenance. In Java, everything is virtual by default. Saying you shouldn't use v...
3,050,835
3,050,991
Rewriting a simple Pygame 2D drawing function in C++
I have a 2D list of vectors (say 20x20 / 400 points) and I am drawing these points on a screen like so: for row in grid: for point in row: pygame.draw.circle(window, white, (particle.x, particle.y), 2, 0) pygame.display.flip() #redraw the screen This works perfectly, however it's much slower then I exp...
DirectX doesn't have functions for drawing just one point. It operates on vertex and index buffers only. If you want simpler way to make just one point, you'll need to write a wrapper. For drawing lists of points you'll need to use DrawPrimitive(D3DPT_POINTLIST, ...). however, there will be no easy way to just plot a p...
3,051,042
3,051,200
How might one implement FileTimeToSystemTime?
I'm writing a simple wrapper around the Win32 FILETIME structure. boost::datetime has most of what I want, except I need whatever date type I end up using to interpolate with Windows APIs without issues. To that end, I've decided to write my own things for doing this -- most of the operations aren't all that complicate...
Windows SYSTEMTIME and FILETIME data types are intended to represent a particular date and time. They are not really suitable to represent time differences. Time differences are better of as a simple integer representing the number of between two SYSTEMTIMEs or FILETIMEs. might be seconds, or something smaller if ...
3,051,204
3,051,265
strerror_r returns trash when I manually set errno during testing
During testing I have a mock object which sets errno = ETIMEDOUT; The object I'm testing sees the error and calls strerror_r to get back an error string: if (ret) { if (ret == EAI_SYSTEM) { char err[128]; strerror_r(errno, err, 128); err_string.assign(err); } else { err_string.a...
According to this page, http://linux.die.net/man/3/strerror_r, if you're using the GNU version of strerror_r(), the function might decide to not store anything at all into the buffer you provide; you'd need to use the string returned from the function (seems like a rather bizarre interface): The GNU-specific strerror_...
3,051,479
3,052,252
How do I cast Qt's QVariant to boost::any?
How do I cast Qt's QVariant to boost::any?
i dont think there is an easy way, i would do following: boost::any qvariant_to_any(const QVariant& v) { switch(v.userType()) { case QVariant::Bool: return boost::any(v.value<bool>()); //or: return boost::any(v.toBool()); case QVariant::Int: return boost::any(v.va...
3,051,483
3,051,763
Is this a MinGW bug?
I have been trying to execute this program on my MinGW, through Code::Blocks: #include <string.h> #include <math.h> #include <stdio.h> #define N 100 int p[N]; int pr[N]; int cnt; void sieve() { int i,j; for(i=0;i<N;i++) pr[i]=1; pr[0]=pr[1]=0; for(i=2;i<N;i++) if(pr[i]) { p[cnt]=i; ...
There are two important bugs in your code. One is that your p array is too small, so you are writing off the end of it. This is undefined behaviour, though on the platforms you are using it overwrites the start of the pr array. This has no effect on the output, since the location you are overwriting is before the loca...
3,051,776
3,052,022
While within a switch block
I've seen the following code, taken from the libb64 project. I'm trying to understand what is the purpose of the while loop within the switch block - switch (state_in->step) { while (1) { case step_a: do { if (codechar == code_in+length_in) { ...
Although this is Duff's Device, this version is not about implementing a loop-unrolling optimisation but rather to implement an iterator over a Base64 encoded stream. So you can do something like this: Base64Stream stream; // the base64 data char c; while ((c == stream->NextChar ()) != 0) { // do something with c }...
3,052,028
3,052,990
Detect pointer arithmetics because of LARGEADDRESSAWARE
I would like to switch my application to LARGEADDRESSAWARE. One of issues to watch for is pointer arithmetic, as pointer difference can no longer be represented as signed 32b. Is there some way how to find automatically all instances of pointer subtraction in a large C++ project? If not, is there some "least effort" ma...
As our code already compiles with GCC, I think perhaps the fastest way might be: build a GCC create a custom modification of GCC so that it prints warning (or error) whenever pointer subtraction is detected build the project and gather all warnings about pointer subtraction Here is the outline of changes which need t...
3,052,138
3,052,287
Pause the log4c++ logger
is it possible to pause the logger in log4c++, and by pause I mean to stop writing messages in the log file but not finalize the logger object or delete it. thanks in advance
I think you can change the level with setLevel() to OFF
3,052,158
3,052,246
Socket send recv functions
I have created a socket using the following lines of code. Now i change the value of the socket i get like this m_Socket++; Even now the send recv socket functions succeeds without throwing SOCKET_ERROR. I expect that it must throw error. Am i doing something wrong. struct sockaddr_in ServerSock; ...
It's because of the peculiar nature of Windows handles -- when created they are divisible by four and when used their two lowest bits are ignored. Incrementing a handle by one will make m_Socket refer to the same socket as before (only when you increment by four will the function return an error -- unless there is anot...
3,052,298
3,052,321
Strange iterator behaviour
#include "stdafx.h" int _tmain(int argc, _TCHAR* argv[]) { string s = "Haven't got an idea why."; auto beg = s.begin(); auto end = s.end(); while (beg < end) { cout << *beg << '\n'; if (*beg == 'a') {//whithout if construct it works perfectly beg = s.erase(beg);...
There are several problems with this code. Don't cache the value of s.end(); it changes as you delete elements. Don't use beg < end. The idiomatic approach is to write beg != end. If you try to iterate past end, the result is undefined, and a debug version of the string library may deliberately crash your process, so ...
3,052,415
3,052,618
Template class that refers to itself as a template template parameter?
This code: template <template <typename> class T> class A { }; template <typename T> class B { A<B> x; }; doesn't compile, I suppose since A<B> is interpreted as A<B<T> > within B's scope. So, how do you pass B as a template template parameter within it's scope?
Try this: template <typename T> class B { A< ::B > x; // fully qualified name for B }; According to C++ Standard 14.6.1/2 you should use the normal name of the template (i.e., the name from the enclosing scope, not the injected-class-name).
3,052,467
3,059,767
How to iterate over a STL set and selectively remove elements?
The following code does not work correctly. How should it be done correctly? for (std::set<Color>::iterator i = myColorContainer.begin(); i!=myColorContainer.end(); ++i) { if ( *i == Yellow) { DoSomeProccessing( *i ); myColorContainer.erase(i); } }
You don't need a loop as youre dealing with a set. std::set<Color>::iterator it = myColorContainer.find(Yellow); if (it != it.myColorContainer.end()){ DoSomeProcessing(*it); myColorContainer.erase(it); }
3,052,486
3,052,596
sending sms from windows application
I am creating a windows application which needs to send some sms to mobile phone.This is just for testing purpose. Now can I use my cell phone to get this done. I have android phone which can be connected to pc using USB. Application is created in C++, windows api. Any pointers will help
You can write a simple android application that runs in the background that checks for text files. When you want to send an SMS just push a new text file with the phone number and the message onto the sd card. You can use the android SDK 'adb push' command for that. It's a hacky way tho, wouldn't recommend it unless it...
3,052,579
3,052,604
Explicit specialization in non-namespace scope
template<typename T> class CConstraint { public: CConstraint() { } virtual ~CConstraint() { } template <typename TL> void Verify(int position, int constraints[]) { } template <> void Verify<int>(int, int[]) { } }; Compiling this under g++ gives t...
VC++ is non-compliant in this case - explicit specializations have to be at namespace scope. C++03, §14.7.3/2: An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member...
3,052,625
3,052,648
typedef boost::shared_ptr<MyJob> Ptr; or #define Ptr boost::shared_ptr
I've just started working on a new codebase where each class contains a shared_ptr typedef (similar to this) like: typedef boost::shared_ptr<MyClass> Ptr; Is the only purpose to save typing boost::shared_ptr? If that is the case, is the only reason not to do #define Ptr boost::shared_ptr in one common header the g...
A macro (#define) is always defined globally. This means that every use of the 'string' Ptr (even a variable) will be replaced by the macro. The typedef can be placed in a class, in a namespace, ... so you have much better control over it. EDIT: another advantage is that you can haver different Ptr types in different c...
3,052,788
3,052,796
How to select a random element in std::set?
How can I select a random element in an std::set? I naively tried this: int GetSample(const std::set<int>& s) { double r = rand() % s.size(); return *(s.begin() + r); // compile error } But the operator+ is not allowed in this way.
You could use the std::advance method. #include <set> #include <algorithm> int main() { using namespace std; // generate a set... set<int> s; for( int i = 0; i != 10; ++i ) s.insert(i); auto r = rand() % s.size(); // not _really_ random auto n = *select_random(s, r); } Where template<typename S> auto sele...
3,052,949
3,052,957
How do I sort a file that has a very long list of items?
I have a text file that has a very long list of items. So I want to sort them alphabetically but I do not want to load all the file into the memory (RAM). I tried loading all the contents of the file to an array and sort them just like I do normally. But the system complains that there are no much memory!! Thanks, Moha...
You'll need to read up on external sorting. The basic approach is to use some sort of divide-and-conquer routine like merge sort, where you read and sort a portion of the file, then read and sort another portion of the file, etc. and when you get to the end you merge the sorted portions together.
3,053,081
3,053,353
C++ and virtual methods overriding
Sorry for this stupid question, but I can't find an answer by myself, I'm too new in C++ :( class DBObject : public QObject { ... protected: virtual QString tableName() = 0; }; class DBUserObject : public DBObject { ... protected: virtual QString tableName() { return "profiles"; }; }; And I have this...
Based on the OP's followup comment: DBUserObject user(3). It is loading item in its constructor. If you mean the DBObject constructor (and not the DBUserObject constructor), then there's your problem. Virtual functions do not work inside constructors. Constructors run from the least-derived (most base) class to the...
3,053,219
3,053,238
Retrieve Heap memory size and its usage statistics etc...?
Lets say I open some application or process. Did some work with that. Now I closed it. Need to know whether this application caused any memory leak. i.e used up some heap memory and not cleared it properly. Can I get this statistics some how? I'm using Visual Studio (for development) under Windows OS. Even I would be i...
When an application closes all resources are automatically released by Windows. A quick & dirty tool to get an indication for memory/resource-leaks inside an application is Perfmon. The actions executed by an application, can cause other processes to use more memory. SQL Server can make its cache size bigger, maybe yo...
3,053,359
3,923,696
Creating Binary Block from struct
I hope the title is describing the problem, i'll change it if anyone has a better idea. I'm storing information in a struct like this: struct AnyStruct { AnyStruct() : testInt(20), testDouble(100.01), testBool1(true), testBool2(false), testBool3(true), testChar('x') {...
I've now used the std::bitset for generating bit-sequences for the datatypes and then concatenated these bitsets to one big bitset. This then holds the data I need. I just have to check for little/big endian.
3,053,513
3,053,626
Converting a macro to an inline function
I am using some Qt code that adds a VERIFY macro that looks something like this: #define VERIFY(cond) \ { \ bool ok = cond; \ Q_ASSERT(ok); \ } The code can then use it whilst being certain the condition is actually evaluated, e.g.: Q_ASSERT(callSomeFunction()); // callSomeFunction not evaluated in release bui...
In case of inline functions there's no guarantee the function arguments are not evaluated. Since their evaluation might have or not have side effects you will at very best have hard times maintaining the code - in cases where there is a side effect evaluation will surely take place, in other cases it will take or not t...
3,053,561
18,919,937
How do I assign an alias to a function name in C++?
It's easy to create a new name for a type, a variable or a namespace. But how do I assign a new name to a function? For example, I want to use the name holler for printf. #define is obvious... any other way? Solutions: #define holler printf void (*p)() = fn; //function pointer void (&r)() = fn; //function reference in...
There are different approaches: With C++11 with non-template non-overloaded functions you can simply use: const auto& new_fn_name = old_fn_name; If this function has multiple overloads you should use static_cast: const auto& new_fn_name = static_cast<OVERLOADED_FN_TYPE>(old_fn_name); Example: there are two overloads...
3,053,578
3,053,600
How to declare ULARGE_INTEGER in c#?
Based upon this question How to declarate LARGE_INTEGER in C# with answer of: [StructLayout(LayoutKind.Absolute, Size=8)] struct LARGE_INTEGER { [FieldOffset(0)]public Int64 QuadPart; [FieldOffset(0)]public UInt32 LowPart; [FieldOffset(4)]public Int32 HighPart; } Is my assumption below for declaring ULARGE...
It is simply an ulong in C#, no need to jump through the LayoutKind.Explicit hoop. The union was necessary because C and C++ compilers didn't have a native 64-bit type in the olden days.
3,053,667
3,054,207
Qt - How to place a QTextEdit with left and right margins in a QVBoxLayout?
How to place a QTextEdit with left and right margins in a QVBoxLayout? I could use, of course, a QHBoxLayout, place the QTextEdit into that horizontal layout in between to spacings (addSpacing(40)) and only then the horizontal layout could add into the vertical layout, but want to know if there is a direct way of doing...
If you want the margins only for your QTextEdit and not any other element in the QVerticalLayout you can use QT stylesheets for that. You just need to give a name to the QTextEdit object (like "myMarginsTextEdit") and style it, eg: QTextEdit#myMarginsTextEdit { margin-left: 40px; margin-right: 40px; } If you a...
3,053,681
3,053,885
Declaration of struct variables in other class when obtained by getters
I am using Qt 4.5 so do C++. I have a class like this class CClass1 { private: struct stModelDetails { QString name; QString code; ..... // only variables and no functions over here }; ...
You've already gotten a couple of suggestions for how to attack your problem directly. I, however, would recommend stepping back for a moment to consider what you're trying to accomplish here. First of all, you've said you only really want the name member of each stModelDetails item. Based on that, I'd start by changin...
3,053,739
3,053,759
error C2504: 'BASECLASS' : base class undefined
I checked out a post similar to this but the linkage was different the issue was never resolved. The problem with mine is that for some reason the linker is expecting there to be a definition for the base class, but the base class is just a interface. Below is the error in it's entirety c:\users\numerical25\desktop\int...
The problem is You need to have #include "GXRenderer.h" at the top of both: GXGL.h and also GXDX.h. The base type must be defined not just declared before defining a derived type. By the way, the error is a compiling error not linking error. Edit: About your class type redefinition: at the top of every header file y...
3,053,851
3,053,866
Difference between Object var and Object* var = new Object()
If I have a class named Object, what's the difference between creating an instance just like that: Object var; and: Object* var = new Object(); ?
Here you are creating var on the stack: Object var; So in the above, var is the actual object. Here you are creating var on the heap (also called dynamic allocation): Object* var = new Object() When creating an object on the heap you must call delete on it when you're done using it. Also var is actually a pointer w...
3,053,904
3,054,003
Is a C++ compiler allowed to emit different machine code compiling the same program?
Consider a situation. We have some specific C++ compiler, a specific set of compiler settings and a specific C++ program. We compile that specific programs with that compiler and those settings two times, doing a "clean compile" each time. Should the machine code emitted be the same (I don't mean timestamps and other b...
The C++ standard certainly doesn't say anything to prevent this from happening. In reality, however, a compiler is normally deterministic, so given identical inputs it will produce identical output. The real question is mostly what parts of the environment it considers as its inputs -- there are a few that seem to assu...
3,053,956
3,054,024
How do I implement a dictionary "with a Python tuple" as key in C++?
I currently have some python code I'd like to port to C++ as it's currently slower than I'd like it to be. Problem is that I'm using a dictionary in it where the key is a tuple consisting of an object and a string (e.g. (obj, "word")). How on earth do I write something similar in C++? Maybe my algorithm is horrendous a...
map<pair<..., string>, ...> if you're hellbent on using C++ for this.
3,054,048
3,054,360
Why doesn't C++ allow you to request a pointer to the most derived class?
(This question should probably be answered with a reference to Stroustrup.) It seems extremely useful to be able to request a pointer to the most derived class, as in the following: class Base { ... }; class DerivedA { ... }; class DerivedB { ... }; class Processor { public: void Do(Base* b) {...} void Do(Derived...
What you are suggesting would be equivalent to a switch on the runtime type, calling one of the overloaded functions. As others have indicated, you should work with your inheritance hierarchy, and not against it: use virtuals in your class hierarchy instead of dispatching outside it. That said, something like this cou...
3,054,068
3,056,015
How to create named pipe acsessible Only on your machin? (VS08 C++)
I have created a program that write video stream to a named pipe on windows, using Visual Studio C++ 2008 . how to be sequre that no one exept programms on this computer can acsess this pipe? npipe = CreateNamedPipe("\\\\.\\pipe\\TestChannel", PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT, PIPE_UNLIMITED_INSTAN...
As of Windows Vista, you can include the PIPE_REJECT_REMOTE_CLIENTS flag in the dwPipeMode parameter. For earlier Windows versions, the documentation suggests using the lpSecurityAttributes parameter to deny access to the network.
3,054,078
3,054,177
ASCII definition of symbol
I've spent hours with no luck on this. In terms of cmd prompt, what does the white filled in square with a 1 followed afterwards mean? e.g. http://i1012.photobucket.com/albums/af249/dororoj/square1.jpg I've tried using string.find() (using C++) with various hex symbols listed on the ascii table at: http://web.cs.mun.ca...
I ran the following C# code bit and found the symbol you mentioned when the loop hit 166. So i doubt that it could mean anything useful.Although it doesnt mean anything it could've been used for primitive ASCII based display/drawing :) namespace block { class Program { static void Main(string[] args) ...
3,054,161
3,054,199
Does any compiler support constexpr yet?
I want to play with constexpr, does any compiler support it yet?
The Apache Stdcxx project has a nice table detailing which C++0x features are supported by which compilers. It's been updated on a regular basis and covers most of the modern C++ compilers. According to that, only GCC 4.5 supports constexpr (note that that support may be experimental). Between that list and what has b...
3,054,235
3,054,242
TCHAR* envp[]: What is it?
I created a VC++ console project with Visual Studio and it auto-generated this function: int _tmain(int argc, TCHAR* argv[], TCHAR* envp[]) { ... } I was just wondering what envp stands for and how/when I can/should use it? Thank you!
The envp argument above will store the environment variables. The envp array, which is a common extension in many UNIX® systems, is used in Microsoft C++. It is an array of strings representing the variables set in the user's environment. This array is terminated by a NULL entry. It can be declared as an...
3,054,257
3,054,274
Is there STDCALL in Linux?
I'm trying to port a Windows app to Linux. This appplication marks some functions with the __stdcall attribute. However, I was told by a friend that stdcall is used only on Windows and has no meaning in Linux (but DOES exist in Windows GCC). Searching Google - some results state that there IS stdcall in Linux. Is there...
The simplest solution is to just define __stdcall to nothing conditionally on Linux.
3,054,400
3,055,545
Application disappears after starting - C++ linking managed code dll
we have a problem with our applications. We have recently upgraded our toolchain to Visual Studio 2010 and friends, it all works fine on Windows Vista + Windows 7 developer machines and Windows 7 customer machines. (all x86) Today we did a first installation to a client PC running Windows XP SP2 x86, and all applicatio...
See if drwtsn32 is configured as the application debugger on the client pc. Check for "C:\Documents and Settings\All Users\Application Data\Microsoft\Dr Watson". If you have a log in that location, search for "fault ->" and you will find the address within the process that caused the access violation. From there, yo...
3,054,442
3,055,497
Is it possible to use threads to speed up file reading?
I want to read a file as fast as possible (40k lines) [Edit : the rest is obsolete]. Edit: Andres Jaan Tack suggested a solution based on one thread per file, and I want to be sure I got this (thus this is the fastest way) : One thread per entry file reads it whole and stocks its content in a container associated (->...
Your question got a little bit deeper, when you asked further. I'll try to cover all your options... Reading One File: How many threads? Use one thread. If you read straight through a file front-to-back from a single thread, the operating system will not fetch the file in small chunks like you're thinking. Rather, it w...
3,054,460
3,054,484
Possible to call a managed DLL from unmanaged C++?
Is it possible to call CLR DLL (one for example which is made with C#) from unmanaged C++ code? I need a DLL that is not managed to call into it somehow, maybe even via some proxy C++ process that is built with C++ / CLI?
The CLR DLL would have to be built as a COM visible assembly. If you have control of the C#, it's a simple rebuild, otherwise, is pretty much impossible to use it directly.
3,054,567
3,054,584
"Right" way to deallocate an std::vector object
The first solution is: std::vector<int> *vec = new std::vector<int>; assert(vec != NULL); // ... delete vec; An alternative is: std::vector<int> v; //... vec.clear(); vec.swap(std::vector<int>(vec)); The second solution's a bit of a trick --- what's the "right" way to do it? Update: I'm aware that the destructor will...
The simplest and most reliable way to deallocate a vector is to declare it on the stack and simply do nothing. void Foo() { std::vector<int> v; ... } C++ guarantees that the destructor of v will be called when the method executes. The destructor of std::vector will ensure any memory it allocated is freed. As lon...
3,054,892
3,055,093
What's the best way to write to more files than the kernel allows open at a time?
I have a very large binary file and I need to create separate files based on the id within the input file. There are 146 output files and I am using cstdlib and fopen and fwrite. FOPEN_MAX is 20, so I can't keep all 146 output files open at the same time. I also want to minimize the number of times I open and close an ...
A couple possible approaches you might take: keep a cache of opened output file handles that's less than FOPEN_MAX - if a write needs to occur on a files that already open, then just do the write. Otherwise, close one of the handles in the cache and open the output file. If your data is generally clumped together in ...
3,055,028
3,055,438
How to send stream data via Bluetooth from an iPhone/iPod Touch to a Windows C++ application?
I need to develop an iPhone/iPod Touch application that creates a server to send some data stream (characters or bytes) to a Windows C++ application via Bluetooth. I'm thinking of creating a TCP connection, but don't know where to start. What iPhone API should I use do to something like this? Does anyone knows some cod...
Yes. From what it looks like you can use the PAN bluetooth profile (the same profile used for tethering) with everything except the original iPhone. Here's an article doing bluetooth over iPhone/iPad using GameKit. The article notes that you would need at least 2 iPhone/iPad devices running iPhone OS 3.0, but I would...
3,055,141
3,055,155
Interview question about virtual functions in C++
I was asked this crazy question. I was out of my wits. Can a method in base class which is declared as virtual be called using the base class pointer which is pointing to a derived class object? Is this possible?
If you're trying to invoke a virtual method from the base class pointer, yes. That's polymorphism. If you're asking, with a base class pointer to a derived class, can you invoke a base class method that is overriden by the derived class? Yes that's also possible by explicitly scoping the base class name: basePtr->BaseC...
3,055,240
3,055,306
Create a modifiable string literal in C++
Is it possible to create a modifiable string literal in C++? For example: char* foo[] = { "foo", "foo" }; char* afoo = foo[0]; afoo[2] = 'g'; // access violation This produces an access violation because the "foo"s are allocated in read only memory (.rdata section I believe). Is there any way to force the "foo...
You could create a multidimensional array of chars: #include <iostream> int main(int argc, char** argv) { char foo[][4] = { "foo", "bar" }; char* afoo = foo[0]; afoo[2] = 'g'; std::cout << afoo << std::endl; } More verbose way to define the array: char foo[][4] = { {'f', 'o', '...
3,055,267
3,056,082
Combine Video and Audio Streams (Qt, OpenCV, PortAudio,libsnd?)
I was wondering, how would I combine recorded audio and video into one if I have them in separate files? Preferably using OpenCV and PortAudio/libsnd. Thanks in advance.
FFmpeg is used to decode and encode almost all popular formats. It can be used as an alternative to all of these. PortAudio will probably only be useful for audio playback, so unless you need to play the stuff back it won't be needed. In case you do need A/V playback, FFmpeg is also good (VLC uses it.)
3,055,421
3,056,049
Find missing number in sequence in set or list
If a std::set or std::list contains a sequence of natural numbers (1, 2, 3..). would there be a function in standard library to find the missing number?
You can find all missing numbers using set_difference and a custom iterator: class seqIter : public std::iterator<std::input_iterator_tag, int> { public: seqIter(int n) : num(n) {} seqIter(const seqIter & n) : num(n.num) {} int & operator *() {return num;} seqIter & operator ++() { ++num; return *this; ...
3,055,733
3,055,764
Strange GCC 'expected primary expression...' error
Possible Duplicate: Templates: template function not playing well with class’s template member function template <typename T> struct A { template <int I> void f(); }; template <typename T> void F(A<T> &a) { a.f<0>(); // expected primary-expression before ‘)’ token } int main() { A<int> a; a.f<...
When a dependent name is used to refer to a nested template, the nested name has to be prepended with the keyword template to help the compiler understand that you are referring to a nested template and parse the code correctly template <typename T> void F(A<T> &a) { a.template f<0>(); } Inside main the name a is ...
3,055,924
3,057,051
Problems with system() calls in Linux
I'm working on a init for an initramfs in C++ for Linux. This script is used to unlock the DM-Crypt w/ LUKS encrypted drive, and set the LVM drives to be available. Since I don't want to have to reimplement the functionality of cryptsetup and gpg I am using system calls to call the executables. Using a system call to...
Amardeep is right, system() on POSIX type systems runs the command through /bin/sh. I doubt you actually have a legitimate need to invoke these programs you speak of through a Bourne shell. A good reason would be if you needed them to have the default set of environment variables, but since /etc/profile is probably al...
3,056,113
3,123,255
Recording Audio with OpenAL
I've been comparing various audio libraries available in C++. I was wondering, I'm kind of stuck starting with OpenAL. Can someone point out an example program how to record from a mic using OpenAL in C++. Thanks in advance!
Last time I checked OpenAL it was quite simple. You create the recording device and start the recording going. You then just call the get buffer function. It will wait until there is enough data to fill the buffer and then return when there is enough data. Why not just look at the "capture" example that comes with t...
3,056,174
3,056,288
Deleting a element from a vector of pointers in C++
I remember hearing that the following code is not C++ compliant and was hoping someone with much more C++ legalese than me would be able to confirm or deny it. std::vector<int*> intList; intList.push_back(new int(2)); intList.push_back(new int(10)); intList.push_back(new int(17)); for(std::vector<int*>::iterator i = i...
Your code is fine. If you're worried for some reason about the elements being invalid momentarily, then change the body of the loop to int* tmp = 0; swap (tmp, *i); delete tmp;
3,056,309
3,056,326
Meaning of int(0) in int *pi = new int(0);?
int *pi = new int(0); What's the significance of 0 here? Does it mean integer array of length 0?
It is an initializer (constructor parameter). The newly created int will have value of 0.
3,056,597
3,056,619
Are vectors more rigorous at checking out of bounds than heap arrays?
How rigorous is the bounds checking on vectors compared to heap arrays? How exactly is it checking bounds and how does that compare with how a heap array is checked?
A vector will do bounds checking if you use the at() function, for example: std::vector<int> v(5); v.at(3) = 10; v.at(5) = 20; // throws an exception, std::out_of_range However, if you use operator[], there is no bounds checking. (And accessing non-existent elements leads to undefined behavior.) It should be noted, t...
3,056,655
3,056,753
Can overloading is possible with two version of function, constant member function and function without const
I just came across various overloading methods like type of parameter passed, varying number of parameters, return type etc. I just want to know that can I overload a function with following two version //function which can modify member String& MyClass::doSomething(); //constant member function String& MyClass::doS...
Yes you can. If you have MyClass m; m.doSomething(); The non-const version will be called. When you have const MyClass m; m.doSomething(); The const version will be called.
3,056,696
3,056,728
is there any faster way to parse than by walk each byte?
is there any faster way to parse a text than by walk each byte of the text? I wonder if there is any special CPU (x86/x64) instruction for string operation that is used by string library, that somehow used to optimize the parsing routine. for example instruction like finding a token in a string that could be run by ha...
The x86 had a few string instructions, but they fell out of favor on modern processors, because they became slower than more primitive instructions which do the same thing. The processor world is moving more and more towards RISC, ie, simplistic instruction sets. Quote from Wikipedia (emphasis mine): The first highly ...
3,056,698
3,057,121
Item in multiple lists
So I have some legacy code which I would love to use more modern techniques. But I fear that given the way that things are designed, it is a non-option. The core issue is that often a node is in more than one list at a time. Something like this: struct T { T *next_1; T *prev_1; T *next_2; T *prev_2; ...
As another possible solution, look at Boost Intrusive, which has an alternate list class a lot of properties that may make it useful for your problem. In this case, I think it'd look something like this: using namespace boost::intrusive; struct tag1; struct tag2; typedef list_base_hook< tag<tag1> > base1; typedef lis...
3,056,839
3,056,857
Checking for open ports in C/C++
There have been other questions regarding the subject of verifying the accessibility and accessibility of socket ports. How would one go about looking for a port to listen on dynamically in C/C++? The basic process I'm trying to accomplish is this: Client starts Client finds open port XYZ and listens on it. Client t...
If you bind to port 0, a random port will be allocated. Then getsockname() may be used to find out the actual port used.
3,056,853
3,056,932
any stl/boost functors to call operator()
template <typename T> struct Foo { void operator()(T& t) { t(); } }; Is there any standart or boost functor with the similar implementation? I need it to iterate over container of functors: std::for_each(beginIter, endIter, Foo<Bar>()); Or maybe there are other way to do it?
Binders like Boosts or C++0x bind() make it trivial to generate such a functor: std::for_each(begin, end, boost::bind(&Bar::operator(), _1)); Or using mem_fun_ref: std::for_each(v.begin(), v.end(), std::mem_fun_ref(&Bar::operator()));
3,056,925
3,057,057
CURL C API: callback was not called
The code below is a test for the CURL C API . The problem is that the callback function write_callback is never called. Why ? /** compilation: g++ source.cpp -lcurl */ #include <assert.h> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <curl/curl.h> using namespace std; static s...
You need to check the value of still_running and call curl_multi_perform() again if there are still pending operations. Simple example: int still_running=0; /* lets start the fetch */ do { while(::curl_multi_perform(multi_handle, &still_running) == CURLM_CALL_MULTI_PERFORM); } while (still_running);
3,056,996
3,057,023
Stringified template argument
Is it possible to get a stringified version of a template argument name? Something like this, if only we were running the preprocessor: template <typename T> struct Named{ const char* name(){ return "Named<" #T ">"; } }; Edit Duplicate. See here Stringifying template arguments
No. The closest thing you can have is typeid(T).name(). However, the result of this is unspecified, even an implementation which returned empty strings for all types would be conforming. For debugging purposes it often is sufficient, though.
3,057,009
3,057,219
Storing objects in the array
I want to save boost signals objects in the map (association: signal name → signal object). The signals signature is different, so the second type of map should be boost::any. map<string, any> mSignalAssociation; The question is how to store objects without defining type of new signal signature? typedef boost::signals...
This has nothing to do with any or map. Boost signals are simply non-copyable. You can wrap them in a smart pointer such as shared_ptr if you want something that's copyable and cleans up after itself.
3,057,029
3,057,797
Do I have to bind a UDP socket in my client program to receive data? (I always get WSAEINVAL)
I am creating a UDP socket (AF_INET, SOCK_DGRAM, IPPROTO_UDP) via Winsock and trying to recvfrom on this socket, but it always returns -1 and I get WSAEINVAL (10022). Why? When I bind() the port, that does not happen, but I have read that it is very lame to bind the client's socket. I am sending data to my server, whic...
With UDP, you have to bind() the socket in the client because UDP is connectionless, so there is no other way for the stack to know which program to deliver datagrams to for a particular port. If you could recvfrom() without bind(), you'd essentially be asking the stack to give your program all UDP datagrams sent to ...
3,057,101
3,057,248
C++ function-pointer and inheritance
I have an generic math-method, that operates under a set of functions (with a lot of variables and states, so it can't be static). I've implemented method in parent class and I want to declare a different set of functions in every child-class. I've try to do something like this: class A { public: typedef int (A::*f...
Curiously recurring template pattern would help. template<typename Derived> class A { public: typedef int (Derived::*func)(); func * fs; void f() { Derived* const This = static_cast<Derived*>(this); /* call functions like (This->*(fs[0]))() */ } }; class B : public A<B> { public: ...
3,057,105
3,059,028
Thread raising event gets blocked by handlers?
I am raising an event from managed C++ which is handled by a C# app. Is the C# event handler executed on the same thread it was raised from C++ ?? In other words, Is raising event blocking for C++ until it is completely handled by C#?
Event handler invocation is synchronous by default in .NET, and since your code is both Managed C++ and C#, it is all ".NET". If you wish your event handlers to function asynchronously, you could simply attach a handler on the C# side that either starts another Thread to do the work, drops a worker into ThreadPool, or ...
3,057,136
3,057,502
Is Private Bytes >> Working Set normal?
OK, this may sound weird, but here goes. There are 2 computers, A (Pentium D) and B (Quad Core) with almost the same amount of RAM running Windows XP. If I run the same code on both computers, the allocated private bytes in A never goes down resulting in a crash later on. In B it looks like the private bytes is constan...
The fact that a memory leak (increasing private bytes) doesn't have an effect on working set is no surprise. The working set size is determined by the number of memory pages the application has touched recently. Private bytes is the amount of memory that a process has allocated (and not shared with other processes). ...
3,057,153
3,061,727
Tips for submitting a library to Boost?
Summer is coming, and a group of friends and I are getting ready for it :) We decided to build a compile-time Arbitrary precision Unsigned Integers. We would like to provide a set of integers algorithms(functions) with the library. We have seen a number of requests for such a library(SoC2010, C++0x Standard Library wis...
Two additional hints: a) Planning for a pure C++0x library seems not to be a good idea in the context of Boost. One of Boost's goals is to provide cross-platform/cross-compiler libraries. Usually Boost authors interested in using C++0x features do that as an alternative enabled when using a C++0x compiler. For that pu...
3,057,213
3,057,228
accessing a vector from the back
Is there a way to access an element on a vector starting from the back? I want to access the second last element.currently I'm using the following to achieve that: myVector[myVector.size() - 2] but this seems slow and clunky, is there a better way?
Not likely to be any faster, but this might look nicer: myVector.end()[-2]
3,057,346
3,057,540
Vertical Rebar (WinAPI)
I was wondering if it was possible to make a Rebar that goes vertically instead of controls horizontally? Thanks
The answer is Yes :) Google for CCS_VERT style as keyword (this one makes toolbars vertical).
3,057,448
3,057,465
Angle between 3 vertices
For example, GetAngle((0,0),(100,0),(100,100)) = 90. How could I find the angle between 3 2D Points.
Given points A, B, and C, you want the angle between AB and AC? First compute the vectors AB and AC -- it's just the coordinates of B minus coordinates of A and likewise for AC. Take the dot product of the two vectors. This is just the product of the x coordinates plus the product of the y coordinates of the vectors. D...
3,057,826
3,058,959
ServicedComponent not being disposed in finaliser
Questions needing answers : Does the finalizer of the client side ServicedComponent call ServicedComponent.DisposeObject or Dispose? How should destruction (release of memory) occur in the com server in relation to its usage in the client? Basically - we are reaching a 2 gig limit on process size (memory) of the COM s...
You should definitely be calling either Dispose or ServicedComponent.DisposeObject on the client side. Microsoft says "It is preferable to use the Dispose design pattern rather than DisposeObject." Exactly what is happening in COM+ will depend on a few things: Is the application a Library or Server application Is ...
3,057,845
3,057,861
C++ initializing constants and inheritance
I want to initialize constant in child-class, instead of base class. And use it to get rid of dynamic memory allocation (I know array sizes already, and there will be a few child-classes with different constants). So I try: class A { public: const int x; A() : x(0) {} A(int x) : x(x) {} void f() { ...
It isn't a constant though. It can still be modified by the constructor. Only a compile time constant is allowed for the size of an array. When the compiler says "constant expression", it is not meaning an expression which returns a constant value, but an constant, such as "52" or "45" or something along those lines. U...
3,057,859
3,057,880
What's the difference between explicit and implicit assignment in C++
int value = 5; // this type of assignment is called an explicit assignment int value(5); // this type of assignment is called an implicit assignment What is the difference between those, if any, and in what cases do explicit and implicit assignment differ and how? http://weblogs.asp.net/kennykerr/archive/2004/08/31/E...
They differ if a class has a constructor marked 'explicit'. Then, one of these does not work. Otherwise, no difference.
3,057,975
3,058,077
How to iterate a list of vector
If I have a vector of object vector, how can I check if A* myA is inside that vector?
Try this... #include <algorithm> bool in_vector(const std::vector<A*>& vec, const A* myA) { std::vector<A*>::const_iterator end = vec.end(); return std::find(vec.begin(), end, myA) != end; }
3,057,977
3,057,994
Rewinding std::cout to go back to the beginning of a line
I'm writing a command-line tool for Mac OS X that processes a bunch of files. I would like to show the user the current file being processed, but do not want a bazillion files polluting the terminal window. Instead I would like to use a single line to output the file path, then reuse that line for the next file. Is the...
"\r" should work for both windows and Mac OS X. Something like: std::cout << "will not see this\rwill see this" << std::flush; std::cout << std::endl; // all done
3,058,006
3,058,048
C++: Trouble with Pointers, loop variables, and structs
Consider the following example: #include <iostream> #include <sstream> #include <vector> #include <wchar.h> #include <stdlib.h> using namespace std; struct odp { int f; wchar_t* pstr; }; int main() { vector<odp> vec; ostringstream ss; wchar_t base[5]; wcscpy_s(base, L"1234"); for (int ...
... odp foo; foo.f = i; wchar_t loopStr[1]; //A foo.pstr = loopStr; //B foo.pstr[0] = base[i]; //C vec.push_back(foo); ... A - You allocate an array (of size 1) to the stack B - You assign foo.pstr to point to the array on the stack C - You assign base[i] to the first element of...
3,058,101
3,058,144
Setting the default stack size on Linux globally for the program
So I've noticed that the default stack size for threads on linux is 8MB (if I'm wrong, PLEASE correct me), and, incidentally, 1MB on Windows. This is quite bad for my application, as on a 4-core processor that means 64 MB is space is used JUST for threads! The worst part is, I'm never using more than 100kb of stack per...
You do not need to do this. The machine's physical memory is employed only where it is needed by a demand page fault system. Even if the thread stacks are significantly larger than the amount you are using the extra size is in virtual address space and does not tie up physical RAM. Had physical RAM been tied up at th...
3,058,109
3,066,411
Named captured substring in pcre++
I want to capture named substring with the pcre++ library. I know the pcre library has the functionality for this, but pcre++ has not implemented this. This is was I have now (just a simple example): pcrepp::Pcre regex("test (?P<groupName>bla)"); if (regex.search("test bla")) { // Get matched group by name int...
My mistake unfortunately, I tested the regex in my real program and there the regex was different. I used something like this: (?:/(?P<controller>[^/]+)(?:/(?P<action>[^/]+))?)? So the group name to number conversion goes well, but when i try to access the group i get index of range because of the (?: ... )? groups. ...
3,058,267
3,058,343
Nested Class member function can't access function of enclosing class. Why?
Please see the example code below: class A { private: class B { public: foobar(); }; public: foo(); bar(); }; Within class A & B implementation: A::foo() { //do something } A::bar() { //some code foo(); //more code } A::B::foobar() { //some code foo(); //<<comp...
foo() is a non-static member function of A and you are trying to call it without an instance. The nested class B is a seperate class that only has some access privileges and doesn't have any special knowledge about existing instances of A. If B needs access to an A you have to give it a reference to it, e.g.: class A {...
3,058,481
3,058,506
c++ callback syntax in a class
I am trying to figure out the syntax to register a callback with this 3rd party software. I think it is probably a basic question, I just am not too familiar with c++. They have a method for registering a callback function so their code can call a function in my code when an event happens. They provided a working ex...
You need to use a trampoline function as member functions can't be called without an instance: void STDCALL trampoline(void* data, smEngineHeadPoseData hp, smCameraVideoFrame vf) { static_cast<FaceEngine*>(data)->receiveFaceData(hp, vf); } // ... register: smHTRegisterFaceDataCallback(hFaceAPIEngine, static_cast<v...
3,058,552
3,058,595
Raw OpenGL equivillant of GLUPerspective?
how could I do the same as GluPerspective without Glu? Thanks ex: gluPerspective(45.0, (float)w / (float)h, 1.0, 200.0);
void gluPerspective( GLdouble fovy, GLdouble aspect, GLdouble zNear, GLdouble zFar ) { GLdouble xmin, xmax, ymin, ymax; ymax = zNear * tan( fovy * M_PI / 360.0 ); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum( xmin, xmax, ymin, ymax, zNear, zFar ); }
3,058,561
3,058,733
How do I make a class whose interface matches double, but upon which templates can be specialized?
How do I make a class whose interface matches double, but whose templated types do not dynamic cast to double? The reason is that I have a run-time type system, and I want to be able to have a type that works just like double: template<int min_value, int max_value> class BoundedDouble: public double {}; And then use t...
You can't derive from native types. Use composition instead: #include <cstdlib> #include <string> #include <stdexcept> #include <iostream> using namespace std; template<typename Type = double, const Type& Min = -10.0, const Type& Max = 10.0> class Bounded { public: Bounded() {}; Bounded(const Type& rhs) : val...
3,058,820
3,067,365
How do you return a pointer to a base class with a virtual function?
I have a base class called Element, a derived class called Vector, and I'm trying to redefine two virtual functions from Element in Vector. //element.h template <class T> class Element { public: Element(); virtual Element& plus(const Element&); virtual Element& minus(const Element&); }; and in another file //Vector.h...
compiler says what is obvious: the base class Element doesn't have member variable 'x' because x is declared and in Vector and not in Element. Try this: Element<T>& plus(const Element<T>& v) const { const Vector<T> & vect = dynamic_cast<const Vector<T> &>(v); Vector<T>* ret = new Vector((x + vect.x), (y + vect.y...
3,058,833
3,058,845
Strange exception phenomenon in Windows 7
I spot some interesting articles about exception handle in CodeProject http://www.codeproject.com/KB/cpp/seexception.aspx After reading, I decided to do some experiment. The first time I try to execute the following code char *p; p[0] = 0; The program died without question. But After several times when I executed the...
Dereferencing a pointer that doesn't point to an object (for example, an uninitialized pointer) results in undefined behavior. This means that anything can happen. Typically, writing via an uninitialized pointer will cause your program to crash--either immediately or at some point in the future. It is conceivable tha...
3,058,878
3,059,339
OpenGL polygons stuck at top left?
I'm using theallegro library and through it OpenGL. I enable depth testing, then upon resize I do: glEnable(GL_CULL_FACE); glCullFace(GL_BACK); glEnable(GL_DEPTH_TEST); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum(0,event.display.width,event.display.height,0,1,300); Then my drawing ...
I don't know any specifics of the allegro library, but two things come to mind when reading your code snippet. Why don't you call glViewport(event.display.width,event.display.height) upon resize? The glFrustum call usually shouldn't depend on the display size. Do you ever call glMatrixMode(GL_MODELVIEW)? Otherwise all...
3,058,992
3,059,528
All possible paths in a cyclic undirected graph
I'm trying to develop an algorithm that identifies all possible paths between two nodes in a graph, as in this example: . in fact, i just need to know which nodes appear in all existing paths. in the web only got references about DFS, A* or dijkstra, but i think they doesn't work in this case. Does anyone know how to s...
You can find all paths using DFS like |Vlad described. To find which nodes appear in every path, you could just maintain an array of booleans that says whether each node has appeared in every path so far. When your DFS finds a path, go through each vertex not in the path and set the corresponding array value to false. ...
3,059,032
3,059,120
Documentation for Qt documentation comments? Qt + Doxygen?
Where can I find documentation for Qt documentation comments? I'm referring to how Qt uses a specific style for documentation comments, like so: /*! \class MyClassName \brief The MyClassName class is used as an example on Stack Overflow. This class serves a few functions, the most important being: \li...
Don't use qdoc. It is deprecated. Use Doxygen, which is based on qdoc anyway. That said, the documentation (in qdoc format :-D ) is here.
3,059,143
3,059,228
what the snippet of code does
I would like to know what the snippet of code does.. Drive[0] = 'A'; Drive[1] = ':'; Drive[2] = '\\'; Drive[3] = 0; DriveMask = GetLogicalDrives(); for( anIndex = 0; anIndex < 26; anIndex++ ) { if( DriveMask & 1 ) { Drive[0] = 'A' + anIndex; DriveMask >>= 1; } } Please let me...
It's enumerating all the possible attached drives between A:\ and Z:\ and checking to see whether they're removable (eg CD, floppy). It loops 26 times, and each time DriveMask >>= 1; causes the bitmask to be shifted right by 1 bit, so that each logical drive can be tested for via the if( DriveMask & 1 ) in successio...
3,059,343
3,063,343
How to give 'Everybody' full rights to a file (programmatically)
I'm modifying an old C++ program to run on Vista. It does not require Admin privileges. I've changed the code to put logfiles in \ProgramData\MyApp\. These logfiles are written with the stdio functions (fopen, fprintf, fclose). Here's the problem: UserA runs the program first, it creates \ProgramData\MyApp\MyLogFile....
+1 to everyone for trying, but eventually I found the answer here: how to change the ACLs from c++? I did have to change one line of that solution, from this: ea[0].grfAccessMode = DENY_ACCESS; to this: ea[0].grfAccessMode = GRANT_ACCESS;
3,059,358
3,059,378
how to get the type of a deferred template parameter
Is there a way to get the defered type of a class template parameter ? template <class TPtr> struct foo { typedef TPtr ptr_type; typedef ??? element_type; /* shall be the type of a deferred TPtr*/ }; so foo<const char*>::element_type results in const char, and foo<std::vector<int>::iterator_type>::element_type...
If TPtr can only be a pointer, you're looking for Boost's remove_pointer. If you're wondering how in the world that works, it uses partial specialization in this manner: template<typename T> struct RemovePointer; template<typename T> struct RemovePointer<T*> { typedef T Type; }; int main() { RemovePointer<int...
3,059,649
3,059,673
STL in C++ how does it work
I have very technical question, I was working with C, and now I'm studying C++, if I have for example this class class Team { private: list<Player> listOfPlayers; public: void addPlayer(string firstName, string lastName, int id) { Player newPlayer(string firstName, string lastName, int id); l...
Here's a "correct" implementation of what you have now: #include <list> #include <string> class Player { private: std::string strLastName; std::string strFirstName; int nID; public: // You should pass std::strings to functions by const reference. // (see Kirill V. Ly...
3,059,756
3,059,944
C++: how to truncate the double in efficient way?
I would like to truncate the float to 4 digits. Are there some efficient way to do that? My current solution is: double roundDBL(double d,unsigned int p=4) { unsigned int fac=pow(10,p); double facinv=1.0/static_cast<double>(fac); double x=static_cast<unsigned int>(d*fac)*facinv; return x; } but using pow and delet...
round(d*10000.0)/10000.0; or if p must be variable; double f = pow(10,p); round(d*f)/f; round will usually be compiled as a single instruction that is faster than converting to an integer and back. Profile to verify. Note that a double may not have an accurate representation to 4 decimal places. You will not truly ...
3,059,768
3,059,848
Qt - QTimeEdit as a timer viewer
I have a QTimeEdit which I want to set to some value and the each second I want to decrease by 1 the value that shows the QTimeEdit. So when it will be 0, the I want to have a QMeesageBox that says "Your time is off.". Can I some how do this with QTimeEdit interface, or I should use QTimer?
You can use QTimeEdit for displaying the time but you will have to use QTimer to decrease the time every second. You can do something like this: timeEdit->setTime(...); //set initial time QTimer timer; timer.start(1000); //timer will emit timeout() every second connect(&timer, SIGNAL(timeout()), this, SLOT(slotTimeout(...
3,059,917
3,059,964
Are unspecified and undefined behavior required to be consistent between compiles of the same program with the same compiler in the same environment?
Let's pretend my program contains a specific construct the C++ Standard states to be unspecified behavior. This basically means the implementation has to do something reasonable but is allowed not to document it. But is the implementation required to produce the same behavior every time it compiles a specific construct...
Undefined behavior can vary between runs of the same program, and even between execution of the same code in the same run of the program. As an example, the value of an uninitialized (automatic) variable is undefined, and then its actual value is just whatever value that happened to be at that place in memory. Obviousl...
3,059,932
3,059,970
Why would I use a struct in a program?
I see lot of struct code like below struct codDrives { WCHAR letter; WCHAR volume[100]; } Drives[26]; We can use variables or array something like that to store the data. But I am not sure why would I use a struct in the programs?
Structs are inherited from C, and in C++ they are almost identical to classes. The difference is that the members of a struct are by default public, while class members are by default private. So the typical use of structs in C++ is dummy data structures which contain no logic (only - possibly - constructors and/or nec...
3,059,946
3,060,248
localtime_r supposed to be thread safe, but causing errors in Valgrind DRD
I searched google as much as I could but I couldn't find any good answers to this. localtime_r is supposed to be a thread-safe function for getting the system time. However, when checking my application with Valgrind --tool=drd, it consistantly tells me that there is a data race condition on this function. Are the comm...
If the documentation says it is reentrant (and thus thread-safe), then it is. If ever there was a bug in the code (not your code) and the function wasn't really thread-safe, there is nothing much you can do about it (unless using another function), and it's not up to you to fix this in your code: the function must beha...
3,060,006
3,060,024
Is it worth setting pointers to NULL in a destructor?
Imagine I have a class that allocates memory (forget about smart pointers for now): class Foo { public: Foo() : bar(new Bar) { } ~Foo() { delete bar; } void doSomething() { bar->doSomething(); } private: Bar* bar; }; As well as deleting the objects in the destructor is it also worth sett...
Since the destructor is the last thing that is called on an object before it "dies," I would say there is no need to set it to NULL afterwards. In any other case, I always set a pointer to NULL after calling delete on it.
3,060,015
3,060,047
organizing external libraries and include files
Over the years my projects use more and more external libraries, and the way I did it starts feeling more and more awkward (although, that has to be said, it does work flawlessly). I use VS on Windows, CMake on others, and CodeComposer for targetting Digital Signal Processors (DSPs) on Windows. Except for the DSPs, bot...
Why not use file system links? ln -s /path/to/apis/apiA/include /path/to/api/include/apiA Voilá. Similar can be done on Windows, but I don't have the command line handy right now.
3,060,157
3,060,164
What determines when a destructor is called for a temporary object in C++?
Guys I've asked few days ago a question and didn't have really time to check it and think about it, but now I've tried one of the solutions and I can't understand why does it work? I mean why destructor is called at the end of line like this: #include "stdafx.h" #include "coutn.h" #define coutn coutn() int _tmain(int...
coutn() create a temporary object, which will be destroyed at the next sequence point (the end of the line in this case).
3,060,187
3,060,196
an error "has no member named"
I have this snippet of the code account.cpp #include "account.h" #include <iostream> #include <string> using namespace std; Account::Account(string firstName, string lastName, int id) : strFirstName(firstName), strLastName(lastName), nID(id) {} void Account::printAccount(){ cout << strFirstName; } account...
You forgot the parentheses after printAccount(). Otherwise, it's not a method call. Also, you need to use the -> operator, since it's an iterator. for(list<Account>::iterator i = listOfAccounts.begin(); i != listOfAccounts.end(); ++i) { i->printAccount(); // Note the ()! // This is equivalent to (*i).prin...
3,060,201
3,060,934
Compile OpenCL kernels with debug information?
How can I compile opencl kernels with debug information? If i do it like hear debugging [const char* options = "-g"; clBuildProgram( *hProgram, 0, 0, options,NULL,NULL);]: i get following error: clang: Unknown command line argument '-g'. Try: 'clang --help'
"-g" is not a supported build option in OpenCL, see section 5.4.3/5.6.3 (version 1.0/1.1 respectively) of the specification for a list of the supported options. If you're targetting a CPU then "-g" may work but is unsupported. For debugging on GPUs you could check out gDEBugger CL perhaps, I've not tried it though. NVI...