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,506,414
3,506,511
memory management issues in C++
I would like to know what are the common memory management issues associated with C and C++. How can we debug these errors. Here are few i know 1)uninitialized variable use 2)delete a pointer two times 3)writing array out of bounds 4)failing to deallocate memory 5)race conditions 1) malloc passed back a NULL pointer....
Preemptively preventing these errors in the first place: 1) Turn warnings to error levels to overcome the uninitialized errors. Compilers will frequently issue such warnings and by having them accessed as errors you'll be forced to fix the problem. 2) Use Smart pointers. You can find a good versions of such things ...
3,506,456
3,506,487
Can I destruct a structure in C++?
Is there a way to destruct a structure (not a class)?
In C++ a struct is exactly the same as a class with the exception of the default visibility on members and bases. So if there is a way to "destruct" a class, you can use the exact same way to "destruct" a structure. So, if you have a struct s { } in your C++ program you can do this: s *v = new s(); delete v; // will ca...
3,506,504
3,506,544
C code changes terminal text color; how can I restore defaults? Linux
I have a C file running on Linux. It prints some lines in red (failures) and some in green (passes). As you might expect, it uses escape codes in the printf statements as follows: #define BLACK "\033[22;30m" #define GREEN "\033[22;31m" printf(GREEN "this will show up green" BLACK "\n"); If the BLACK at the end wasn...
Try using: #define RESETCOLOR "\033[0m" That should reset it to the defaults. More about these terminal codes can be found in ANSI escape code.
3,506,524
3,506,824
C++ - building libraries
I'm building static libraries (right now libpng) in Microsoft Visual Studio 2008 SP1. Do I have any possibility to build single library (one file) for both Debug and Release modes assuming that my library has only C code in it? As far as I remember, gtkmm, for instance, has it's pre-built package, where C++ based libra...
In theory you could build just one library if all the external headers for the library (ie the ones pulled in by the client) don't use #ifdef _DEBUG (or any other macro that may be defined in a debug build but not a release build. Consider a case like this: // file: mylib.h struct A { int member1; int member2; ...
3,506,661
3,506,732
C++ double buffer and memory
Ok so my double buffer works fine but it seems that it use a lot of memory. i know that double buffer should store a copy of the ellipse I'm drawing than paint it on the screen but it after that it deletes the copy and makes new copy but it doesn't seem to delete it here is my code hdc=GetDC(hWnd); HDC memDC=CreateCom...
You are destroying all objects, but not the DC. You must call ReleaseDC after the drawing. See the MSDN: After painting with a common device context, the ReleaseDC function must be called to release the device context.
3,506,775
3,507,154
TR1 from Boost or VC10 - Which one is better?
I'm currently migrating from Visual Studio 2008 to 2010. My software makes heavy use of Boost and its TR1 features. I now get a lot of compiler errors, because VC10 has it's own TR1 implementation. I know I can disable Microsoft's TR1 implementation with the _HAS_CPP0X switch (see here), but I'm not sure if this also d...
If your code doesn't compile with VC10's standard library, then that might indicate that it isn't standard-conforming. The standard library in VC10 comes from Dinkumware, and these guys aren't bad when it comes to implementing a standard library. (PJP used to be the lib working group's chair.) I'd look very closely at ...
3,506,796
3,506,938
pinvokestackimbalance -- how can I fix this or turn it off?
I just switched to vs2010 from vs2008. Exact same solution, except now every single call to a C++ dll yields a 'pinvokestackimbalance' exception. This exception does not get fired in 2008. I have complete access to the C++ dll and to the calling application. There does not appear to be any problem with the pinvoke, ...
First, understand that the code is wrong (and always has been). The "pInvokeStackImbalance" is not an exception per se, but a managed debugging assistant. It was off by default in VS2008, but a lot of people did not turn it on, so it's on by default in VS2010. The MDA does not run in Release mode, so it won't trigger i...
3,506,820
3,506,962
undefined reference to `Class::Class()'
I am writing a GTKmm window program; the main window creates two buttons, one for English and one for Chinese. The user can click on the button to bring up a different window in the appropriate language. Currently I am having trouble initializing the multiple-item container inside the main window. It is an object of ty...
Undefined reference errors mean you either forgot to write define the missing function (by writing an implementation in the .cpp file), or you forgot to link the appropriate object file or library into the final binary. In this case, it's the later reason. You need to include MainWindowPane.o in the linker command in y...
3,507,085
3,507,145
Input Box in an MFC CWinApp program?
I need an input box in a UI program that is already written derived from the CWinnApp class and using MFC. I see it is using message boxes but I don't see any examples of input boxes.... How do I do this? (Using Visual Studio 6.0 in C++) Thank You.
I know it's something that's often required, but there isn't a built-in input box in MFC, so you'll have to create your own. I usually just create a simple dialog with a label and edit box (the dialog already comes with OK/Cancel buttons), then create a class, say CInputDlg, add member variables for the label and edit ...
3,507,100
3,507,226
order of destruction using virtual
Can some one please help what the order of destruction is when I am using virtual functions. Does it start with the base class and then derived class?
Since I don't see how virtual function change any objects' destruction order, I assume you're referring to the order of destruction for base classes and data members in a virtual inheritance scenario. Sub-objects are constructed base classes are constructed from most base to most derived; multiple base classes are ...
3,507,285
3,507,326
white space free path to My Documents
In building a C++ project with the GNU tool chain, make tells me ~ src/Adapter_FS5HyDE.d:1: *** multiple target patterns. Stop. Search, search, search, and I found out that make thinks that it has multiple targets because the path to my included headers has spaces in it. If you've got your headers stored in some s...
You can figure out what the old path is by doing a DIR /X in your command prompt. Or, most of the time you can fake it with the first 6 characters - spaces + ~1 + extension (8.3 paths won't have spaces). Or, you can use quotes: "C:\Documents and Settings\Administrator\My Documents".
3,507,322
3,507,348
Change background color of another program from C++ program
I'm trying to change the background color of a program I did NOT write. Looking at it with Spy++ I can see that the main class is "ThunderRT6FormDC". One of its children has the class "ThunderRT6Frame". Inside ThunderRT6Frame there are a bunch of ThunderRT6CommandButtons. I want to change the background color behind th...
You might see some success if you handle the WM_ERASEBKGND message similarly to the way you handle WM_PAINT.
3,507,352
3,507,441
When I derive a class in C++, does it create an object of base class and store it as my member variable in derived class?
Say i create a derived class as below, class CHIProjectData : public QObject { CHIProjectData(QMap<QString,QString> aProjectData, CHIMetaData* apMetaData = 0, QObject* parent = 0); private: QMap<QString,QString> m_strProjectData; C...
QObject(aParent) calls QObject's constructor with the aParent parameter. QObject is not a member variable in this case. It may seem like a subtle point, but its an important one because the way you access the properties and methods of a subobject requires different syntax than as for a member variable. Here's an anal...
3,507,442
3,507,452
How to truncate HWND title
I am creating a window which opens to a dynamic title. I would like to have the window's title truncate if the window is resized and there isn't room to show the full title. For example, I have HWND handle = GetHWND(); // gets me the correct handle std::wstring title = L"some fairly long window title"; SetWindowTextW(...
You can get the width of a string drawn to a given device context (HDC) by means of the GetTextExtentPoint32 function.
3,507,530
3,515,174
'QObject::QObject' cannot access private member declared in class 'QObject'
class CHIProjectData : public QObject { public: CHIProjectData(); CHIProjectData(QMap<QString,QString> aProjectData, CHIAkmMetaData* apAkmMetaData = 0, QObject* parent = 0); private: QMap <QString,QString> m_strProjectData; CHIAkmMetaData* m_pAkmMetaData; }; CHIPro...
Adding a copy constructor to CHIProjectData class did the trick.
3,507,600
3,507,660
c++ handling derived class that's self referencing
So suppose I have a tree class like this in c++ class Node{ void addChild(Node*); /*obvious stuff*/ protected: Node* parent; vector<Node*> children } class specialNode : public Node{ void addChild(specialNode*); /*obvious stuff*/ /*special stuff*/ } Now whenever I access the ch...
If you only need SpecialNode objects in your tree (and just want to encapsulate all generic tree functionality in Node) you can make Node a so called "mix-in" class like template <class N> class Node : public N { public: void addChild(Node<N>*); protected: Node<N>* parent; vector<Node<N>*> children; }; class Spe...
3,507,617
3,507,632
Variable of class A in class B and pointer of class B in class A?
This may seem weird but I have a problem in one of my programs where I have a class A which needs a variable of class B inside it, and the class B needs a pointer to class A inside it, so that I can determine which class is attached to what.... I get errors because in class A it says that the class B is not defined yet...
You need to declare A before you define B: class A; // declaration of A class B // definition of B { A* foo; // ... }; class A // definition of A { B bar; // ... }; This kind of declaration is often referred to as a forward declaration.
3,507,716
3,530,469
Example of using UDP in obj-c/C++?
I'm making an iOS app - real-time game, wanna use UDP protocol. I'm searching a lot for examples/guides, but can't find any. Also, the software on the server will use C++, and I've searched a lot and can't fina a nice way to use it, for begginers in C++... I found that: http://developer.apple.com/mac/library/samplecode...
Maybe have a look at UDT: UDT -- UDP-based data transfer http://udt.sourceforge.net/software.html The UDT software is a C++ library containing the UDT API implementation and programming examples. The most recent version is UDT version 4, including 3 separate packages: pure source code, GNU package, and pre-compiled WI...
3,508,017
3,508,117
mmap SIGSEGV when memory map is to a class member and modified outside the class
I have a very simple class that opens a file and creates a memory mapped file. The region is mapped to the member variable called data_ which is defined as unsigned char* data_; The memory map part looks like this: // Create memory mapped file unsigned char* data_ = (unsigned char*)mmap(NULL, 1024, ...
I am not fully sure what you mean that you have done so far. In the code you posted, it appears as if you assign the return-value of mmap to a local variable data_ instead of the member-variable data_. Is this just the currently "working" version (that isn't intended to use the member-variable), or is it an error? Are ...
3,508,053
3,508,078
How to use pass-by-reference arguments of template type in method templates?
I am currently struggling to get the following code to compile. First the header file containing a class with a method template: // ConfigurationContext.h class ConfigurationContext { public: template<typename T> T getValue(const std::string& name, T& default) const { ... } } Somew...
5 is a literal, and you cannot bind literals to non-const references. Either take T per copy or per const reference: template<typename T> T getValue(const std::string& name, const T& def) const (BTW, I doubt that your compiler accepts T default, because default is a keyword and must not be used as an identifier.) The...
3,508,108
3,508,553
Convert managed String (C#) to LPCOLESTR (C++)
I wave a method in C++ that receives a parameter of the LPCOLESTR type. I'm accessing this method through C#, but I can't make the correct conversion between String and this type. Let's say the method signinature in C++ is: void Something(LPCOLESTR str) In C#, I'm trying to call it (all reference issues to access the ...
The argument will appear as Char* on the C# side. That requires unsafe code, like this: unsafe static void CallSomething(MyClass obj, string arg) { IntPtr mem = Marshal.StringToCoTaskMemUni(arg); try { obj.Something((Char*)mem); } finally { Marshal.FreeCoTask...
3,508,248
3,508,275
mfc directory picker?
I did see this to modify CFileDialog (http://support.microsoft.com/kb/105497) but it looks like a lot more than I need. I'm using the CFileDialog to pick files, is there a simple way to use it to just select a directory? Any other suggestions? (I also saw this but is for XP only? http://msdn.microsoft.com/en-us...
You will probably want to use the SHBrowseForFolder API. There are lots of wrapper classes out there that make it easier to use. Like this one.
3,508,273
3,508,535
Why only one object gets constructed but multiple objects are destroyed when using functor?
The following example, beats me. I've been so far thinking, that when functor is being used, the object gets constructed once and the same object is used multiple times, when used with for_each algorithm and that seems to be correct. However, even though, only one object gets constructed, but multiple objects are dest...
Here is how I have for_each on my system: template<class _InIt, class _Fn1> inline _Fn1 _For_each(_InIt _First, _InIt _Last, _Fn1 _Func) { // perform function for each element for (; _First != _Last; ++_First) _Func(*_First); return (_Func); // a copy could be created her...
3,508,628
3,508,688
Meaningful diagnostic messages
Looking at several posts, I get a feel that many of the questions arise because compilers/implemenetation do not emit a very meaningful message many times (but not always). This is especially true in the case of templates where error messages could be at the least very daunting. A case in point could be the discussion ...
A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools. --- Douglas Adams I'll try to explain some rationale behind diagnostics (as the standard calls them): a) Why is it that compilers are sometimes unable to ...
3,508,839
3,508,852
C++ function return scope and reference
recently I am learning C++ and have some doubt on the following case. void function_a(const int &i){ //using i to do something } int function_b(){ return 1; } ok, if I am going to call... function_a(function_b()); is there any chance that function_a read dirty reference from the it's param? Thank for your time.
In this case, the compiler will generate an unnamed temporary value whose reference will be passed to function_a. Your code will be roughly equivalent to: int temporary = function_b(); function_a(temporary); The scope of temporary lasts until the end of the statement that calls function_a() (this is inconsequential fo...
3,508,947
3,557,418
LGPL Machine Learning with Random Forest - C++
I am looking for a library with following features: Minimalistics with Random Forest learning and classification LGPL licenced In C++ CMake build system - not compulsory So far Waffles looks good, any other contenders ?
How about TMVA or alglib? I haven't used them personally, but the license terms look to be favorable for your uses, and both are C++. Not sure if they have the specifics you're looking for, though.
3,509,011
3,509,025
Socket Programming in C++
Can anybody provide me some sample example on Client and server connection using sockets in C++. I have gone through some tutorials now i want to implement it. How to start ?
You can find a working client-server program here: Beej's Guide to Network Programming
3,509,436
3,509,607
Best practices for maintaining symbols of binaries
I have a product which has around 7 services and one User Interface. Time to time new releases are given in the product and hence the binaries get changed over a period of time. The customer base is huge and so we get queries related to crashes of our services in some cases. To identify the cause for crash we get the s...
You mentioned PDBs, so I'm going to assume a Microsoft environment. You could setup a local symbol server, and have your release builds copy their symbols to the server as a post build step. Then you can add the symbol server to Visual Studio or WinDbg and it will take care of finding the correct PDBs. See this blog po...
3,509,447
3,509,492
Initialize a reference - warning C4355: 'this' : used in base member initializer list
class A; class B { public: B(A& a) : a(a) {} private: A& a; }; /* Method 1 */ /* warning C4355: 'this' : used in base member initializer list */ /* class A { public: A() : b(*this) {} private: B b; }; */ /* Method 2 */ /* But I need to manually perform memory dellocation. */ class A { public: A(...
Note this is a warning (so it is dangerous not illegal). What the compiler is worried about is that you are passing a pointer for an object that has not been fully initialized. Thus if the pointer is used in the B class constructor you are in undefined behavior. So if you do use this the only thing you can do is assign...
3,509,556
3,511,736
How to make object pointer NULL without setting it explicitly, without deleting explicitly and without static functions?
I am working on a c++ application. In my code i have an object pointer like TestClass *pObj = new TestClass(); and Member function call like pObj->close(); Inside close() member function, i should make pObj to NULL. As per our requirement, TestClass users should not call delete on pObj.(Destructor of Test...
An insane problem requires an insane solution, so here is one. You can't do exactly what you want, since it's impossible to keep track of the raw pointers to your object. However, if you use some kind of smart pointer, then they can be tracked and nullified when the object is destroyed. This is a common requirement in ...
3,509,598
3,540,606
EditStreamCallback with C#, Migrating from C++
I am trying to accomplish much the same thing as is being done here http://www.vbforums.com/showthread.php?t=449171 However using C#, instead of VB. What is snagging me the most is the C++ portion of the code. I have little to no experience with C++, and I have tried time and time again to make this '.dll' being spoken...
I find the code example which you use not the best one, it is really dirty written. Nevertheless because you wrote that your main current problem is the C/C++ code I suggest you following: Replace GetModuleHandle to GetModuleHandleA in the C/C++ code. You can aslo to change settings of the project to avoid usage of "U...
3,509,763
3,512,208
Singleton dead reference problem
I was reading around a lot about singleton. I am thinking about the dead reference problem between singletons. In every primer on net , this problem is encountered when one singleton calls other singleton in its destructor, and that singleton is already destroyed, say Log singleton can be called from destructor of many...
Copied from here: Finding C++ static initialization order problems (Nobody would have followed just a link sorry) Also see this article: C++ Singleton design pattern Destruction Problems: There is a potential problem of accessing the object after it has been destroyed. This only happens if you access the object from t...
3,509,919
3,510,264
Emacs C++, opening corresponding header file
I am new to emacs and I was wondering if there is a shortcut to switch between header/source and the corresponding source/header file if there is a reference card like the general emacs ref card Thanks !
There's ff-find-other-file. You can bind this to your own key using something like: (global-set-key (kbd "C-x C-o") 'ff-find-other-file) But of course you'll need to pick a key that doesn't already have something useful bound to it :)
3,510,151
3,587,162
Calling LowLevelKeyboardProcedure in DLL
I've managed to get input hooks working, but now I'm kinda lost with putting them into a library. I have a simple header with INPUTHOOK_EXPORTS defined in the IDE, so the dll exports (Visual Studio). #pragma once #ifdef INPUTHOOK_EXPORTS #define INPUTHOOK_API __declspec(dllexport) #else #define INPUTHOOK_API _...
SetWindowsHookEx is a macro that should turn into SetWindowsHookExA' for ascii orSetWindowsHookExWfor wchar. Similary forUnhookWindowsHookEx` . The error reported should be specific to which function is missing - A or W - which seems to indicate for some reason the macro is not in place. You seem to be missing winuser....
3,510,573
3,513,477
How to avoid thread preemption in C++, VisualStudio(Windows)
I developed a logger for testing our modules in c++, Win32 console, visual studio(Windows) Logger is running in one thread. While it displays output in console window, thread is getting preempted. Some other module thread is running. So output of other modules is getting mixed with output of Logger module in Co...
The standard solution is to use a mutex . After formatting, but before starting the output to the console, you lock the mutex. When all output is sent, you unlock the mutex again. If a second thread comes in, its attempt to lock the mutex will cause that thread to be preempted until the first thread is done. CriticalSe...
3,510,604
3,510,729
A problem with Vivek's vcam of directshow
CVCam::CVCam(LPUNKNOWN lpunk, HRESULT *phr) : CSource(NAME("Virtual Cam"), lpunk, CLSID_VirtualCam) { ASSERT(phr); CAutoLock cAutoLock(&m_cStateLock); // Create the one and only output pin m_paStreams = (CSourceStream **) new CVCamStream*[1]; m_paStreams[0] = new CVCamStream(phr, this, L"Virtua...
I have no idea what this code is about, but I can assure you that m_paStreams is only initialized once in what you've posted. It appears that m_paStreams is intended to be an array of pointers to CSourceStream objects. Presumably, it's possible to have more than one of these objects, hence, the array. Your code simpl...
3,510,662
3,510,695
Vectors within classes: handling copy constructor and destructor (C++)
Take a simple class with the "big 3" (constructor, copy constructor, destructor): #include <vector> using namespace std; //actually goes in the C file that links to this header file ... class planets(){ //stores mass and radii data for planets in a solar system. public: vector <double> mass; vector <doub...
No, you don't need to do anything because you aren't managing any resources. You only write the Big Three when you're managing a resource, but vector is doing that. It's the one with the Big Three properly written, you just use it. This is why the single responsibility principle is key in resource management: once you ...
3,510,753
3,510,795
How to convert from LPCTSTR to LPSTR?
I have the following line of code: LPSTR address = T2A((LPTSTR)hostAddress); Can I convert LPCTSTR hostAddress to LPSTR without using T2A macros from "afxpriv.h"?
This macro is defined in in AtlBase.h, use this h-file which is public and doesn't require any dependencies. Correction: it is not defined directly in AtlBase.h, but it is enough to include AtlBase.h to use string conversion macros.
3,510,981
3,511,067
Is Visual C++ optimizer sensitive to amount of memory available?
Turns out it is perfectly valid for a C++ compiler to emit different machine code when recompiling the same program with exactly the same compiler/environment/whatever settings. Which implies that the compiler optimizer can decide how "deep" to optimize depending on various factors, amount of available memory included....
If you're asking "does MSVC emit different output when I run the compiler itself on a machine with 1Gb of RAM versus one with 4Gb of RAM?" the answer is it theoretically could, but in our experience it doesn't. We're very sensitive to small details of code generation in our app so we've tested MSVC's behavior under all...
3,510,987
3,511,046
what is the persistent c++ system?
plz Send me the answer of the following question. what is the persistent c++ system?
A persistent C++ system could be a software layer or an entire ORM responsible for the persistence of C++ objects in a database, The persistent C++ system doesn't mean anything out of context.
3,511,049
3,511,616
Global variables not destructed in main thread?
I have a mixed-mode executable and I noticed that the constructor of my native global variables is called in the main thread, but the destructor is called in some other thread. The name of thread is 'Thread::intermediateThreadProc'. What is the reason for this? And what is this 'Thread::intermediateThreadProc' thread? ...
Thread::intermediateThreadProc() is a little helper function in the CLR that's used as the thread start function for any thread started by the CLR. Find it back in the SSCLI20 source, src\vm\threads.cpp Seeing this run on another thread is to be expected. Cleanup code runs when the appdomain gets unloaded. The CLR l...
3,511,110
3,511,291
Unexpected behaviour of getline() with ifstream
To simplify, I'm trying to read the content of a CSV-file using the ifstream class and its getline() member function. Here is this CSV-file: 1,2,3 4,5,6 And the code: #include <iostream> #include <typeinfo> #include <fstream> using namespace std; int main() { char csvLoc[] = "/the_CSV_file_localization/"; if...
You are reading comma separated values so in sequence you read: 1, 2, 3\n4, 5, 6. You then print the first character of the array each time: i.e. 1, 2, 3, 5, 6. What were you expecting? Incidentally, your check for eof is in the wrong place. You should check whether the getline call succeeds. In your particular case it...
3,511,295
3,511,383
Can I pass STL data structures to a Win32 message loop?
I have a multithreaded Windows application where one of the threads has a message pump in it. I need to send a message to that thread, passing information to it. However, one of the libraries I want to use in the worker thread requires std::string. Can I do something like the following: typedef struct tagCOMMAND { ...
It is ok and normal to pass pointer to objects as async message parameters, as long as there is a single receiver (no more and no less). It should be the responsibility of the receiver to free the memory, since the caller has no indication when it is safe to do it.
3,511,341
3,511,401
Threading in Windows using C++
In C++ how can you use threads to not block my receive functionality in case of Sockets? // Receive until the peer closes the connection do { iResult = recv(lhSocket, recvbuf, recvbuflen, 0); if ( iResult > 0 ) printf("Bytes received: %d\n", iResult); else if ( iResult == 0 ) printf("Connec...
Call CreateThread() to create a new thread. If you want to update your UI with information received from the socket, you should define a user message for your window (with a value greater than WM_USER), and call PostMessage() to notify your window of the desired information.
3,511,682
3,511,816
Are stdin, stdout, and stderr Files?
Someone told me that whenever a C++ program is run three files STDIN, STDOUT and STDERR are opened and he gave this link in his support.. http://tldp.org/LDP/abs/html/io-redirection.html But I am confused weather these streams are actually Files? Can anyone clarify?
On POSIX systems, streams are special file descriptors. Windows has its own err.. thing, but they are file descriptors there as well. Examples of special files on Windows are the standard streams stdout, stdin and stderr, as well as serial ports like COMn, which can be opened with OpenFile(). On Linux, special files ar...
3,511,748
3,511,875
surprising constructors for a class!
What is the problem here in this code? It gives segmentation fault. I found value of size in vector (int *a) is no more 3. How is this? #include <iostream> using namespace std; class vector { int *v; int size; public: vector(int m) { v = new int[size = m]; for(int i=0; i<size; i++) ...
In essence the reason it generates a fault is in the line v1=x; As you have no assignment operator this in effect becomes: v1=vector(x) Which called your int * constructor. This constructor runs with size initialised to garbage which causes the seg fault as the loop progresses towards invalid memory. Strategically the ...
3,511,755
3,512,018
File open problem with many process in C
Iam working in c++ .i have an problem while run an application ,which have my dll within it ,My dll code is suitable to application (needed process).i wrote a log file (xml file) throughout application using fopen within all function(dll source) ,here i receive exception like "cannot access the file ,due to using by ...
Unless you are using a different file for each process that uses your DLL then the problem is that you have the potential for multiple processes trying to access the same resource. You should do one of the following: Change your code so that it uses a separate file for each calling process. Change it so that it uses s...
3,511,868
3,511,920
What's the point of this kind of macros?
#define NAME(x) TEXT(x) #define TEXT(quote) __TEXT(quote) // r_winnt #define __TEXT(quote) quote // r_winnt The above is from winNT.h, isn't NAME("Virtual Cam") the same as "Virtual Cam",what's the point to use this macro?
__TEXT macro expansion is selected based on whether UNICODE flag is defined or not. If not it just expands to quote else it will append L to the quote so that it becomes L"Virtual Cam" . This string is interpreted as a wide char string.
3,511,931
3,516,612
How to log all commands run By system() System Call
I am trying to debug a C++ application which invokes many command line applications such as grep, etc through a the system() system call. I need to see all the commands the application is executing through the system() call. I tried to view these commands by enabling history and view the .history file. But these comman...
To trace every command executed by "yourProgram": truss -s!all -daDf -t exec yourProgram eg: $ truss -s!all -daDf -t exec sh -c "/bin/echo hello world;/bin/date" Base time stamp: 1282164973.7245 [ Wed Aug 18 22:56:13 CEST 2010 ] 5664: 0.0000 0.0000 execve("/usr/bin/i86/ksh93", 0x080471DC, 0x080471EC) argc = 3 ...
3,511,975
3,512,004
What's the functioning scope of an critical section locker in c++?
// locks a critical section, and unlocks it automatically // when the lock goes out of scope CAutoLock(CCritSec * plock) The above is from wxutil.h, does it lock the access of different process , or just locks different threads in the same process?
Just across threads. From the doc of CAutoLock: The CAutoLock constructor locks the critical section, ... and CCritSec: The CCritSec class provides a thread lock. More explicitly, from the description of Critical Section Objects: A critical section object provides synchronization similar to that provided by a mute...
3,512,045
3,512,145
C++ - basic Qt question
Do I have any simple way to have context menu items, that aren't highlighted when mouse goes over them (using Qt)? I want to make simple context menu with various item groups such as | Group1 | ----- | DoSomething | DoSomethingWow | DoSomethingCool | | Group2 | ------ | DoSomethingCoolHuh and I want Group1 a...
simple solution which comes to my mind "out of the box" is to: set those items disabled: item.setEnable(False) Then you could use some style to make it look different. Hope this helps.
3,512,099
3,513,121
What's the difference of CSource and CSourceStream in directshow?
These two classes looks similar to me, can you remind me the great difference between these two classes so that I can judge which class a specific interface belongs to without refering to the document??
As by the definition in the MSDN : The CSource class is a base class for implementing source filters. A filter derived from CSource contains one or more output pins derived from the CSourceStream class. Each output pin creates a worker thread that pushes media samples downstream.
3,512,271
3,512,380
How to copy text file in C or C++?
When trying to copy a text file A to another file B, there may have several methods: 1) byte by byte 2) word by word 3) line by line which one is more efficient?
Using buffers: #include <fstream> int main() { std::ifstream inFile("In.txt"); std::ofstream outFile("Out.txt"); outFile << inFile.rdbuf(); } The C++ fstreams are buffered internally. They use an efficient buffer size (despite what people say about the efficiency of stream :-). So just copy one st...
3,512,396
4,159,062
Are there specific defines of linuxthreads and nptl
I hav a programme, which must work differently for linuxthreads and nptl. Are there defines in this libs, that can be used in my programme to detect, is nptl is used or is linuxthreads is? UPDATE1: For runtime there is a getconf GLIBC_LIBPTHREADS, but what for compile-time?
Doesn't look like this is possible, you can change the implementation at load time so there's no way to know at compile time no matter what you do. from the pthreads man page: On systems with a glibc that supports both LinuxThreads and NPTL (i.e., glibc 2.3.x), the LD_ASSUME_KERNEL environment variable can be us...
3,512,413
3,512,489
OpenGL: Is it acceptable to work with textures like 2500*2500 pixels?
Of course the texture will not be completely visible on the screen. And I can make it always draw just the visible part (With glTexCoord2f and then glVertex2f). (It is the big "level"-image, which I have to move around for a sliding camera). Notice this rendering has to be real-time in my game (game is written in C++)....
That's a lot for one texture. Shouldn't be too much of a problem if the video card has enough memory to keep it onboard (at least 32MB, and that's if you have nothing else in your game! 128MB is actually more reasonable), but if it doesn't then the system will have to push the bits to the video card each frame as lon...
3,512,537
3,512,715
How to make a program that automatically synchronizes
Hey i am hoping to write a program where the program automatically just copy pastes all my dad's documents from D:\office folder. So whenever I plug-in my pen-drive , the program silently copies all documents inside my pen-drive. Also all files should be pasted to a hidden folder in the pen-drive (so it remains privat...
I infer you are on Windows. Window has a plethora of functions to manipulate files. A few functions are below. CopyFile Copies an existing file to a new file. FindFirstFile Searches a directory for a file or subdirectory name that matches a specified name. FindFirstFileEx Searches a directory for a file or subdirecto...
3,512,650
3,512,887
Fastest JSON reader/writer for C++
I need a C++ JSON parser & writer. Speed and reliability are very critical, I don't care if the interface is nice or not, if it's Boost-based or not, even a C parser is fine (if it's considerably faster than C++ ones). If somebody has experience with the speed of available JSON parsers, please advise.
http://lloyd.github.com/yajl/ http://www.digip.org/jansson/ Don't really know how they compare for speed, but the first one looks like the right idea for scaling to really big JSON data, since it parses only a small chunk at a time so they don't need to hold all the data in memory at once (This can be faster or slower...
3,512,685
3,512,819
A template class in C++
What is the function of the following C++ template class? I'm after line by line annotations: template<class T> string toString(const T& t, bool *ok = NULL) { ostringstream stream; stream << t; if(ok != NULL) *ok = stream.fail() == false; return stream.str(); } Is it like Java's toS...
Basically, it will take any object which has an operator<< defined for output to a stream, and converts it to a string. Optionally, if you pass the address of a bool varaible, it will set that based on whether or not the conversion succeeeded. The advantage of this function is that, once defined, as soon as you defin...
3,512,692
3,512,868
How to read this kind of pointer in c++?
CUnknown* (*)( LPUNKNOWN pUnk, HRESULT* phr ); Seems I've always been in trouble reading such complicated pointers.. How do you read it? what if the expression even longer?
The Clockwise Spiral Rule helps me understand things like this. From the site: Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements: Keep doing this in a spiral/clockwise direction until all tokens have b...
3,512,728
3,727,524
Error with C++ partial specialization of template
I am using PC-Lint (great tool for static code analysis - see http://www.gimpel.com/) For the following chunk of code: class ASD { protected: template<int N> void foo(); }; template<> inline void ASD::foo<1>() {} template<int N> inline void ASD::foo() {} PC-lint gives me a warning: inline void AS...
The bug was in PC-Lint itself. It has been fixed in the newest version.
3,512,742
3,515,549
File decriptors and socket connections
I am trying to understand how are file descriptors related to sockets. As per my understanding, you listen on a particular file descriptor, once a connection comes in , you accept it , which returns you another file descriptor ( 2 in all ) and you use this 2nd descriptor to send/recv data. The strange behaviour i am o...
Your extra file descriptor is most likely related to syslog. Syslog has to open a socket to the syslogd to report messages. Unless you explicitly call openlog this socket is opened upon the first call to syslog, and since you aren't calling syslog until you have an error you are most likely observing syslog's side ef...
3,512,749
3,512,881
memcpy adds ff ff ff to the beginning of a byte
I have an array that is like this: unsigned char array[] = {'\xc0', '\x3f', '\x0e', '\x54', '\xe5', '\x20'}; unsigned char array2[6]; When I use memcpy: memcpy(array2, array, 6); And print both of them: printf("%x %x %x %x %x %x", array[0], // ... etc printf("%x %x %x %x %x %x", array2[0], // ... etc one prints lik...
I've turned your code into a complete compilable example. I also added a third array of a 'normal' char which on my environment is signed. #include <cstring> #include <cstdio> using std::memcpy; using std::printf; int main() { unsigned char array[] = {'\xc0', '\x3f', '\x0e', '\x54', '\xe5', '\x20'}; ...
3,512,864
3,513,043
Visual Studio 2010 C++ linker performance for large projects
At my company we're still using Visual Studio 2005, but are peeking at Visual Studio 2010 in the hope that it will speed up some parts of our development cycle. At the moment we're most interested in the performance of the C++ linker of Visual Studio 2010. When building our application, we're looking at link times betw...
My understanding is that the big change (performance wise) that MS made to the linker in VS2010 is that writing the .pdb file is done on a separate thread. Of course, since the linker does much more than this, there's a limit to how much it'll improve the overall link time: Linker throughput And here's an article th...
3,512,953
3,513,654
Using Visual Studio 2010 C++ compiler and linker without Visual Studio 2010 having been installed
At my company we really like for our development tools to be able to be used from perforce, without having been installed. For a lot of tools (perforce, gcc compiler, snc compiler, even maya) this works after some tweaking, but for Visual Studio 2005 we could not get it to work. As far as we could see, the problem was ...
Yeah, mspdbsrv.exe would be a hangup. It is a service required to arbitrate access to the program database to allow concurrent compilation. Can't get a service going without getting the registry entries right. This did not improve in VS2010. It has an entirely new build system, based off MSBuild. There's a ton of s...
3,512,961
3,522,645
Remote GDB debugging
I've just spent a whole day trying to find a way to enable GDB debugging from Qt Creator or Eclipse. I learned that there are basically two approaches to launch the target application: Using ssh (ssh host gdb) Using gdbserver I was able to use both approaches to launch gdb remotely and start the application. However,...
Due to peculiarities in our makefile build system the file references contained in the debugging symbols look like this: ../src/main.cpp ../../src/utils/logger.cpp This is no problem for GDB, but Qt Creator was unable to map these paths to the actual files. I was able to fix this by adding 'dir' statements in the GDB ...
3,512,982
3,513,032
Which of these are getting called?
Say I have the following code: struct date { int day; int month; int year; }; class mydateclass { public: int day; int month; int year; }; mydateclass date; date.day; Which date variable is being referred to? The date instance named mydateclass, or the date struct?
The struct declaration is called "date". There is no object date created before mydateclass date;. Therefore, the "call" is not ambigeous. If you want to create an object in that fashion it would be: struct datestruct { int day; int month; int year; } date; If you would do that, your compiler should compla...
3,513,028
3,513,283
Marshall multiple protobuf to file
Background: I'm using Google's protobuf, and I would like to read/write several gigabytes of protobuf marshalled data to a file using C++. As it's recommended to keep the size of each protobuf object under 1MB, I figured a binary stream (illustrated below) written to a file would work. Each offset contains the number o...
Don't use new []/delete[]. Instead us a std::vector as deallocation is guaranteed in the event of exceptions. Don't assume that reading will return all the bytes you requested. Check with gcount() to make sure that you got what you asked for. Rather than have Glob implement the code for both input and output depending...
3,513,169
3,520,048
Update only part of a binary file with c++
Is it possible to update only a part of a file in c++ ? Example: Old File A: 'A''A''A''B''B''C''C''C' New File A: 'A''A''A''X''X''C''C''C' as the real files are not as tiny like these examples, and I do know exactly what has changed ( offset and writeLenght for changed content ) it would be great to be able to open ...
Ok, thank you: Here's a working piece of code in case anyone encounters the same question. void update file( list<unsigned char> content, int offset, int writeLength){ fs::basic_fstream< char > fileStream( path , ios::out | ios::in | ios::binary ); list< unsigned char >::const_iterator contentIter = content.beg...
3,513,173
3,513,201
Converting ostream into standard string
I am very new to the C++ STL, so this may be trivial. I have a ostream variable with some text in it. ostream* pout; (*pout) << "Some Text"; Is there a way to extract the stream and store it in a string of type char*?
std::ostringstream stream; stream << "Some Text"; std::string str = stream.str(); const char* chr = str.c_str(); And I explain what's going on in the answer to this question, which I wrote not an hour ago.
3,513,179
3,513,251
How to Access File Descriptor of Open File
Is there any way to access the file descriptor of a file opened in c++? So ... #include <iostream> #include <fstream> using namespace std; int main() { ifstream inputFile( "file.txt",ios::in ); cout << inputFile.fileDesc << endl;//made up call return 0; } The question is, does something like f...
If you're trying to get to the FILE* from the stream then the answer is basically "you can't" as stated by more enlightened people than me here.
3,513,191
3,513,215
function returns pointer to int
My main() crashes below when add(4) is called. As I understand int* add, it should return a pointer to integer. Then, I should be able in main to say: int * a = add(3); to return a pointer to int. Please explain what I'm doing wrong. #include <cstdlib> #include <iostream> using namespace std; int* add (int a) { i...
In *c = d; the pointer c is not initialized, so your program runs into undefined behavior. You could do something like the following instead: void add( int what, int* toWhat ) { (*toWhat) += what; } and call it like this: int initialValue = ...; add( 4, &initialValue );
3,513,239
3,513,340
Fields in a struct skipping bytes
I have a struct I have written which is supposed to represent an entire UDP packet, with the ethernet header and all. Here it is: #pragma pack(1) struct UDPPacket { // an array to hold the destination mac address of the packet unsigned char dstmac[6]; // an array to hold the source mac address of the packe...
Your #pragmas look right. Bitfields don't "auto-pack" to the smallest type that fits the number of bits explicitly specified. I suspect that verlen is taking your given type "unsigned" and assuming that it's a bitfiend of size unsigned int, which sounds like 32 bits in your compiler. Try making the fields of verlen "u...
3,513,456
3,513,605
How can a type that is used only in one compilation unit, violate the One Definition Rule?
I was told that these types, that are visible in there own unique translation unit, were in violation of the One Definition Rule. Can someone explain this? //File1.cpp #include "StdAfx.h" static struct S { int Value() { return 1; } } s1; int GetValue1() { return s1.Value(); } //File2.cpp #include "StdAfx.h" static str...
You have defined struct S in the global namespace in two different ways, which breaks the One Definition Rule. In particular, there are two different definitions of ::S::Value(), and it's undefined which will actually end up being called. You should use nameless namespaces to make sure a distinctly named version of str...
3,513,788
3,514,174
Qt - QGraphicsView without ScrollBar
I am trying to show a picture in it's full view using QGraphicsScene. But when ever I put the QgraphicsScene inside the QGraphicsView, I am getting a scroll bar. I tried so many ways But all are went to veins. So can anybody tell me how to obtain the full view without the scrollbar.
QGraphicsView v; v.setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); v.setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); To adjust the scrolling programmatically once these have been hidden, use one of the overloads of v.ensureVisible().
3,513,793
3,517,831
Convert a number from Base B1 to Base B2 without using any intermediate base
Is there a way Convert a number from Base B1 to Base B2 without using any intermediate base. Ex: 214 from base 5 to base 16 without converting it first to decimal and then decimal to hexadecimal. -- Thanks Alok Kr.
To convert 214base5 to base 16 without an intermediate base, you "just" have to know how to calculate directly in base 5. First, you need a table of what the base 16 digits are in base 5 (you need a similar table when converting base 10 to base 16, it's just that that one is easier to keep in your head!). This table i...
3,513,907
3,513,991
linking mac framework to qt creator
I have a project that uses SystemConfiguration.Framework. I've been using xcode, where adding the framework is quite easy, just add it to xcode project's framework. But now, I need my project to be cross platform, so I'm using QT Creator as a single IDE, for Windows and Mac. The problem is that I don't know how to tell...
I assume the project itself is using Qt i.e. it is using .pro files to configure things like include paths and library/framework paths? If so then you just need to update the relevant .pro file to add the framework. See the qmake docs for more detail. The gist of it is to add QMAKE_LFLAGS += -F/path/to/framework/direct...
3,514,035
3,514,339
c++ std::copy with type cast to derived class possible?
I am pretty sure that there is no way around doing this explicitly but I would like to ask nontheless in case there is a better way. I have a base class A and a derived class B, now I have a std::list of A* which point to B*'s and I want to copy this list of A*'s to a std::vector of B*'s so basically I want to do this:...
It's not safe do the conversion implicitly, so you have to make it explicit. The standard algorithm for applying some kind of transformation to a sequence is std::transform, which you can use to populate an empty container as follows: struct A {}; struct B : A {}; template <typename From, typename To> struct static_ca...
3,514,302
3,514,553
log function misbehaviour!!! Any clue?
I am writing some program in C. It has a part where it does some probability calculations, where I am using log function. normal library function log()... The code is something like this double somevalue = 0.29558101472995091; temp = log(somevalue) And guess what? The temp gets value -1856.0000000000000!!! As the valu...
You need to #include <math.h> so the compiler will call log() correctly. Using VC10, I get the following result from printf ("log(%lf) = %lf\n", somevalue, temp ) when math.h is included: log(0.295581) = -1.218812 If math.h isn't included, I get: log(0.295581) = -1856.000000 What's probably happening is that the co...
3,514,345
3,514,424
Reading C++ code CreateFrame function (from C# prespective)
// Create test video frame void CreateFrame(char * buffer, int w, int h, int bytespan) { int wxh = w * h; static float seed = 1.0; for (int i = 0; i < h; i ++) { char* line = buffer + i * bytespan; for (int j = 0; j < w; j ++) { // RGB line[0] = 255 * sin(((float)i / wxh * seed) * 3.14);...
In C/C++, the value line in line is actually a memory address of an array, and line[1] actually represents the value at the address of the variable line plus a 1 item offset. (If the type of the items in line is an int, then it means the address of line plus four bytes; since it is a char, it means the address of line ...
3,514,457
3,514,647
Using boost::iterator_facade<>
I have a linked list structure: struct SomeLinkedList { const char* bar; int lots_of_interesting_stuff_in_here; DWORD foo; SomeLinkedList* pNext; }; It is part of an existing API and I cannot change it. I would like to add iterator support. The boost::iterator_facade<> library seemed ideal for the purp...
When your iterator is dereferenced, it would return a const SomeLinkedList& however your DoSomething function is expecting a const SomeLinkedList*. Either alter the iterator to somehow return pointers when dereferenced or alter your DoSomething function. EDIT in response to further discussion: I haven't actually used ...
3,514,461
3,514,636
Access result type of a function template parameter in the template?
Given the following template: template<class T> class Container { private: boost::function<T> f; }; ... and its instantiation, perhaps as follows: Container<bool(int, int)> myContainer; , is there a way to access the return type of the function description and compile conditionally against it? For example...
I don't think you actually need to specialize for void return type. A void function is allowed to return the "result" of another void function for exactly this scenario. void foo() { } void bar() { return foo(); } //this is OK int main() { bar(); } So your only problem would be how to determine the return type. I...
3,514,888
3,514,940
C++: overriding pure virtual member variable?
This question is best described in code. I have a class called Vertex that contains an instance of a class called Params: class Params { virtual Params operator + (Params const& p) = 0; }; class Vertex { public: Params operator + (Params const& ap) const { return p + ap }; ...
Well...you need to initialize the Params in Vertex somehow. So make it a parameter on the Vertex constructor. Then your EllVertex will pass an EllParams to the parent constructor from its constructor and that will be how the private Vertex.p is initialized. For example: class Params { virtual Params operator + (Par...
3,514,935
3,516,254
3D text on QGLWidget in Qt 4.6.3
I'm looking for a simple way to draw 3D text on QGLWidget without using FTGL, FreeType, "render to texture" or framebuffer objects, i.e. using documented Qt 4 functions only, no additional libraries. Ideas? P.S. "3D text" means that letters are flat and have zero thickness, but can be rotated in 3D space. Think about ...
Found something. QPainterPath path; glDisable(GL_LIGHTING); QFont font("Arial", 40); path.addText(QPointF(0, 0), QFont("Arial", 40), QString(tr("This is a test"))); QList<QPolygonF> poly = path.toSubpathPolygons(); for (QList<QPolygonF>::iterator i = poly.begin(); i != poly.end(); i++){ glBegin(GL_LINE_LOOP); ...
3,514,991
3,516,147
c++ initialization order of globals
Is this portable or at least safe to use with g++? #include <iostream> #include <vector> struct c {}; std::vector<c*> v; struct i : c { i () { v.push_back (this); } } a, b, c; int main () { std::cout << v.size () << "\n"; // outputs 3 with g++ } EDIT: Ok, what I need turned out to be a bit harder: The same code wi...
For your updated question, I haven't waded through the standard to find out when members of implicitly-instantiated templates are supposed to be initialized, but explicit instantiation does seem to be the solution: template class cv<int>; // Not a dummy. Declares the template like a class. Standardese at 14.7.2/7: Th...
3,515,042
3,515,109
In NTFS Compressed Directory, How to read Files compressed and uncompressed size?
In our application, we are generating some large ASCII log files to an Windows NTFS compressed directory. My users want to know both the compressed and uncompressed size of the files on a status screen for the application. We are using Rad Studio 2010 C++ for this application. I found this nice recursive routine onli...
The Win32 API GetFileSize will return the uncompressed file size. The API GetCompressedFileSize will return the compressed file size.
3,515,119
3,515,305
where is the ublas::vector push_back?
hi may i know where is the ublass::vector push_back or what ever does the same ? p.s (i'm not talking about std::vector)
As far I can tell from reading the documentation there isn't one, the ublas::vector cannot be expanded. You must initialize it like this: vector<double> v (3); for (int i = 0; i < v.size (); ++i) v (i) = i;
3,515,169
3,674,299
Can intellisense be enabled in VS2008 within preprocessor directive blocks like #ifndef ... #endif
While working within C++ libraries, I've noticed that I am not granted any intellisense while inside directive blocks like "#ifndef CLIENT_DLL ... #endif". This is obviously due to the fact that "CLIENT_DLL" has been defined. I realize that I can work around this by simply commenting out the directives. Are there any...
By getting what you want, you would lose a lot. Visual C++ IntelliSense is based on a couple major presumptions 1. that you want good/usable results. 2. that your current IntelliSense compiland will present information related to the "configuration" you are currently in. Because your current configuration has that pre...
3,515,204
3,515,232
Byte frequency table for Huffman coding
I'm writing a huffman compressor and decompressor (in C++) that needs to work on arbitrary binary files. I need a bit of data structure advice. Right now, my compression process is as follows: Read the bytes of the file in binary form to a char* buffer Use an std::map to count the frequencies of each byte pattern in t...
You don't need a map; there are only 256 possible values. Just have int freq[256] = {0} and add to it with freq[data[idx]]++ for each byte in the input. If you REALLY want a map, use map<unsigned char, int>; your suspicion on using map from char* is correct.
3,515,219
3,515,256
C++ beginner question: dereference vs multiply
Just getting into C++. I'm getting constantly thrown off track when I see the symbol for multiply (*) being used to denote the dereferencing of a variable for example: unsigned char * pixels = vidgrabber.getPixels(); Does this throw other people off? What's the tip for getting my head around this? Thank you. p.s. ...
C, and by inheritance C++, are swamped with operators and are inherently context-sensitive. You will have to get used to it: If * appears before the name of a variable that is being declared (or defined), it's a type modifier and makes that variable a pointer. If it is a unary prefix operator for a variable that is pa...
3,515,357
3,515,443
Using a (mathematical) vector in a std::map
Related: what can I use as std::map keys? I needed to create a mapping where specific key locations in space map to lists of objects. std::map seemed the way to do it. So I'm keying a std::map on an xyz Vector class Vector { float x,y,z } ; , and I'm making a std::map<Vector, std::vector<Object*> >. So note the k...
Instead of defining operator< for your key class, you can give the map a custom comparator. This is a function object that takes two arguments and returns true if the first comes before the second. Something like this: struct CompareVectors { bool operator()(const Vector& a, const Vector& b) { // insert...
3,515,399
3,517,378
Thread related issues and debugging them
This is my follow up to the previous post on memory management issues. The following are the issues I know. 1)data races (atomicity violations and data corruption) 2)ordering problems 3)misusing of locks leading to dead locks 4)heisenbugs Any other issues with multi threading ? How to solve them ?
Eric's list of four issues is pretty much spot on. But debugging these issues is tough. For deadlock, I've always favored "leveled locks". Essentially you give each type of lock a level number. And then require that a thread aquire locks that are monotonic. To do leveled locks, you can declare a structure like this:...
3,515,618
3,515,655
Different styles of flow of program?
I am a computer science student therefore I do not know that much. I was recently talking with a friend who just got a job as a (java) software developer. He told me that in his job there is a guy who is really experienced in C++, but unfortunately every time he writes code in java, he is using the try-catch to contro...
Using try-catch to control the flow of the program is wrong anywhere... Exception handling is what it says it is: Handling of exceptional circumstances. Of course for every rule there are a dozen counter-examples of necessary deviations, but generally speaking: Don't control program flow with exceptions. Using excepti...
3,515,675
3,515,710
How to call a derived class method from a base class method within the constructor of base
I am wondering if it is possible to call a derived class´ function from within a function called by the base constructor (shouldn´t it already be created when the code in the brackets are executed?) #pragma once class ClassA { public: ClassA(void); virtual ~ClassA(void); void Init(); protected: short m_a; short ...
No. All parts of B (starting with A, as it's base) are constructed before B's constructor is called. So, by the time SetNumbers is called, no part of B (except for the A part) has been constructed --- and that may include the v-table, so there's no way to know where that call is going to go. Of course, there is a sim...
3,515,770
3,523,329
g++ linking issues: undefined reference to functions
I used CMake and Visual C++ to build the HyDE library. Then, still in VC++, I was able to successfully create code and build an executable that links into HyDE.lib and the HyDE header files. I then discovered that in order to work with others at my company, it would be preferable to develop in Eclipse CDT. Knowing ve...
Solution: Since the HyDE library was compiled with the Visual Studios compiler and I'm attempting to build the code that links to it with the Cygwin toolchain the two compilers use different name mangling schemes so that the latter linker can not find the expected symbols in the HyDE library. The only solution that I'...
3,515,888
3,515,985
boost lambda question
#include <iostream> #include <set> #include <algorithm> #include <boost/lambda/lambda.hpp> #include <boost/bind.hpp> using namespace std; using namespace boost::lambda; class Foo { public: Foo(int i, const string &s) : m_i(i) , m_s(s) {} int get_i() const { return m_i; } const string &get_s() const { re...
This program runs and produces the expected output after the following changes: implement Foo::operator<(const Foo&) const (otherwise set<Foo> will not compile) put typedef set<Foo> fooset; after class Foo disambiguate _1 between the boost.bind and boost.lambda placeholders use '\n' instead of endl, as already mention...
3,516,039
3,516,059
How do I make Qt dialog get info while locking main window from user?
I have a Qt main window that will pop up a dialog box that has an OK and Cancel button. This dialog has a simple spinner that asks a user for a number that should be returned to the main window when OK or Cancel is pressed (for cancel, it will just send back -1). I thought about using code in a signal in mainWindow.cpp...
What you should do is create a function in your dialog class that returns the value you want, and use it like so from your main window: void mainWindow::slot_openNumberDlg(){ // Create a new dialog numberDlg dlg( this ); // Show it and wait for Ok or Cancel if( dlg.exec() == QDialog::Accepted ){ ...
3,516,109
3,516,469
Overloading/specializing STL algorithms for non-local containers (database back end)
What I want to do is, in a separate namespace, define my own sort(), copy(), etc implementations that work with database tables/views/etc containers instead of in-memory std containers. If I define my own sort() that accepts my custom forward iterator, how does the compiler resolve that? Or, what do I need to do so t...
It's actually defined behaviour to specialize std namespace algorithms for your own UDTs. namespace std { template<> void sort<sometype::someiterator>(sometype::someiterator begin, sometype::someiterator end) { ... } }; Edit: Oopsie Sort instead of sort. Edit again: Oh man, I wrote something totally wrong....
3,516,196
3,516,224
Testing whether an iterator points to the last item?
I have an stl iterator resulting from a std::find() and wish to test whether it is the last element. One way to write this is as follows: mine *match = someValue; vector<mine *> Mine(someContent); vector<mine *>::iterator itr = std::find(Mine.begin(), Mine.end(), match); if (itr == --Mine.end()) { doSomething; } B...
Do this: // defined in boost/utility.hpp, by the way template <typename Iter> Iter next(Iter iter) { return ++iter; } // first check we aren't going to kill ourselves // then check if the iterator after itr is the end if ((itr != Mine.end()) && (next(itr) == Mine.end())) { // points at the last element } That...
3,516,359
3,522,546
Impersonation in asp.net not shared with com object
So I have an ASP DOT NET web service which needs to impersonate Windows Authenticated users. This web service calls into a Com Api to perform database operations. It seems like the Impersonation does not persist into the Com Api. Is this because the Com DLL is loaded into its own memory space and treated as a separate ...
So I fixed the problem. The Com Object is loaded into its own thread and Impersonation being set the way I did is Thread level. Since I have control of the Com Object adding the Windows function CoImpersonateClient(); before any code that needed to be impersonated did the trick. Here is the article I finally found that...
3,516,395
3,522,632
Align a GtkLabel relative to a GtkDrawingArea
I have a GtkLabel and a GtkDrawingArea within a VBox, I want to center the label relative to a X-coordinate of the GtkDrawingArea (which is below of the label in the VBox), how can I tell GTK to center that label relative to that "anchor" point ? This point should be the center of the label.
I solved my problem by using gtk_alignment_new in order to create a centered alignment and then I used gtk_alignment_set_padding to fill the right padding with the amount of padding needed to align with an arbitrary x-axis value. Thanks for the answers !