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,469,815
1,576,600
Trying to make SDL widget in QT4 using SDL_WINDOWID, but can't get widget to show
I'm trying to create an SDL drawing canvas inside of a simple QT4 window, following the information provided in the SDL wiki and in another question on this site. The project is an NES emulator using QT and SDL that a friend and I decided we wanted to try creating. Currently, I have a main_window class that will conta...
I guess you already know, but the SDL_WINDOWID trick probably isn't portable - I am pretty sure it won't work on Mac. I am curious what you want SDL for, in this scenario - if you simply want a pixel-addressable image buffer (or several), use QPixmap / QImage and stick to pure Qt. Or if you want the SDL sprite features...
1,469,947
1,470,026
How to use cross platform C++ with a WPF C# GUI
I'm currently in a project that need to work both on Mac and Windows. We are using standard portable C++ for all the application logic. However, since we want the app to feel totally native on both platform, the GUI will be written with C#/WPF for Windows and Objective-C/Cocoa for Mac. However, for the windows part, I ...
C++/CLI has several restrictions over standard C++ that don't always make it easy to recompile standard C++ as C++/CLI. Keep in mind that you'll have to distinguish 'managed' and 'unmanaged' pointers, for starters. As these are using different symbols, you've got your first set of #ifdefs right there. And then you get ...
1,470,009
1,470,113
How do you call a managed (C#) function from C++?
I have a C# DLL file project (my_cs_dll.dll) which defines a static class with a static member function. namespace Foo { public static class Bar { public static double GetNumber() { return 1.0; } } } I also have a C++ DLL project which is using /clr. #using <my_cs_dll.dll> double get_number_from_c...
It sounds like your C# assembly is not being resolved at runtime. Is your C# dll in the same directory as (or a subdirectory of) your executable? It's been a while since I did this, but my recollection is that unless your assembly is installed in the GAC, it must be in the directory (or a subdirectory) where your exe...
1,470,171
1,753,191
Controlling mouse in linux
Basically I'm currently using the wiiuse library to get the wiimote working on linux. I want to now be able to control the mouse through the IR readings. Can somebody point me in the right direction as to how to approach this? I know of uinput but there doesn't seem to be a lot of tutorials/guides on the web. I'm worki...
In the end I decided to just draw "cursor" objects on the screen and use setup each input device to control a separate "cursor" object. This seemed the best idea as we were short on time.
1,470,217
1,470,306
Usage of D in the Field
I have tried to find some information on D. I do especially like this comparison with C++ to get an overview on what it is. Now I am asking myself: how often D is used in the field, and how much of a viable alternative is it to C++?
I think D is a great language, but what people might hold back from using it is that it is (afaik) not compatible with c++ libraries. So all libraries you can use have to be written in C or D. So if you are a C++ developer switching to D isn't so much fun.
1,470,528
1,470,576
Whereto put "plugins" in linux
I am currently developing/hacking an image analyzing/transforming tool. The filters therein will be loaded at runtime using dlopen&co. My question is where do *nix tools usually put plugins (*.so files) when installed? bin/program lib/program/plugins/thisandthat.so maybe? Secondly how do I use it and where do I put it...
The layout seems sensible. You can, for instance, look in current directory, look up environment variable or command line switch during development. It depends on the details of your development environment and workflow.
1,470,530
1,470,690
Does c/c++ have a delay function?
Does c/c++ have a delay/wait/sleep function?
C++ does not have a sleep function. But most platforms do. On Linux you have sleep() and usleep(). On Windows you have Sleep(). You just have to include the appropriate headers to get access to them.
1,470,605
1,470,693
abstract an Interface `ISingleton` to be base class
I have 3 interface classes IVideo , IAudio , IGPIO and three other classes that will implement those interface: Video_impl , Audio_impl , GPIO_impl. Things is simple so far. But then ,I want all those object to be singleton. Here are the questions: Is it a good idea to abstract an Interface ISingleton , so that Video_i...
I would recommend reading Alexandrescu's "Modern C++ Design". In it, among many other things, he designs a fully-fledged singleton template and thinks through many of the issues, such as when it should be destroyed, whether it should resurrect after being destroyed because it is needed during the destruction of other ...
1,470,654
1,470,728
Define a symbol in another namespace
Here is my problem: in a header I define a structure template type_to_string, which aims at defining a string corresponding to a given type argument: namespace foo { template <typename T> struct type_to_string { static const char * value; }; } template <typename T> const char * foo::type_to_st...
According to C++ Standard 14.7.3/2: An explicit specialization shall be declared in the namespace of which the template is a member, or, for member templates, in the namespace of which the enclosing class or enclosing class template is a member. An explicit specialization of a member function, member class or stat...
1,470,716
1,470,740
How do I abort a MATLAB m-file function from C/C++?
I deployed a MATLAB project into a DLL, to be called from C++, and it works just fine. Happy days. But what happens when the user asks to cancel an operation? I tried creating a global variable named UserAborted. I initialize it to 0 before running the long function in MATLAB. I also wrote the following two functions: ...
Matlab needs to provide callback functions to show execution progress and possibly halt it. A Google search shows lots of people wanting this but no implementation from Mathworks.
1,470,741
1,470,959
Intel Inspector reports a data race in my spinlock implementation
I made a very simple spinlock using the Interlocked functions in Windows and tested it on a dual-core CPU (two threads that increment a variable); The program seems to work OK (it gives the same result every time, which is not the case when no synchronization is used), but Intel Parallel Inspector says that there is a...
Parallel Inspector's documentation for data race suggests using a critical section or a mutex to fix races on Windows. There's nothing in it which suggests that Parallel Inspector knows how to recognise any other locking mechanism you might invent. Tools for analysis of novel locking mechanisms tend to be static tools...
1,471,104
1,471,113
Does malloc/new return memory blocks from Cache or RAM?
I wanted to know whether malloc/new returns memory blocks from Cache or RAM. Thanks in advance.
You are abstracted of all that when living as a process in the OS, you only get memory. You shouldn't worry ever about that, the OS will manage all that for you and the memory unit will move things from one to another. But you still see a single virtual memory layout.
1,471,109
1,599,437
C/C++ Libraries for reading from Universal Disk Format devices or files
Are there any good free C/C++ libraries that enable reading from common devices with filesystems such as UDF, and ISO9660 and extracting files/metadata etc.? So far all I've been able to find is GNUs libcdio which is promising, and some "Magic UDF" which has so many hits I'm disgusted, pushes other results in Google, a...
After extensive investigation, I ended up rolling my own solution to perform the operations on UDF that I required. I'm unable to open the source, in all it was about 800 lines of C++. However here are several links which got me through: The reference standard on which UDF is built Universal Disk Format specification ...
1,471,219
1,471,231
How to write a launching program in C++ or C# for Windows Vista
How do I write a program in C++ or C# that launches applications on Windows Vista? For example launching Dreamweaver CS 4 ("C:\Program Files\Adobe\Adobe Dreamweaver CS4\Dreamweaver.exe) and place it on top with the BringWindowToTop-function?
In c# Process.Start("c:\whatever\somefile.exe", <commandline args>); should do it
1,471,222
1,471,233
Storage of variables in memory
If I have a list of global variables like this... int a; char b; float c[10]; double d[3]; and I have an identical sequence of variables listed inside a class... class test_type { int a; char b; float c[10]; double d[3]; } is it guaranteed that the arrangement of all the variables in memory are identi...
No. I don't think the C++ standard guarantees anything about the memory layout of global variables.
1,471,333
1,471,406
casting a pointer in Run Time [non-trivial Scnerio]
I have to fix a typical memory leak, Problem is like that : typedef std::map<unsigned long,Response> mapType; class Response { public: void *dataPtr; unsigned long tag; } class anyClass { public:: DataType x; } From client i am getting a map of Type mapType , Which has Response object as map->second , As Respon...
Given that you mention "legacy" code, but may have some freedom to modify, I would likely suggest that whatever interface provided you the map be extended to include a free-ing function. Then it could apply the same type logic as when it created the object in the first place. If that is impossible, then you will likely...
1,471,353
1,471,378
What's the C++ equivalent of UINT32_MAX?
In C99, I include stdint.h and that gives me UINT32_MAX as well as uint32_t data type. However, in C++ the UINT32_MAX gets defined out. I can define __STDC_LIMIT_MACROS before including stdint.h, but this does not work if someone is including my header after already including stdint.h themselves. So in C++, what is th...
Not sure about uint32_t, but for fundamental types (bool, char, signed char, unsigned char, wchar_t, short, unsigned short, int, unsigned int, long, unsigned long, float, double and long double) you can use the numeric_limits templates via #include <limits>. cout << "Minimum value for int: " << numeric_limits<int>::min...
1,471,370
1,471,671
Normalizing from [0.5 - 1] to [0 - 1]
I'm kind of stuck here, I guess it's a bit of a brain teaser. If I have numbers in the range between 0.5 to 1 how can I normalize it to be between 0 to 1? Thanks for any help, maybe I'm just a bit slow since I've been working for the past 24 hours straight O_O
Others have provided you the formula, but not the work. Here's how you approach a problem like this. You might find this far more valuable than just knowning the answer. To map [0.5, 1] to [0, 1] we will seek a linear map of the form x -> ax + b. We will require that endpoints are mapped to endpoints and that order is ...
1,471,644
1,472,210
Dllimport can't import an old Borland dll
I have a lot of legacy code which I currently compile using an antiquated install of Borland C++ 3.0. There's a rules engine in this code that I'd like to extract and use in a C# .NET application. The thing is, if I extract the rules engine into it's own DLL, I want to be able to call this DLL from both the existing le...
As far as I know, DllImport will only work for unmanaged dlls that are the same word size as the .Net app. E.g. DllImport in a 64-bit .Net app will only work on 64-bit dlls, a 32-bit .Net app can only load 32-bit dlls, etc. I also don't think it's possible to get DllImport to load a 16-bit dll. Some possible solution...
1,471,721
1,471,765
Using dynamic multi-dimensional arrays in c++
I am making a C++ program that checks if given aray is a latin square. I need to use a dynamic multi-dimensional array that stores given latin square. But I cant pass the array to a function that does the checking... Currently I have such code for calling the function: int squaretest(int **p, int n, int sum) { //s...
To be able to do that.. You actually need to do this: int **lsquare = new int*[n]; for (int i=0; i<n; ++i) lquare[i] = new int[n]; for (int i=0; i<n; i++) for (int j=0; j<n; j++) cin >> lsquare[i][j]; blocktest(lsquare,n,sum); The better system would be to do: int *lsquare = new int[n*n]; for (int ...
1,471,800
1,471,828
Getting rid of error C2243
Is it possible to getting rid of error C2243? class B {}; class D : protected B {}; D d; B *p = &d; // conversion from 'D *' to 'B &' exists, but is inaccessible I had this error in my app and at the end I've managed to compile it by making an explicit conversion: D d; B *p = (B*)&d; I can't understand why by maki...
If you want to allow conversion, you should be using public inheritance. Using protected or private inheritance, you are declaring that the fact that the derived type inherits from the base class is a detail that should not be visible from the outside: that's why you are getting that error. You should regard non-publ...
1,471,816
1,489,049
Finding type of break in icu::BreakIterator
I'm trying to understang how to use icu::BreakIterator to find specific words. For example I have following sentence: To be or not to be? That is the question... Word instance of break iterator would put breaks there: |To| |be| |or| |not| |to| |be|?| |That| |is| |the| |question|.|.|.| Now, not every pair of break p...
Have you tried the ICU documentation? It appears to explain everything you are asking about including handling of internationalisation, reverse iteration, and the rules, both default and how to create your own custom set. They also have code snippets to help.
1,472,048
1,472,075
How to append a char to a std::string?
The following fails with the error prog.cpp:5:13: error: invalid conversion from ‘char’ to ‘const char*’ int main() { char d = 'd'; std::string y("Hello worl"); y.append(d); // Line 5 - this fails std::cout << y; return 0; } I also tried, the following, which compiles but behaves randomly at runtime: int mai...
y += d; I would use += operator instead of named functions.
1,472,123
1,472,579
Qt signals and slots, threads, app.exec(), and related queries
[related to this question] I wrote this piece of code to understand how qt signals and slots work. I need someone to explain the behaviour, and to tell me if I'm right about my own conclusions. My program: connectionhandler.h #ifndef CONNECTIONHANDLER_H #define CONNECTIONHANDLER_H #include <QTcpServer> class Connectio...
If you don't call app.exec() then the program hits the end of your main() and ends. (Why? There's no more code to execute!) app.exec() is an infinite loop of the following style: do { get event from system handle event } while (true); If you use a queued connection, then the event is added to your event queue, a...
1,472,330
1,472,402
Encapsulated boost thread_group. Questions about ids and synchronization
I´m using a class that encapsulates a thread_group, and have some questions about it class MyGroup{ private: boost::this_thread::id _id; boost::thread::thread_group group; int abc; //other attributes public: void foo(); }; In the class constructor, i launch N threads for (size_t i=0;i<N;i+...
Yes, shared data access must be protected even if you use thread creation helpers as boost. In the end they all will execute the same code at the same time, and there is nothing a library can do to put protection around a variable you own and you manage. If this->_id prints the current thread id then yes, it will print...
1,473,107
1,473,252
most effective row removal strategy for QStandardItemModel
I have a QStandardItemModel with several 100,000 records of data, and a QSortFilterProxyModel on top of it for filtering and sorting capabilities. I want to remove a substantial number of records, say 100,000, based on the value of one of the columns. The current implementation iterates over the source model, tests for...
QAbstractItemModel::removeRows() is a candidate, provided that the rows are contiguous. If the model is sorted by the column you are using to do the removal test, then you should be able to use this.
1,473,183
1,473,232
What is the best way to find wide string headaches such as L"%s"?
Here is an example of one of the headaches I mean: We have a multiplatform project that uses mostly Unicode strings for rendering text to the screen. On windows in VC++ the line: swprintf(swWideDest, LEN, L"%s is a wide string", swSomeWideString); compiles fine and prints the wide string into the other wide string. H...
As none of the functions of *printf family are typesafe you either search for probable errors via regular expressions and fix them manually use another approach that is typesafe, maybe based on stringstreams or boost.format
1,473,353
1,473,389
Debugging C++ template class in VS 2008
I'm learning C++ and using VS C++ 2008 Express. I have a simple project with 2 code files. One is for my Class and the other is "_tmain()". My class file is using: template <typename T> code. The program seems to run fine, but I can't step into my class file code in c++ view. I have to look at the assembly code. I can...
Maybe you just forgot to active debug information (happens if you create an empty project). This can (at least in VS2005) be activated via the Projects Properties -> Configuration Properties -> Linker -> Generate Debug Info.
1,473,487
1,473,833
Debugging MMC (Unmanaged c++)?
I work on a legacy MMC application and one thing I have noticed is that once in awhile when closing the MMC, an error will be reported. "MMC has detected an error in a snap-in. It is recommended that you shut down and restart MMC". How can I debug this? The error is not displayd until you close the console and if you t...
Why not run the MMC under debugger? Clearly there is something wrong (Unhandled exception probably) with the shutdown code of the snapin. Just run mmc.exe under your favorite debugger and tell the debugger to stop on all exception. attach your snapin exit and wait for the crash. You can try to run ProcDump which can...
1,473,520
1,473,775
how to call a C# dll from unmanaged c++ using IDispatch?
I have a C# dll that I need to call from unmanaged C++. The main problem that I have is that my c++ code corresponds to an excel add-in, that can be installed for excel 2003 and excel 2007, when I install my add-in in excel 2007, and I try to call my C# dll, it works just fine, but for some reason that I still haven't ...
I've had a similar problem before. I wasn't calling C# from C++, but the concept is the same. I had to load a .NET dll into a host application via COM, which looks like what you are trying to do. The problem was the host application (in your case excel) was loading the .NET runtime 1.1. Our dll was compiled for .NE...
1,473,921
1,473,980
optimizing branching by re-ordering
I have this sort of C function -- that is being called a zillion times: void foo () { if (/*condition*/) { } else if(/*another_condition*/) { } else if (/*another_condition_2*/) { } /*And so on, I have 4 of them, but we can generalize it*/ else { } } I ha...
It's not portable, but many versions of GCC support a function called __builtin_expect() that can be used to tell the compiler what we expect a value to be: if(__builtin_expect(condition, 0)) { // We expect condition to be false (0), so we're less likely to get here } else { // We expect to get here more often, so ...
1,473,977
1,473,987
Hanging else problem?
What is the "hanging else" problem? (Is that the right name?) Following a C++ coding standard (forgot which one) I always use brackets (block) with control structures. So I don't normally have this problem (to which "if" does the last(?) else belong), but for understanding possible problems in foreign code it would be ...
Which if does the else belong to? if (a < b) if (c < d) a = b + d; else b = a + c; (Obviously you should ignore the indentation.) That's the "hanging else problem". C/C++ gets rid of the ambiguity by having a rule that says you can't have an-if-without-an-else as the if-body of an-if-with-an-el...
1,473,983
1,474,510
Is there a way to figure out the top callers of a C function?
Say I have function that is called a LOT from many different places. So I would like to find out who calls this functions the most. For example, top 5 callers or who ever calls this function more than N times. I am using AS3 Linux, gcc 3.4. For now I just put a breakpoint and then stop there after every 300 times, th...
I wrote call logging example just for fun. A macro change the function call with an instrumented one. include <stdio.h>. int funcA( int a, int b ){ return a+b; } // instrumentation void call_log(const char*file,const char*function,const int line,const char*args){ printf("file:%s line: %i function: %s args: %s\n",...
1,474,416
1,474,421
C++ Passing a class as a parameter
I'm wondering if it's possible to pass a class as a parameter in c++. Not passing a Class Object, but the class itself which would allow me to use this class like this. void MyFunction(ClassParam mClass) { mClass *tmp = new mClass(); } The above is not real code, but it hopefully explains what I'm trying to do in ...
You can use templates to accomplish something similar (but not exactly that): template<class T> void MyFunction() { T *tmp = new T(); } and call it with MyFunction<MyClassName>(). Note that this way, you can't use a "variable" in place of T. It should be known at compile time.
1,474,417
1,474,448
Typedef a template class without specifying the template parameters
I'm trying to typedef either an unordered_map or std::map depending whether there are TR1 libraries available. But I don't want to specify the template parameters. From what i've read so far, typedef'ing templates without arguments is not possible until official c++0x standard is available. So does anyone know an elega...
The way I've seen this done is to wrap the typedef in a template-struct: template<typename KeyType, typename MappedType> struct myMap { #ifdef _TR1 typedef std::tr1::unordered_map<KeyType, MappedType> type; #else typedef std::map<KeyType, MappedType> type; #endif }; Then in your code you invoke it like so: myM...
1,474,790
1,474,819
How to read-write into/from text file with comma separated values
How do I read data from a file if my file is like this with comma separated values 1, 2, 3, 4, 5\n 6, 7, 8, 9, 10\n \n and after reading the file, I want to write the data back into other file as same format above. I can get total number of lines, using string line; while(!file.eof()){ getline(file,line); ...
Step 1: Don't do this: while(!file.eof()) { getline(file,line); numlines++; } numline--; The EOF is not true until you try and read past it. The standard pattern is: while(getline(file,line)) { ++numline; } Also note that std::getline() can optionally take a third parameter. This is the character to bre...
1,474,894
1,474,953
Why isn't the [] operator const for STL maps?
Contrived example, for the sake of the question: void MyClass::MyFunction( int x ) const { std::cout << m_map[x] << std::endl } This won't compile, since the [] operator is non-const. This is unfortunate, since the [] syntax looks very clean. Instead, I have to do something like this: void MyClass::MyFunction( in...
For std::map and std::unordered_map, operator[] will insert the index value into the container if it didn't previously exist. It's a little unintuitive, but that's the way it is. Since it must be allowed to fail and insert a default value, the operator can't be used on a const instance of the container. http://en.cppr...
1,474,990
2,213,169
How do you use a variable stored in a boost spirit closure as input to a boost spirit loop parser?
I would like to use a parsed value as the input to a loop parser. The grammar defines a header that specifies the (variable) size of the following string. For example, say the following string is the input to some parser. 12\r\nTest Payload The parser should extract the 12, convert it to an unsigned int and then re...
This is much easier with the new qi parser available in Spirit 2. The following code snippet provides a full example that mostly works. An unexpected character is being inserted into the final result. #include <iostream> #include <string> #include <boost/version.hpp> #include <boost/spirit/include/qi.hpp> #include <bo...
1,475,016
1,475,038
How do I automatically clean up code in C++?
I'm working as a TA in an introductory programming class, and the students tend to submit their programs as either one line, or without any indentation. Is there any tool that allows me to insert indents and things like that automatically? (We're using C++ and VisualStudio)
Select the entire file (Ctrl-A) and then hit Ctrl-K Ctrl-F, which is essentially format the entire document. EDIT: Of course in Visual Studio IDE
1,475,021
1,475,045
Normal looking button with c++ / win32
I'm trying to make a button but it always looks like windows 95 flat button. How do I make it look vista style? hWndEdit = CreateWindowA("button", "Test", WS_CHILD | WS_VISIBLE | BS_DEFPUSHBUTTON, 100, 20, 140, 20, hWnd, NULL, NULL, NULL); Where ami I going wrong? Thanks
It can only look Vista style in Vista, mind you. Your application must also embed a manifest as per http://msdn.microsoft.com/en-us/library/aa289524(v=VS.71).aspx to enable visual styles.
1,475,415
1,490,594
Having trouble building c++ project in Eclipse CDT in OS X for a silly reason
I'm trying to build a very simple c++ program in eclipse and I'm getting a very silly error: **** Internal Builder is used for build **** g++ -O0 -g3 -Wall -c -fmessage-length=0 -oMyFirst.o ../MyFirst.cpp g++ -oLinkedLists MyFirst.o ld: unknown option: -oLinkedLists collect2: ld returned 1 exit status Bu...
Mark actually pointed me in the right direction but what I had to do to make it work was to go to: Project >> Properties >> C/C++ Build >> Tool Chain Editor I then changed the "Current toolchanin" select box to "MacOSX gcc" and that fixed it :)
1,475,662
1,475,726
How to get Process in windows mobile
i want to get the running process in .net compact framework windows mobile.. i want to kill the running process.. but i know process.GetProcessesByName() function is present in desktop, but for mobile its not supported i think so.. please let me know how to kill the presently running process in c# windows mobile. Than...
Hey i found answer here it is Process.GetCurrentProcess().Kill(); .net CF is crazy :-)
1,475,782
1,477,583
Qt4.5: Implicitly shared QImage: are methods like .bits() always copying (documentation unclarity)
I am writing a Qt application that has to handle big QImage s. QImage uses implicit sharing, which means it reference counts an internal data pointer. Whenever the refcount is > 1 the object counts as "shared" and any even only potentially data modifying call issues a deep copy of the image data. In short: I don't wan...
Operations that could modify the shared instance will detach. setPixel detaches. Try QImage::isDetached() which does a return d && d->ref == 1;. By using a debugger, you can get to the actual refcount. Other than passing by reference/shared pointer no.
1,475,940
1,475,967
Qt library MainWindow destructor
Im new to the Qt library and i was going through the demonstrations. I came across this class without a destructor.... this is the cpp file https://docs.huihoo.com/qt/4.5/demos-mainwindow-mainwindow-cpp.html and here is the .h file https://docs.huihoo.com/qt/4.5/demos-mainwindow-mainwindow-h.html the constructor uses t...
Yes you are. Qt provides parent-child relationship. When a QObject is deleted, it deletes all of its children automatically. In the line below, a QTextEdit is created with this pointer as its parent. center = new QTextEdit(this); So, when the parent (MainWindow) is deleted, center is automatically deleted too. Take ...
1,475,992
1,476,004
C++ thinks '<<' is not a member of class, but it is
I have to write a simple log class, that would write the output to a file. I want it to work with overloading the << operator, so I can do this: MyLog log("C:\\log.txt"); log<<"Message"; But Visual C++ tells me: "error C2039: '<<' : is not a member of 'MyLog' " I don't know what I am doing wrong. Here is the code: MyL...
You have declared the free function MyLog& operator<<(MyLog& l,char* msg) to be a friend of the MyLog class. It is not a member of the class itself, so your definition of the function should start with this: MyLog& operator<<(MyLog& l,char* msg) { //...
1,476,794
1,477,158
Cocoa counterpart to Windows' SetTimer
Is there any equivalent function on OS X to SetTimer in Windows? I'm using C++. So I'm writing a plugin for some software, and I need to have a function called periodically. On Windows I just pass the address of the function to SetTimer() and it will be called at a given interval. Is there an easy way to do this on OS ...
Consider using the Boost Asio library. The class deadline_timer works on all platforms. Just use bind to attach a function to async_wait and call expires_from_now. io_service io; deadline_timer timer(io); void handler() { static int second_counter = 0; cout << second_counter++ << endl; timer.expires_fro...
1,477,072
1,477,134
Behavior of C++ after destruction
I have an object that reads from a socket continuously like below: void CSocketReader::ReadComplete ( ) { messageProcessor->ResponseReceived ( response ); read (); } void CSocketReader::read() { socket.read(response); } My problem is, depending on the response and on the protocol that I am executing the ResponseRe...
How can I reliably detect that the method that's been executing on an object has been deleted. You can't set a 'bool amDeleted' flag inside the object itself (because after it's deleted that flag/memory may be reused/overwritten by something else). The only reliable way to do it (that I can think of) would be like th...
1,477,145
1,477,177
Reducing code duplication between operator= and the copy constructor
I have a class that requires a non-default copy constructor and assignment operator (it contains lists of pointers). Is there any general way to reduce the code duplication between the copy constructor and the assignment operator?
There's no "general way" for writing custom copy constructors and assignment operators that works in all cases. But there's an idiom called "copy-&-swap": class myclass { ... public: myclass(myclass const&); void swap(myclass & with); myclass& operator=(myclass copy) { this->swap(copy); ...
1,477,197
1,477,543
How to change an object's interface based on its state?
Given a fairly complex object with lots of state, is there a pattern for exposing different functionality depending on that state? For a concrete example, imagine a Printer object. Initially, the object's interface lets you query the printer's capabilities, change settings like paper orientation, and start a print job...
How do you expose the interface of an object without surrendering control of that object's lifetime? If I give the caller a pointer to a Page Just to address this point in particular, aside from the rest of the question. You seem to be talking about an API that looks a bit like this: Page *Printer::newPage(); I would ...
1,477,199
1,481,426
transparent icons on toolbar draw ugly borders
I'm trying to set transparent icons in a QAction, which is then added to a Menu and a toolbar. I'm styling the application with a style sheet. The icon transparency works, but the icons are being drawn on the toolbar with what looks like a 1px black border on the left and top edges of the icons. Now, all my icons are ...
First of all, I think you're doing things in an unnecessarily complicated way by having them all in one image. However... What version of Qt are you running? On what platform? At one point about 6-12 months ago (I think), I encountered a bug with drawing one transparent image on top of another transparent image as ...
1,477,239
1,477,283
LPTHREAD_START_ROUTINE / array of classes
I wrote some test code like this which compiled and worked fine... void threadtest() { HANDLE hThrd; DWORD threadId; int i; for (i = 0;i < 5;i++) { hThrd = CreateThread( NULL, 0, ThreadFunc, (LPVOID)i, 0, &threadId ); } // more stuff } DWORD WINAPI ThreadFunc(LPVO...
The following explains the difference between a pointer to a function and a pointer to a member function C++ FAQ Lite. See section 33.2 which explains why what you are doing is a bad idea.
1,477,602
1,477,703
C++ Circular declaration
I have a couple of cases of circular declaration in my class delaractions in my main (global) header. #include <cstdlib> #include <iostream> using namespace std; enum piece_t {BLACK, WHITE, EMPTY, WALL}; //wall is area out side of board (board array is 21x21 but only 19x19 is playable) enum dir_t {ABOVE,BELOW,LEFT, ...
The forward references in your code seems to be to board_t and point_t, which is resolved by forward declaring them. Since you reference board_t in member function declarations of point_t, you cannot define the member functions right away in point_t. Their definitions have to appear after board_t is defined. So you ha...
1,478,003
1,478,049
How to detect whether a monitor is widescreen in Windows
I need a way to programatically detect whether the monitor is wide or not, in Windows. GetSystemMetrics returns the size of the desktop, which sort of works, but if an user has a widescreen monitor at, say, 1024x768, I'll incorrectly classify it as non-wide. GetDeviceCaps has similar problems with HORZRES and VERTRES, ...
You might be able to get the actual physical size through EDID. See here: How to obtain the correct physical size of the monitor?
1,478,092
1,478,119
C++ pragma GCC system_header directive
What this C++ directive do: "#pragma GCC system_header"?
I googled and got this: #pragma GCC system_header This pragma takes no arguments. It causes the rest of the code in the current file to be treated as if it came from a system header. Section 2.7 System Headers. More info on System headers 2.7. System Headers The header files declaring interfaces to the operating ...
1,478,330
1,478,344
C++ STL map with a custom class as second type
I'd like to create a map with an int and my own custom class. Is there a way to do this? map<int, MyClass> myMap; If not, how do I go about accomplishing this? Basically, I want an id(or preferably an enum) to point to my own custom class. In most other languages, this would be a simple hash.
#include <map> std::map<int, MyClass> myMap; MyClass foo; myMap[5] = foo; myMap[5].bar = 10; You do need MyClass to be default- and copy- constructible, so it can be created (if you use, e.g., myMap[5]) and copied into the map.
1,478,355
1,478,377
Programmatically block screen saver in Mac OSX
Is it possible to programatically ask Mac OS X not to turn on the screen saver while your application is active?
You want to use: UpdateSystemActivity(UsrActivity); Here is Apple's example code. Be aware this is deprecated for 64bit binaries, and I have not found a suitable replacement, but the struggle continues.
1,478,734
1,479,089
Matrix Circular Shift
Does anyone know an efficient way to right circular-shift a matrix? Btw, the matrix is binary but a method to solve a non-binary matrix is also fine. Right now, I'm thinking of implementing a circular array for the rows of my matrix and updating each row whenever a shift operation is required. Another method, I was con...
Something like this perhaps, class matrix { std::vector<bool> elements; int rows, cols, row_ofs, col_ofs; std::size_t index(int r, int c) { r = (r + row_ofs) % rows; c = (c + col_ofs) % cols; return std::size_t(r)*cols + c; // row major layout } public: matrix() : rows(0), c...
1,479,100
1,479,106
How is if statement evaluated in c++?
Is if ( c ) the same as if ( c == 0 ) in C++?
No, if (c) is the same as if (c != 0). And if (!c) is the same as if (c == 0).
1,479,117
1,479,145
how to overload > operator for a queue
i have a priority queue and i have defined like this: priority_queue<Node*,vector<Node*>,greater<Node*>> myQueue; i have to add to queue on the basis of a parameter param and i have overloaded it like this bool Node::operator>(const Node& right) const { return param>right.param; } since the overload function ...
You need to write your own functor for the comparison because you can't overload operator> for pointers. So, instead of greater you would be using your own dedicated class with the appropriate function call operator. This could be even done generically. template<typename T, typename Cmp = std::less<T> > struct deref_co...
1,479,161
1,479,189
VC++ CLI application 32 - 64 bit CString question
SO, I am in the process of resolving the port of a 32bit app to 64 bit. When I compile for x64 I see a warning come up for the line ` CString sig; sig = "something"; sig = sig.left(strlen(something defined)); <<<<<< ` So, I get the warning for the sig.left where it implicitly converts the strlen value to int. Since i...
strlen always returns size_t. However, size_t is a different width on 64bit and 32bit operating systems. CString.left, however, expects an int. Your code should be fine (provided your strings won't be too long to overrun an int value), but the compiler will warn you that you're causing this problem. You can ignore th...
1,479,291
1,479,300
Calculating the value of pi-what is wrong with my code
I'm doing another C++ exercise. I have to calculate the value of pi from the infinite series: pi=4 - 4/3 + 4/5 – 4/7 + 4/9 -4/11+ . . . The program has to print the approximate value of pi after each of the first 1,000 terms of this series. Here is my code: #include <iostream> using namespace std; int main() { dou...
Well, i % 1000 will never = 0, as your counter runs from i = 1, then in increments of 2. Hence, i is always odd, and will never be a multiple of 1000. The reason it never terminates is that the algorithm doesn't converge to exactly 3.14157 - it'll be a higher precision either under or over approximation. You want to sa...
1,479,419
1,482,280
how to fix the error c2118: negative subscript
Again, porting 32-bit app to 64-bit. I get the negative subscript error on the C_ASSERT statement mentioned below.. C_ASSERT (sizeof(somestruct) == some#define); I also read the http://support.microsoft.com/kb/68475 article but not sure if I know how to fix it in this case. Help is appreciated. Thanks in advance.
I'm guessing the C_ASSERT macro is defined something like this: #define C_ASSERT(x) typedef char C_ASSERT_ ## __COUNTER__ [(x) ? 1 : -1]; This is a compile-time assertion: if the compile-time expression x is true, then this expands to something like typedef char C_ASSERT_1[1]; which declares the typename C_ASSERT_1 t...
1,479,498
1,479,525
How to subclass a templated base class?
I have the following data structures: struct fastEngine { ... } struct slowEngine { ... } template<typename T> class Car { T engine; vector<T> backupEngines; virtual void drive() = 0; } class FastCar : public Car<fastEngine> { virtual void drive() { // use the values of "engine" in some way } } ...
You could create a non-templated base class that Car<T> inherits, e.g. struct ICar { virtual void drive() = 0; }; template <typename T> class Car : public ICar { // ... } int main() { // BTW, it's always `int main`, not `void main` ICar *myCar = getCarFromCarFactory(); myCar->drive(); }
1,479,886
1,479,973
I want to show off my C++ projects through a website
The problem is that, well, it's C++. The way I've created them makes it such that they've always been run via a terminal/console window and wait for user input or else simply take a sample input and run with that. The output has also always been to the terminal screen or sometimes to a file. I'm not quite sure how I...
The easiest interaction model to bring to the web is an application that takes its input up front and produces its output on stdout. In this situation, as the unknown poster mentioned, you could use CGI. But due to the nature of CGI, this will only work (in the simplest sense) if all the information is collected from...
1,479,888
1,479,977
Call C++ class member function from C (Visual Studio)
I need to call a C++ member function from a C program. I created .cpp/.h wrapper files in the C code, wrapping the C++ member functions. i.e.- wrapper.cpp #include "wrapper.h" extern "C" { void wrap_member1() { Class::member1(); } void wrap_member2() { Class::member2(); } } and wrapper.h: #inc...
There are two issues: One, you are including a C++ header file in a C header file. This means the C compiler gets C++ code. This is what causes the error you are experiencing. As Reed Copsey suggests, put the #include in the C++ source file instead of the C header file. Two, you are using extern "C" in the C header ...
1,479,945
1,484,628
Setting thread priority in Linux with Boost
The Boost Libraries don't seem to have a device for setting a thread's priority. Would this be the best code to use on Linux or is there a better method? boost::thread myThread( MyFunction() ); struct sched_param param; param.sched_priority = 90; pthread_attr_setschedparam( myThread.native_handle(), SCHED_RR, &param);...
That's the basic template for how I would do it but after searching around I found next to no code examples so I guess the verdict is out on whether it is best or not. The problem is that boost::thread does not have a constructor that allows pthead attributes to be passed in at thread creation so you have to make chang...
1,479,953
1,479,993
Porting 32 bit C++ code to 64 bit - is it worth it? Why?
I am aware of some the obvious gains of the x64 architecture (higher addressable RAM addresses, etc)... but: What if my program has no real need to run in native 64 bit mode. Should I port it anyway? Are there any foreseeable deadlines for ending 32 bit support? Would my application run faster / better / more secure a...
x86-64 is a bit of a special case - for many architectures (eg. SPARC), compiling an application for 64 bit mode doesn't give it any benefit unless it can profitably use more than 4GB of memory. All it does is increase the size of the binary, which can actually make the code slower if it impacts on cache behaviour. Ho...
1,479,987
1,480,037
Linux runtime linker error
I'm working though the First Steps tutorial on the POCO Project site, and I've successfully built the library (Debian Linux, 2.6.26, gcc 4.3.2) under my home directory ~/Development/POCO with the shared libraries located in ~/Development/POCO/lib/Linux/x86_64/lib My problem is that any application I build that depends...
If you don't want to have to deal with the LD_LIBRARY_PATH variable, you can add the linker -rpath option to the gcc command line. In your case, this would be: gcc ... -Wl,-rpath=/home/npalko/Development/POCO/lib/Linux/x86_64 This effectively hardcodes that path in the executable, so it may or may not be suitable for ...
1,480,085
1,480,093
What's going on with overriding and overloading here in C++?
This doesn't work: class Foo { public: virtual int A(int); virtual int A(int,int); }; class Bar : public Foo { public: virtual int A(int); }; Bar b; int main() { b.A(0,0); } It seems that by overriding Foo::A(int) with Bar::A(int) I have somehow hidden Foo::A(int,int). If I add a Bar::A(int,int) thing...
Essentially, name lookup happens before overload resolution so the function A in your derived class overrides the virtual function in the base class but hides all other functions with the same name in any base classes. Possible solutions include adding a using Foo::A; directive into your derived class to make all the b...
1,480,090
1,480,340
Casting to an object with pointers
I have a class, Fixture, that I want to cast to a 3rd party library class, b2FixtureDef. Currently, my function looks like this: Fixture::operator b2FixtureDef() const { b2FixtureDef fd; fd.density = m_density; fd.friction = m_friction; fd.isSensor = m_isSensor; fd.restitution = m_restitution; ...
A conversion operator always has to make a copy of everything, so that the result is valid even if the original object is freed. Which means that you need to make a copy of m_polygon as b2PolygonShape and assign a pointer to it to b2FixtureDef::shape. You can make a copy by implementing a copy constructor in b2Polygon...
1,480,394
1,480,404
C++ STL - iterate through everything in a sequence
I have a sequence, e.g std::vector< Foo > someVariable; and I want a loop which iterates through everything in it. I could do this: for (int i=0;i<someVariable.size();i++) { blah(someVariable[i].x,someVariable[i].y); woop(someVariable[i].z); } or I could do this: for (std::vector< Foo >::iterator i=someVariab...
You could use for_each from the standard library. You could pass a functor or a function to it. The solution I like is BOOST_FOREACH, which is just like foreach in other languages. C+0x is gonna have one btw. For example: #include <iostream> #include <vector> #include <algorithm> #include <boost/foreach.hpp> #define f...
1,480,417
1,482,460
building objects from xml file at runtime and initializing, in one pass?
I have to parse the XML file and build objects representation based on that, now once I get all these data I create entries in various database for these data objects. I have to do second pass over that for value as in the first pass all I could do is build the assets in various databases. and in second pass I get the ...
You might be interested in learning several techniques of building XML parsers like DOM or SAX. As it is said in SAX description the only thing which requires second pass could be the XML validation but not the creating the tree.
1,480,430
1,480,436
Member initialization of a data structure's members
I just ran into an awkward issue that has an easy fix, but not one that I enjoy doing. In my class's constructor I'm initializing the data members of a data member. Here is some code: class Button { private: // The attributes of the button SDL_Rect box; // The part of the button sprite sheet that will be s...
You can only call your member variables constructor in the initialization list. So, if SDL_Rect doesn't have a constructor that accepts x, y, w, h, you have to do it in the body of the constructor.
1,480,446
1,480,449
p2p communication using winsock
I am trying to achieve peer to peer communication using winsock but gethostbyaddr always return me NULL ,this thing works only on localhost, server_name is destination ip address server_name="<--ipaddress-->" struct sockaddr_in server; addr = inet_addr(server_name); cout<<"inet_addr(server_name) "<<addr<<endl; hp = g...
Where are you getting server_name from? Are you sure it's a valid IP address? Also, check WSAGetLastError() to see specifically what's going wrong. Remember that not all hostnames have reverse DNS entries. It's perfectly legitimate for gethostbyaddr to fail on a real, valid IP address. If you're doing p2p, it's best no...
1,480,490
8,849,082
Python interpreter as a c++ class
I am working on embedding python in to c++. In some peculiar case I require two separate instances of the interpreter in same thread. Can I wrap Python interpreter in to a c++ class and get services from two or more class instances?
I have used Py_NewInterpreter for different interpreters in different threads, but this should also work for several interpreters within one thread: In the main thread: Py_Initialize(); PyEval_InitThreads(); mainThreadState = PyEval_SaveThread(); For each interpreter instance (in any thread): // initialize interpreter...
1,480,525
1,480,534
C++ Collection of instances implementing a pure virtual class
I am working in cross platform C++, and have some classes defined like so: (heavily simplified for this example) class ExampleBase { public: ExampleBase( int blah ) : blah_test(blah) { } virtual void DoSomething( ) = 0; private: int blah_test; }; class ExampleImplementer : public ExampleBase { public: ...
boost::ptr_vector is the way to go if you can have Boost. It should work for your scenario - if it does not, then something else is wrong, so please post the error message. Alternatively, you can go for std::vector< boost::shared_ptr<ExampleBase> >. This is less ideal, because that refcounting will add some overhead, e...
1,480,596
1,480,644
How do you get how much memory a program uses?
I have two programs, one in C++, the other in assembler. I want to compare how much memory they use when running respectively. How can I do this? I am doing the testing on Windows, but I also would like to know how to do it on Linux.
Run the program in one shell. Open another shell and run 'top' command. it will list running processes and home much memory they consume. you can, i guess, poll /proc/yourprocessid/stat to see how much memory it is using over time.
1,480,655
1,480,829
How can I, on some global keystroke, paste some text to current active application in linux with Python or C++
I want to write app, which will work like a daemon and on some global keystroke paste some text to current active application (text editor, browser, jabber client) I think i will need to use some low level xserver api. How i can do this with Python or C++ ?
You can use the xmacroplay utility from xmacro to do this under X windows I think. Either use it directly - send it commands to standard input using the subprocess module, or read the source code and find out how it does it! I don't think there are python bindings for it. From the xmacroplay website xmacroplay: Reads...
1,480,916
1,480,962
How do I enable the SSE/SSE2 instruction set in Visual Studio 2008 (using CMake)?
In Visual Studio 2005 I went in: View --> Property Pages --> C/C++ --> Code Generation --> Enable Enhanced Instruction Set But in Visual Studio 2008? Thanks in advance
If you're looking for SSE/SSE2: Project > Properties > Configuration Properties > C/C++ > Code Generation > Enable Enhanced Instruction Set, or append /arch:SSE (or /arch:SSE2) in Command Line > Additional Options. You need to have a native project, and at least one .cpp file added to access this, though.
1,480,971
1,481,890
Is there a non-java, cross platform way to launch the associated application for a certain file type?
First, I found a couple of java specific questions and answers for this. I am looking for more "native", but cross platform solution, using C, C++, some kind of shell scripts, or, in my case, Qt. So the question is, are there standard, cross platform, ways to programmatically open the associated application for certai...
I don't know of any cross-platform way. In Windows, there is the start command, which will launch the associated default application. (E.g. start foo.doc will launch the default Word document editor, start http://StackOverflow.Com/ the default web browser and start mailto:mail@example.com the default mail app.) In OS X...
1,480,973
1,485,657
How can I make my char buffer more performant?
I have to read a lot of data into: vector<char> A 3rd party library reads this data in many turns. In each turn it calls my callback function whose signature is like this: CallbackFun ( int CBMsgFileItemID, unsigned long CBtag, void* CBuserInfo, int CBdataSize, ...
If my wild guess about your callback function makes sense, you don't need anything more than a vector: std::vector<char> foo; foo.reserve(MAGIC); // this is the important part. Reserve the right amount here. // and you don't have any reallocs. setup_callback_fun(CallbackFun, &foo); CallbackFun ( in...
1,481,041
1,481,069
Destructor for Singleton
Question : Should i write destructor for a singleton which has program scope (comes alive when program starts and dies when program ends) Detail : i am in a dilemma on "shall i write destructor for a singleton class or not ?" 1) This class has program scope 2) Class uses a lot of memory on heap, So releasing that...
If it takes a long time to release memory, then don't do it. This may be a big and time-consuming issue, especially if releasing memory leads to numerous cache misses. OS will do the job (of course, if you are operating on the systems that actually does that). However, if your destructor does finalization of some res...
1,481,050
1,481,061
Where Does SYMBOL TABLE Reside?
I wanted to know where does SYMBOL TABLE reside. Is it in .obj files or an .exe file? Thanks in advance.
There's another similar SO Question. In the answers to this question, it mentions that the symbol table is in each .obj file.
1,481,216
1,481,244
C++ reference type recommended usage
I am programming in C++ more then 5 years, and have never met any place where reference of the variable is recommended to use except as a function argument (if you don't want to copy what you pass as your function argument). So could someone point cases where C++ variable reference is recommended (I mean it gives any a...
As a return value of an opaque collection accessor/mutator The operator[] of std::map returns a reference. To shorten the text needed to reference a variable If you miss old-school with Foo do ... statement (that's Pascal syntax), you can write MyString &name = a->very->long_->accessor->to->member; if (name.upcase()...
1,481,282
1,481,336
Poco C++ SAX parser: how to get element "inner text"?
I've been going over the Poco SAX parser header files a few times but I can't seem to find any info on how to obtain an element's inner text. For example: <description>This is the inner text.</description> Can anyone point me in the right direction?
Ok, found the solution myself. I needed to use implement the 'characters' method like this: void MyParser::characters(const Poco::XML::XMLChar ch[], int start, int length) { std::string innerText = std::string(ch + start, length); }
1,481,382
1,481,516
runtime error (SIGSEGV)
#include<iostream> #include<string> using namespace std; int main() { char arr[1000][80]; char output[1000][80]; int n,i,j; int num[1000]; cin>>n; for(i=0;i<n;i++) { cin>>num[i]; cin>>arr[i]; } for(i=0;i<n;i++) { for(j=(num[i]-1);j<(strlen(arr[i])-1);j++) { ar...
Depending on the input you pass to this program, the variable n may be more than 1000, cin>>arr[i] may read more than 80 characters, and if num[i] <= 0 || num[i] >= 80 then you will index past the beginning or end of one of your strings. All of these problems exist because this code uses fixed-size arrays and doesn't d...
1,481,612
1,481,764
What is the difference between throw and throw with arg of caught exception?
Imagine two similar pieces of code: try { [...] } catch (myErr &err) { err.append("More info added to error..."); throw err; } and try { [...] } catch (myErr &err) { err.append("More info added to error..."); throw; } Are these effectively the same or do they differ in some subtle way? For example, does ...
Depending on how you have arranged your exception hierarchy, re-throwing an exception by naming the exception variable in the throw statement may slice the original exception object. A no-argument throw expression will throw the current exception object preserving its dynamic type, whereas a throw expression with an ar...
1,481,616
1,481,622
Smart pointers in Qt
Like it has been written here Qt up to now has 8 specilized smart pointer classes. It looks like it is all you will ever need. However, in order to use any of these smart pointers your class must be derived from QObject which is not always convenient. Is there other implementations of smart pointers in Qt which work wi...
Many Qt classes are derived from QObject, and while some of the built in smart pointer classes are related to QObject (or QSharedData), the QSharedPointer and QScopedPointer templates appear to allow pointers to anything. Beyond that, you'll find some smart pointer templates in Boost: scoped_ptr - Simple sole ownershi...
1,481,677
1,481,796
How to provide a explicit specialization to only one method in a C++ template class?
I have a template class that looks something like this: template<class T> class C { void A(); void B(); // Other stuff }; template<class T> void C<T>::A() { /* something */ } template<class T> void C<T>::B() { /* something */ } What I want is to provide an explicit specialization for only A while retaini...
Alternatively to Martin York's inline solution you could also do in your header file: class D { }; template<> void C<D>::A(); // Don't implement here! And supply a .cpp file with the implementation: template<> void C<D>::A() { /* do code here */ } So you avoid the multiple definitions by supplying a single one. This ...
1,481,733
1,481,768
Portable C++ 03 Exact Width Types
Background Unfortunately the current C++ standard lacks C99's exact-width types defined in the stdint header. The next best thing I could find (in terms of portability) was Boost's cstdint.hpp implementation from the Boost.Integer library. Concerns That said, I've got a few problems with it: Boost's implementation du...
You could just use stdint.h, and provide one for compilers that don't have it (e.g. for MSVC - msinttypes). Or write cstdint that is using all of Boost's typedefs (it's a write-once, so I don't think maintenance will be problematic). It's easy to generate, too. Using this little script, i got that. You could also add d...
1,481,793
1,481,811
Return value of XXTEA
This may seem a stupid question but I can't find the anwer... This is the code for XXTEA from Wikipedia: #include <stdint.h> #define DELTA 0x9e3779b9 #define MX ((z>>5^y<<2) + (y>>3^z<<4)) ^ ((sum^y) + (k[(p&3)^e] ^ z)); void btea(uint32_t *v, int n, uint32_t const k[4]) { uint32_t y, z, sum; unsigned p, rounds, e...
Operators = -= += has the same priority in expressions and they are associated from right to left according to C++ Standard 5.17 (and I believe there is the same rule in C) . For example, this: y = v[p] -= MX; Could be replaced with: v[p] -= MX; // <<< modification of data here y = v[p];
1,481,886
1,481,899
Failed to open an FTP connection
I had a problem when trying to connect and upload a file to an FTP server. Here's my code: #include <windows.h> #include <wininet.h> #pragma comment(lib, "wininet.lib") int main() { HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0); HINTERNET hFtpSession = InternetConnect(hInt...
There is nothing wrong with code you've posted. Linker error refers to redefined symbol - you have two same variables in global namespace, in two different object files (svDialog and MainDlg). Try not to use global variables; and if you have to, and you have HINTERNET hFtpSession; HINTERNET hInternet; in one of your h...
1,481,971
1,483,019
MFC: CToolTipCtrl causes ASSERT
I have implemented tool tips seemingly successfully in an app which is MFC based and uses CPropertyPage. However after adding a button to open a dialog box called IDC_USERMSG which contains a single CEdit control on one of the CPropety pages an Assert is thrown when the IDC_USERMSG dialog is dismissed. _AFXWIN_INLIN...
You are calling CDialog::PreTranslateMessag twice, remove the second call.
1,481,996
1,482,063
How to call an instantiated class member variable through other function that was unrelated to the class?
I'm now creating a file transaction system (through FTP) using wxWidgets for the GUI and a multithreading class from CodeProject (http://www.codeproject.com/KB/threads/SynchronizedThreadNoMfc.aspx) - Please read the article first for reference. In my GUI, I have a textbox (wxTextCtrl) that stores the file path that wan...
It's quite simple. You should create a start function that takes a std::string (or any other parameters) and store it (them) in the svThread object. Then you can access it in the run function: class svThread : public Thread { private: char* ThreadName; std::string FileName; public: svThread(con...
1,482,515
1,483,945
Clearing/resetting a model in qt (removing all rows)
I'm confused about the correct way to reset or clear the data associated with a QAbstractItemModel. I'm writing an application in which the user can "start over" with a new set of data (empty, or small). Should I be deleting the old model when the user makes this request? Or should I leave the model alone and just remo...
Generally I would prefer to have the model react to changes and take the necessary actions to update it's view (indirectly ofcourse). However, programming models can be (=is) a PITA, so I would probably look through the fingers if I was reviewing code that created a new model and deleted the old one. Only do this if yo...
1,482,535
1,482,690
Automatically deducing operators in C++?
Is it possible in C++ for the compiler/language to automatically deduce unimplemented operators? For example, if I have: class X { public: bool operator ==(const X &x) const; }; Is there a way for != to be deduced implicitly? And I'll exploit this questions for a semi-related one: How come map's only requirement fr...
The STL already has a set of definitions. In the namespace stl::rel_ops the following definitions can be found. namespace std { namespace rel_ops { // Uses == template <class _Tp> inline bool operator!=(const _Tp& __x, const _Tp& __y); // Uses < template <class _Tp> inline bool operator>(const _Tp&...
1,482,584
1,493,220
Drawbacks to nesting of child windows?
Just for fun I'm developing a native Win32 port of Mozilla XUL. XUL allows to create complex nested structures of all kinds of layout boxes (hbox, vbox, grid, deck..). For my Windows implemenation it would be convenient to implement them as STATIC child windows. Because then I can position their child windows using x &...
I've been down this path, and I don't recommend you actually make deep hierarchies of windows. Lots of Windows helper functions (e.g., IsDialogMessage) work better with "traditional" layouts. Also, windows in Windows are relatively heavy objects, mostly for historical reasons. So if you have tons of objects, you cou...
1,482,610
1,482,630
Multiple threads for multiple ports?
I have a program (process) which needs to listen on 3 ports... Two are TCP and the other UDP. The two TCP ports are going to be receiving large amounts of data every so often (could be as little as every 5 minutes or as often as every 20 seconds). The third (UDP) port is receiving constant data. Now, does it make sen...
In general, avoid threads unless necessary. On a modern machine you will get better performance by using a single thread and using I/O readiness/completion features. On Windows this is IO Completion Ports, on Mac OS X and FreeBSD: kqueue(2), on Solaris: Event ports, on Linux epoll, on VMS QIO. Etc. In boost, this i...
1,482,656
1,482,668
How to get rid of the warning with time.h in C++?
When I use this #include<time.h> //... int n = time(0); //... I get a warning about converting time to int. Is there a way to remove this warning?
Time returns time_t and not integer. Use that type preferably because it may be larger than int. If you really need int, then typecast it explicitly, for example: int n = (int)time(0);
1,482,806
1,505,616
Manually incrementing and decrementing a boost::shared_ptr?
Is there a way to manually increment and decrement the count of a shared_ptr in C++? The problem that I am trying to solve is as follows. I am writing a library in C++ but the interface has to be in pure C. Internally, I would like to use shared_ptr to simplify memory management while preserving the ability to pass a r...
In your suggestion The client will then be responsible to decrement the counter. means that the client in question is responsible for memory management, and that your trust her. I still do not understand why. It is not possible to actually modify the shared_ptr counter... (hum, I'll explain at the end how to...) but...