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
6,904,918
6,904,946
Redefinition error using namespace
// main.cpp const double MAX = 3.5; namespace ns { const int MAX = 3; } int main() { } will this cause redefinition error? I'm referring to this MSDN page, which says in the Remarks section that this is an error. Update: I think I may miss one important statement when copying around the code. using ns::MAX;
No - I don't see how that code would cause a redefinition error. And in fact, you can compile it and see for yourself. EDIT: Following up now that you've supplied the link to the MSDN page you mentioned... That MSDN page is talking about name clashes in the context of a using directive: If a local variable has the sa...
6,904,924
6,907,745
SDL RenderTextShaded Transparent Background
any Idea how I could have the follow code output text with a transparent background? SDL_Color co = {tp->col.r, tp->col.g, tp->col.b,tp->col.a}; SDL_Color bco = {255, 0, 255,1}; ts = TTF_RenderText_Shaded(tp->font, text.c_str(),co,bco);
TTF_RenderText_Shaded doesn't allow for transparent backgrounds (as it uses 8bit color), you want to use TTF_RenderText_Blended, see this.
6,905,249
6,905,275
If I declare an instance variable as volatile, will the object of this class be volatile?
Like: class A { volatile int i; }; A a; My question is that will the entire a become cv qualified? May be a naive question.
No, all of a will not be volatile. Just as you can have fields of a class that are const without every instance of the class being const, you can have volatile fields that do not make the entire class instance volatile.
6,905,334
6,906,511
using templates to check for member variable not working on int
I need to check and see if a given type has a member variable. However when a type that is not a class or a struct is given, I get a compiler error. struct Vector { int x; }; template <typename Type> class has_member_x { class yes { char m;}; class no { yes m[2];}; struct BaseMixin { int x; };...
After fixing a bug in the original has_member_x class, and adding specialization for class types as it was suggested by others the final working version looks like this: #include <type_traits> template <typename Type, bool Enabled = std::is_class<Type>::value> class has_member_x { public: static const bool result =...
6,905,536
6,935,132
c++ Getting vertex properties of a Boost::Graph
Given a Vertex as: class VertexProps { public: int id; float frame; string name; }; I have initialized my boost graph using bundled properties. I know I can get the frame by using: std::cout << "Vertex frame: " << boost::get(&VertexProps::frame, graph, vertex) << std::endl; //Need to make this work: flo...
There is no way to do that with out any macro magic at compile time. C++ doesn't allow string literals as non-type template parameters and has very slim reflection capabilities. The solution you propose (and want to avoid) requires some work at run-time and should generally be avoided. The macro solution would be along...
6,905,566
6,905,589
a pointer bound to a function may only be used to call a function
I've just moved from char arrays to std::string and I've already ran into a problem, I'm probably doing something extremely stupid, feel free to ridicule: int main() { string * p = new string; memset(p, 0, sizeof(string)); expected_exepath(p); cout << p->data; delete p; } The error is in p->data...
Because data is a function, not a data member. More importantly, half the point of std::string is that it's a value. You shouldn't use new unless you have an extremely good reason- allocate on the stack, or if you must dynamically allocate use a container or smart pointer. Also: Do not ever, ever, ever memset UDTs like...
6,905,598
6,905,612
C++ equivalent to Java this
In Java you can refer to the current object by doing: this.x = x. How do you do this in C++? Assume that each of these code examples are part of a class called Shape. Java: public void setX(int x) { this.x = x; } C++: public: void setX(int x) { //? }
Same word: this Only difference is it is a pointer, so you need to use the -> operator: void setX(int x) { this->x = x; }
6,905,695
6,905,987
C++ Syntax/Semantics Question: Reference to Function and typedef keyword
What would typedef int (&rifii) (int, int) be used for? What is the typedef before this "statement" do? I want to think of this as typedef (int (&rifii) (int, int)) [new name] but the [new name] is not there like if you do typedef int INTEGER; Similar question for the following syntax: typedef void (*PF) (); PF edi...
Typedef does not work like typedef [type] [new name]. The [new name] part does not always come at the end. You should look at it this way: if [some declaration] declares a variable, typedef [same declaration] would define a type. E.g.: int x; declares a variable named x of type int -> typedef int x; defines a type x a...
6,905,747
6,905,773
How do I run another program from a C++ program
I am trying to call on another program to perform a function (I have no idea what, only that it is not written in C++, but in shell) on a file within my C++ program. I do not know how to actually perform the function within my program. I do know that I write something like this system(PROGRAM HERE); The problem is th...
You could format the string first. With <sstream> included: int arg = 5; std::stringstream ss; ss << "dostuff " << arg; system(ss.str().c_str()); Alternatively, you could use the concatenation feature of std::string. If you prefer the C-style formatters, you could use snprintf to similar effect.
6,905,914
6,905,950
Using Java on Ubuntu - Package conflict?
On linux, I often launch and compile from the command line (java/javac) Though, Java isn't the only language I use - I use C++, and for that I have GCC. Because I have both java and GCC, for example, there are more than one instance of 'javac': From the terminal, passing 'javac' with no arguments: The program 'javac' c...
update-java-alternatives -s openjdk-6-jdk On Ubuntu there is a system called alternatvies installed, to switch between different implementations: update-java-alternatives man update-java-alternatives shows the usage: NAME update-java-alternatives - update alternatives for jre/sdk installations SYNOPSIS ...
6,905,991
7,083,930
MSVC Heap Reserve/Commit
I wrote a program that requires ~1GB of RAM zeroed at startup, and this is taking more time than the rest of the program combined from a cold start. (it's a simple program, subsequent runs take almost no time at all to allocate). When watched via task manager, it starts with almost no RAM, and then grows about 2MB/sec...
I realized it's probably because the first run has to page stuff out of RAM to the hard drive, whereas the subsequent run has all that unused RAM left behind after the first run. The allocation/zeroing has nothing to do with it. Sorry all.
6,906,521
6,906,569
How to check whether a vector is a subset of another in c++
I am trying to find a simple way to check whether a vector is a subset of another without sorting the order of elements in the vector. Both the vectors contain random number elements in them. std::includes seems to work only for sorted ranges. How can I accomplish this?
Copy the vectors. Sort the copies. Then use std::includes on the copies. template <typename T> bool IsSubset(std::vector<T> A, std::vector<T> B) { std::sort(A.begin(), A.end()); std::sort(B.begin(), B.end()); return std::includes(A.begin(), A.end(), B.begin(), B.end()); }
6,906,553
6,906,659
Is it recommended to specify e.g. vector<t> in my public interface?
I'm new to C++, and while writing a class I realized one of my methods was asking for a vector-of-vectors. Should this be done or should I rethink my class's interface? (How?)
I think it is no problem what container you use. You could do it like void func(std::vector<std::vector<int> > const& int_matrix); or in C++11, successive > won't be considered as '>>' so you could also use void func(std::vector<std::vector<int>> const& int_matrix); But the problem is, if your work are published as b...
6,906,842
6,907,004
WINAPI C++ VS 2008 vs VS 2010
I've been writing an application that monitors certain directory for files being added, and sending those files in certain order. It does work perfectly. But I've encountered an interesting problem - I wrote this project on Windows XP, using VS 2008, and I need to merge my solution with another one, located on PC with ...
Most probably, the problem here is that your VS 2008 project was Multibyte CharacterSet based and VS 2010 project is UNICODE based. Right-click on Project->Properties->General->Character Set Change it to 'Use Multi-Byte Character Set'. Alternatively, if you want to keep your code UNICODE based, then add _T before all ...
6,906,991
6,907,294
How to support commandline syntax "-DEVICE:iphone" in Boost::Program_Options?
The default syntax for Boost::Program_Options is "--DEVICE iphone". How can I support syntax "-DEVICE:iphone" or "-DEVICE=iphone"?
Boost.Program_Options has a pretty large number of option styles. The particular combination you seem to be going for would be: command_line_style::long_allow_adjacent | command_line_style::short_allow_adjacent | command_line_style::allow_long_disguise These options should be given to the style function of your comman...
6,907,093
6,908,937
Sparing User from Specifying Policy Template Parameter
I'm designing a kind of istream_iterator (call it my_istream_iterator) designed to extract words from an input stream. The manner in which the words extracted from the iterator will be dealt with is independent of the way the words are delimited in the stream, but the words themselves may follow one of many formats. To...
For your task there is no need to build your own istream iterator since std::istream_iterator<T> uses T's operator<<(). For example: #include <iostream> #include <iterator> #include <vector> #include <boost/algorithm/string/split.hpp> #include <boost/algorithm/string/classification.hpp> template<char field_delim, char...
6,907,116
6,907,336
WCHAR to String, how do i do it?
String* Adder::downloadUrl(String* url) { DWORD dwSize = 0; LPVOID lpOutBuffer = NULL; BOOL bResults = FALSE; HINTERNET hSession = NULL, hConnect = NULL, hRequest = NULL; // Use WinHttpOpen to obtain a session handle. hSession = WinHttpOpen( L"A WinHTTP Example Pro...
Looks like you need the WideCharToMultiByte function
6,907,134
6,907,146
Regular Expressions C++ Qt
QRegExp rx("\\btest\\b"); rx.indexIn("this is a test string"); QString captured = rx.cap(1); std::string capturedstr = captured.toUtf8().constData(); std::cout << capturedstr; I wanted the above to print out test and match the word test within the string but it doesn't seem to be doing that. Could anyone shed some lig...
You don't have any capturing parens in your regex so there is no capture group 1. Try this instead: QRegExp rx("\\b(test)\\b");
6,907,194
6,907,216
How to typedef a template class?
How should I typedef a template class ? Something like: typedef std::vector myVector; // <--- compiler error I know of 2 ways: (1) #define myVector std::vector // not so good (2) template<typename T> struct myVector { typedef std::vector<T> type; }; // verbose Do we have anything better in C++0x ?
Yes. It is called an "alias template," and it's a new feature in C++11. template<typename T> using MyVector = std::vector<T, MyCustomAllocator<T>>; Usage would then be exactly as you expect: MyVector<int> x; // same as: std::vector<int, MyCustomAllocator<int>> GCC has supported it since 4.7, Clang has it since 3.0, ...
6,907,615
6,909,370
Finding item row index in ListView by text and by column
I'm using the following code to retrieve the index of a row that contains certain text in the second column (of which it has 3, an index one, and two that contain other text). LVFINDINFO inf={0}; inf.flags=LVFI_PARCIAL|LVFI_STRING; inf.psz="textToFind"; std::cout<<ListView_FindItem(mywinHandle, -1, (LPARAM)&inf); Howe...
You can't search in the sub-columns. You can only search in the primary column. The lParam value specifies which row to start searching from. You are mistaken in thinking that it allows you to specify which column to search.
6,907,917
6,908,077
Android App and Open Source Libraries
I have an existing app(not released public yet just internal) based on c++ which i would like to port to android and use its services in my android app. I use STL and boost in that app. My question is if i want to port the existing code to android, can i just compile them as static or shared objects. I was planning to...
You first have to learn Java... and figure out that there is no STL and boost libraries. The Java ecosystem has its own crowd of opensource libraries you can use to be more productive. Including them in your apps is just like copying a set of .jar files in the right folder and add them in the build path. About licensin...
6,908,051
6,908,156
c++ classes - how do I pass a function to an included class for it to use?
I'm sure this has something to do with virtual functions, but I'm struggling to work out how. Here is my (simplified) situation: Roughly what the program does is have one pair of files (computer.h) draw a computer with a blank screen, and another pair (program.h) which has a function that needs to draw on that computer...
Well you're half-way there. For something like this, yes I'd use virtual functions (in order to define an abstract interface). Here's the basic outline of how I'd do it: // First create a class to define an interface for drawing a screen class IScreen { public: // Defines an interface named drawScreen virtual v...
6,908,591
6,908,641
C++ class member function pointer to function pointer
I am using luabind as my lua to C++ wrapper. Luabind offers a method to use my own callback function to handle exceptions thrown by lua, set_pcall_callback(). So I paraphrased an example from the documentation, the changes being the logger->log() function and putting the function in a class called 'Engine', so instead ...
No. A member function is not a free function. The type is entirely different, and a pointer to a member function (PTMF) is a completely different, incompatible object from a function pointer. (A PTMF is usually much bigger, for example.) Most importantly a pointer-to-member must always be used together with an instance...
6,908,782
6,908,939
Operator [] overloading
I have the following code: class A { public: A() {}; void operator[](int x) { } }; int _tmain(int argc, _TCHAR* argv[]) { A a; a.operator[](0); a[0]; } Both calls work, but I want to know whether there is any difference. Is one more efficient than the other? Do other things happen(besi...
The explicit operator[] (and any other explicit operator) is used in an inheritence heirarchy, where you are trying to call operator[] on a base class. You can't do that using the normal [], as it would result in a recursive function call. ie; you might use something like this: struct Base { void operator[] (int i)...
6,908,976
6,909,051
Generalized exception translation for boost python
The current boost::python example for translating a specific C++ exception into python goes like this: void translate (const MyException& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); } boost::python::register_exception_translator<MyException>(translate); Unfortunately, this requires that we write a specific...
You're passing the this pointer as the translate function, and this fails because a pointer to an object can't be called as a function. If you pass *this instead this should work (note that this will copy-construct the GeneralizedTranslator object). Or you can move the registration out of the constructor, and call regi...
6,908,988
6,909,075
Controlling Multiple UI files in Qt framework
Question asked twice: see Handling multiple ui files in Qt I am new to Qt framwork , i have been given this simple task: In the MainWindow , i have a submit button , once its clicked another total different window should appear i thought of doing this by doing one extra UI file called From.ui file and to switch from Ma...
It seems that SubmitClicked slot is not connected to clicked event of your button Put a cout/printf at the top of your SubmitClicked method to make sure that it is called.
6,909,335
6,909,685
C++ not catching lua exceptions
I have a C++ program that I have bound to Lua using luabind. I am currently testing the error handling methods that lua and luabind have to offer in order to help with debugging the lua scripts down the road. The objective is to have luabind or lua throw an exception when syntax errors and programming mistakes arise so...
If you want to load a Lua script through Luabind, then you can't use luaL_dofile or other regular Lua functions to do it. You have to use Luabind functions. So that would look something like this: namespace lb = luabind; int luaError = luaL_loadfile(pLuaState, "scripts/start.lua"); //Check for errors lb::object compil...
6,909,530
6,909,560
Why won't this c++ code compile?
Seeig that i'm new to C++ I thought i'd try and write a very simple console app that populates a 2D-array and displays its contents. But the code I've written won't compile. Some of the errors I get are: error C2065: 'box' : undeclared identifier error C2228: left of '.GenerateBox' must have class/struct/union Here i...
The C++ compiler reads source files in a single pass, from top to bottom. You have described the Box class at the bottom, after main(), after the part where you attempt to use the class. Accordingly, when the compiler gets to the part where you say 'Box box;', it has not yet seen the class definition, and thus has no i...
6,909,591
6,917,932
Problem with using Boost::Regex (Console just freezes up)
For some reason boost::regex overloads my application and it freezes without an error, but it compiles fine. For instance this code fails flatly. What am I doing wrong? I updated to boost 1.47 to see if it was a DLL error, but it still doesn't work. Can I get an example program to test out the boost::regex? static cons...
After some work I deleted the boost installation from BoostPro and compiled boost myself and now it works. The problem was that BoostPro did not install all of the DLL's and I thought when it asked me for a missing DLL that BoostPro named them wrong (boost_regex-vc100-mt-1_47.dll instead of boost_regex-vc100-mt-gd-1_47...
6,909,759
6,910,100
How concerned should I be about the loss blocked in valgrind
In my code I have a class lipid which holds three beads: struct lipid{ particle mainPart; bead * head; bead * body; bead * tail; int LID; vec direction; bead * operator[](int index){ switch(index){ case 0: return head; case 1: return body; case 2: return tail; default: return body; ...
Like the other posters excellently explained, these lost blocks are memory that was allocated, but never freed, and thus will never be usable again in the same run of your program. When you try to run your program for a longer time and need many new lipid structures, this is a definitive problem. From a software engine...
6,909,838
6,909,869
Why does assigning to a reference to std::ostream fail to compile?
I am using an abstract class std::ostream. There is the following reference: std::ostream &o = std::cout; If any condition is met I need to initialize o so that the output will be redirected to std::cout. If not, output will be redirected to the file if (!condition) o = file; //Not possible How to correctly wri...
You can't reseat a reference. This is an alternative though : std::ostream &o = (!condition) ? file : std::cout;
6,910,590
6,910,721
Search value in a functor's c'tor
Say I had a std::vector<std::pair<int, std::vector<int> > >, that is, a vector containing pairs of ints to vectors. ( I know I could acheive the same thing with a map, but that's not what I'm asking ) How would I search for the int (the one in the pair) using STL? I wrote a solution that works: struct FindFirst { F...
This is the best way to do it, when using only the STL. What exactly do you not like about it (except maybe it's verbosity)? It is versatile, because you can use with other algorithms like for instance std::binary_search. It is quite simple and direct (at least to someone used to C++ functors). The only thing to reall...
6,910,732
6,910,864
c++ long long int is not enough?? errors
I am working in c++. I have a string that contains the following number std::string s= "8133522648"; I want to convert this number in long long int nr; I did: nr=atoll(s.c_str()). The result is: -456410944. How to solve this error? Thanks Edit: In fact I have: const char* str="8133523648"; I have to convert it into ...
use int64_t instead of long long. which is defined in stdint.h If you rely on boost you can use std::string s= "8133522648"; int64_t nr = boost::lexical_cast<int64_t, std::string>(s);
6,910,884
6,912,972
Stackdump in C++ not showing the stack trace
I have an app that crashes sometimes and creates the next file: (APP.exe.stackdump) Exception: STATUS_ACCESS_VIOLATION at eip=6BA4B246 eax=67452301 ebx=EFCDAB89 ecx=98BADCFE edx=10325476 esi=FFFFFFFF edi=98BADCFE ebp=FFFFFFFF esp=01A2C928 program=C:\APP.exe, pid 168, thread unknown (0x13E8) cs=001B ds=0023 es=0023 fs=0...
Or any extra info? Use valgrind or efence. Both are very good at finding usage of wild pointers at the time of dereference, instead of later when the corrupted data is used.
6,910,946
6,911,747
How to Display a "*.png" file on a UI in QT framework?
I am new to Qt Framework... I want to display a .png pic in my Form1.ui , so I dragged and dropped a Graphic view from the widget box then I placed test.png in the same directory (inside the project folder) and i did this in the code //Form1.cpp #include "form1.h" #include "ui_form1.h" Form1::Form1(QWidget *parent) ...
The Widget you should use to show pictures is a QLabel. You can do it directly from QtCreator, by setting its pixmap property. As others said, you should first create a resource file and then add the image to that resource file. To create a Qt Resource File, go to the menus: File > Qt > Qt Resource File. EDIT To do it ...
6,911,126
6,911,190
is it possible to define the static member function of a class in .cpp file instead of its header file?
i am having a function which should be run only once for all instance of the class.i thought to use the static function calling method. all the web example shows that static function define in the Header file(inside the class) itself. my function is big one i cant define that in header file what should i do? for that.
Like you do for normal functions: FooBar.h #ifndef FOOBAR_H #define FOOBAR_H class FooBar { public: static void test(); }; #endif FooBar.cpp #include "FooBar.h" void FooBar::test() { }
6,911,289
6,911,339
Should I use std::vector::at() in my code
I noticed today that std::vector::at() is significantly slower than accessing values with square brackets []. According to the doc .at() is safer because it won't let me access values beyond the bounds of the array. However, even if I access out of bound values with at(), I'll obviously still have an error, so that's s...
If you have reason to believe that the index is not in your control, or if the control flow is particularly complicated and you're tracing bugs, then you might want to use at() during the debug phase, but never inside loops or any situation where you know that the index is safe. Even in other situations you should eith...
6,911,348
6,911,392
What is the difference between main in C & C++
What is the difference between main in a C program and in a C++ program? Other than return statement ( default 1 in C,`0 in C++) syntax: int main() { /* … */ } int main(int argc, char* argv[]) { /* … */ } int main() , void main() ,etc ... Mainly: difference between main in C Program & C++ program Are there a...
In modern C, and modern C++: main is always either int main() or int main(int, char*[]). In C89, you have to return from main explicitly. In C99 and C++, if you don't return explicitly, you implicitly return 0. [(I've checked the C99 standard now and edited this paragraph.)] For your second question, in C99 you must ...
6,911,700
6,911,769
How can you strip non-ASCII characters from a string? in c++
How can you strip non-ASCII characters from a string? I like to know how we can achieve this in c++
Maybe something like: struct InvalidChar { bool operator()(char c) const { return !isprint(static_cast<unsigned char>(c)); } }; std::string s; HypoteticalReadFileToString(&s); s.erase(std::remove_if(s.begin(),s.end(),InvalidChar()), s.end()); Its nicer to define a reusable function for the erase-remov...
6,911,805
6,911,848
Pthread: Does starting location makes a difference
A simple question. Does it make any difference if one pthread starts multiple sub-pthreads? rather than all of them started from the main ? I consider only performance at this stage. Thanks.
There is no performance difference.
6,912,254
6,912,545
wxwidgets - exit the thread the right way
I run openCL /openGL program which uses wxWidget as gui enviroment Inside object of class ,which derives from wxThread,I perform some complicated calculations and build many openCL programs. I want to delete the thread .But the thread is not deleted immediately – it continue to build programs and just after it fini...
Killing a thread like that is indeed very bad. It's best to give the thread a chance to clean up. Graceful thread termination is usually done by periodically checking a flag that tells it to exit: volatile bool continue_processing = true; thread thread; void compile_thread() { while(continue_processing) { ...
6,912,346
6,912,405
Webcam Video Capture using Visual C++ 6.0
I am trying to create an application to capture a snapshot using a webcam. I have been able to accomplish this using WIA, but this solution becomes unstable when ran on Windows 7 with a camera that has a resolution of more than 1.3 megapixels. We are coding for a tablet computer that has a built in webcam with 2.0 meg...
The simplest way is videoinput lib that wraps directshow, it's the same lib used by openCV. If that isn't good enough then the AMCAP sample in the multimedia/directshow dir of the Microsoft SDK shows how to run a camera in directshow ps. as Hans said you should update the compiler,VC++6 is little old. There is a free v...
6,912,456
6,913,747
How do I save base64 string as png image in Qt?
I want to write function which saves input base64 string as a png image to local. How can I do it in Qt?
This is a simple program I wrote sometime ago for testing png and base64. It accepts a png encoded in base64 from standard input, show it and than save it to specified path (output.png if nothing has been specified). This wont work if base64 string is not a png. #include <QtCore> #include <QApplication> #include <QIma...
6,912,696
6,912,739
Is there a way to automatically generate getters and setters if they aren't present in C++?
I'm experienced with Objective-C, and in Objective-C you can let the compiler generate getters and setters for you if they aren't already present (@synthesize). Is there a way to do this in C++, or do I need to implement all getters and setters myself?
The C++ Core Guidelines advise against using trivial getters and setters because they’re unnecessary and a symptom of bad object-oriented design. As such, C++ has no built-in functionality for auto-generating getters and setters (though metaclasses, if they ever get included in the language, would make this possible). ...
6,912,761
6,912,962
How to use C++ for apache server
We can integrate php, perl, python with apache and build sites in them. Is it also possible to use C/C++ with apache and build web sites in it?
It works. You can do basic stuff using CGI: for every request to an address on your site, Apache starts a new process with a given executable. This executable can be C++. Disadvantage is that a new process is created for every request. For better results, you can use FastCGI, where the CGI process can run for several d...
6,912,842
6,950,520
QPaintEvent - updating only a region of the screen
in my code I'm trying to draw points every time my app gets GPS coordinates. The points are moved by "i" pixels to the right and down. I would like them to stay there drawn but it seems like the whole screen is always updated, even though I'm using a QRegion parameter which is meant to specify an area on the screen whi...
Your paintEvent must be able to repaint the entire widget. For example, if a user minimizes and then maximizes your application, the entire widget must be repainted. The QPaintEvent::region can be used to suppress some of that painting if those paint operations are expensive. Here is a sample. (This is only a proof of ...
6,912,844
6,913,032
Returning result of button pressed on UIAlertView to C++ method
I need to call a UIAlertView to be displayed from a C++ file. Depending on the button pressed, I need to return a bool to the C++ class itself (that bool in turn gets returned and is used elsewhere). I would like some advice on how to return the result to the C++ class. I have presumed that we can't set the C++ class a...
You can't do this easily as thinking about the code flow will tell you. The problem is the run loop and that UIAlertView is non blocking to display the alertView (i.e. after calling [alert show]) you need to return control to iOS which means that your C++ function bool CPlatform::WarningMessage(const wchar_t* message) ...
6,913,221
6,913,355
c++ Error C2064 for function pointer in C++ template
If I compile the code below, I get an "Error C2064: term does not evaluate to a function taking 2 arguments" in the doOpp() method. If I change q = f(p, i); for q = add(p, i); everything compiles fine (with add() being the second argument in the doOpp() method). I've tried a couple of solutions but nothing seems to ...
Since oppFunc f is a member function pointer you should use the special syntax to make a call through a member function pointer: q = (this->*f)(p, i);
6,913,373
6,913,556
Help with linking in Visual C++ Express
I'm new to VC++ and would like to know know how to link "wsock32.lib" within VC++. I'm trying to write a simple c++ server app and these are the error messages I'm getting. So how do I go about linking something in VC++?. Also is wsock32 the correct lib that I need? 1>------ Build started: Project: bla, Configuration: ...
You should link with "ws2_32.lib" library. Specify it in project settings or in source code via pragma directive: #pragma comment(lib, "ws2_32.lib") Addition: AFAIK Visual C++ Express does not includes Platform SDK, so if you can't find library on your computer you should download and install Platform SDK and add nece...
6,913,575
6,913,658
Programatically setting the pixmap of a QLabel in Qt
The Widget we should use to show pictures is a QLabel. we can do it directly from QtCreator, by setting its pixmap property. we should first create a resource file and then add the image to that resource file. To create a Qt Resource File, we go to the menus: File > Qt > Qt Resource File. we can set the image of the QL...
The signature of the method you are trying to use is setPixmap ( const QPixmap & ) but you are passing in a pointer. Try using a value instead. QPixmap mypix (":/karim/test.png"); ui->label->setPixmap(mypix);
6,914,035
6,917,418
Setting the pixmap of a QLabel in QT framework
My problem is mainly around two UI files, Form.ui and Form1.ui: in Form i have multiple QLabels (a png pic is set by default , because we have lots of pics we can only show a small portion of them) and a button for each QLabel widget. once this button is clicked , form1 should appear with a large QLabel showing the pic...
The statement "ui->Form1" assumes that there is something in "form" called Form1 that you added in the designer. From your explanation and your code that doesn't appear to be the case. What I think you want instead is something like Form1* f= new Form1(); f->ui->labelk->setPixmap(mypix); // Setting the png to the la...
6,914,147
6,915,695
Qt's best way to display very large rich text?
I need to display very large logs that uses HTML tags for marking different types of data. Using QTextEdit and QTextBrowser really slows the application, especially on append operations. I would really like to keep the QTextEdit interface and abilities. I've seen people that implemented their own flavor of TextEdit to ...
Since your log is presumably tabular at some level, then the Model/View framework sounds like it could work for you. Perhaps you could try using a QListView with QGraphicsTextItem: http://doc.qt.nokia.com/latest/qgraphicstextitem.html It has methods for setting/getting the HTML: http://doc.qt.nokia.com/latest/qgraphic...
6,914,434
6,914,469
How to save the error output of gcc to file
When I compile my code I get a bunch of errors which I span through the screen and I can see where does the error start. How can I save the output of gcc to a file? I tried tricks like gcc > log.txt or grepping the result but it didn't work. Searching google yields mostly result on explaining how to print to file...
GCC outputs errors to the standard error stream not to the standard output stream. You need to redirect standard error, instead of standard output. In bash: gcc 2> log.txt
6,914,705
6,915,848
Sending POST data using winsock (and receiving them with PHP server side script)
So I thought I would play with HTTP a bit and try to send simple plain(not encoded) text from my program to a server. However, something is not right and I don't know what. Here is the server side PHP script, I have tested it by sending POST data from HTML form and it worked just great, so I guess there isn't anything ...
You aren't recieving the data because you aren't actually sending any data. Although buffer appears in the sprintf, there's no format specifier to consume it (only the length is formatted). Try removing the buffer from the sprintf call altogether, and then call send twice, once for the headers (as you already do) and ...
6,915,047
6,915,132
__cdecl and __declspec calling conventions confusion
I am writing a DLL for a third party application. The main software engineer mentions that the application uses the __cdecl (/Gd) calling convention. That I need to make sure that I use that. Additionally, the third party has provided to me a C++ DLL skeleton which exports the functions as follows: #ifdef _EXPORTING ...
__declspec() and __cdecl are addressing two different aspects of calling the function, and you can (and in this case by the sounds of it you should) use both. __cdecl specifies the calling convention, which specifies how parameters are passed to the function via the stack, and, very importantly, who cleans up the stack...
6,915,054
6,915,086
Is there a C++ version of ungetc?
Is there a C++ version of ungetc? That is, can I put a character back onto an istream?
Yes. istream::putback is the same as ungetc except if using unget(): You can't lie with unget(). It "ungets" the last-read character. You can lie with putback(c). You can "putback" some character other than the last-read character. Sometimes putting back a character other than the last-read character can be usef...
6,915,115
6,928,009
Compiling festival TTS C/C++ example
I tried to compile the example from here with no luck. This is the command that i used g++ festival_test.cpp -Ifestival/src/include/ -Ispeech_tools/include/ -Lfestival/src/lib/ -Lspeech_tools/lib/ -lFestival -lestools -leststring -lestbase and the errors i get festival/src/lib//libFestival.a(HTS_audio.o):HTS_audio.c:(...
Finally i got it working. I've added -lwinmm -lncurses and it compiles with no errors. g++ festival_test.cpp -Ifestival/src/include/ -Ispeech_tools/include/ -Lfestival/src/lib/ -Lspeech_tools/lib/ -lFestival -lestools -leststring -lestbase -lwinmm -lncurses
6,915,191
6,915,636
Simple IPC between C++ and Python (cross platform)
I have a C++ process running in the background that will be generating 'events' infrequently that a Python process running on the same box will need to pick up. The code on the C side needs to be as lightweight as possible. The Python side is read-only. The implementation must be cross-platform. The data being sent ...
zeromq -- and nothing else. encode the messages as strings. However, If you want to get serialiazation from a library use protobuf it will generate classes for Python and C++. You use the SerializeToString() and ParseFromString() functions on either end, and then pipe the strings via ZeroMq. Problem solved, as I doubt ...
6,915,556
6,915,660
How do objects get sent over a network transfer without invalidating header information
Does a an object have any header data that is relative to its current machine and process, and if so, how does this object transfer over a network connection without invalidating this kind of data? I know I can't directly copy the binary data of an object across a network connection to another pc/process, and the other...
A .net object can be transmitted across process boundaries in only 2 ways: Serialization and MarshalByRef. Serialization This simply takes the values of (most) fields on the object and stores them in a SerializationInfo instance. Then, your formatter of choice converts that into bytes on a Stream. This has no "header...
6,915,635
6,915,693
C code does not work when coded like C++
Hello Developers! I am learning algorithms from Algorithms Design Manual Book by Skiena. There I have the following code: #include <stdio.h> #include <stdlib.h> typedef int item_type; typedef struct{ item_type item; struct list* next; }list; void insert_list(list **l, item_type x){ list *p; p...
Your problem in both cases is in the struct definition: struct list *next doesn't refer to the struct you are in the process of declaring. Try this instead: typedef struct list { item_type item; struct list* next; } list; In addition, in C++ you must cast the void * returned by malloc to the appropriate pointe...
6,915,828
7,313,304
Cannot link to lib file after upgrading to VS10
So I imported this VS9 solution into VS10 and VS10 would convert the whole thing into its new format for solution and project files. However, now it is giving me linker errors. One project, a native C++ project, is using a set of header files and a .lib file to link to some external library. In the project, this libra...
No ,that still works in VS2010 (just tested it to make sure)!
6,915,897
6,917,260
can I mix __cdecl export calls with __stdcall import calls in a DLL?
I am writing a module for a third party application; the application uses __cdecl calling convention. At the same time, I have a legacy DLL which uses __stdcall calling convention. Can I create a wrapper that in one end exports __cdecl functions, while in the other end imports __stdcall functions? which other options ...
The DLL will typically come with a header file (.h) and an associated import library (.lib) that deal with the calling conventions, exported function prototypes etc. Simply include the header file, link to the import library, and you will be able to call the functions directly. That header file will specify that the fu...
6,915,963
6,916,027
Multiple increment operators in single statement
Possible Duplicate: Undefined Behavior and Sequence Points Pleae explain the behaviour of following statements int b=3; cout<<b++*++b<<endl; How will it be calculated?
The behavior here is undefined. See this question Relevant standard quote: §5/4.1 Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. The most common sequence point is the end of a statement. Also worth noting from the standa...
6,915,967
6,916,002
strange behavior of templated type
#include <iostream> template<typename T, int = 0> struct test { typedef char type[3]; }; template<int N> struct test<long *, N> { typedef char type[7]; }; int main() { std::cout << sizeof( test<int*>::type ) << std::endl; // 3 std::cout << sizeof( test<long*>::type ) << std::endl; // 7 return 0; ...
What you did is you specialized the template, saying that whenever the type argument is long*, you should use the second form of the template. For other arguments, it will use the initial form of the template (with size 3).
6,916,348
6,916,509
Read hex text format 0x from stream
I'm looking for a simple method to read a hex value from a text file using streams. I searched Stack Overflow using "C++ hex read stream 0x" and most of responses were about writing hex as text or reading in hex values without the "0x" prefix. This question is about reading the hex number, with "0x" prefix as a numbe...
A solution is to read the value using an unsigned int then convert to unsigned char: unsigned int value; inp >> hex >> value; unsigned char byte; byte = value & 0xFF; I guess there is something about the type unsigned char that is causing the issue. Any C++ language lawyers can quote a section that describes this be...
6,917,079
6,926,815
Tag dispatch versus static methods on partially specialised classes
Suppose I want to write a generic function void f<T>(), which does one thing if T is a POD type and another thing if T is non-POD (or any other arbitrary predicate). One way to achieve this would be to use a tag-dispatch pattern like the standard library does with iterator categories: template <bool> struct podness {};...
I would like tag dispatch because: Easy to extend with new tags Easy to use inheritance (example) It is fairly common technique in generic programming It seems tricky to me to add third variant in second example. When you'll want to add, for example non-POD-of-PODs type you'll have to replace bool in template <typena...
6,917,206
6,917,291
Speeding up transform calculations
I am programming an OpenGL3 2D Engine. Currently, I am trying to solve a bottleneck. Please hence the following output of the AMD Profiler: http://h7.abload.de/img/profilerausa.png The data was made using several thousand sprites. However, at 50.000 sprites the testapp is already unusable at 5 fps. This shows, that m...
The first thing I would do is concatenate your rotation and transform matricies into one matrix before you enter the for-loop ... that way you aren't calculating two matrix multiplications and a vector on every for-loop; instead you would only be multiplying a single vector and matrix. Secondly, you may want to look i...
6,917,230
6,917,399
How to find all references of a particular class's overloaded operator in Visual Studio?
If I have a class that contains an overloaded == operator function, how do I find out where this overloaded operator is being used throughout the code? (Other than placing a break point inside the overloaded == method and seeing if the code ever hits it.) I tried going to the class view in Visual Studio, right clicking...
Temporarily make the operator private and unimplemented. That will catch the uses when you compile.
6,917,428
6,917,471
How to determine complexity (as in CPU cycles) of C++ code with Visual Studio 2008
I often have to write code that I would like to optimize for performance, and I often have several solutions to a particular problem. Is there a simple way to determine the number of CPU cycles a particular statement/function would take? I'm not talking about complex code that access the file system, Windows APIs or th...
Using the Visual Studio prompt you can invoke cl.exe (the VC++) compiler and produce assembly listings with the option /FA[c|s|u]. cl.exe /FA mycode.c Generates a file named mycode.asm, containing the listings, looking something like: ; Line 16 push ebp mov ebp, esp ; Line 17 cmp DWORD PTR _argc$[ebp],...
6,917,520
6,917,606
Calling methods of the main program from run time loaded Dll
I have a (big and complex) C++ program with its own classes and methods.(obviously) I would like to load at runtime a dll. From the main program i want to call a function inside the dll passing a class instance , and this function will use the method of this class. In pseudo code Main program: class MyClass{ my...
It is valid and doable. Generate a sample DLL in visual C++ and the code will have all the bases covered. Replace the static linking in the client with LoadLibrary and GetProcAdress. Name mangling could be an issue, DependencyWalker will help you there. Keep a low profile with emory management. For example, if you use...
6,917,585
6,918,370
Substituting `find_if` function
I wrote a class method using STL find_if. The code is the following: void Simulator::CommunicateEvent (pEvent e) { pwEvent we (e); std::list<pEvent> l; for (uint32_t i = 0; i < m_simulatorObjects.size (); i++) { l = m_simulatorObjects[i]->ProcessEvent (we); // no action needed if list is empty if (...
From the error, it appears that you're attempting to use an anonymous type as the argument. I do not believe anonymous types are allowed to be template arguments. From the error, I believe you have something like this: class Simulator { struct { bool operator(const pEvent& p) { ... } ; } IsJustGreater; ...
6,917,607
6,917,789
C++ MFC Get current date and time
I've been programming in VB.NET for most of my very programming career. I have a C++ project provided to me, which I need to make a few modifications, and I am feeling hopelessly lost and confused. It is a Visual Studio 2008 MFC project in C++. an output variable has been defined: char szout[900]; This line below, i...
If you are using MFC, why not: // uses printf() format specifications for time CString t = CTime::GetCurrentTime().Format("%H:%M"); // Or, if you have OLE Support CString t = COleDateTime::GetCurrentTime().Format("%H:%M");
6,917,686
6,917,708
C++: map or vector for objects keyed by integers?
I am going to store some objects keyed by various numbers. Most numbers will have no objects, some will have 1, and some will have multiple. std::map<int, std::vector<MyObject>> myObjects; // or... std::vector<std::vector<MyObject>> myObjects; std::vector<MyObject> GetObjectsForNumber( int number ) { // how best t...
What you are looking for is probably the multimap, see http://www.cplusplus.com/reference/stl/multimap/. But you should point out what exactly your goals are - memory efficiency, performance? Also, how is the "distribution" of the values over the keys? If it's an important decision, you should prototype. P.S.: Don't wr...
6,917,713
6,919,137
How to step into unmanaged C++ library from my C++/CLI code
I have the following three projects in my solution: 1. C# library 2. C++/CLI managed code 3. C++ unmanaged code I did check "Enable Unmanaged Code Debugging" in my C# project, and built both C++ projects in Debug/Win32. However, I cannot step into unmanaged code - when I F11 on the call of any unmanaged method, it show...
When I've had this problem it has come from one of these things: 1) Enable unmanaged code debugging not checked. You already fixed this. 2) Built the EXE as x64 or Any CPU (they say x64 works, but it doesn't). I think you already fixed this. 3) "Just my code" being turned on sometimes causes trouble with unmanaged co...
6,917,769
6,917,815
Opposite of const - in other words, a writeonly qualifier?
I was reading Stroustrup's c++ FAQ and I noticed that, at one point, he had a writeonly qualifier in the language. After some discussion, a colleague and I could only come up with one purpose - side effects, specifically in the case of some memory mapped IO. Is there any other legitimate usage for a writeonly qualifier...
The write-only qualifier would be useful for hardware registers since reading from a write-only register would lead to undefined behavior or subtle run-time errors. You can use a #define such as #define write-only and then apply this to a register like, special_register write_only UTXBUF; There is a blog post at EE Ti...
6,917,819
6,929,646
Create a Gtk Button with an image in the background, and a label in front of it
Okay, I'm trying to create a Gtk button in C++ (gtkmm 3.0) that has an image in the background that I can change depending on state, and a label in the foreground that I can change depending on a language string. I tried extending the Gtk::EventBox class which works great for the image, but I can't put a label in it. I...
Actually you will need to invent the wheel. What you need is composition of two widgets. I know there's a implementation of someting like that in Gedit, Nautilus, and the new Gtk+ 3.1.X includes a widget that does something like that called GtkOverlay. GtkOverlay is a new container that allows to place one or more ...
6,917,832
6,918,145
Permutation of String letters: How to remove repeated permutations?
Here is a standard function to print the permutations of characters of a string: void permute(char *a, int i, int n) { int j; if (i == n) printf("%s\n", a); else { for (j = i; j < n; j++) //check till end of string { swap((a+i), (a+j)); permute(a, i+1, n); s...
Take notes which chars you swapped previously: char was[256]; /* for(j = 0; j <= 255; j++) was[j] = 0; */ bzero(was, 256); for (j = i; j <= n; j++) { if (!was[*(a+j)]) { swap((a+i), (a+j)); permute(a, i+1, n); swap((a+i), (a+j)); //backtrack was[*(a+j)] = 1; } } This has to ...
6,917,929
6,917,974
How to send a image to a client from my HTTP Server?
I am building a small http server. I am able to send html,css,xml files to the client over HTTP. But I am not able to send image files-.jpg,.png.gif. How do I send it so the browser is able to display the image. Thanks.
Send it just like any other (binary-data) file, with the correct Content-Type and Content-Length headers. Content-Type for: JPEG: image/jpeg PNG: image/png GIF: image/gif
6,918,085
9,025,950
C++: Wrapping unmanaged dll using dll export
I am using Visual Studio 2010 targeting .Net 4.0 I am working with an unmanaged C++ dll using a managed C++ wrapper. I am using _declspec(dllexport) to export the unmanaged .dll below is the header file for the unmanaged dll: class DllExport KeyManager { public: KeyManager(const char *pszKeyFileName, int thisProduct);...
This type of error is probably attributable to the Configuration Manager setup. When you set up the x64 configuration, configuration manager will often set dependant .dll's to be compiled as Win32 instead of x64. Open Configuration Manager for the solution, review the settings for each project. Verify that they will...
6,918,382
6,929,046
How to export multiple classes with a C++/CLI wrapper library for a native C++ library
I have a native C++ library (let's call it CoreLib.dll) and it exposes two classes: Core.h Atom.h I have a CLI/C++ wrapper (let's call it CoreWrapper.dll) that allows .NET projects to instantiate Core and Atom objects: CoreDotNet.h AtomDotNet.h (includes Atom.h and CoreDotNet.h) When I compile the CoreWrapper, onl...
Merely writing your code in header files doesn't cause it to be included in the project. You need to add .cpp files to the project, and #include the headers.
6,918,663
6,918,926
Generic way to handle many types of messages
I'm working on a little client that interfaces with a game server. The server sends messages to the connected client over HTTP. Its relatively easy to parse the text messages coming into the client and form responses to send back. Now what I'm trying to figure out is how to break up the process. I want to have a thread...
Basically what you're asking about is called a protocol: how data is exchanged and interpreted. Traditionally you'd define your own (and odds are they'd tend to start out rather naive -- sending plain text data with newlines to indicate the end of a command, or something like that). After a while you begin to realize t...
6,918,684
6,918,708
Preventing std::vector from resizing on push_back
I have a std::vector that I know will never have to grow--it will always have n elements (unfortunately, n isn't known at compile time so I can't use std::array). I can do: std::vector<blah> v(n); Which correctly sets its capacity to n. But when I proceed to fill v with push_back, it automatically resizes to 2n. I rea...
That constructor does not sets the capacity of the vector to n, but insteads creates a vector containing n objects constructed with blah's default constructor. This can be confusing for people with a Java or .NET background, where ArrayList and List<T> both have a constructor that sets an initial capacity. The solution...
6,918,714
6,918,765
Overloading function call operator and assignment
In a project of mine, I'm writing a wrapper for std::vector. I'm doing this because I am using homogeneous coordinates and for some operations it's just easier to temporarily 'forget' the fourth coordinate. Now I stumbled upon a problem. I have loads of assignments like the following: Vector v; v(0) = 5; v(...
Just return reference. class Vector { int data[4]; int & operator() (int index) { return data[index]; } };
6,918,737
7,208,340
WS_CPLUSPLUS with WWSAPI
I am implementing a relatively complex object model service using WWSAPI (WCF hosted) and have successfully downloaded the wsdl and code gen'd the service implementation. My question is, has anyone else noticed all of the #if defined(WS_CPLUSPLUS) defines littered throughout the generated code? Inside them is a C++ o...
Ok, answered my own question after digging through the sdk samples. Once you generate the schema and wsdl files and import them into your project do the following: Select all of the generated .c files, and right click -> properties In the [Precompiled Headers] section: Change [Precompiled Header] to "Not Using Preco...
6,918,826
6,918,872
gcc: weffc++ with Wextra and member initialization
Suppose I have a class like this: class MyClass { private: vector<MyOtherClass> myMember; public: MyClass(const YetAnotherClass& myCollection); } MyClass::MyClass(const YetAnotherClass& myCollection) { myMember = convert(myCollection); } Or, in other words, I have a class with a member tha...
You're not actually using a member initialization list in this instance. To use the member initialization list in this case, your constructor implementation would look like this: MyClass::MyClass(const YetAnotherClass &myCollection) : myMember(convert(myCollection)) { } The member initialization list is a comma separ...
6,919,134
6,919,308
Calling Python functions passed by weakref
Using Boost.Python, is there a way to call a Python function that's been passed through a weakref? The following code doesn't work: import weakref def foo(): print 'it works' def func(): return weakref.ref(foo) The following is the C++: object module = import("test"); object func(module.attr("func")); object...
From weakref documentation: Return a weak reference to object. The original object can be retrieved by calling the reference object if the referent is still alive... So, given your snippet: import weakref def foo(): print "It Works!" def func(): return weakref.ref(foo) ref = func() # func returns the refer...
6,919,192
6,919,295
c++ STL copy_backward question
int main () { vector<int> myvector; vector<int>::iterator it; // set some values: for (int i=1; i<=5; i++) myvector.push_back(i*10); // myvector: 10 20 30 40 50 myvector.resize(myvector.size()+3); // allocate space for 3 more elements copy_backward ( myvector.begin(), myvector.begin()+5, my...
That output looks right to me according to the way the code is written. You are copying from and into the same vector. You are copying from [begin, begin +5] (10 20 30 40 50) and you are copying to [end, end-5]. So 10 20 30 [10 20 30 40 50] is the right output for that code. The first 3 elements are untouched.
6,919,204
6,919,339
C++: Correct implementation for passing a std::string to a C function that wants to change the string?
I have a function in a third-party library written in C: char* fix_filename_slashes(char* path). This function expects a mutable C-string passed to it so it can change all the slashes in the path to the correct use based on the operating system. All the strings I'm using in my Facade are declared as std::strings. I att...
If the string length does not change, you can use a pointer to the first character of the string. This is undefined behavior in the C++03 standard, but all known implementations work properly and it is explicitly allowed under the C++11 standard. fix_filename_slashes(&filename[0]); If the size of the string may change...
6,919,330
6,919,372
return "this" in C++?
In Java you can simply return this to get the current object. How do you do this in C++? Java: class MyClass { MyClass example() { return this; } }
Well, first off, you can't return anything from a void-returning function. There are three ways to return something which provides access to the current object: by pointer, by reference, and by value. class myclass { public: // Return by pointer needs const and non-const versions myclass* ReturnPointerToCu...
6,919,380
6,919,412
Pointer vs Variable speed in C++
At a job interview I was asked the question "In C++ how do you access a variable faster, though the normal variable identifier or though a pointer". I must say I did not have a good technical answer to the question so I took a wild guess. I said that access time will probably be that same as normal variable/identifier ...
A variable does not have to live in main memory. Depending on the circumstances, the compiler can store it in a register for all or part of its life, and accessing a register is much faster than accessing RAM.
6,919,534
6,919,586
Problem linking to boost_thread
I'm trying to link with boost 1.47 on xubuntu with gcc4.6 and glibc 2.13. So far I can't compile the following simple program, main.cpp: #include <cstdlib> #include <boost/ref.hpp> #include <boost/thread.hpp> int main() { size_t n_threads = boost::thread::hardware_concurrency(); return 0; } when I compile with...
Try moving the "-lpthread" to be the last argument to the linker. See this link
6,919,593
6,919,630
Is cout guaranteed available during static deinitialization?
I've got a quasi-singleton class (quasi-singleton in that most use refers to a single object that is a function static, but users can also construct their own local copy for short-term use) that I would like to have write to cout from its destructor, and wanted to know if cout was guaranteed to be available during the ...
Short Answer: Yes Long Answer: Yes There are a couple of tricks that the standard library uses to make sure that std::cout (and std::cin/std:cerr) are available before any other objects (But you must #include <iostream> in the translation unit). Because they are created first (the reverse order of destruction rule guar...
6,919,698
6,919,756
Why can I pass a "C string" to a function expecting a std::string and it works?
I have a method: void Foo::Bar(const std::string &str) { printf("%d", str.length()); } and it works seamlessly when I do foo.Bar("hello"); I thought "hello" was a const char *, not a std::string?
There are two ways user-defined types can be implicitly converted: With a conversion constructor (e.g. "std::string::string(const char* c_string)"). With a conversion operator (e.g. "OldType::operator NewType() const"). Any constructor that takes a single parameter and does not use the keyword "explicit" defines an ...
6,919,766
6,919,870
Which algorithms require functors to be pure functions?
Generally the standard requires functors to be pure functions because algorithms are allowed to copy their functors to their heart's content. However, there are some algorithms (e.g. find_if) for which no sane implementation would be doing any form of functor copying. Can we rely on this?
I think what you're trying to ask is which functors need to be stateless due to being copied at arbitrary times. I can't think of any algorithms that require free functions to be used, but most/all certainly require the object itself to not hold state. What you can do is have the object have a reference to a state obje...
6,920,202
6,920,220
Reading a file without reading the whole thing into memory
I am trying to read an extremely large text file. I want to write a program (C++) to read it line by line until I reach a certain set of characters, then begin to write the following text into a string until it reaches another set of characters. It is a XML file, so I'm looking at <flag>info</flag> I need my program t...
Use an XML SAX parser such as Xerces; they will allow you to parse the XML file in a streaming fashion, so you don't need to load it into memory all at once. Reading line-by-line will not give you correct results on general XML files.
6,920,329
6,920,390
Is QtCore too 'heavy' for server-side use?
I am looking into writing a self contained http server using Qt libraries, although many people have the view that QtCore is too bloated and that the overhead would be too large. Would a QtCore http server manage a load of about 50 concurrent connections, using a thread pool. The QtCore library is dynamically linked on...
There is no reason that one could not write a server with Qt, however, there is really no way to tell beforehand whether the performance will be what you want (depends on what your server does). Note that the optimal number of concurrent threads is typically dependent on the number of hardware cores, as well as the lev...
6,920,497
6,920,559
Boost::unordered_map with initialization list?
Is it possible to initialize a boost::unordered_map with a initialization list? -Weffc++ requires it. I can't use a method to initialize it because I only fill the map after some processing inside the constructor. I could create an empty map inside a method and return it, but that doesn't sound like a good idea to me. ...
Just default-construct the member variable in the initialization list: struct S { boost::unordered_map<int, int> m; S() : m() { } }; This is enough to make -Weffc++ shut up.
6,920,917
6,921,050
C++ "Best" Parameter Passing Method
I was coding up a C++ class today, and I wrote a function that took an argument as a reference rather than a pointer, something I rarely ever do. I've always passed by pointers. So I was about to change it back, and then I realized - I have no idea if I should, or if it even matters. So I turn to you guys. I have th...
I would suggest to pass your argument by reference if it is expected to be valid. This would be a by-design optimization and save you from defensive programming. Reference cannot be null while pointer can. If you are dealing with pointer, you will need to verify whether given pointer is valid (non-null) regardless it i...
6,920,959
6,920,970
Store data of different types into a vector<char>?
I'm trying to write a generic function that casts and stores arguments of different data types into a vector<char>. By casting I mean that the bit representation is preserved within the vector of characters. For instance a 4 byte int such as 0x19a4f607 will be stored in the vector as vc[0] = 0x19, vc[1] = 0xa4, vc[2] =...
You need an iterator that is capable of inserting at the end of the vector; .begin() and .end() are only capable of modifying existing elements. Try std::back_inserter(vc).
6,921,013
6,921,180
Possible causes of pthread_cond_wait()'s not releasing a mutex?
My program is seemingly having a deadlock problem. Basically I have a class that looks like this: class Foo { public: Foo(); void bar(); private: void monitor(); bool condition_; pthread_t monitor_; pthread_mutex_t mutex_; pthread_cond_t cv_; }; In Foo's constructor, I invoke monitor() in a separate t...
I would look at your constructor and the bar() function, and possibly if you've accidentally made a copy of the object in question. I've copied the classes you provided, and my assumptions on how the rest of it operates below. The program below wakes up every second, and signals the thread. #include <pthread.h> #incl...