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 |
|---|---|---|---|---|
1,482,908 | 1,482,916 | Confusion in exception handling | Consider the following program
#include <iostream>
#include<cstdlib>
using namespace std;
class E {
public:
const char* error;
E(const char* arg) : error(arg) { }
};
void my_terminate() {
cout << "Call to my_terminate" << endl;
}
struct A {
A() { cout << "In constructor of A" << endl; }
~A(){
... | The C++ rule is that you must never throw an exception from a destructor that is being called during the "stack unwinding" process of another exception.
You throw an exception in A's destructor, which is something you are not supposed to do.
|
1,482,998 | 1,483,079 | Best way to deal with object that can't instantiate itself? | I guess I've asked a few similar questions before, but I was beating around the bush. I think this is the real problem that I can't quite lay to rest.
I'm dealing with a third party library, and there's an object that can't create itself, b2Body. The b2World has to instantiate it. I personally don't like this design pa... | I think, if you're going to use a third-party library, you should only fight its design if you have a much better reason than oh, I don't like that design pattern much. Your library has a way of doing things — apparently, by using a factory object — and fighting that will increase your code complexity, possibly substan... |
1,483,068 | 1,483,578 | How to get a CString object from a file with CFile::Read() in Unicode? | The charset is Unicode. I want to write a string of CString type into a file, and then read it out from the file afterwards.
I write the string into a file with CFile::Write() method:
int nLen = strSample.GetLength()*sizeof(TCHAR);
file.Write(strSample.GetBuffer(), nLen);
Here is the question: I want to obtain the CSt... | UINT nBytes = (UINT)file.GetLength();
int nChars = nBytes / sizeof(TCHAR);
nBytes = file.Read(strSample.GetBuffer(nChars), nBytes);
strSample.ReleaseBuffer(nChars);
|
1,483,344 | 1,483,369 | How to use double buffer in this case? | Let's say i have three control A, B, C. They are all inherited from CDialog,
A is a main dialog , A contains B, and B contains C.
and each time i use mouse mouse drag C, B and C will move together.
This is a image:http://img507.imageshack.us/img507/7039/31709956.jpg
We know this will cause B and C to redraw themselves.... | what helpes flickering a lot is to overload the erasebackground method. This method fills the entire background with a solid color. The paint than paints all items on it. By removing the erasebackground, the paint will just paint over stuff which is already there, thus removing flickering.
|
1,483,403 | 1,483,441 | Are standard output streams in C++ thread-safe (cout, cerr, clog)? | I know that there is no concept of threads in current C++, but this article is saying:
A typesafe, threadsafe, portable
logging mechanism
.....
The fprintf() function is threadsafe,
so even if this log is used from
different threads, the output lines
won't be scrambled.
What about cout, cerr and clog?
I think t... | The article makes a claim about the POSIX standard for the fprintf API. It says nothing about C++ streams. And this is quite correct, as there are no such guarantees on those stream.
Note that although the logging class in that article uses C++ stream syntax, it does this via a std::ostringstream object that is created... |
1,483,491 | 1,483,498 | C++: Including header-file fails compilation but including source cpp file compiles | This is probably really simple, but it's hindering me on my way down c++ road.
I am currently reading through accelerated c++ and I decided to overkill one of the exercises. It all worked well and my code ran fine until I split it into a header and separate source file. When I import my .cpp source file containing some... | Compilation fails, because you have only declared this function. Its definition is in different compilation unit, and you're not linking those two together.
Do g++ -Wall -o quartile quartile.cpp stats.cpp and it'll work.
|
1,483,566 | 1,483,602 | Activating an application as a child/popup of another application | Under Windows XP, is it possible to execute a 3rd party application, so its main window will be a child/popup window of my VC++ MFC application?
I want to control it's Z-Order like any other window in my app
I don't want it be be visible in the taskbar
I want to catch its WM_CLOSE and handle it in my app
In general, ... | Here is an example on hosting other applications in your application:
Hosting .exe applications into a dialog
Also you may want to check out hooks and specifically the WH_CALLWNDPROC if you want to monitor all messages.
|
1,483,941 | 1,483,967 | C++ class to access bytes/words of an unsigned integer | union LowLevelNumber
{
unsigned int n;
struct
{
unsigned int lowByte : 8;
unsigned int highByte : 8;
unsigned int upperLowByte : 8;
unsigned int upperHighByte : 8;
} bytes;
struct
{
unsigned int lowWord : 16;
unsigned int highWord : 16;
} words;
};
This union allows me to access the unsigned in... | union LowLevelNumber {
unsigned int n;
struct {
unsigned int lowByte : 8;
unsigned int highByte : 8;
unsigned int upperLowByte : 8;
unsigned int upperHighByte : 8;
};
struct {
unsigned int lowWord : 16;
unsigned int highWord : 16;
};
};
Note the remov... |
1,483,990 | 1,484,003 | read words from line in C++ | I was wondering if there was a way to read all of the "words" from a line of text.
the line will look like this: R,4567890,Dwyer,Barb,CSCE 423,CSCE 486
Is there a way to use the comma as a delimiter to parse this line into an array or something?
| Yes, use std::getline and stringstreams.
std::string str = "R,4567890,Dwyer,Barb,CSCE 423,CSCE 486";
std::istringstream iss(str);
std::vector<std::string> words;
while (std::getline(iss, str, ','))
words.push_back(str);
|
1,484,021 | 1,484,037 | Is a bit field any more efficient (computationally) than masking bits and extracting the data by hand? | I have a numerous small pieces of data that I want to be able to shove into one larger data type. Let's say that, hypothetically, this is a date and time. The obvious method is via a bit field like this.
struct dt
{
unsigned long minute :6;
unsigned long hour :5;
unsigned long day :5;
unsigned long mont... | The compiler generates the same instructions that you would explicitly write to access the bits. So don't expect it to be faster with bitfields.
In fact, strictly speaking with bitfields you don't control how they are positioned in the word of data (unless your compiler gives you some additional guarantees. I mean that... |
1,484,052 | 1,484,062 | Should I expose iterators and adaptor methods or a whole container in C++? | Consider the piece of code:
class Foo
{ // ...
std::vector<Bar> bars;
};
Should I expose the whole container, or should I expose typedef'd iterator class and write adaptor methods (begin(), end(), size(), and whatever I need)?
If the answer is it depends, how should one make a decision?
| You only expose iterators or iterator-ranges (and typedefed iterator types) unless you absolutely need to expose the container.
This avoids breaking other code when changing the implementation details and also follows the guide-lines of information hiding / encapsulation.
|
1,484,140 | 1,484,149 | How do you get an unsigned long out of a string? | What's the safest and best way to retrieve an unsigned long from a string in C++?
I know of a number of possible methods.
First, converting a signed long taken from atol.
char *myStr; // Initalized to some value somehow.
unsigned long n = ((unsigned)atol(myStr));
The obvious problem with this is, what happens when the... | One way to do it:
stringstream(str) >> ulongVariable;
|
1,484,237 | 1,484,239 | Platform-independent way to obtain maximum C++ float value | What’s the best, platform-independent way to obtain the maximum value that can be stored in a float in C++?
| std::numeric_limits
|
1,484,350 | 1,484,363 | Validating a user's input to make sure it's in binary (C++) | I'm working on a c++ program and I need to take in a binary number from 0-255, inclusive, as a string(it has to be a string). What can I write in a while(input invalid) loop to check that the string is between 00000000 to 11111111, inclusive. Thanks so much
| Assuming you use std::string:
while( str.length()==8 && str.find_first_not_of("01")==std::string::npos )
that is, if you really want it to be always 8 characters. Adjust to suit your taste (for what I can tell by your comment, you want str.length()<=8 or (!str.empty()) && str.length()<=8.
|
1,484,462 | 1,484,476 | How to require certain concepts in C++ code? | How do I require and check that an argument is a certain concept in C++?
For example, the random_shuffle function in the algorithm header requires that its arguments are RandomAccessIterators:
template<typename _RandomAccessIterator>
inline void
random_shuffle(_RandomAccessIterator __first, _RandomAccessItera... | Boost has a library for this. It's probably easier and more well documented than figuring out how to use the version your STL implementer has hacked together.
http://www.boost.org/doc/libs/1_40_0/libs/concept_check/concept_check.htm
|
1,484,518 | 1,484,668 | getrusage() get system time, user time. Unix programming help | I am writing a shell where I need to launch several child processes at once and record the system time and user time.
So far I am able to do it. The only problem is that I am using wait4 to grab the system resources used by the child program and put it in my rusage structure called usage.
How can I launch all the proce... | A convoluted answer.
In a POSIX environment, launch the children, then use waitid() with the WNOWAIT option to tell you that some child has exited. The option leaves the child in a waitable state - that is, you can use another wait-family call to garner the information you need. You can then use the non-POSIX wait4()... |
1,484,543 | 1,484,560 | Is it safe to use fastcall in a shared library? | For example, let's say I have a function that will swap bytes in a 32 bit value for you:
uint32_t byte_swap(uint32_t in);
Well it seems silly to push that 32-bit value onto the stack and pop it off again, especially if we're going to be calling this function a lot, so let's pass it in through ECX:
#if __FASTCALL_SUPPO... | __attribute__((fastcall)) is a gcc extension; as such, it may not be usable if the caller is not using gcc as well. Moreover, in the sample you gave, if __FASTCALL_SUPPORTED_ is not defined, you'll end up with a call with the wrong calling convention - bad idea.
One way to deal with this may be using a fallback wrapper... |
1,484,641 | 1,484,665 | C++ override/overload problem | I'm facing a problem in C++ :
#include <iostream>
class A
{
protected:
void some_func(const unsigned int& param1)
{
std::cout << "A::some_func(" << param1 << ")" << std::endl;
}
public:
virtual ~A() {}
virtual void some_func(const unsigned int& param1, const char*)
{
some_func(param1);
}
};
clas... | The problem is that in the derived class you are hiding the protected method in the base class. You can do a couple of things, either you fully qualify the protected method in the derived object or else you bring that method into scope with a using directive:
class B : public A
{
protected:
using A::some_func; // bri... |
1,484,739 | 1,484,906 | how to properly delete a pointer to array | I'm new to C++, and I'm confused about arrays and pointers. Could someone tell me how I can properly delete a pointer. Like for example,
int *foo;
foo = new int[10];
delete foo;
or
delete [] foo;
Thanks.
| The requirement to match new[] with delete[] is technically correct.
Much better, however (at least in my opinion), would be to forget that you ever even heard of new[], and never use it again. I'm pretty sure it's been (at least) 10 years since the last time I used new[], and if I'd understood the situation very well,... |
1,484,744 | 1,484,883 | Calling WinSock functions using LoadLibrary and GetProcAddress | Basically I have a header file like this:
#if WIN32
typedef DWORD (WSAAPI *SocketStartup) (WORD wVersionRequested, LPWSADATA lpWSAData);
typedef SOCKET (WINAPI *MakeSocket)(IN int af, IN int type, IN int protocol, IN LPWSAPROTOCOL_INFOW lpProtocolInfo, IN GROUP g, IN DWORD dwFlags );
typedef DWORD (WI... | Solved! Thank you all for your help. To fix it I just changed the typedef as follows:
typedef int (WSAAPI SocketStartup)( IN WORD wVersionRequested, OUT LPWSADATA lpWSAData );
Basically I copy and pasted from Winsock2.h :P
|
1,484,882 | 1,484,917 | Why use an object instance rather than class::staticFunction? | Why should I use an object instance to access member functions rather than class::staticFunction?
( or why not? )
| You're allowed to use the object.function() notation for a static function, but I'd advise against it -- it gives the misleading impression that the function is associated with the specific object, like with a non-static member function. Using the classname::function() syntax portrays the situation clearly and accurate... |
1,484,950 | 1,484,991 | Using cin in QtCreator | For school, we use C++ as the language of choice. I am currently using QtCreator as an IDE, and for its GUI library, it is wonderful. The school is using Visual Studio.
However, most of the programs we are writing make use of cin and cout for input/output. cout works fine as output, as you can see what it puts out in t... | In Preferences, under the Environment section, set the "Terminal" option to /Applications/Utilities/Terminal.app, as pointed out by Alex Martelli.
Then, in the Projects tab, under Run Settings, check the box marked "Run in Terminal".
Now, QtCreator will use Apple's built-in Terminal.app instead of Qt's console, allowin... |
1,485,044 | 1,485,064 | Folding away assertions in C++ class? | So, in a non-class type of situation, I can do something like this:
int val_to_check = 0;
int some_func(int param) {
assert(val_to_check == 0);
return param*param+param;
}
int main() {
printf("Val: %i\n", some_func(rand()));
return 0;
}
If val_to_check is declared const instead, the assertion can be folded a... | In the class example you provided, there's no way for the compiler to assume the constant is zero because you have two runtime variables:
Your const int val_ is only constant for each instance of the class so it can never optimise the class's function code since it must cater for every case.
The example instantiation ... |
1,485,239 | 1,695,675 | QtCreator build returns collect2: ld returned exit status 1 | While building several different projects in QtCreator, I have run across the following build error:
collect2: ld returned 1 exit status
After only changing a few things (that should not change anything significant in the build), it will go away if it has already appeared, or it will appear if it's not there.
In my cu... | Checking the "Compile Output" pane reveals that the .pro file was trying to link the same .cpp file twice.
|
1,485,435 | 1,485,714 | Force relink when building in QT Creator | I have a subdirs project which wraps a couple libraries and a main application. When I change something in one of the libraries the main application does not relink with them.. does anyone have a trick for getting an application to relink with its statically linked libs automatically when using QtCreator?
| There is a workaround for this and also an interesting discussion on the subject (qmake seems to be the problem here) on the Qt Creator mailing list.
The workaround is to add a PRE_TARGETDEPS command to your main applications .pro file, e.g.:
PRE_TARGETDEPS += /path/to/your/lib.a
This forces the relink.
|
1,485,697 | 1,488,082 | CreateProcessWithLogonW and mmc.exe | I wrote a program, that should work like RunAs. It works fine, but i have one problem with it. If i want to run for example compmgmt.msc, then i should run mmc.exe and compmgmt.msc as it's parameter. Computer Management will open, but not under the user as i want to run it. It will run under that username who is logged... | Have you looked at the online MSDN docs?
http://msdn.microsoft.com/en-us/library/ms682431(VS.85).aspx
Have a look at the sample code. Seems pretty straightforward.
|
1,485,978 | 1,486,006 | Arranging global/static objects sequentially in memory | In C++, is it possible to force the compiler to arrange a series of global or static objects in a sequential memory position? Or is this the default behavior? For example, if I write…
MyClass g_first (“first”);
MyClass g_second (“second”);
MyClass g_third (“third”);
… will these objects occupy a continuous chunk of ... | The compiler can do as it pleases when it comes to placing static objects in memory; if you want better control over how your globals are placed, you should consider writing a struct that encompasses all of them. That will guarantee that your objects will all be packed in a sequential and predictable order.
|
1,485,983 | 1,486,279 | Calling C++ member functions via a function pointer | How do I obtain a function pointer for a class member function, and later call that member function with a specific object? I’d like to write:
class Dog : Animal
{
Dog ();
void bark ();
}
…
Dog* pDog = new Dog ();
BarkFunction pBark = &Dog::bark;
(*pBark) (pDog);
…
Also, if possible, I’d like to invoke the c... | Read this for detail :
// 1 define a function pointer and initialize to NULL
int (TMyClass::*pt2ConstMember)(float, char, char) const = NULL;
// C++
class TMyClass
{
public:
int DoIt(float a, char b, char c){ cout << "TMyClass::DoIt"<< endl; return a+b+c;};
int DoMore(float a, char b, char c) const
{ ... |
1,485,985 | 1,486,862 | Can a nested C++ class inherit its enclosing class? | I’m trying to do the following:
class Animal
{
class Bear : public Animal
{
// …
};
class Giraffe : public Animal
{
// …
};
};
… but my compiler appears to choke on this. Is this legal C++, and if not, is there a better way to accomplish the same thing? Essentially, I want to... | You can do what you want, but you have to delay the definition of the nested classes.
class Animal
{
class Bear;
class Giraffe;
};
class Animal::Bear : public Animal {};
class Animal::Giraffe : public Animal {};
|
1,486,141 | 1,486,163 | Best way to store constant data in C++ | I have an array of constant data like following:
enum Language {GERMAN=LANG_DE, ENGLISH=LANG_EN, ...};
struct LanguageName {
ELanguage language;
const char *name;
};
const Language[] languages = {
GERMAN, "German",
ENGLISH, "English",
.
.
.
};
When I have a function which accesses the arra... | If the enum values are contiguous starting from 0, use an array with the enum as index.
If not, this is what I usually do:
const char* find_language(Language lang)
{
typedef std::map<Language,const char*> lang_map_type;
typedef lang_map_type::value_type lang_map_entry_type;
static const lang_map_entry_type lan... |
1,486,203 | 1,495,731 | how to draw namespace/package scope method/variable in UML? | I'm currently trying to draw a class diagram of a couple of namespaces in C++.
Right now, some variables and methods inside the namespace(free, not part of classes) are part of the namespace API, others are the external part of some classes API (like operator<< and those).
I'm only willing to represent those methods/va... | UML is for modelling Object Oriented designs, it is not intended to model implementation idioms. Apply the Principle of a Single Responsibility Principle to determine where the function should exist, either in the core class or a handler class.
|
1,486,324 | 1,486,344 | Is it possible for programmer to analyze unknown code fast? | I got a task related to ANCIENT C++ project which hasn't any documentation, comments at all and all code/variables is written in foreign language. Do I have a chance to analyze this code in a 1 working day and make a design/UML to create new features? I have been sitting around for 3 hours already and I feel so frustra... | I suspect the biggest issue may be the fact that it's in a foreign language. You can use various static code analysis tools to try and understand what's going on, but if everything is presented in an unfamiliar language then that's still no use. Your first step (I believe) is to find someone who can speak this language... |
1,486,402 | 1,486,425 | c++ need help on how to use callback functions | The function header is defined below:
/**
* \fn int fx_add_buddylist(const char* name, EventListener func, void *args)
* \brief rename the group.
*
* \param name The group name which you want to add.
* \param func The send sms operate's callback function's address, and the operate result will pass to this... | EventListener defines the interface of a function you have to write and pass as argument to fx_add_buddylist.
Do something like this:
void MyEventListener(int message, WPARAM wParam, LPARAM lParam, void* args)
{
printf("Callback called!\n");
}
...
fx_add_buddylist("SomeName", MyEventListener, NULL);
...
You c... |
1,486,492 | 1,486,544 | Qt tr does not seem to work on static constant members? | I'm working on translating our Qt gui at the moment.
I have the following code:
// header file
static const QString Foo;
// cpp file
const QString FooConstants::Foo = "foo";
// another cpp file
editMenu->addAction(tr(FooConstants::Foo));
This doesn't seem to work though.
That is, there is no entry in the .ts file f... | Wrap your literal in the QT_TR_NOOP macro:
// cpp file
const QString FooConstants::Foo = QT_TR_NOOP("foo");
From the guide:
If you need to have translatable text completely outside a function, there are two macros to help: QT_TR_NOOP() and QT_TRANSLATE_NOOP(). They merely mark the text for extraction by the lupdate t... |
1,486,545 | 1,486,805 | Qt GUI app: warning if QObject::connect() failed? | I recently migrated my Qt project from Linux to Vista, and now I'm debugging signals blindly.
On Linux, if QObject::connect() fails in a debug build, I get a warning message on stderr. On Windows, there is no console output for GUI applications, only an OutputDebugString call.
I already installed DebugView, and it catc... | Call the static function QErrorMessage::qtHandler().
As per the documentation, this 'installs a message handler using qInstallMsgHandler() and creates a QErrorMessage that displays qDebug(), qWarning() and qFatal() messages'.
Alternatively, install a message handler with qInstallMsgHandler().
Another alternative (descr... |
1,486,740 | 1,487,093 | How do I get the default check box images? | I'm trying to build an owner-drawn check box using CButton, but since I only want to change the text color, I'd like the check-box marks to remain the same.
Is there a command that allows me to retrieve the default check box bitmaps for the platform where the program is running?
(alternatively: how could I change onl... | I use UxTheme.dll to draw my custom checkbox.
First I draw the check-box marks using: DrawThemeBackground passing it a modified rect (checkboxRect.right = pCustomDraw->rc.left + 15;)
And then I draw the text by myself using ::DrawText.
I hope it helps.
|
1,486,818 | 1,486,849 | C/C++ - Any good web server library? | Are there any open source, fast web server libraries? Thanks.
| mongoose (formely shttpd, GPL v2 and commercial license), libmicrohttpd (LGPL v2.1 license).
|
1,486,904 | 1,486,931 | How do I best silence a warning about unused variables? | I have a cross platform application and in a few of my functions not all the values passed to functions are utilised. Hence I get a warning from GCC telling me that there are unused variables.
What would be the best way of coding around the warning?
An #ifdef around the function?
#ifdef _MSC_VER
void ProcessOps::send... | You can put it in "(void)var;" expression (does nothing) so that a compiler sees it is used. This is portable between compilers.
E.g.
void foo(int param1, int param2)
{
(void)param2;
bar(param1);
}
Or,
#define UNUSED(expr) do { (void)(expr); } while (0)
...
void foo(int param1, int param2)
{
UNUSED(param2... |
1,487,238 | 1,487,269 | Copy constructor: deep copying an abstract class | Suppose I have the following (simplified case):
class Color;
class IColor
{
public:
virtual Color getValue(const float u, const float v) const = 0;
};
class Color : public IColor
{
public:
float r,g,b;
Color(float ar, float ag, float ab) : r(ar), g(ag), b(ab) {}
Color getValue(const float u, const fl... | Take a look at the virtual constructor idiom
|
1,487,318 | 1,487,353 | Qt4 modular synth editing widget | I'm about to start writing a GUI for a modular synthesis app (like Alsa Modular Synth, Pure Data, Ingen) that will be used for patch (sound) editing.
What I need to do is something like this:
(source: drobilla.net)
(source: mcgill.ca)
So, basically, it's an area where I can draw some rectangles (boxes) that repres... | Take a look at QGraphicsScene and QGraphicsView.
This way you will be able to create a scene filled with items.
Each item can receive mouse events and you can manually paint it.
|
1,487,375 | 1,506,875 | Qt stylesheets: QHeaderView draws header text in bold when view data is selected | I'm trying to style a QTableView with Qt Stylesheets. Everything works OK, except that all the table header texts (column headers) are drawn as bold text whenever data in the table view is selected.
I've tried things like this:
QTableView::section {
font-weight: 400;
}
QTableView::section:selected {
font-weight... | I haven't tested it, but setting the QHeaderView::highlightSections property to false should do the trick.
You can get a pointer to a QHeaderView object using QTableView's verticalHeader() and horizontalHeader() methods.
|
1,487,387 | 1,487,778 | Why do Boost Parameter elected inheritance rather than composition? | I suppose most of the persons on this site will agree that implementation can be outsourced in two ways:
private inheritance
composition
Inheritance is most often abused. Notably, public inheritance is often used when another form or inheritance could have been better and in general one should use composition rather ... | EDIT: Ooopss! I posted the answer below because I misread your post. I thought you said the Boost library used composition over inheritance, not the other way around. Still, if its usefull for anyone... (See EDIT2 for what I think could be the answer for you question.)
I don't know the specific answer for the Boost Par... |
1,487,440 | 1,487,483 | Convert hexadecimal string with leading "0x" to signed short in C++? | I found the code to convert a hexadecimal string into a signed int using strtol, but I can't find something for a short int (2 bytes). Here' my piece of code :
while (!sCurrentFile.eof() )
{
getline (sCurrentFile,currentString);
sOutputFile<<strtol(currentString.c_str(),NULL,16)<<endl;
}
My idea is to read a f... | Have you considered sscanf with the "%hx" conversion qualifier?
|
1,487,476 | 1,487,530 | Debugging multitheaded programs | I have been a C programmer for many years and my favorite "debugger" has always been the printf() function - I only resort to visual studio's debugger when absolutely forced and so have never been very proficient in using it. Recently I have had to modify a program from C to C++ (although of course printf still works f... | Visual Studio supports thread debugging to some extend. Via the Threads Window you can select threads, suspend and resume threads etc. When you switch between threads the Call Stack Window is updated accordingly so you can inspect what each thread is doing. You may also restrict breakpoints to specific threads.
If you ... |
1,487,674 | 1,489,095 | How to work out which widget to target with Qt stylesheets | I'm attempting to use Qt stylesheets to style a reasonably complex UI. So far things are going reasonably well, but I'm running into a difficulty:
How can I work out what widget name I should be targeting for a particular part of a UI? For example, if I want to change the font size in the cells of a QTableView, do I wr... | Rendering of items in an item view is done by the delegate. Since Qt 4.4, the built-in item views use a style-able delegate implementation by default (see this blog post), but it seems that you want more control that it allows you.
In that case, make sure that your model's data() method returns proper values for the ap... |
1,487,695 | 1,487,762 | C++ Cross-Platform High-Resolution Timer | I'm looking to implement a simple timer mechanism in C++. The code should work in Windows and Linux. The resolution should be as precise as possible (at least millisecond accuracy). This will be used to simply track the passage of time, not to implement any kind of event-driven design. What is the best tool to accompli... | For C++03:
Boost.Timer might work, but it depends on the C function clock and so may not have good enough resolution for you.
Boost.Date_Time includes a ptime class that's been recommended on Stack Overflow before. See its docs on microsec_clock::local_time and microsec_clock::universal_time, but note its caveat that ... |
1,487,815 | 1,487,856 | What could be causing this crash? | I have a C++ program (GCC) and when I add one or more int members to an abstract base class, the program starts crashing. In the case I've examined, it seems that by adding this member, a member in a derived class quits getting initialized (or gets stomped on at some point). If I add more members, it starts (not) worki... | Off the top of my head, without seeing any code (see comments on your question) I would suggest a rogue pointer which normally stomps on something you don't notice, but introducing a new member makes it stomp on something you do notice.
Try adding members of different sizes, or more (unused) int members, or maybe a str... |
1,487,840 | 1,487,992 | Search Hex substring in string | Well i got a socket that receives binary data and I got that data into an string, containing values and strings values too. (for example "0x04,h,o,m,e,....")
How can i search for an hex substring into that string?
I.e. i want to search "0x02,0x00,0x01,0x04".
I'm asking for a c++ version of python 'fooString.find("\x02\... | Good documentation for string is here:
http://www.sgi.com/tech/stl/basic_string.html
Hex tokens are passed just like Python (Where do you think Python got the syntax from).
The character \x?? is a single hex character.
#include <iostream>
#include <string>
int main()
{
std::cout << (int)'a' << "\n";
std::stri... |
1,487,950 | 1,502,908 | access violation in WM_PAINT not caught | To test this problem I have written a minimal windows application. If I force an access violation in the WM_PAINT handler this exception never gets to the debugger. If started without debugger the access violation also does not show up. Usually you should get the Windows Error Reporting dialog.
Digging a bit deeper it ... | As a workaround I remove all registered exception handlers in my window procedure. Quite ugly.
LRESULT CALLBACK window_proc(
HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
// get thread information block
NT_TIB* tib;
__asm {
mov EAX, FS:[18h]
mov [tib], EAX
}
// old exc... |
1,488,234 | 1,488,274 | play video clip in windows c++ app | Im currently using wxMediaCtrl to play videos in my app. The api is unfortunately a little buggy, and doesn't playback all media types i need to support (e.g. wmv).
I am wondering if there is an alternative c++ api, that will allow me to do this. I am currently just concerned with supporting windows.
What do people nor... | wxMediaControl uses DirectShow on Windows, it should be able to play wmv files. If you can play a media file with GraphStudio, you should be able to play it with wxMediaControl.
If not, you need to install the proper video codecs. Have you tried installing FFDShow?
You can try Video Control, and here is a sample on how... |
1,488,775 | 1,488,815 | C++ Remove new line from multiline string | Whats the most efficient way of removing a 'newline' from a std::string?
| #include <algorithm>
#include <string>
std::string str;
str.erase(std::remove(str.begin(), str.end(), '\n'), str.cend());
The behavior of std::remove may not quite be what you'd expect.
A call to remove is typically followed by a call to a container's erase method, which erases the unspecified values and reduces th... |
1,489,239 | 1,489,315 | Do threads clean-up after themselves in Win32/MFC and POSIX? | I am working on a multithreaded program using C++ and Boost. I am using a helper thread to eagerly initialize a resource asynchronously. If I detach the thread and all references to the thread go out of scope, have I leaked any resources? Or does the thread clean-up after itself (i.e. it's stack and any other system re... | The thread's stack gets cleaned up when it exits, but not anything else. This means that anything it allocated on the heap or anywhere else (in pre-existing data structures, for example) will get left when it quits.
Additionally any OS-level objects (file handle, socket etc) will be left lying around (unless you're usi... |
1,489,249 | 1,489,350 | Center QGraphicsView in Widget | I have a QDialog that contains several dock widgets and one QGraphicsView. The widget layout is set to grid, the QGraphicsView size policy is set to fixed on the 2 axes and it the QGraphicsView is center in the empty zone of the QDialog.
I would like to resize my QGraphicsView and let it at the center of the empty zone... | You could try
ui->mProjectView->setFixedSize(mProject->getSize() + QSize(2,2));
instead.
|
1,489,255 | 1,489,460 | architecture/design advise for a test program | I am trying to build a test program in c++ to automate testing for a specific application. The testing will involve sending requests which have a field 'CommandType' and some other fields to a server
The commandType can be 'NEW', 'CHANGE' or 'DELETE'
The tests can be
Send a bunch of random requests with no pattern
Se... | I would not create your own framework. There are many already written that follow a common pattern and can likely accomodate your needs elegantly.
The xUnit framework in all incarnations I have seen allows you to add new test cases without having to edit the code that runs the tests. For example, CppUnit provides a mac... |
1,489,313 | 1,489,335 | C++ std::transform() and toupper() ..why does this fail? | I have 2 std::string. I just want to, given the input string:
capitalize every letter
assign the capitalized letter to the output string.
How come this works:
std::string s="hello";
std::string out;
std::transform(s.begin(), s.end(), std::back_inserter(out), std::toupper);
but this doesn't (results in a progr... | There is no space in out. C++ algorithms do not grow their target containers automatically. You must either make the space yourself, or use a inserter adaptor.
To make space in out, do this:
out.resize(s.length());
[edit] Another option is to create the output string with correct size with this constructor.
std::string... |
1,489,674 | 1,489,704 | From Static Typing to Dynamic Typing | I have always worked on statically typed languages (C/C++, Java). I have been playing with Clojure and I really like it.
One thing I am worried about is: say that I have a windows that takes 3 modules as arguments and along the way the requirements change and I need to pass another module to the function. I just change... | This is one of the reasons automated testing/test driven development is even more important in dynamically typed languages. I haven't used Clojure (I mostly use Ruby), so unfortunately I can't recommend a specific testing framework.
|
1,489,830 | 1,489,873 | Efficient way to determine number of digits in an integer | What is a very efficient way of determining how many digits there are in an integer in C++?
| Well, the most efficient way, presuming you know the size of the integer, would be a lookup. Should be faster than the much shorter logarithm based approach. If you don't care about counting the '-', remove the + 1.
#include <climits>
// generic solution
template <class T>
int numDigits(T number)
{
int digits = ... |
1,490,092 | 1,490,142 | C/C++: Force Bit Field Order and Alignment | I read that the order of bit fields within a struct is platform specific. What about if I use different compiler-specific packing options, will this guarantee data is stored in the proper order as they are written? For example:
struct Message
{
unsigned int version : 3;
unsigned int type : 1;
unsigned int id : ... | No, it will not be fully-portable. Packing options for structs are extensions, and are themselves not fully portable. In addition to that, C99 §6.7.2.1, paragraph 10 says: "The order of allocation of bit-fields within a unit (high-order to low-order or low-order to high-order) is implementation-defined."
Even a singl... |
1,490,100 | 1,490,140 | How to efficiently copy istringstream? | Or ostringstream?
istringstream a("asd");
istringstream b = a; // This does not work.
I guess memcpy won't work either.
| istringstream a("asd");
istringstream b(a.str());
Edit:
Based on your comment to the other reply, it sounds like you may also want to copy the entire contents of an fstream into a strinstream. You don't want/have to do that one character at a time either (and you're right -- that usually is pretty slow).
// create fst... |
1,490,225 | 1,490,263 | C++: Copy constructor: Use getters or access member vars directly? | I have a simple container class with a copy constructor.
Do you recommend using getters and setters, or accessing the member variables directly?
public Container
{
public:
Container() {}
Container(const Container& cont) //option 1
{
SetMyString(cont.GetMyString());
}
//OR
Cont... | Do you anticipate how the string is returned, eg. white space trimmed, null checked, etc.? Same with SetMyString(), if the answer is yes, you are better off with access methods since you don't have to change your code in zillion places but just modify those getter and setter methods.
|
1,490,286 | 1,490,340 | "Pinnacle" of Encapsulation - Question Regarding Advice from Effective C++ | Item 23 of Effective C++ states: Prefer non-member non-friend functions to member functions.
The whole purpose of the item was to encourage encapsulation, as well as package flexibility and functional extensibility, but my question is how far do you go when it comes to taking this advice?
For example, you could have y... | First, not everyone agrees with this advice. I don't think I've seen anyone but Meyers (edit: and Herb Sutter) give this advice, and I've only seen it given within the context of C++. For example, creating "non-member non-friend functions" in Java or C# isn't really possible, since Java and C# have no free functions,... |
1,490,339 | 1,490,343 | Best Type for UTF-8 data? | What is the best type, in C++, for storing UTF-8 string? I'd like to avoid rolling my own class if possible.
My original thought was std::string — however, this uses char as the underlying type. char may be unsigned or signed — it varies. On my system, it's signed. UTF-8 code units, however, are unsigned octets. This s... | I'd just use std::string, as it is consistent with the UTF-8 ideal of treating data just as you would null-terminated ASCII strings unless you actually need their unicode-ness.
I also like GTKmm's Glib::ustring, but that only works if you're writing a GTKmm (or at least Glibmm) application.
|
1,490,593 | 1,491,828 | Mixing RTTI flags in C++ | If I have multiple linked C++ statically linked libraries in C++, is it possible for them to share (pass to and from functions) class objects if they have been compiled with differing values of enabled/disabled run time type information (RTTI)?
--edit:
Thanks for the responses, the specific things I was worried about w... | How RTTI information is stored is an implementation detail and thus not portable across different compilers.
Also most compilers do not even guarantee that objects compiled with different flags will use the same ABI for their methods. This is most prominently shown with release and debug libraries but other flags can c... |
1,490,877 | 1,490,889 | Structs in C++ can be modified? or there is a restriction? | I have this class which has a double list template of a struct of two chars and another struct
typedef struct KeyC{
char K[5];
char C[9];
} TKeyC;
typedef struct Bin{
char Car;
char Cad[9];
TKeyC *KC;
} TBin;
class Bo {
private:
TDoubleList<TBin> *Ent;
public:
...... | A structure in C++ is a class whose members are all public. If your assignment isn't changing the value you want it to, then you are not assigning to what you think you are.
Your getObj() function returns a copy of the structure, not a reference to the original. So you update the value in the copy, and the original rem... |
1,491,032 | 1,503,211 | Is there any software or library available to draw screws in 3 dimensions in C, C++, Java, or Ruby? | Is there any software or library available to draw screws in 3 dimensions in C, C++, Java, or Ruby?
| Iam not familiar with the topic but, May be this could help. Here
|
1,491,181 | 1,491,451 | How to turn a function of 3 nested loops into one recursive function? | what would the recursive version for the following function would be like:
void tri_loop(size_t i, size_t j, size_t k)
{
for(size_t x = 0; x < i; ++x)
for(size_t y = 0; y < j; ++y)
for(size_t z = 0; z < k; ++z)
{
cout << x <<y << z;
}
}
Just for mental dr... | void recurse(accumulator,b,c,d,limit)
{
if (limit == 0)
printf("%i %i %i\n", b, c, d);
else
if (accumulator<limit)
{
recurse(accumulator+1,b,c,d,limit);
recurse(0,accumulator,b,c,d);
}
}
main()
{
int x=2,y=3,z=4;
recurse(0,0,x,y,z);
}
Is that recursive enough?
|
1,491,491 | 1,491,570 | Can I use std::stack as object pool container? | I need to create a pool of objects to eliminate dynamic allocations. Is it efficient to use std::stack to contain pointers of allocated objects?
I suspect every time I push the released object back to stack a new stack element will be dynamically allocated. Am I right? Should I use std::vector to make sure nothing new ... | Whether a stack is suited for your particular purpose or not is an issue I will not deal with. Now, if you are concerned about the number of allocations, the default internal container for a std::stack is an std::deque<>. It will not need to allocate new memory for the stack in each push (as long as it has space) and w... |
1,491,537 | 1,493,204 | Can I use a "\n" character in strings that are to be translated with Qt Linguist | I'm working on supporting different languages for our GUI. I'm having a problem translating strings that have a '\n' in them. They seem to be ignored.
In Qt Designer I have a QCheckBox with this in the text field:
Here's an \nexample that doesn't work
This appears in english in our french translation.
Having looked at... | The "\n" character itself was not my problem.
Some invisible carriage returns in the string was the culprit.
See http://qt.nokia.com/developer/task-tracker/index_html?method=entry&id=81275
|
1,491,671 | 1,493,216 | How to format/change qmake build output | how can I format the make output (!!by only changing the qmake project file!!).
My compilation lines continue growing, and the one-line-warnings/errors almost disappear between them.
I am thinking of something like
$(CC) in.ext -o out.ext
thanks in regard
| In qmake, you can add a silent configuration option:
CONFIG += silent
(note: I think that's the command. It's something similar to this.)
Which should suppress most of the output, and only print lines like "compiling a.o", along with your warnings and errors. I believe this is similar to make's .SILENT. directive (I... |
1,491,716 | 1,492,059 | best lib for vector array in c++ | I have to do calculation on array of 1,2,3...9 dimensional vectors, and the number of those vectors varies significantly (say from 100 to up to couple of millions). Of course, it would be great if the data container can be easily decomposed to enable parallel algorithms.
I came across blitz++(almost impossible to comp... | Eigen, supports auto-vectorisation of vector on certains compilers (GCC 4, VC++ 2008).
|
1,491,753 | 1,491,781 | Can C++ automatic variables vary in size? | In the following C++ program:
#include <string>
using namespace std;
int main()
{
string s = "small";
s = "bigger";
}
is it more correct to say that the variable s has a fixed size or that the variable s varies in size?
| It depends on what you mean by "size".
The static size of s (as returned by sizeof(s)) will be the same.
However, the size occupied on the heap will vary between the two cases.
What do you want to do with the information?
|
1,491,971 | 1,492,158 | MFC IMPLEMENT_DYNCREATE with template | Is there any way to use IMPLEMENT_DYNCREATE with a template class? If not, why not? Is there another solution to this?
Example:
template<typename T>
class A : public B{
public:
A(){ printf("A constuctor "); }
void fn( ){ T* a = new T(); }
};
IMPLEMENT_DYNCREATE(A<CObject>, B);
| OK I've taken a quick look at the macros and thrown together a completely un tested macro that may work.
#define _RUNTIME_CLASS(class_name, template_name) ((CRuntimeClass*)(&class_name<template_name>::class##class_name##template_name))
#define RUNTIME_CLASS(class_name, template_name) _RUNTIME_CLASS(class_name, template... |
1,492,087 | 1,492,208 | What language would you use to implement auto-update/sync functionality on a memory stick? | We need to distribute documents to our partners on a USB key. I've been asked to develop a piece of software that will check if some documents have been updated on the server and proceed with the synchronization of files on the memory stick.
The software itself will also need to have an auto-update functionality in ca... | I'm assuming this is for Windows. C# would be an excellent choice, unless you can't be sure the user already has .Net installed. Otherwise I'd use Delphi, which can create native executables easily. The auto-update feature will be a pain no matter what language you use, given that a running EXE file can't replace it... |
1,492,118 | 1,492,195 | Which library would you consider on linux for DEA (Data Encryption Algorithm)? | I need a 3DES encrypt/decrypt library for my project.
Do you know an implementation working on linux ?
Linux is the target platform, but I essantially compile/debug on Windows. Therefore it could be really appreciated if it could work on Windows, while not mandatory.
| OpenSSL is a very reputable, well tested open source security library. It's available for *nix and Windows. You can find it here
Edit, can't find a simple example right now. The API documentation is pretty good though.
There's a pre-compiled version for windows available for download from the openssl site. Most pac... |
1,492,264 | 1,493,277 | Deleting a method from Visual Studio properties window | The "Events", "Messages" and "Overrides" tabs in the Properties Window can be used to add new methods to a class as well as to remove them. However, when you select to "Delete" a method, it comments the method code instead of deleting it.
I know this is for safety issues, but I almost never need the commented code and ... | No there is no way of doing this, especially in C++ where there are too many places that directly or indirectly exist as part of the method declaration.
|
1,492,298 | 1,492,358 | C++ expected type specifier error | I am trying to write a wrapper function to figure out who is calling a specific function. So in .h file I added the following: (and implementation in the .cc file)
extern int foo(/*some arguments*/);
extern void call_log(const char*file,const char*function,const int line,const char*args);
#define foo(...) (call_log(... | The best way to find out what's wrong would be to make the compiler show the preprocessed code. You can then easier spot the problem in the offending line.
|
1,492,504 | 1,492,548 | How to manage object life time using Boost library smart pointers? | There is a scenario that i need to solve with shared_ptr and weak_ptr smart pointers.
Two threads, thread 1 & 2, are using a shared object called A. Each of the threads have a reference to that object. thread 1 decides to delete object A but at the same time thread 2 might be using it. If i used shared_ptr to hold obje... | There's 2 cases:
One thread owns the shared data
If thread1 is the "owner" of the object and thread2 needs to just use it, store a weak_ptr in thread2. Weak pointers do not participate in reference counting, instead they provide a way to access a shared_ptr to the object if the object still exists. If the object doesn'... |
1,492,513 | 1,494,213 | Excel OpenText method | I keep getting the ambiguous error code of 0x800A03EC.
I've been searching quite a bit to see if I could find a specific reason for the error but unfortunately that code seems to cover a multitude of possible errors. I will copy and paste the code that seems to be giving me problems and hopefully someone will be able... | From the KB article you linked to:
One caveat is that if you pass
multiple parameters, they need to be
passed in reverse-order.
From MSDN, the parameters to OpenText are:
expression.OpenText(Filename, Origin, StartRow, DataType,
TextQualifier, ConsecutiveDelimiter, Tab, Semicolon, Comma,
Space, Other, OtherChar... |
1,492,517 | 1,492,551 | read matrix from a file in C C++ | Just wonder, for a matrix stored in a file as what it is, i.e. each line in the file being a row of the matrix where elements are separated by space(s), how can I predetermine the size of the matrix, then create an array of the same size and read it into the array in C and C++? If you have some code example, that would... | Something like this. You need to include vector, sstream and string.
There is no need to find out the size of the vector in advance.
std::vector<int> readRow(std::string row) {
std::vector<int> retval;
std::istringstream is(row);
int num;
while (is >> num) retval.push_back(num);
return retval;
}
std::vector... |
1,492,735 | 1,492,748 | Differences between struct in C and C++ | I am trying to convert a C++ struct to C but keep getting "undeclared identifier"? Does C++ have a different syntax for referring to structs?
struct KEY_STATE
{
bool kSHIFT; //if the shift key is pressed
bool kCAPSLOCK; //if the caps lock key is pressed down
bool kCTRL; //if the control key is pressed do... | In C, the name of the type is struct KEY_STATE.
So you have to declare the second struct as
typedef struct _DEVICE_EXTENSION
{
WDFDEVICE WdfDevice;
struct KEY_STATE kState;
} DEVICE_EXTENSION, *PDEVICE_EXTENSION;
If you do not want to write struct all the time, you can use a typedef declare KEY_STATE similar t... |
1,492,918 | 1,493,043 | How do you get what kind of encoding your system uses in c/c++? | In linux terminal one would type
locale charmap
in order to see what kind of character-encoding your system uses, eg UTF-8.
My question is how would you do this using c/c++. (I'm using linux)
edit: I tried using
nl_langinfo(CODESET)
but I got ANSI_X3.4-1968 instead of UTF-8 (which is what I get when typing: locale ... | SETLOCALE(3) Linux Programmer’s Manual SETLOCALE(3)
NAME
setlocale - set the current locale
SYNOPSIS
#include <locale.h>
char *setlocale(int category, const char *locale);
DESCRIPTION
The setlocale() function is used to set or query the program’s current
... |
1,492,982 | 1,514,510 | Compiling an application that uses WinUsb | I am in the process of writing an application to communicate with Usb devices using WinUsb.dll. This is a user-mode library that allows communication with a device through winusb.sys installed as its driver in the kernel.
I am writing this application in C++ with Visual Studio 2008.
The header WinUsb.h is found in the ... | I am working on writing a cross-platform USB library and using the DDK build environment would make my build process much more complicated.
WinUsb is meant to be used by client applications for devices who load WinUsb.sys as their driver. However there doesn't seem to be a version of the WinUsb headers packaged for use... |
1,493,000 | 1,493,181 | What happens if I ReleaseMutex() twice? | The Microsoft documentation is silent about what happens if I mistakenly call ReleaseMutex() when the mutex is already unlocked.
Details:
I'm trying to fix up some Windows code without having access to the compiler.
I realise that WinApi mutexes are all recursive, and reference-counted. If I were making use of that fe... | peejay provided a good link in his comment to the ReleaseMutex documentation. I believe that this line from the documentation answers your question:
The ReleaseMutex function fails if the
calling thread does not own the mutex
object.
While it is not explicitly said, I think that releasing a mutex (the first time)... |
1,493,045 | 1,493,054 | How to initialize a static member | I want to initialize two static data members. See the two files
// Logger.h
class Logger
{
public:
static LoggerConcrete error;
static LoggerConcrete write;
};
and
//Logger.cpp
Logger::error = LoggerConcrete(LOG_DEBUG);
Logger::write = LoggerConcrete(LOG_DEBUG);
The initilization of the two s... | You need to specify the type:
LoggerConcrete Logger::error = LoggerConcrete(LOG_DEBUG);
LoggerConcrete Logger::write = LoggerConcrete(LOG_DEBUG);
|
1,493,450 | 1,559,535 | Adobe Dreamweaver Extensions | Does anyone know if its possible to turn off dreamweavers "custom icons" that it shows in the file browser so you can see the standard system-cache ones instead?
Something I'm trying to do via an extension but I cant find where its coming from in the large pile of XML files that is dreamweaver.
As the guy below pointed... | Its actually impossible via the extension interface; but is possible by editing the Dreamweaver library files.
Rubbish solution though and would never make it through adobe-exchange
|
1,493,524 | 1,493,592 | How to handle different protocol versions transparently in c++? | This is a generic C++ design question.
I'm writing an application that uses a client/server model. Right now I'm writing the server-side. Many clients already exist (some written by myself, others by third parties). The problem is that these existing clients all use different protocol versions (there have been 2-3 prot... | Since you need to dynamically choose which protocol to use, using different classes (rather than a template parameter) for selecting the protocol version seems like the right way to go. Essentially this is Strategy Pattern, though Visitor would also be a possibility if you wanted to get really elaborate.
Since these ar... |
1,493,540 | 2,200,911 | Troubleshooting Assembly Linker Error, C++, VS 2005 | Using Visual Studio 2005 with the latest Service Pack.
I have a managed C++ solution with 38 projects (that I've just inherited.) When I build this solution, I'm receiving the following error from the Assembly Linker:
"error AL1019: Metadata failure while creating assembly -- The process cannot access the file becau... | Finally tracked this down to the order of the XML Filter Collections in the Project file when using the external resource compiler (i.e. resgen.)
The failing project had, in its Proj file:
<files>
<Filter Name="Header Files" ...>
...
</Filter>
<Filter Name="Resource Files" ...>
...
</F... |
1,493,581 | 1,504,635 | How to go about benchmarking a software rasterizer | Ok, ive been developing a software rasterizer for some time now, but have no idea how to go about benchmarking it to see if its actually any good.... i mean say you can render X amount of verts ant Y frames per second, what would be a good way to analyse this data to see if its any good? rather than someone just saying... | What do you want to measure? I suggest fillrate and triangle rate. Basically fillrate is how many pixels your rasterizer can spit out each second, Triangle rate is how many triangles your rasterizer + affine transformation functions can push out each second, independent of the fillrate. Here's my suggestion for measuri... |
1,493,652 | 1,494,634 | display map every time it is updated sorted by value | basically, I have the
map<std::string, int>
so if i have
foo 5
bar 10
jack 3
in the map, I want to display it (notice the reverse order)
bar 10
foo 5
jack 3
And every time it is updated, I want iterate through all the elements, cout them, sorted by value. What is the good way to implement that? should I provi... | struct keyval_t { std::string key; int val; };
int operator<(const keyval_t &a, const ketval_t &b)
{ return a.val<b.val || (a.val==b.val && a.key<b.key); }
Then you need one map and one set:
map<std::string, int>; set<keyval_t>;
On update, you need to look up the map first to determine the key-value pair and then upd... |
1,493,904 | 1,493,925 | Can I increment a char* passed to a function? | I'm working on a C++ application that will build a fixed-length record from a set of database fields. I'm writing a function that will accept the output record as a char*, the string to write, and the total length of the field. The purpose of the function is to copy the string to the current position of the char pointe... | Since you are not passing your arguments by reference, the compiler creates a copy of the pointer and modifies the copy accordingly within the function.
Change your function signature to the following.
void writeOut(char*& output, string data, const int length)
You may also want to consider passing string as const str... |
1,493,933 | 1,494,002 | How to prevent a function from being optimized | I am optimizing the entire code, yet I dont want a certain function from being optimized, say for debugging purposes. Is there a way to do it on gcc 3.4+ compiler?
| Easiest way, place the function in its own compilation unit, compile that one without optimization flags.
Recent gcc versions (4.4+ I think) have an attribute to control optimization per functions, use
__attribute__((optimize(0)))
on the function to disable optimizations
|
1,494,010 | 1,494,926 | AV while iterating through hash_map? | _transaction is a private member variable of my class, declared as:
public:
typedef stdext::hash_map<wchar_t*, MyClass*, ltstr> transaction_hash_map;
private:
transaction_hash_map _transactions;
During cleanup I am trying to iterate through this list and free up any objects still unfreed. However I am getting... | One possible thing I can think of is that your class has already been deleted elsewhere before you try to iterate through the hash_map, and thus begin() will be operating on garbage. Worth a check...
Also - how are your wchar_t*'s getting allocated/freed? The code you've shown doesn't appear to be dealing with those. I... |
1,494,109 | 1,494,154 | Is it bad that C++0x's lambda expressions don't have a named type? | I've been reading a bit about lambda expressions on the internet recently and it seems to me that C++0x's lambda expressions will not have a single type (or types) that will bind exclusively to lambda expressions -- in other words, lambda expressions will only match template arguments or auto arguments/variables. What ... | Lambdas are independent types. The code
void h(lambda func)
{
func(2);
}
doesn't make any sense because lambdas don't have runtime polymorphism. Recall that a lambda is the equivalent of
struct unique_name
{
return_type operator()(Arg1 a1, Arg2 a2, ... , Argn an)
{
code_inside_lambda;
}
}
W... |
1,494,122 | 1,494,165 | Performance issues with hard disk reading | I have a C++ program which reads files from the hard disk and does some processing on the data in the files. I am using standard Win32 APIs to read the files. My problem is that this program is blazingly fast some times and then suddenly slows down to 1/6th of the previous speed. If I read the same files again and agai... | 1) Windows does cache recently read files in memory. The book Windows Internals includes an excellent description of how this works. Modern versions of Windows also use a technology called SuperFetch which will try to preemptively fetch disk contents into memory based on usage history and ReadyBoost which can cache t... |
1,494,164 | 1,494,479 | Memory corrupt in adding string to vector<string> loop | This is on Visual Studio 2008 on a dual-core, 32 bit Vista machine.
In the debug code this runs fine, but in Release mode this bombs:
void getFromDB(vector<string>& dates) {
...
sql::Resultset res = stmt->executeQuery("SELECT FROM ...");
while (res->next()) {
string date = res->getString("date");
... | imho, problem may arise from VS run time libraries.That means, DLL you use for sql connector methods are compiled not with "multi thread dll" code generation option.So different versions of strings are passed through parameters and they chrash.I think you should check this code generation flag.
|
1,494,182 | 1,495,582 | Setting the internal buffer used by a standard stream (pubsetbuf) | I'm writing a subroutine that needs to write data to an existing buffer, and I would like to use the stringstream class to facilitate the formatting of the data.
Initially, I used the following code to copy the contents of the stream into the buffer, but would like to avoid this solution as it copies too much data.
#in... | After some more research on this problem, and scrutiny of my code, I came across a post suggesting the use of a hand-coded std::streambuf class. The idea behind this code is to create a streambuf that initializes its internals to refer to the given buffer. The code is as follows.
#include <streambuf>
template <typen... |
1,494,231 | 1,494,267 | How to get a timestamp older than 1901 | I'm trying to find to accurately count the number of seconds since Jan 1, 1850 to the present in a couple of languages (JavaScript, C++, and Python [don't even ask, I stopped asking these questions long ago]).
Problem is the platforms store timestamps as 32-bit signed integers, so I can't get a timestamp for dates olde... | In python, there's the datetime module. Specifically, the date class will help.
from datetime import date
print date(1850, 1, 1).weekday() # 1, which is Tuesday
# (Mon is 0)
Edit
Or, to your specific problem, working with timedelta will help out.
from datetime import datetime
td = datetime.now() - datetime(1850, 1,... |
1,494,399 | 1,494,435 | How do I Search/Find and Replace in a standard string? | How do I replace all occurrences of a substring with another string, for std::strings?
std::string s ("One hello, two hellos.");
s = s.replace("hello", "world"); // something like this
| Why not implement your own replace?
void myReplace(std::string& str,
const std::string& oldStr,
const std::string& newStr)
{
std::string::size_type pos = 0u;
while((pos = str.find(oldStr, pos)) != std::string::npos){
str.replace(pos, oldStr.length(), newStr);
pos += newStr.le... |
1,494,407 | 1,494,530 | Undefined symbol _main when trying to build shared library g++ / mac | I am trying to build libdecodeqr on a mac. My c++ building and linking history is all on windows, so it's an exciting journey of discovery.
I have finally got to the point where I want to create the linked library. The command I am running is:
g++ -shared -o libdecodeqr.so.0.9.3 bitstream.o codedata.o container.o eci... | -shared is not supported on OSX. Use either -dynamiclib or -bundle (depending on which type of shared library you want to create).
|
1,494,423 | 1,494,767 | How To Prepare An ActiveX Control For Delivery Over The Web | So i have the misfortune of embedding this proprietary ActiveX control we created into a web page so that it downloads the code from our server and installs as necessary.
Our ActiveX requires a host of other files which need to be installed along with the activex control itself. It should also be noted that the acti... | You can create a dependency between the installer and a dll that is on the system like this:
[Add.Code]
Your-dll-name
[Your-dll-name]
Version=Your dll version
hook=setup.exe
[Setup.exe]
file-win32-x86=thiscab
run=%EXTRACT_DIR%\Setup.exe
If the system cannot find your dll or the version is lower, then ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.