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,296,030
3,296,108
Run Linux commands from Daemon
I need to run a linux command such as "df" from my linux daemon to know free space,used space, total size of the parition and other info. I have options like calling system,exec,popen etc.. But as this each command spawn a new process , is this not possible to run the commands in the same process from which it is in...
There is no standard API, as this is an OS-specific concept. However, You can parse /proc/mounts (or /etc/mtab) with (non-portable) getmntent/getmntent_r helper functions. Using information about mounted filesystems, you can get its statistics with statfs.
3,296,178
3,296,377
How to get the last but not empty line in a txt file
I want to get the last but not empty line in a txt file. This is my code: string line1, line2; ifstream myfile(argv[1]); if(myfile.is_open()) { while( !myfile.eof() ) { getline(myfile, line1); if( line1 != "" || line1 != "\t" || line1 != "\n" || !line1.empty() ) line2 = line1; } ...
It wouldn't be enough to change your ||'s to &&'s to check if the line is empty. What if there are seven spaces, a tab character, another 3 spaces and finally a newline? You can't list all the ways of getting only whitespace in a line. Instead, check every character in the line to see if it is whitespace. In this code...
3,296,456
3,298,008
Pass boost::signal as boost::function
I have a class with signal member encapsulated with boost::function. Is it possible to add another signal as a handler with this API? class Foo { public: VOID AddHandler(boost::function<VOID()> handler) { m_signal.connect(handler); } private: boost::signal<VOID()> m_signal; }; boost::signal<VOID()> sign...
use the type "slot_type" that is declared inside your signal type class Foo { public: typedef boost::signal0<void> Signal; typedef Signal::slot_type Slot; //allowed any handler type which is convertible to Slot void AddHandler(Slot handler) { m_signal.connect(handler); } private: Sig...
3,296,626
3,296,932
What does rg mean in a member variable named m_rgNames?
I found the member variable name of m_rgNames in some source code. According to the naming convention, such as m_iNumber typed as int, rg could represent a type name. If this is case, what type did rg represent? Or else what's the meaning of rg in this variable name?
It stands for array or range. The author uses the Hungarian notation.
3,297,201
3,297,240
Function srand in C++
This code #include <stdio.h> #include <stdlib.h> #include <time.h> int main () { printf ("First number: %d\n", rand() % 100); srand ( time(NULL) ); printf ("Random number: %d\n", rand() % 100); srand ( 1 ); printf ("Again the first number: %d\n", rand() %100); return 0; } has the following ou...
If you call rand() without first calling srand(), the behavior is as if you called srand() with 1 as the argument. This behavior is defined in the original C standard. I don't have a full copy of it handy, but The Open Group's POSIX standards are the next best thing, as they incorporate the full C standard (with some e...
3,297,304
3,297,527
How to convert 24-bit wav to mp3 with Lame using C++
I am using the Lame library in a C++ application to encode wav files to mp3 files. It works ok for 16-bit wavs, but now I need to convert some 24-bit wavs and I cannot seem to find the way. In particular, I cannot find a function for setting the "bitwidth" parameter taken as a switch by the lame command line. (The com...
The command line executable does convert 24-bit wavs correctly when setting "bitwidth" to 24, so I think it must be possible Perhaps the solution then is to look at the source-code for the command line utility, or even step it in your debugger and see how it does it.
3,297,421
3,297,496
calling methods in cpp like @selector(someMethod:) in Objective-C
In Objective-C you can pass a method A as a parameter of other method B. and call method A from inside method B very easily like this: -(void) setTarget:(id)object action:(SEL)selectorA { if[object respondsToSelector:selectorA]{ [object performSelector:selectorA withObject:nil afterDelay:0.0]; } } Is th...
C++ and Objective-C are quite different in that regard. Objective-C uses messaging to implement object method calling, which means that a method is resolved at run-time, allowing reflectivity and delegation. C++ uses static typing, and V-tables to implement function calling in classes, meaning that functions are repres...
3,297,518
3,297,543
Memory issues with two dimensional array
Following this nice example I found, I was trying to create a function that dynamically generates a 2D grid (two dimensional array) of int values. It works fairly well the first couple of times you change the values but if crashes after that. I guess the part where memory is freed doesn't work as it should. void testAp...
2-dim array in C++ with no memory issues: #include <vector> typedef std::vector<int> Array; typedef std::vector<Array> TwoDArray; Usage: TwoDArray Arr2D; // Add rows for (int i = 0; i < numRows; ++i) { Arr2D.push_back(Array()); } // Fill in test data for (int i = 0; i < numRows; i++) { for (int j = 0; ...
3,297,601
3,298,311
Three-way conditional in c++ to determine sign equivalance of two numbers
I need the most efficient way (in cpu cycles) to determine if two numbers have the same/different sign. But the catch is if either number is zero I need to be able to distinguish it from numbers with same/different signs (ie. zero is treated as a "third" sign). The following code is similar to what I need, but the retu...
Here is another version (with ugly, non-portable bit manipulation tricks): int foo(int x, int y) { return ((x^y) >> 4) - ((x^(-y)) >> 4); } Some explanations: ((x^y) >> 4) is -1 if exactly one of x and y is negative, otherwise it is 0. ((x^(-y)) >> 4) is -1 if exactly one of x and -y is negative, otherwise it is ...
3,297,602
3,297,632
C++: float value reused across iteration
Let's look at the following piece of code which I unintentionally wrote: void test (){ for (int i = 1; i <=5; ++i){ float newNum; newNum +=i; cout << newNum << " "; } } Now, this is what I happened in my head: I have always been thinking that float newNum would create a new variable newNum with a brand-n...
Since newNum is not initialized explicitly, it will have a random value (determined by the garbage data contained in the memory block it is allocated to), at least on the first iteration. On subsequent iterations, it may have its earlier values reused (as the compiler may allocate it repeatedly to the same memory locat...
3,297,681
3,297,904
Template friend and nested classes
please consider the following code: template <typename T> struct foo { template <typename S> struct bar { template <typename> friend struct bar; }; }; I'd like all instantiations of foo<T>::bar to be friends of foo<T>::bar<S> for any S. If bar is not a nested template, the syntax above works ju...
All restrictions for friend of a class or class template are described in section 14.5.3 of the C++ Standard. Your code is valid. Check you have installed all latest service packs for the Visual Studio. Here you can find related bugs in Visual Studio.
3,297,831
3,381,388
How to resume appending data to a file at a specific position? (std::ostream, streampos, tellp/seekp)
I'm trying to append some data to a file, but in some cases want to skip back a bit from the end to overwrite the tail end of the file. However, neither seekp( pos ) nor seekp( offset, relative ) is having any effect for me (except complaining when using a negative offset). Am I using them incorrectly or are they broke...
You need to open the file with both input and output attributes. The following code doesn't have the usual error handling, it is just to illustrate a technique. #include <iostream> #include <fstream> int main() { const char *szFname = "c:\\tmp\\tmp.txt"; std::fstream fs(szFname, std::fstre...
3,297,920
3,297,958
Unresolved external symbol
Main article there is a header file and a source file. After copying those two files and adding few headers: #include <Windows.h> #include <d2d1.h> #pragma comment(lib, "d2d1") #include <dwrite.h> #include <d2d1helper.h> #include "SafeRelease.h" //Safe realease file template<class Interface> inline void SafeRelease( ...
You need to link to Dwrite.lib, which includes the implementation of DWriteCreateFactory See here for documentation. Requirements section at the bottom explains what you need to include and link to to use the function that the error refers to. You could probably fix this by adding the line #pragma comment(lib, "Dwrite"...
3,298,053
3,298,819
Port Visual Studio C++ to Linux
We have a not very complicated but big (i.e. lots of files) Visual Studio C++ Win32 Console written in C++0x standard in VS2010. It does not use any non standard code or anything (Hopefully!). I now wanna port it to Linux. Which way is the quickest way to do it? autoconf? old-fashioned make file? any other solution?
I would use regular make but keep it simple with default rules as much as possible. Add in dependencies as you go along. EDIT: As in interim step, build it with mingw so that you can avoid the whole API porting issue until you have a working build in your new build mechanism. If your console app calls win32 API funct...
3,298,054
3,298,961
SSL_connect() produces certificate verify failure
I'm currently rewriting some existing technologies that were once using RSA Security's libraries into OpenSSL, but I'm starting to run into a few issues. Currently, all of the certificate verification code appears to be running without a hitch, until that is, I call SSL_connect(). Before, the call to SSL_connect() wou...
Usually this error means that the server certificate your client received in response to SSL_connect() couldn't be verified. This can happen for different reasons: If the server certificate is self-signed, you'll have to authorize that on your SSL_CONTEXT. If the server certificate was signed by a certificate authorit...
3,298,133
3,298,848
Purify's Uninit Memory Read (UMR) on class/structure padding
I experience quite annoying side-effect of class/structure padding with Purify. E.g. struct something { int field1; char field2; }; /* ... */ struct something smth, smth2; smth.field1 = 1; smth.field2 = 'A'; smth2 = smth; The last line would highly likely trigger UMR warning saying that 3 bytes of initializ...
I have no experience with purify, but perhaps explicitly initialising the first struct removes this warning: struct something smth = {0}; struct something smth2; I assume your structs have block scope (not file). If they have file scope the zero initialising is implicit.
3,298,160
4,543,062
How to get complete HTML body using browser helper object (BHO) in case of DHTML/AJAX page?
I'm writing a BHO that analyze the HTML taken from the 'onDocumentComplete' event of 'DWebBrowserEvents2'. Currently it works fine, unless I have a DHTML/AJAX page, where HTML handle is delivered too soon. For sample, I tried using it on 'http://www.google.com'. From the 'onDocumentComplete' event I can get most of the...
The AJAX DHTML changes mostly don't cause a further onDocumentComplete call. You need to register for further Window or Document events such as DISPID_HTMLWINDOWEVENTS2_ONLOAD. One method is to advise the window of a com object that you provide with the generic event sink interface. hr = AtlAdvise(winDisp, pWinHandler,...
3,298,275
3,304,817
How to 'web enable' a legacy C++ application
I am working on a system that splits users by organization. Each user belongs to an organization. Each organization stores its data in its own database which resides on a database server machine. A db server may manage databases for 1 or more organizations. The existing (legacy) system assumes there is only one organi...
From what I can gather, this is essentially a sharding problem. Regardless of how you split the instances at a hardware level (using VMs, multiple servers, all on one powerful server, etc), you need a central registry and brokering layer in your overall architecture that maps given users to the correct destination ins...
3,298,309
3,298,326
C++ What is this simple macro doing?
I'm converting a C++ application in C# and managing to work my way through most of it. However I'm stuck with the following statement: #define GET_SHCALL_ID(L) (((L) >> 24) & 0x000000FF) It's called by another part of the application that receives a Window Message and is passing in the lParam...
Consider that 32-bit integer be composed of 4 octets (bytes): zzyyxxww 0x12345678 That operations extracts the "zz" (0x12) byte. But that's just the implementation. The usage is clearly written in the name GET_SHCALL_ID — It gets the shock call ID from the lParam. C# and C++ share many operators, in this case the fu...
3,298,375
3,298,614
How can I make socket access behave 'asynchronously' without requiring a message loop?
My program uses a NetworkOutput object which can be used to write data to a remote server. The semantic is that in case the object is currently connected (because there is a remote server), then the data is actually sent over the socket. Otherwise, it's silently discarded. Some code sketch: class NetworkOutput { public...
You can use WSAEventSelect instead of WSAASyncSelect, which takes the handle of a WSAEVENT instead of a message ID, and then use WSAWaitForMultipleEvents to wait for the event to be signalled. Instead of WSAEVENT you can also use normal Win32 events created with CreateEvent, and the normal synchronisation functions su...
3,298,488
3,298,515
C++ class declared as static class member
Is there any problem with declaring a class with a static member which is another class in a header. E.g: class Stat { public: int avar; Stat(); }; class Test { public: static Stat stat; }; The reason I fear it might cause problems is that it seems very similar to declaring a global variable in a header. ...
The answer is that you are DECLARING the static (like you can DECLARE a global). But you should only DEFINE it in cpp files. in a .h : extern int myGlobal; class A { static int myStaticMember; }; in a .cpp : int myGlobal = 42; int A::myStaticMember = 42;
3,298,652
3,298,679
why headerFileName_H
while I am creating a c++ header file, I declare the header file like; /*--- Pencere.h ---*/ #ifndef PENCERE_H #define PENCERE_H I want to learn that why do I need to write underline.
You don't need to use the underline, it's just a convention to separate the header name and extension. You cannot use the literal . since that's not valid in an identifier so you replace it with an underscore which is valid. The reason you actually do it is as an include guard. The entire contents of the file are somet...
3,298,980
3,298,998
Qt4 slots and signals: Qt4 has trouble finding the signal
I am trying to get the statusbar to update with the FPS of the contents of a QGLWidget. I have connected them as follows (In class MainWin): glWidget = new GLWidget; ui.verticalLayout->addWidget(glWidget); connect(glWidget, SIGNAL( updateFPSSignal(float) ), this, SLOT( updateFPSSlot(float) ...
do you have class GLWidget : public QGLWidget { Q_OBJECT /* ... rest of declaration ... */ }; in your class declaration? and have you put your glwidget.h header into the HEADERS section of your .pro file? the implementation of a signal is done by moc, not you.
3,298,992
3,299,148
Enable C++ exceptions in Visual Studio 2010 compilation options
I'm trying to compile this source code : // exception_set_unexpected.cpp // compile with: /c /EHsc #include<exception> #include<iostream> using namespace std; void unfunction( ) { cout << "I'll be back." << endl; terminate( ); } int main( ) { unexpected_handler oldHand = set_unexpected( unfunction ); ...
Right click on your project -> Properties -> Configuration Properties -> C/C++ -> Command Line Put your flags in the command Line
3,299,126
3,304,151
Updating XML file using Boost property_tree
I have the following XML file: <xml version="1.0" encoding="utf-8"?> <Data> <Parameter1>1</Parameter1> </Data> I want to add a new node: Parameter2="2" to the Data node. This code doesn't work, saved file still contains only one parameter: boost::property_tree::ptree tree; boost::property_tree::ptree dat...
Your code is almost right, that is the right way to update a child node. However, there is a small bug. When you type: dataTree = tree.get_child("Data"); You assign to dataTree a copy of the "child". So, the next line refers to the copy and not to your hierarchy. You should write: boost::property_tree::ptree &dataTree...
3,299,193
3,299,290
How to make tab key press work with win32 window that is not a dialog
I've created several controls in my window in the WM_CREATE message handler and I want to allow using the tab key to advance the focus through the set of controls from one to the next. The control creation is like this: case WM_CREATE: { CreateWindowA("button", "Refresh Listview", BS_MULTILINE | ...
To get tabbing to work, you need a call to IsDialogMessage() in your message loop. Your message loop should look something like: HWND hwnd; // main window handle MSG msg; while (GetMessage(&msg, 0, 0, 0) > 0) { if (!IsDialogMessage(hwnd, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } IsDial...
3,299,257
3,301,180
Copy constructor question Lippman
I was trying to solve a copy ctro qs given in lipman n not sure If i got it right. Since the class has pointers to itself it confused me a bit. Here is the code #include <iostream> #include <string> using namespace std; class BinStrTreeNode{ public: BinStrTreeNode(const string& val):_val(val){ ...
you got it basically correct. You just forgot to check for NULL pointers. BinStrTreeNode::BinStrTreeNode(const BinStrTreeNode& rhs) :_val(rhs._val) ,_leftchild(NULL) ,_rightchild(NULL) { cout << "copy ctor" << endl; if (rhs._leftchild != NULL) {_leftchild = new BinStrTreeNode(*(rhs._leftchild));} ...
3,299,276
3,299,292
What is the purpose of including the stdafx.h file in a C++ program using opencv
here is a sample code. If I remove the stdafx.h file, the program wont compile. stdafx.h file '#pragma once '#include "targetver.h" '#include <stdio.h> '#include <tchar.h> Capture.ccp // Capture.cpp : Defines the entry point for the console application. // '#include "stdafx.h" '#include "string.h" '#include "cv.h" '...
It's part of the compilers Precompiled Header to speed up builds.
3,299,460
3,299,522
When an MFC dialog is hidden after DoModal, are its controls destroyed?
I've used MFC dialogs before where you do: EnterNameDlg dlg; dlg.DoModal(); string str = dlg.GetName(); However a dialog I have now actually looks at a list-box control in such a method and it's not working. Although the class instance clearly exists after DoModal(), does the actual dialog get destroyed? I noticed cal...
Yes, DoModal creates a dialog on each call and destroys the window before returning. Only the data members will still be valid. Of course, you can add more data members in your EnterNameDlg class if you want to collect data during dialog's lifetime. As soon as the dlg gets out of scope, everything will be deallocated.
3,299,765
3,299,827
Where to store Class Specific named constants in C++
If you have a class that has some named constants, what is the best practive for storing the constants: Option 1: Namespace in Class header So in my class header I will have: class myClass { ... ... }; namespace NamedConstants { const string Bucket = "Bucket"; } Option 2 Member Constants class MyClass { // t...
If the strings are meant to be seen/used by users of the class, you wouldn't consider to make them private class members. So I conclude they are not meant to be seen/used by users of the class. But then it doesn't make sense to put them into the header at all. If you put them into the class (or into namespace scope in...
3,299,881
3,299,943
tmpnam warning saying it is dangerous
I get this warning saying that tmpnam is dangerous, but I would prefer to use it, since it can be used as is in Windows as well as Linux. I was wondering why it would be considered dangerous (I'm guessing it's because of the potential for misuse rather than it actually not working properly).
From tmpnam manpage : The tmpnam() function generates a different string each time it is called, up to TMP_MAX times. If it is called more than TMP_MAX times, the behavior is implementation defined. Although tmpnam() generates names that are difficult to guess, it is nevertheless possible that between the time t...
3,299,909
3,300,262
C++ to C# conversion of SendMessage using COPYDATASTRUCT
I'm converting a C++ application into C# which has generally been fairly straight forward, but now I'm dealing with pointers and running into problems. This is the original C++ code ShockVideoInfo* pVideoInfo = new ShockVideoInfo; COPYDATASTRUCT cd; cd.dwData = bSelf ? SHOCK_REQUEST_SELFVIEW_WINDOW : SHOCK_REQU...
I think I've found my issue: IntPtr cdPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(videoInfo)); Marshal.StructureToPtr(videoInfo, cdPointer, true); Should have been: IntPtr cdPointer = Marshal.AllocCoTaskMem(Marshal.SizeOf(cd)); Marshal.StructureToPtr(cd, cdPointer, false); In other words, I wasn't passing the poi...
3,299,918
3,299,957
How can I shuffle a list without randomness, and guarantee that a portion of elements will eventually appear on one side?
Given a list of elements, does a shuffling algorithm exist that will guarantee that eventually a selected half portion will be on one side, and the remainder on the other? Example: { 4, 3, 10, 7, 2, 9, 6, 8, 1, 5 } Given the set above, I'd like to have a mixing algorithm that eventually moves the marked ones to the ...
Would std::next_permutation() be what you want? (Since it creates all possible permutations, it will, eventually, also put the marked once to the left.)
3,300,241
3,300,331
rand select between n and m
here is code from programming pearls this code prints random numbers in decreasing form void randselect(m,n){ pre 0<=m<=n; poset : m distinct integers from 0 ...n-1 printed in decreasing form if (m>0) if ( bigrand() %n)<m print n-1//here i dont understand print n-1 what means?printf(n-1) or?i will show code ...
Your output problem is printf("",n-1);, which doesn't have a format specifier and therefore doesn't do anything with the remaining function values. Change it to something like printf("%d\n", n - 1);, which will print out one integer (%d) per line (\n).
3,300,257
3,308,205
How does one convert cdt managed to makefiles?
Recently I started doing a C++ project, and started it using the internal building tools of eclipse, which seemed the easiest approach to this. However, because this project will need to be built on more than one architecture, I figured it was best to have some other approach of building this on the other architectures...
After looking further it seems it's possible to change this internal builder to Gnu Make Builder by going to Project -> Properties -> C/C++ Build -> Tool Chain Editor. At this point, the makefile is found in the Debug folder.
3,300,290
3,300,439
Cast to int vs floor
Is there any difference between these: float foo1 = (int)(bar / 3.0); float foo2 = floor(bar / 3.0); As I understand both cases have the same result. Is there any difference in the compiled code?
Casting to an int will truncate toward zero. floor() will truncate toward negative infinite. This will give you different values if bar were negative.
3,300,419
3,300,547
file name matching with wildcard
I need to implement something like my own file system. One operation would be the FindFirstFile. I need to check, if the caller passed something like ., sample*.cpp or so. My "file system" implementation provides the list of "files names" as a array of char*. Is there any Windows function or any source code that implem...
There are quite a few such functions around. Here's a directory of various implementations, sorted into recursive and non-recursive, etc. In case you don't like the licensing there (or have trouble with the link, etc.) here's one possible implementation of a matching algorithm that at least closely approximates what Wi...
3,300,708
3,302,105
C++ templates and "no matching function to call"
I'm getting a strange error. I have a function of the following signature: template <typename DATA, DATA max> static bool ConvertCbYCrYToRGB(const Characteristic space, const DATA *input, DATA *output, const int pixels) { Which is later called like this: case kByte: return ConvertCbYCrYToRGB<U8, 0xFF>(space, (con...
As aaa pointed out, you can't use floating point numbers as template value parameters. But in this instance you don't need to. Get rid of the second parameter entirely, and then in the definition of ConvertCbYCrYToRGB instead of using 'max' use std::numeric_limits<DATA>::max(). Documentation on numeric_limits is here: ...
3,300,743
3,300,795
I want to see if a character is present in a string
I'm programming a program in C++ (typical game) in which you need to guess a letter and it will check if it is present in a string. For example Secret String: I like to program. Guess1: 'a' Display: . .... .. .....a... Etc. But i don't know how to see if a character is in this secret string. I'm using std::string (obli...
Begin by learning searching in a documentation like : http://www.cplusplus.com/reference/string/string/ . (Hint : you want to "find" something ... )
3,300,792
3,300,818
bind() for using member function as STL comparison function
Could someone tell me why the following won't compile? #include "a.h" #include <list> #include <algorithm> #include <tr1/functional> using namespace std; class B { public: B() { list< A* > aList; A* a = new A(); lower_bound( aList.begin(), aList.end(), a, tr1::bind( &B::aComp, tr1::placeholder...
aComp is a nonstatic member function of B, so you need to bind to the this pointer as well: tr1::bind(&B::aComp, this, tr1::placeholders::_1, tr1::placeholders::_2)
3,301,053
3,302,352
c++ win32: how to set back color of a window?
I can set the back color when i am registering the class, e.g.: wincl.hbrBackground = CreateSolidBrush(RGB(202, 238, 255)); RegisterClassEx(&wincl); But how would i do it to any window i have created with the CreateWindow function? like a button on my main window, i have visual styles enabled, and i can notice the win...
All the windows controls send a message to their parent to get the brush to use to fill their background. Assuming you save a copy of the brush handle somewhere, you can do the following in your WindowProc, or DialogProc, to ensure everything draws with the correct background brush. case WM_CTLCOLORSTATIC: case WM_CTLC...
3,301,152
3,301,211
Calling a C++ macro with fewer arguments
Is it possible to call function-like-macros with less that all the parameters in linux? Actually doing this only generates a warning in Visual Studio (warning 4003) and unassigned variables replaces with "". But compiling it using g++ generates an error in linux ("error: macro *** requires ** arguments, but only ** giv...
The number of arguments in a macro invocation must exactly match the number of parameters in the macro definition. So, no, you cannot invoke a macro with fewer arguments than it has parameters. To "overcome" it, you can define multiple differently named macros with different numbers of parameters. C++0x (which is not ...
3,301,210
3,401,408
OpenGL flickering problem
I'm trying to make a multi instance engine in C++ with a wrapper for C#. In made the engine in such way that there is a function like CreateEngine that takes as a parameter the handle to the window or control on which I want the engine to be initialized. In C# I made a custom control that initializes opengl for drawing...
You may want to explore double buffering - if your machine has a lot of excess horsepower then you might not notice the screen clear and redraw with a single control, but as soon as there's two controls and all the setup/teardown overhead in the render pipe Basically, double buffering means you are always rendering to...
3,301,271
5,110,631
EvtArchiveExportedLog fails with ERROR_DIRECTORY
I need to export some events from Windows Event Log to XML on Windows Server 2008 R2. To achieve it I export these events to a file using EvtExportLog and then try to use EvtArchiveExportedLog to get localized descriptions for events. Here's the sample: EvtExportLog( 0, 0, query, logFileName, EvtExportLogChannelPath );...
It seems that I've found the reason. EvtArchiveExportedLog makes an RPC call to svchost.exe which hosts eventlog service. This service tries to create a file in "%windir%\ServiceProfiles\LocalService\AppData\Local\Temp" folder, fails with ERROR_ACCESS_DENIED code and returns ERROR_DIRECTORY to RPC client. So far as RPC...
3,301,294
3,301,451
scanf / field lengths : using a variable / macro, C/C++
How can I use a variable to specify the field length when using scanf. For example: char word[20+1]; scanf(file, "%20s", word); Also, is it correct to use 20+1 (since it needs to add a \0 at the end?). Instead, I'd like to have something like: #define MAX_STRING_LENGTH 20 and then char word[MAX_STRING_LENGTH+1]; scan...
The following should do what you need for the first case. #define MAX_STRING_LENGTH 20 #define STRINGIFY(x) STRINGIFY2(x) #define STRINGIFY2(x) #x { ... char word[MAX_STRING_LENGTH+1]; scanf(file, "%" STRINGIFY(MAX_STRING_LENGTH) "s", word); ... } NOTE: Two macros are required because if you tried to use...
3,301,348
3,301,435
Program Memory Issue
Can I always assume that if... int main() { ... foo1(); foo2(); foo3(); ... return 0; } that foo1() will always precede foo2() and foo2() will always precede foo3() in program completion (referring to highest abstraction of completion)? In my actual program, whether foo2() and foo3() happen dep...
without real-code is very difficult help you. use "print" outputs to follow your code (weir but help) if you aren't using threads foo2 .. fooN will happen, except that some abnormal exit happen. to check this use print or something else to "trace" where your program are.
3,301,362
3,301,400
C++ template function default value
Is it possible to define the default value for variables of a template function in C++? Something like below: template<class T> T sum(T a, T b, T c=????) { return a + b + c; }
Try this: template<class T> T sum(T a, T b, T c=T()) { return a + b + c; } You can also put in T(5) if you are expecting an integral type and want the default value to be 5.
3,301,684
3,301,719
map operations(find most occurence element)
here is code #include <iostream> #include <map> using namespace std; int main(){ map<int ,int>a; map<int,int>::iterator it; int b[]={2,4,3,5,2,6,6,3,6,4}; for (int i=0;i<(sizeof(b)/sizeof(b[0]));i++){ ++a[b[i]]; } // for (it=a.begin();it!=a.end();it++){ // cout<<(*it).first<<" =>"...
You have a typo in your second loop. This: for (it!=a.begin();it!=a.end();it++){ Should be this: for (it=a.begin();it!=a.end();it++){ By the way, (*it).first can be more idiomatically written as it->first. The arrow operator (->) is a combination of the dereference (*) and member access (.) operators.
3,301,930
3,302,005
How do I execute WinZip from Visual Studio without it's GUI opening?
int sysReturn = system("\"C:\\Program Files\\WinZip\\winzip32\" -a C:\\LOG\\test.zip C:\\LOG\\LOG_7-20-2010_17_8_48_834.csv"); Everything seems to work - as in it creates test.zip However, it opens the WinZip GUI (that shows how much has been compressed, etc while my program is running.) How can I skip that part whe...
I'd agree with the other's answers about using a different utility. However, to answer your question: the link that you posted also mentions another option -min to run WinZip minimized. Did you try that? Also, instead of using system, try using ShellExecute and ask for the window to be hidden: ShellExecute(NULL, NULL, ...
3,302,047
3,302,108
C++ and CTime & System clock changing
I want to write simple application in C++ using ctime library. I'm getting the actual time and do some calculation in the loop. Very important for me is the fact that user can modify OS clock during calculations. Is there any way to get to know inside my app if the user has changed OS clock? Thnx for help in advance. P...
POSIX has the clock_gettime() function, that lets you access a monotonic clock (using CLOCK_MONOTONIC.)
3,302,086
3,302,102
Calculate QGraphicsTextItem font size based on scale
I have QGraphicsTextItem objects on a QGraphicsScene. The user can scale the QGraphicsTextItem objects by dragging the corners. (I am using a custom "transformation editor" to do this.) The user can also change the size of the QGraphicsTextItem by changing the font size from a property panel. What I would like to do is...
Please no holy wars about the loop-with-exit construct. We're comfortable with it. void MapTextElement::FinalizeMapScale() { // scene_document_width is the width of the text document as it appears in // the scene after scaling. After we are finished with this method, we want // the document to be as close as pos...
3,302,306
3,312,676
How would i use a C++/CLI dll that wraps native code with multiple dependent libraries in C#?
I am wondering how I would go about correctly setting up a C++/CLI library that wraps native c++ code that has several dependencies. I have tried both statically and dynamically linking the native library to its dependent libraries with no luck. The Managed C++/CLI dll builds just fine and can be added as a referenc...
I figured out the problem and everything is working correctly now. It was a combination of several incorrect things all happening together. If anyone has the same issue, I resolved it by setting up the following: 1) The Boost libraries that were referenced (specifically boost_thread) needed to be compiled with BOOST_T...
3,302,315
3,302,369
Tell Windows XP to Standby programmatically
How can I tell Windows XP to switch to standby mode programmatically with C/C++ native code?
A likely function in the Win32 API is SetSuspendState: SetSuspendState(TRUE, FALSE, FALSE); From: http://msdn.microsoft.com/en-us/library/aa373201(VS.85).aspx
3,302,321
3,302,477
Is it reasonable to write a server application in C# in my case?
I want it to work on windows servers. It will be a cloud type server - it'll consist of modules\parts running on different machines all over the world using http\tcp + upnp to connect to each other There are going to be controlling\monitoring\observing modules on each machine to provide stats on performance This net i...
I'm not exactly sure why people have brought up Cross Platform concerns as clearly the OP has stated the app will run on Windows. As to the actual questions. Can you build a server application that communicates via tcp/http in C# that does not have to run in IIS. -> Yes. Can you build a server application that is perf...
3,302,469
3,302,725
What HID device information is returned in LParam when a device is reported by the system?
I have been searching for information on this for about 30mins now and got nothing so far. Does anyone know what HID information is buried within LParam that's returned when the system (in this case windows) reports a system device change? (either removal or arrival)
Starting from the accepted answer to your previous question, I went to the very first link which says: Any application with a top-level window can receive basic notifications by processing the WM_DEVICECHANGE message. Then I clicked on WM_DEVICECHANGE which brought me to another page that says: lParam A pointer to ...
3,302,509
3,302,576
invalid use of typedef?
To save some space in my code, I made this typedef: typedef clients.members.at(selectedTab) currentMember; however, g++ gives me this error: error: expected initializer before '.' token I figure that I'm misusing typedef, since clients.members.at(selectedTab) is a function call and not a type. Is there a way to do w...
If this is used function-local and neither clients.members nor selectedTab change between its uses, just use references. E.g.: Member& currentMember = clients.members.at(selectedTab); currentMember.foo(); currentMember.bar();
3,302,542
3,316,830
Tiny asymmetric cipher implementation to validate download
To allow a small C++ application to update itself at clients connected over the internet, I am in need of a mechanism that validates the download based on a public key. Algorithms such as DSA or RSA seem to be able to do this nicely. However, looking at well-known available libraries for this (Crypto++, LibTomCrypt) th...
Since I found no libraries that fitted my specific need, I whipped up my own library for this: http://github.com/paiq/dsa_verify. The current implementation has a ~50k footprint of program memory, mainly due to the included bignum math lib, but future versions may be stripped even more.
3,302,814
3,303,914
How to find all matching numbers, that sums to 'N' in a given array
My goal here is to find all possible combinations that sums to a given total. For example, if the array is 2 59 3 43 5 9 8 62 10 4 and if the total is 12, then possible combinations are 2 10 3 9 8 4 5 3 4 Here is the first set of code, that I've written. Wondering the best improvements that can be done on this. ...
#include <iostream> #include <vector> using namespace std; struct State { int v; const State *rest; void dump() const { if(rest) { cout << ' ' << v; rest->dump(); } else { cout << endl; } } State() : v(0), rest(0) {} State(int _v, con...
3,302,841
3,303,281
Change case of QT Moc file
I recently refactored old code files from ABCFile.cpp/.h to AbcFile.cpp/.h to match my company's coding standards. After updating all the references to the old case styling, the code is compiling and running just fine, but looking at qt's automatically generated moc files the casing matches the old style. What do I ne...
This is most likely caused by your Makefile/build procedure. Try to force it to do a full clean and recompile. It should delete all your moc files and regenerate them.
3,303,036
3,303,406
Is there an environmental variable or equivalent for WinZip?
Is there an environmental variable or equivalent for WinZip32.exe I can use to find it's location path? EDIT - This is an in house tool for a controlled system. Thanks.
The installers usually store useful information under HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall but the actual key it's not always easy to find and the information stored varies from installer to installer. It looks like WinZip (at least 14.5) is using an MSI based installer so you'll need to find it's k...
3,303,164
3,303,180
Why isn't ("Maya" == "Maya") true in C++?
Any idea why I get "Maya is not Maya" as a result of this code? if ("Maya" == "Maya") printf("Maya is Maya \n"); else printf("Maya is not Maya \n");
Because you are actually comparing two pointers - use e.g. one of the following instead: if (std::string("Maya") == "Maya") { /* ... */ } if (std::strcmp("Maya", "Maya") == 0) { /* ... */ } This is because C++03, §2.13.4 says: An ordinary string literal has type “array of n const char” ... and in your case a conver...
3,303,209
3,303,257
In C++ syntax, can the condition of the if else, return a int and still execute the statements within
Here is the code which compiles : int select_object = 0; if( select_object ) //condition returns an int { printf("Hello"); } if condition returns an int and not a boolean will the hello be printed ? When I tested this it printed hello. Any idea why even for an int it executes the print statement. THanks
Boolean logic 1 = True 0 = False 1 && 0 = False 0 1 && 1 = True 1 1 || 1 = True 1 1 || 0 = True 1 So the answer is for non-zero it is considered true, for 0 it is considered false. If your value (your int) returns 0 it won't execute. If it returns a value that is not 0 it will execute.
3,303,243
3,303,273
Problem with SetSuspendState
I write a small application to enter the computer to Standby Mode: #include "stdafx.h" #include <windows.h> #include <PowrProf.h> int _tmain(int argc, _TCHAR* argv[]) { SetSuspendState(FALSE, FALSE, FALSE); return 0; } I get this error: 1>Standby.obj : error LNK2001: unresolved external symbol _SetSuspendState...
You should link your programm with the PowrProf.lib library. You could do it by adding the following string: #pragma comment(lib, "PowrProf.lib")
3,303,297
3,303,374
Why can't I declare a friend in one class that is a private member of another class?
Given the following code: class Screen; class WindowMgr { WindowMgr& relocateScreen( int r, int c, Screen& s); }; class Screen { friend WindowMgr& WindowMgr::relocateScreen( int r, int c, Screen& s); // ^ cannot access private member declared in class 'WindowMgr' int m_nR, m_nC; }; WindowMgr...
The friend declaration doesn't work because WindowMgr::relocateScreen() is private to WindowMgr. C++ standard 11.4-7: "A name nominated by a friend declaration shall be accessible in the scope of the class containing the friend declaration..." Personally, I would make relocateScreen() a private member function...
3,303,397
3,304,344
Why do I get "The procedure entry point CreateVssBackupComponentsInternal could not be located in the dynamic link library VSSAPI.DLL."
Hello everybody let me give you the background first: I'm working on a project that is build with vs2005 on a winxp sp3 with the windows sdk 7.0 and most important the hotfix, that is targeted to work from win xp (sp 0) -> windows 7. part of the project is querying the snapshots and play with the a bit. On my developme...
1) Because the DLL is loaded when your application starts, not when it's first needed. Look up delay-loading or the LoadLibrary system call if you want to load it later, or even conditionally. 2) I don't know, but someone asked the same question before: Why does my Volume Shadow Copy Service requester fail: cannot fin...
3,303,427
3,303,514
Doubt in one disadvantage of doing work in constructors
I was reading Google C++ Style Guide, and got confused in the Doing Work in Constructors part. One of the cons of doing heavy work in constructor is: If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce...
I'm blatantly ripping off some example code from the Wikipedia Virtual function page: #include <iostream> #include <vector> class Animal { public: virtual void eat() const { std::cout << "I eat like a generic Animal." << std::endl; } virtual ~Animal() { } }; class Wo...
3,303,527
3,303,546
how to pre-allocate memory for a std::string object?
I need to copy a file into a string. I need someway to preallocate memory for that string object and a way to directly read the file content into that string's memory?
std::string has a .reserve method for pre-allocation. std::string s; s.reserve(1048576); // reserve 1 MB read_file_into(s);
3,303,544
3,303,681
What does "symbol" mean as in "Load Symbol List"?
What does "symbol" mean as in "Load Symbol List"? Or as in this example from MSDN: "#if lets you begin a conditional directive, testing a symbol or symbols to see if they evaluate to true." Where are these symbols defined and declared?
For "Load Symbol List", a symbol is a defined element in the syntax of a programming language. A local variable name is a symbol. A class type identifier is a symbol. PDB files contain symbol information so the debugger can know where things reside and what their names were in the original source code. For #if, "sym...
3,304,369
3,304,386
Cannot call member function without object = C++
I am brushing up again and I am getting an error: Cannot call member function without object. I am calling like: FxString text = table.GetEntry(obj->GetAlertTextID()); FxUChar outDescription1[ kCP_DEFAULT_STRING_LENGTH ]; IC_Utility::CP_StringToPString(text, &outDescription1[0] ); The line: IC_Utility::CP_StringToPSt...
If you've written the CP_StringToPString function, you need to declare it static: static void IC_Utility::CP_StringToPString( FxString& inString, FxUChar *outString) Alternatively, if it's a function in third-party code, you need to declare an IC_Utility object to call it on: IC_Utility u; u.CP_StringToPString(text, &...
3,304,948
3,304,967
How can you force recompilation of a single file in a Makefile?
The idea is that a project has a single file with __DATE__ and __TIME__ in it. It might be cool to have it recompiled without explicitly changing its modification date. edit: $(shell touch -c ..) might be a good solution if only clumsy.
The standard idiom is to have the object file (not the source file!) depend on a target which doesn't exist and has no rules or dependencies (this target is conventionally called FORCE), like this always-recompile.o: FORCE FORCE: This will break if a file named "FORCE" gets created somehow, though. With GNU make you ...
3,305,340
3,305,442
Replacement of random string/char array characters using match ups
while (1) { char j; if (x[j] == y[j]) Here I am trying to start a loop where I want to able to match any of the characters from char array 'x' with char array 'y'. If the characters do match from x to y then I want to keep them as they are and if they don't I want to be able to replace them with a star '*'. (e...
This more or less does what you specify, I think. #include <string.h> for (int j = 0; y[j] != '\0'; j++) { if (strchr(x, y[j]) == 0) y[j] = '*'; } Test program @LooneyTunes asks what happens with: x[] = "apcd" and y[] = "abcd" - do you get "a*cd". The answer is yes. Here's a test program that demonstra...
3,305,478
3,305,502
Linux C++: Does a return from main() cause a multithreaded app to terminate?
This question seems like it's probably a duplicate, but I was unable to find one. If I missed a previous question, apologies. In Java, where I have most of my experience, if your main() forks a thread and immediately returns the process continues to run until all (non-daemon) threads in the process have stopped. In C++...
Yes. In modern linux (more importantly newer versions of GNU libc) exit_group is the system call used when main returns, not plain exit. exit_group is described as follows: This system call is equivalent to exit(2) except that it terminates not only the calling thread, but all threads in the calling process's ...
3,305,534
3,305,564
C++ Functions and Passing Variables
Possible Duplicate: C++ passing variables in from one Function to the Next. The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of...
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-) On top of that, you call getUserData from your main function and then again from doEstimate....
3,305,573
3,305,579
Does std::move result in slicing?
For example, in unique_ptr<Derived> = new deriv; std::vector<unique_ptr<Base>>.push_back(std::move(deriv)); will deriv be sliced to type unique_ptr<Base>?
No slicing will occur; the unique_ptr<Base> will own the pointer to the Derived object. A unique_ptr to a derived class can be implicitly converted to a unique_ptr to a base class.
3,305,682
3,305,728
C++ arithmetic operations in floating point
Is there a way in C++ to have it evaluate each floating point operation as a double even if the arguments are int? I have a program and numerous places I have code such as 1/2, 5/6. In these cases C++ casts the result to an int, that screws up the whole calculation. From the perspective of financial computations, are t...
In C (and thus C++) all builtin operators (ie POD) operato on objects of the same type. Thus if the parameters of a builtin operator have different types then the compiler will implicitly cast one (usually) of them (according to well defined rules) so that they are both the same. The result of the operator is also the ...
3,305,753
3,305,768
shared_ptr and slicing
Someone I worked with once said that shared_ptr was unsafe and would slice when casting from a derived class to a base class (i.e. upcasting). For example if there were 2 classes A and B where B derived from A, then shared_ptr<A> a(new B) would slice. I pointed him to http://www.boost.org/doc/libs/1_43_0/libs/smart_p...
That someone is wrong, object slicing doesn't apply to pointers. That the pointer usage is wrapped away in a shared_ptr doesn't change that - it doesn't do any particular magic here, it initializes an internal pointer with the value passed to its constructor. Simplified it could look e.g. like this for the purpose o...
3,305,801
3,305,809
C++ shared_ptr - attach to a new raw pointer?
I think I'm missing something simple here. I'm using Boost's shared_ptr. shared_ptr<Foo> pA(new Foo()); shared_ptr<Foo> pB(new Foo()); Now, I want to switch pB so it contains the contents of pA, decrementing the ref count of pB. How can I do this?
It's all done automatically: pB = pA; // pB ref count is decrement (in this case causing the value to be released) // pB is then made to point at the same value as pA // Thus incrementing the refCount.
3,305,876
3,305,917
Using template for return value. how to handle void return?
I have structure for storing callback function like this: template<class T> struct CommandGlobal : CommandBase { typedef boost::function<T ()> Command; Command comm; virtual T Execute() const { if(comm) return comm(); return NULL; } }; Seems like it should work fine exc...
This answer is based off this fun-fact: In a function returning void, you can return any expression of which the type is void. So the simple solution is: virtual T Execute() const { if (comm) return comm(); else return static_cast<T>(NULL); } When T = void, the last return statement is equival...
3,306,113
3,306,203
C++ template meta-programming kung-fu challenge (replacing a macro function definition)
Situation I want to implement the Composite pattern: class Animal { public: virtual void Run() = 0; virtual void Eat(const std::string & food) = 0; virtual ~Animal(){} }; class Human : public Animal { public: void Run(){ std::cout << "Hey Guys I'm Running!" << std::endl; } void Eat(const std::strin...
I'm not sure I really see the problem, per se. Why not something like: void Run() { std::for_each(animals.begin(), animals.end(), std::mem_fun(&Animal::Run)); } void Eat(const std::string & food) { std::for_each(animals.begin(), animals.end(), std::bind2nd(std::mem_fun(&...
3,306,138
3,308,198
How I can get ports associated to the application that opened them?
I need to get a list of all opened ports on my machine and what application opened them. I need to get this information programmatically. Thanks.
I was hoping a cleverer answer would appear. I did just this (programmatically in Python), in an attempt to rewrite a program called NetHogs. My version is here, specifically here is the module in Python used to parse the table from /proc. If you're not Python literate (go learn it), then take a look at the original Ne...
3,306,212
3,327,556
Any benefits of learning 3d software rasterization & theory before jumping into OpenGL/Direct3D?
I came across a very interesting book. I have done some 2d games but 3D is a whole new ballpark for me. I just need to know if there any benefits of learning 3d software rasterization & theory before jumping into OpenGL/Direct3D? Any reason why to either approach? Thanks in advance!
if there any benefits of learning 3d software rasterization You'll get deeper understanding of internal working of 3D apis. I think that if you're serious about working with 3D, you should be able to write CSG raytracer, software rasterizer with texture mapping support, know a few related algorithms. Or AT LEAST yo...
3,306,499
3,306,535
Infernal Libraries (aka DLL Hell)
In a Project of mine, I use a Delphi Application which dynamically loads a wrapper DLL (exporting C-Style functions) which in turn is statically link against a bunch of 3rd party DLLs. It works fine on my test machines, but on my customers computer it failed to initialize with an error Message like "Couldn't find entry...
I found another solution myself: SetDllDirectory adds an additional search path to the list of locations to look at. From http://msdn.microsoft.com/en-us/library/ms686203%28v=VS.85%29.aspx After calling SetDllDirectory, the DLL search path is: The directory from which the application loaded. The directory specified b...
3,306,574
3,306,602
which sorting algorithm is used for std::list's sort member function?
Possible Duplicate: Which sorting algorithm is used by STL’s list::sort()? Which sorting algorithm can be used for sorting std::list ?
It's implementation defined. However, it must follow these restrictions (§23.2.​2.4): Stable: the relative order of the equivalent elements is preserved. Complexity: Approximately NlogN comparisons, where N == size(). So it's a stable sort with O(nlog n).
3,306,786
5,355,613
Get intermediate color from a gradient
Say I have a liner gradient as shown: QLinearGradient linearGrad(QPointF(0, 0), QPointF(0, 100)); linearGrad.setColorAt(1, Qt::red); linearGrad.setColorAt(0.5, Qt::yellow); linearGrad.setColorAt(0, Qt::green); How to get the color of the point QPointF(0, 28.5) in this gradient? Indeed I want to have this kind of color...
There is only way to make it: There is a static member in QPixmap class QPixmap QPixmap::grabWindow( WId window, int x = 0, int y = 0, int width = -1, int height = -1 ) 1) draw your gradient on your widget; 2) grab you widget's surface into pixmap using that function; WId can be received from QWidget::effectiveWinId...
3,306,788
3,306,940
I'm an experienced C++ developer - how can I enter the gaming industry?
I've been working in C++ in embedded environments for a number of years, developing navigation applications. There is a gaming company in my hometown that I like the look of, but I don't have game development experience. You could consider a navigation app as a type of game, depending on who you are running from. My ...
Being 30 doesn't really matter, you can enter the games industry at any age assuming you have the drive and ability. Start reading about gaming topics, and game development websites (gamedev, gamasutra etc.) Start writing games. Clones of games you like, your own original ideas, tech demos, anything that you can poin...
3,306,821
3,307,642
Looking for an embeddable scripting language for C++ with 64-bit support and Cross Platform
I'm looking for a scripting language that works on 32-bit and 64-bit machines as well as on Windows and Linux. I will be embedding it into a C++ application so I prefer it to be natively written in C++ rather than C. I also would prefer the script to have thread/asynchronous support. So far the languages that I have l...
I say Lua. It's ultraportable (It even runs under PalmOS, WindowsCE and DOS!), small (200-300k), fast and it is very easy to interface it with C/C++. Also, Michael Pall makes amazing progress with his LUA JIT implementation. His current beta-4 supports x86 and x86_64 jitting and beats the crap out of almost every inte...
3,306,869
3,598,843
openFrameworks (C++): Blur, Glow and other classic effects
I was doing some simple openframeworks (C++ based) tests drawing different shapes and I was wondering how to apply filters like blur, glow... I come from an AS3 background where this is a piece of cake. I know it won't be that easy but I'd like to find some kind of lead. I've read some people is using ofxShader but I c...
ofXShader can be used for these kinds of effects. As with many OF-addons the code is the docs. So you'll have to dig into the actual ofXShader.h and cpp. Prior knowledge of shaders is presumed and the header-file suggests this: http://www.evl.uic.edu/aej/594/ There are also effects, such as blur, in ofxOpenCV but these...
3,307,000
3,307,018
Calling a C++ function from C# - unbalanced stack
I have a unmanaged C++ function with the following signature: int function(char* param, int ret) I am trying to call it from C#: unsafe delegate int MyFunc(char* param, int ret); ... int Module = LoadLibrary("fullpathToUnamanagedDll"); IntPtr pProc = GetProcAddress(Module, "functionName"); MyFunc func = (MyFunc)Syste...
IIRC, you need to decorate the delegate signature with a calling convention. Unfortunately, this can only be done via IL or generating the stub with Reflection.Emit. You can try this: protected static Type MakeDelegateType(Type returntype, List<Type> paramtypes) { ModuleBuilder dynamicMod = ... ; // supply this Ty...
3,307,048
3,307,055
Static const member initialization in templated class
I have a problem regarding 'static const' member initialization. In a templated class I define a const member and initialize it outside the class. When I include the .h file where this class is implemented in multiple .cpp files, I get an LNK2005 error (I'm using VS2010) that says the constant is already defined. // L...
You should define the constant in a source file not a header (so it only gets defined once) since this is a template which you need to keep in the header(and all instances have the same value) you can use a common base class. class ListBase { protected: ListBase() {} // use only as base ~ListBase() { } // prev...
3,307,077
3,316,951
Need help interpreting ld linker error
Can anyone tell me what the file "/usr/include/c++/4.4/exception" would have to do with this error. There is no main defined in that file. I am not sure how to read the error message. ./libfoo.a(main.o): In function `main': /usr/include/c++/4.4/exception:62: multiple definition of `main' interface-wx/App.o:/usr/inclu...
So I figured out what was going on...just in case someone else runs into this. A good way to find out where that duplicate definition is coming from in your code is to use the command: nm -l name_of_object_file.o nm is used to print the symbol table of an object file. I piped the output to a file and searched for ma...
3,307,150
3,307,511
Private method in a C++ interface?
Why would I want to define a C++ interface that contains private methods? Even in the case where the methods in the public scope will technically suppose to act like template methods that use the private methods upon the interface implementation, even so, we're telling the technical specs. right from the interface. Isn...
The common OO view is that an interface establishes a single contract that defines how objects that conform to that interface are used and how they behave. The NVI idiom or pattern, I never know when one becomes the other, proposes a change in that mentality by dividing the interface into two separate contracts: how t...
3,307,170
3,307,383
Rotating logs without restart, multiple process problem
Here is the deal: I have a multiple process system (pre-fork model, similar to apache). all processes are writing to the same log file (in fact a binary log file recording requests and responses, but no matter). I protect against concurrent access to the log via a shared memory lock, and when the file reach a certain s...
Your solution seems fine, but you should store an integer with inode of current logging file in shared memory (see stat(2) with stat.st_ino member). This way, all process kept a local variable with the opened inode file. The shared var must be updated when rotating by only one process, and all other process are aware ...
3,307,204
3,307,238
Adding different objects to std::list
can you add different class objects to same list?
See boost::any. You can use std::vector and then use it to add heterogeneous types into. Example: std::vector<boost::any> v; v.push_back(std::string("hello world")); v.push_back(42);
3,307,452
3,307,474
quick accessing to element of std::map
Do you know if it is any difference in performance when I access a std::map element using find or operator []? One returns an iterator and the other a const ref to the object. Which one might be quicker becuase of all of the behind the scene of the STL?
When you use [] on a key that doesn't exist, the default element will be inserted. This default element depends on your map definition (for example, for an int it will be a zero). When you use find, there is no "automatic" insertion, so it can be quite faster if you often search for keys that does not exist.
3,307,468
3,307,574
Class does not name a type C++
In C++ what does the error mean "class does not name a type"?
As I have said most probably you try to use a type before declaration. The code will make things much clear, but I guess you have a code like this : class someclass { public: ...... otherclass other_object; ...... > }; class otherclass { public: ...... someclass some_object; ...... };
3,307,859
3,307,886
malloc only allocates 4 bits?
I'm trying to make some c programs, ut i'm stuck at the malloc command. This is my code: #include <stdlib.h> #include <iostream> #include "Oef1.h" using namespace std; some methode clled by main{ int ** q=NULL; int m=read(q); } int read(int ** q){ int m=3...
sizeof is returning the size of the data type, which is a pointer. On your system you will find that a pointer is always 4 bytes (not bits). sizeof does not return the size of the array when used on a pointer.
3,307,866
3,307,879
C++: declaring a class with functions, that handle string
I haven`t found answer to my question using search, though I thought it is simple and popular. Anyway, my question is: I have got a header file, which declares a class and functions in it. It looks like that: #ifndef SOME_CLASS_H #define SOME_CLASS_H #include <string> class mySomeClass { public: bool a_func(...
string is declared in the namespace std, so you have to change the function declarations to bool a_func(std::string & myString, unsigned long int & x);
3,307,880
3,310,329
How can I get my very large program to link?
Our next product has grown too large to link on a machine running 32-bit Windows. The sum total of all the lib files exceeds 2Gb and can only be linked on a 64-bit Windows machine. Eventually we will exceed that boundary, since our software tends to grow rather than contract and we are using a 32-bit linker (MS Visua...
Try using the Symbol Sort program to show you where the main bits of bloat are in your code. Also just looking at the size of the raw .obj files will give you a reasonable idea of where to target.
3,307,889
3,315,583
Where to find open-source widgets for Qt library?
I have found quite good stuff here. If you know other sites that have some good code for Qt library (some additional codes, good examples, except the Qt standard examples, of course), please share with us.
Also please look at Qt Solutions
3,307,939
3,308,279
C++ template function with unknown number of arguments
this is probably a useless problem but it stuck on my mind for few hours. I wanna write a function which accepts some (POD) arguments, convert them to string and return the concatenation. for example template<typename A, typename B> string ToString(A a, B b) { stringstream ss; ss << a << b; return ss.str();...
Almost like the real thing :-) #include <iostream> #include <string> #include <sstream> using namespace std; template<class L,class R> struct cons_t { const L &l; const R &r; cons_t(const L &_l, const R &_r) : l(_l),r(_r) {} }; template<> struct cons_t<void,void>{}; typedef cons_t<void,void> cons; template<cl...