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
2,148,921
2,149,775
Best way to comparing perormance of different version of library
Currently for each call in library,I am doing multiple iteration , Measuring time taken for each call and then calculating : Average time taken for each call Min time take Max time taken Standard Deviation But it seems its not a good method . As these time depends upon state of machine ,As if CPU is busy with other process result will be impacted. Please suggest me still if its a good way.Or i can use some better method.
It is a good measure of the basic speed of the algorithm but finding total performance is dependent on how you use something. The number of instructions is not useful, either. For example, say you have some func doMath() written in C, and some templated doMath call that takes 3-4 templated arguments. The C func will often show worse performance in a simple case. However, in a medium to large program the templates will grow to dozens or hundreds or even thousands instead of just one. This will choke out the instruction cache. Same applies for data - some tree implementations will have much more memory efficiency and the more bloated ones will perform better on simple tests, but in actual use they will perform much more poorly. Similarly, it may seem like a tree has performance through basic tests, but you could find over time it fragments the memory so much that performance drops and drops over time until your program barely functions. So, performance always depends on your actual use of something, not just its implementation. Not to say it's always a tradeoff, some implementations are better than others. Ultimately, though, the only way to get great performance is to know to a deep level exactly what the computer is doing and exactly what the compiler generates out or else it will always be a mystery to you. That's part of why people suggest profiling, but profiling will only tell you so much, basically point the way. You will see the symptoms but often not the cause. That's because performance is based on the whole system and it's not just a simple matter of adding up the instruction count.
2,148,967
2,149,077
Using a C++ child class instance as a default parameter?
So I have a couple classes defined thusly: class StatLogger { public: StatLogger(); ~StatLogger(); bool open(<parameters>); private: <minutiae> }; And a child class that descends from it to implement a null object pattern (unopened it's its own null object) class NullStatLogger : public StatLogger { public: NullStatLogger() : StatLogger() {} }; Then I have a third class that I want to take an optional logger instance in its constructor: class ThirdClass { public: ThirdClass(StatLogger& logger=NullStatLogger()); }; My problem is when I do it as above, I get: error: default argument for parameter of type ‘StatLogger&’ has type ‘NullStatLogger’ And if I put an explicit cast in the definition, I get: error: no matching function for call to ‘StatLogger::StatLogger(NullStatLogger) Complaining about not having a constructor from a NullStatLogger even though it's a child class. What am I doing wrong here, is this allowed in C++?
I you want to use inheritance and polymorphism, ThirdClass needs to use either a pointer or a reference to StatLogger object, not with an actual object. Likewise, under the circumstances you almost certainly need to make StatLogger::~StatLogger() virtual. For example, modified as follows, the code should compile cleanly: class StatLogger { public: StatLogger(); virtual ~StatLogger(); // bool open(<parameters>); private: // <minutiae> }; class NullStatLogger : public StatLogger { public: NullStatLogger() : StatLogger() {} }; class ThirdClass { StatLogger *log; public: ThirdClass(StatLogger *logger=new NullStatLogger()) : log(logger) {} }; Edit: If you prefer a reference, the code looks something like this: class StatLogger { public: StatLogger(); virtual ~StatLogger(); // bool open(<parameters>); private: // <minutiae> }; class NullStatLogger : public StatLogger { public: NullStatLogger() : StatLogger() {} }; class ThirdClass { StatLogger &log; public: ThirdClass(StatLogger &logger=*new NullStatLogger()) : log(logger) {} };
2,148,970
2,149,074
Inheriting from a container with non-virtual destructor
I'm trying to use forward declarations and d-pointers to eliminate some include dependencies. Everything is working well, except that I have used XList typedefs for readability in many places (e.g: typedef QList<X> XList). The workaround for the typedef forward declaration issue is to use inheritance: class XList : public QList<X>{};. QList has a non-virtual destructor. Given the fact that Qt's own QStringList inherits QList<QString> and I'm not allocating XLists on the heap, do you see any problems with this workaround? Should I explicitly disallow heap allocations for the XList classes?
Let's have a look at what will happen if we define XList this way: class XList : public QList<X> {}; The following will work as expected: XList* x = new XList; delete x; However the following won't: QList<X>* q = new XList; delete q; QList<X>'s destructor will be called but not XList's, if any. That's what a virtual destructor in the base class will do for you. If you never use heap allocations you should be fine, but you're preparing a trap for the maintainer following you (or even yourself in a few months). Make sure this assumption is documented and make XList's new operator private to prevent heap instantiation as you mentioned. The safe alternative would be making QList<X> a member of your XList, that is: prefer encapsulation to inheritance.
2,149,475
2,149,509
Segmentation fault depending on string length?
I am writing a program that will read lines from an infile using getline into strings, convert the strings to c-strings containing the first m nonwhitespace characters of the string, then concatenate the c-strings into a single char array. A sample file might look something like this: 5 //number of rows and columns in a grid 2 //number of grids XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX XXXXX So I'd end up with a char array of 2x5x5 characters. Now the problem is my code works fine on smaller test cases like the one shown above, but segmentation faults when I try it on bigger grids (i.e. 100x100x100). #include <iostream> #include <string> using namespace std; int main(){ int mapsize,levels; cin>>mapsize; cin>>levels; char map[mapsize*mapsize*levels]; string input; for (int i=0;i<levels;i++){ for (int j=0;j<mapsize;j++){ getline(cin,input); char *row; row=new char[input.size()+1]; strcpy(row, input.c_str()); for (int k=0;k<mapsize;k++){ map[i*mapsize*mapsize+j*mapsize+k]=row[k]; } delete [] row; } } return 0; } I'd call this program with an infile: ./program < infile.in I've run it using gdb and did backtrace. It always points to the line "string input;" Any ideas how I can resolve this segfault? Thanks
map is a VLA, allocated on the stack, so I'd guess that your problem is that you get a stack overflow. gdb points a the construction of input because that's the first thing that gets constructed on this overflowed stack.
2,149,529
2,150,186
Newbie C++ question about functions and error checking
Am working on a small problem and have spent quite a few hours trying to figure out what I did wrong. Using Dev++ compiler which at times has some cryptic error messages. I tried to make the Volume calculation a function and got it to work but I have 2 small nits. Will work on error checking after I resolve this. With the function added, for some reason with dev++ now, the program does not pause (press any key to continue). Volume is coming up with blank instead of a number. Thanks PC // The purpose of this program is to determine the Volume of a // square-based pyramid after the user inputs the Area and // the Height. #include <iostream> #include <iomanip> using namespace std; double calcvolume(double a, double h) { double volume; volume = ( a * h ) / 3; return (volume); } int main() { double area, height, volume; // declare variables cout << "Please enter the Area of the Square-based pyramid:"; // requests users input cin >> area; // assigns user input to area cout << "Please enter the Height of the Square-based pyramid:"; // requests user input cin >> height; // assigns user input to height cout << "Area= " << area << "\n"; // Prints user input for area cout << "Height= " << height << "\n"; calcvolume(area,height); cout << "Volume= " << fixed << showpoint << setprecision(2) << volume << "\n"; // Prints resolution to the formula stored in volume system("pause"); // forces DOS window to pause to allow user to utilize program return 0; }
Your updated code looks correct, but you aren't storing the calcvolume return value. The volume variable you declare in calcvolume is different than the one you declare in main. Each of these variables can only be referenced from within the function it is declared in. In order to save the volume, calcvolume(area,height); should be volume = calcvolume(area,height); This will store the value being returned from calcvolume in the volume variable in your main function.
2,149,554
2,149,578
Removal of elements during iteration through a list - safety
I was wondering if something like this is safe... // Iterating through a <list> while ( iter != seq.end()) { if ( test ) { iter = seq.erase( iter ); } else { ++iter; } I know that iterating through a vector in this way would invalidate the iterator, but would the same thing occur in a list? I assume not since a list is sequential through pointers rather than being "next" to each other in memory, but any reassurance would be helpful.
This is just fine because the erase method returns a new valid iterator.
2,149,774
2,150,016
Template deduction in dynamic_cast
I have a class that is defined as the following: template <class WidgetType> class CometWidget : public WidgetType; Inside a function I am doing this: dynamic_cast<CometWidget *>(iter2->second.second)->changesCommited_(); and it resolves the CometWidget type, complies and run correctly. The code runs inside the CometWidget class. How on earth does this happen? Why is that so? Should it even compile?
If it's inside the declaration of CometWidget then you don't need to explicitly qualify the template (or whatever term you use to say CometWidget<...>).
2,149,903
10,560,763
Strange QT application behavior
I'm developing a QT application with QTCreator (and QT 4.5.3) on Arch Linux. I'm using KDE 4.3 The project is basically a GUI that let you insert a url and make some web requests to give the user some data back. The web requests are asynchronous. I've encountered a weird problem. If I start the application the first time and click on the button that launches the web requests, it crashes. On the second time it works as expected. The third and the fourth time it returns just one of the 900 values I was expecting. What's strange is that on Windows (and QT 4.6) is working always fine.. Have you ever seen such a thing? Thanks in advance for your information Best regards
The problem was related to an array of elements which weren't set in time
2,149,968
2,150,073
How can I profile a complete C++ build?
I'm developing an application in C++ on Windows XP, using Eclipse as my IDE, and a Makefile-based build system (with custom tools to generate the Makefiles). In addition, I'm using LZZ, which allows me to write a single file, which then gets split into a header and an implementation file. I'm using TDM's port of GCC 4. What tools or techniques could I use to determine exactly how much time each part of the build process takes, and why it is slow? Of particular interest would be: How much time does make need to figure out to parse the Makefiles, figure out the dependencies, check the timestamps, etc? How much time does Eclipse need before and after the build? How much time does GCC spend on parsing system and boost headers? P.S.: This is my home project, so expensive tools are out of reach for me, but could be documented here anyway if they are particularly relevant.
Since Make and GCC are very verbose about what they're doing, a very crude way to get a high-level overview of time spent is to pipe make's output through a script that timestamps each line: make | perl -MTime::HiRes -pe "printf '%.5f ', Time::HiRes::time()" (I'm using ActivePerl to do this, but from what I gather, Strawberry Perl may now be the recommended Perl version for Windows.) Reformat or process the timestamps to your liking. To get more details about GCC in particular, use the --time-report option. To find out how much overhead Eclipse adds, use a stopwatch to time builds from Eclipse and from the command line.
2,150,192
41,306,206
How to avoid code duplication implementing const and non-const iterators?
I'm implementing a custom container with an STL-like interface. I have to provide a regular iterator and a const iterator. Most of the code for the two versions of the iterators is identical . How can I avoid this duplication? For example, my container class is Foo, and I'm implementating FooIterator and FooConstIterator. Both of the iterators have to provide methods like operator++() which are identical. My question is similar to How do I remove code duplication between similar const and non-const member functions?, but the answer to that one is specific to const and non-const methods, especially accessors. I don't see how that might generalize to the iterator problem. Should I have FooIterator derive from FooConstIterator and extend it with additional non-const methods? That either leads to virtual methods or method hiding, which seem inappropriate here. Perhaps FooIterator should contain a FooConstIterator. Although that approach does reduce implementation duplication, it seems to re-introduce a lot of boilerplate method definitions. Is there clever template technique for generating the two iterators from a single definition? Or perhaps there's a way to--shudder--use the preprocessor to stamp out these nearly identical classes. I've tried looking at my local STL implementation to see how it handle this. There are so many helper classes that I'm having trouble grokking the design, but it looks like the functionality is simply duplicated. In previous projects, my custom container was built on top of a standard STL container, so I didn't have to provide my own iterators. That's not an option in this case.
[The best answer was, unfortunately, deleted by a moderator because it was a link-only answer. I understand why link-only answers are discouraged; deleting it, however, has robbed future seekers of very useful information. The link has remained stable for more than seven years and continues to work at the time of this writing.] I strongly recommend the original Dr. Dobb's Journal article by Matt Austern entitled "The Standard Librarian: Defining Iterators and Const Iterators", January 2001. Should that link go bad, now that Dr. Dobb's has ceased operating, it's also available here. To prevent this replacement answer from being deleted, I will summarize the solution. The idea is to implement the iterator once as a template that takes an extra template parameter, a boolean that says whether or not this is the const version. Anywhere in the implementation where the const and non-const versions differ, you use a template mechanism to select the correct code. Matt Austern's mechanism was called choose. It looked like this: template <bool flag, class IsTrue, class IsFalse> struct choose; template <class IsTrue, class IsFalse> struct choose<true, IsTrue, IsFalse> { typedef IsTrue type; }; template <class IsTrue, class IsFalse> struct choose<false, IsTrue, IsFalse> { typedef IsFalse type; }; If you had separate implementations for const and non-const iterators, then the const implementation would include typedefs like this: typedef const T &reference; typedef const T *pointer; and the non-const implementation would have: typedef T &reference; typedef T *pointer; But with choose, you can have a single implementation that selects based on the extra template parameter: typedef typename choose<is_const, const T &, T &>::type reference; typedef typename choose<is_const, const T *, T *>::type pointer; By using the typedefs for the underlying types, all the iterator methods can have an identical implementation. See Matt Austern's complete example.
2,150,323
2,150,353
Is it possible to cout to terminal while redirecting cout to outfile?
I'm running a program and redirecting cout to an outfile, like so: ./program < infile.in > outfile.o I want to be able to read in an option ('-h' or '--help') from the command line and output a help message to the terminal. Is there a way I can do this but still have the regular cout from the rest of the program go to the outfile? Would cout be the right object to use for such a thing?
You should use cerr to output your help message to STDERR, which is not included in your redirection to outfile.o. Given ./program < infile.in > outfile.o: cout << "This writes to STDOUT, and gets redirected to outfile."; cerr << "This doesn't get redirected, and displays on screen."; If, later on, you want to redirect both STDOUT and STDERR, you can do ./program < infile.in &> outfile.o If you want to redirect only STDERR, but allow STDOUT to display, use ./program < infile.in 2> outfile.o Bash redirection is more complex than most people realize, and often everything except the simplest form (">") gets overlooked.
2,150,618
2,150,676
how do I fix this c++ typelist template compile error?
(from reading chapter 3 of modern c++ design) typelist.hpp: class NullType {}; struct EmptyType {}; template <class T, class U> struct Typelist { typedef T Head; typedef U Tail; }; #define TYPELIST_1(T1) Typelist<T1, NullType> #define TYPELIST_2(T1, T2) Typelist<T1, TYPELIST_1(T2) > #define TYPELIST_3(T1, T2, T3) Typelist<T1, TYPELIST_2(T2, T3) > #define TYPELIST_4(T1, T2, T3, T4) Typelist<T1, TYPELIST_3(T2, T3, T4) > #define TYPELIST_5(T1, T2, T3, T4, T5) Typelist<T1, TYPELIST_4(T2, T3, T4, T5) > #define TYPELIST_6(T1, T2, T3, T4, T5, T6) Typelist<T1, TYPELIST_5(T2, T3, T4, T5, T6) > namespace TL { template <class TList> struct Length; template <> struct Length<NullType> { enum { value = 0 }; }; template <class T, class U> struct Length< Typelist<T, U> > { enum { value = 1 + Length<U>::value }; }; template <class Head, class Tail> struct TypeAt<Typelist<Head, Tail>, 0> { typedef Head Result; }; template <class Head, class Tail, unsigned int i> struct TypeAt<Typelist<Head, Tail>, i> { typedef typename TypeAt<Tail, i-1>::Result Result; }; } main.cpp #include "typelist.hpp" Typelist<int, double> foo; int main() { } g++ main.cpp typelist.hpp:37: error: ‘TypeAt’ is not a template typelist.hpp:43: error: type/value mismatch at argument 2 in template parameter list for ‘template<class Head, class Tail> struct TL::TypeAt’ typelist.hpp:43: error: expected a type, got ‘i’ Why do I get this error? How do I fix this?
Looks like you're missing a forward declaration. This is a partial specialization: template <class Head, class Tail> struct TypeAt<Typelist<Head, Tail>, 0> But the compiler has no idea what it's a specialization of. Add this before it: template <class List, unsigned Index> struct TypeAt; This let's the compiler know: "There is a class TypeAt which has two template parameters." So now when you specialize it, the compiler knows what class you're talking about. Note, your usage of Typelist is incorrect. These algorithm's are sentinel-terminated. This means, like C-strings, they expect the data to be concluded with a special value. In our case, this is NullType. So, take Éric's advice. (i.e. hint: if you found his answer helpful, up-vote it.)
2,150,655
2,150,717
When you make a file read-only via Properties, can your program write directly to that file?
I'm wondering whether making files read-only so the user can't mess with them will disallow my program from writing information to them via an fstream.
Yes. If a file is read-only, it's read-only. Why not unset the read-only bit, write to the file, and reset it? The lock that you get on the file while writing to it should prevent users from making modifications to it while your application is writing to it. However, IMHO, the whole exercise is pointless, since it takes exactly 4 clicks to make a file writable, so your users can change the file whenever they want anyway. What I'd do is make an md5 or sha1 hash of the file, store it in the registry and check to see if that's changed on application startup.
2,150,902
2,150,934
how to write a c++ template that gives the maximum of two args?
Both arguments are guaranteed to be integers. How do I write myMax such that: myMax<1, 2>; // 2 myMax<3, 2>; // 3 ? I want this to be evaluated at compile time, not run time. (Need to then use this with sizeof for a typelist to allocate space for a variant.) Thanks!
template <int x, int y> struct myMax { static const int value = (x > y) ? x : y; }; If you are going to be using it only with sizes, you can use std::size_t instead of int.
2,150,946
2,151,001
C++ optimise class template function when template parameters identical
I've got a template class with a template method within it, giving two template parameters T and U. The operation is quite expensive and is showing up in profiling to be a major use of CPU time. I could optimise it somewhat, but only for the case where T == U (which is fairly common), however I'm not sure on the syntax for doing this... The class and method in question look like this: template<typename T>class Foo { public: ... template<typename U>U bar()const; }; Foo::bar is generally called from some other template code, so even if I created a separate method (e.g. "T fastBar()const") I don't know how id go about making the other template code call that version where possible... I tried to create an explicit specialisation for T == U, but VC9 gave me errors template<typename T>template<>T Foo<T>::bar<T>()const error C2768: 'Foo::bar' : illegal use of explicit template arguments
So there's some weird things about explicit specialisation of template members of templated classes. See this question. One work around is to use a helper class template< typename T, typename U> struct FooDispatchHelper { static U dispatch( const Foo<T> * f ) { return f->template bar_internal<U>(); } }; template< typename T > struct FooDispatchHelper<T,T> { static T dispatch( const Foo<T> * f ) { return f->bar_fast(); } }; template<typename T>class Foo { public: ... template<typename U>U bar() const { return FooDispatchHelper<T,U>::dispatch( this ); } template<typename U> U bar_internal() const; T bar_fast() const; }; A more complete examnple can be found here
2,151,216
2,151,386
Qt4: Read Default mimeData from QAbstractTableModel
By default, the QAbstractTableModel class has a mimeData() function that returns a QMimeData object which has it's data set as an encoded QModelIndexList (see here). I would like to unpack this data in an overloaded dropMimeData() function, but can't figure out how to convert this QMimeData back into a QModelIndexList. I tried the obvious: bool myTableModel::dropMimeData(const QMimeData * mimeData, Qt::DropAction action, int row, int column, const QModelIndex & parent) { QStringList formats = mimeData->formats(); QByteArray encodedData = mimeData->data(formats[0]); QDataStream stream(&encodedData, QIODevice::ReadOnly); QModelIndexList list; stream >> index; } but get the error: no match for ‘operator>>’ in ‘stream >> ((myTableModel*)this)->QAbstractTableModel::index’ because there is no >> operator for QModelIndex. Note: this question is a much more focused version of this one. Sorry if this breaks SO ettiquete, I'm a bit new here.
Got it, thanks to Kaleb Peterson at the old question's link: bool ObjectAnimation::dropMimeData(const QMimeData * data, Qt::DropAction action, int row, int column, const QModelIndex & parent) { QStringList formats = data->formats(); QByteArray encodedData = data->data(formats[0]); QDataStream stream(&encodedData, QIODevice::ReadOnly); int row, column; stream >> row >> column; qDebug() << "row: " << row << " column:" << column; return false; }
2,151,258
2,158,261
How to structure an application framework
I want to write something that will take care of: If possible the int main() loop, as in, I want the code for the main function located in this file Some mundane tasks like creating windows, initializing various things like opengl, opencv and what not. Various "events" (I quote because I what the c++ concept of events is) for things like keyboard and mouse events. Provide access to pertinent member variables like the hDC. I would like to put this code in one file that I can just drop into a new project and then have something like an App.cpp that can respond to the Events as it chooses, without requiring it to handle all of them. My background is in c#, and I am just beginning c++. I fear that I might not have articulated by question well, but any help would be appreciated. Edit: I am not looking for a prefab solution. I am not too hung up on it being one file. I am interested in the mechanics of how to actually create the framework. I am not at all concerned with cross platform compatibility
I am answering my question here, but I am very interesting in hearing thoughts about this setup. The idea is that I have my framework located in a class in MyApp.cpp (i am ignoring the header files for brevity) The application constructs its main() method initializes an instance of MyApp. Wires up some events (These arent what I would call events in the C# sense of the word because you can only have one "subscriber" here, but in this case it doesnt matter) and then call the Run method on the app instance. The App object is then responsible for constructing whatever mundane stuff like windows. It gets the message pump going and calls the "events" as appropriate. This way the app can be responsible for all the humdrum stuff and hide it away from view. Main.cpp #include <iostream> #include <string> #include "MyApp.cpp" using namespace std; MyApp app; void DataReceived(string txt) { cout << app.SomeSetting << ": " << txt << "\n"; } int main(void) { //Initialize events and what not. app.OnDataReceived = DataReceived; app.Run(); //Run the app cout << "Goodbye\n"; return 0; } MyApp.cpp #include <iostream> using namespace std; //Event signatures typedef void (*DataReceivedEvent)(string); class MyApp { public: //Events DataReceivedEvent OnDataReceived; //Settings int SomeSetting; void Run() { SomeSetting = 123; //Main loop int input; bool isRunning = true; while(isRunning) { cout << "Enter a command: "; cin >> input; switch (input) { case 0: isRunning = false; break; case 1: OnDataReceived("Command 1"); break; default: cout << "What???\n"; } } } };
2,151,302
2,151,353
Counting digits in a float
I am following some beginner tutorials for OpenGL in c++ but as I started off as a c# programmer it has made me take a lot of things for granted. So my problem occurred when I was debug printing my FPS reading to the output. I think the method was something like DebugPrintString off the top of my head which took a char* and basically i was printing "FPS: x". I was using scanf_s to place the fps value into the character array but this is where my problem lies. How big does the character array have to be? Let me elaborate a bit more: my FPS reading is stored as a float as the frames/seconds usually ends up not being a nice number. So my number could be 60, or it could be 59.12345. 60 would only need 2 bytes and 59.12345 would need 8 (1 for the period). So I thought "Oh ok i need to count the amount of digits it has, no problem!" Boy was I in for a shock. I made a method to count the digits, counting the left hand side of the decimal place was easy, just first of all cast it as a int to remove the decimal points and divide by 10 (actually I think I had some bitshifting there) and count the amount of times i can do that until i reach 0. And now to count the digits on the right hand side, well i'll just multiply by 10, subtract the digit, and do this until it reaches zero. The method would usually return 32 i think it was. So i WTF'd and had a look at it in debug, turns out when you multiply the float effectively moving the digit columns up because of the well known precision issue it just appended another digit! I did some major googling, but couldn't really find anything above char str[128] and scanf if in then do strlen(str) minus 1 (null terminator). But i was hoping for a more elegant solution. In the end i just casted it as an int and allowed enough for 9999 fps, also added a check to see if the fps > 9999 but I don't think thats ever going to happen. Better safe than SEG FAULT :( TLDR: Is there a way to get the amount of digits in a float? How does scanf do it?! Sorry for long post, just wanted to share my frustation >:D Edit: spelling errors
Considering it's C++ we're talking about, why not go the STL way? Precision 5 places after decimal dot, may be variable amount of characters: std::stringstream ss; ss << std::setprecision (5) << std::fixed << f; std::string fps = ss.str(); Precision maximum 5 significant digits: std::stringstream ss; ss << std::setprecision (5) << f; std::string fps = ss.str();
2,151,305
2,151,321
gcc: warning: large integer implicitly truncated to unsigned type
#include<stdio.h> int main() { unsigned char c; c = 300; printf("%d",c); return 0; } Is the output in any way predictable or its undefined??
Sorry for the first answer, here is an explanation from the C++ standards :) Is the output in any way predictable or its undefined?? It is predictable. There are two points to look after in this code: First, the assignment of value that the type unsigned char can't hold: unsigned char c; c = 300; 3.9.1 Fundamental types (Page 54) Unsigned integers, declared unsigned, shall obey the laws of arithmetic modulo 2n where n is the number of bits in the value representation of that particular size of integer.41) ... 41) This implies that unsigned arithmetic does not overflow because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting unsigned integer type. Basically: c = 300 % (std::numeric_limits<unsigned char>::max() + 1); Second, passing %d in the format string of printf to print unsigned char variable. This one ysth got it right ;) There is no undefined behavior, because a promotional conversion from unsigned char to int happens in the case of variadic arguments! Note: that the second part of the answer is a rephrasing of what have been said in the comments of this answer but it is not my answer originally.
2,151,549
2,174,604
How to prevent an icon being highlighted?
I have a listwidget with items which have icons. When the item is selected both the text and the icon are highlighted. My problem is that when the icon is highlighted it just goes entirely black because I'm using only two colours. Is there a way to prevent the icon from being selected?
Best solution was to make your own qstyle which handled the painting of the backgrounds of listitem sub controls and draw the icons qrect as white
2,151,567
2,151,606
Eclipse: C/C++ Plugin Download Link?
I'm downloaded the Java EE version of Eclipse 3.5.1. Can I now use it to edit C/C++ with the proper plugin? I went to Help >> Install New Software but I don't know which URL to use to get the C/C++ plugin. I can't find it on the Eclipse website either.
http://www.eclipse.org/downloads/ May be you need to download C/C++ IDE.
2,151,662
2,151,702
Can you make a call to a C++ Application from MS SQL Server?
Is it possible to make a call/notification to a C++ application from Microsoft SQL Server? To give a broader understanding of what I'm trying to achieve: our database is being updated with new information; Whenever a new piece of information is received, we'd like to push this to the C++ application so that its dashboard reflects up-to-date data for the user. We know we can do this by having the C++ application polling the database but I see this as inefficient architecture and would like to have SQL push the information or a notification to C++. Any light shed on this area is greatly appreciated! ----- 28th Jan 3:40pm ---- OK After some reading around on Service Broker External Activation it seems like the right technology to use; however it seems to technology that's introduced in SQL Server 2008; and unfortunately we're using SQL Server 2005. Are there any other suggestive technologies or architectural designs we could use?
You might want to look in to using the Service Broker and handling the events it queues. Here's MSDN: http://msdn.microsoft.com/en-us/sqlserver/cc511479.aspx
2,151,719
2,151,735
Is it possible to make a call to a C# application from a C++ application?
I'm a programming student, and I've now had two classes in C#, this semester I'm taking my first C++ class. Out of curiosity, is it possible to call a C# application from a C++ application? If so, is it also possible to check if the computer running the program has the .NET framework? I'm just curious, and I think if its possible, it would be a great little program to write and have as a tool for the future. Just for your information, here's what I'd like to do: Check to see if .NET framework is installed on the computer If it's not, ask the user if they would like to install it, and if they would, proceed to download and install the framework Call my program written in C# and then kill the C++ program
Out of curiosity, is it possible to call a C# application from a C++ application? Yes. There are a few options here. If you use C++/CLI, you can use types defined in C# directly from within C++. Otherwise, a typical approach is to use COM, esposing your C# types as COM objects. If so, is it also possible to check if the computer running the program has the .NET framework? Yes. Here, typically, you'd just install the framework along with your application. Here's a page that shows a few options for checking which version of .NET (if any) is installed.
2,151,789
2,151,805
What's the difference between managed C++ and C#?
The major advantage I see for using C++ instead of C# is compiling to native code, so we get better performance. C# is easier, but compiles to managed code. Why would anyone use managed C++ for? What advantages it gives us?
Managed C++ and C++/CLI allow you to easily write managed code that interacts with native C++. This is especially useful when migrating an existing system to .Net and when working in scientific contexts with calculations that must be run in C++.
2,151,831
2,151,876
non-integral constants
I want a header file with a non-integral constant in it, e.g. a class. Note the constant does not need to be a compile-time constant. static const std::string Ten = "10"; This compiles but is undesirable as each compilation unit now has its own copy of Ten. const std::string Ten = "10"; This will compile but will fail with a linker error for multiply defined Ten. constexpr std::string Ten = "10"s; This would work but only if the strings constructor was constexpr as well. It will be but I can't count on every non-integral constant to have a constexpr constructor ... or can I? extern const std::string Ten = "10"; This seems to work but I'm afraid I'll get a linker error if I breath on it wrong. inline const std::string Ten( ) { return "10"; } This has everything I want except a clean syntax. Plus now I have to refer the constant as a function call, Ten(). inline const std::string = "10"; This seems to be the ideal solution. Of course inline variables aren't allowed by the standard. Is there something in the c++ standard that says the extern version should work or am I just lucky it works with GCC? Is there a compelling reason not to allow inline variables? Is there a better way with c++03 or will there be a better way in c++0x?
You seem to have them mixed up. You are right about static const std::string Ten = "10"; version. It will "work", but it will create a separate object in each translation unit. The version without static will have the same effect. It won't produce linker errors, but will define a separate object in each translation unit. In C++ language const objects have internal linkage by default, meaning that const std::string Ten = "10"; // `static` is optional is exactly equivalent to the previous version with static. The version with extern and initializer extern const std::string Ten = "10"; // it's a definition! will produce a definition of an object with external linkage (it is a definition because of the presence of an initializer). This version will result in linker errors, since you'll end up with multiple definitions of an object with external linkage - a violation of ODR. Here's how you can do it: In order to achieve what you are trying to achieve, you have to declare your constant in the header file extern const std::string Ten; // non-defining declaration and then define it (with initializer) in one and only one of the implementation files extern const std::string Ten = "10"; // definition, `extern` optional (If the constant is pre-declared as extern, then extern in the definition is optional. Even without an explicit extern it will define a const object with external linkage.)
2,151,854
2,152,093
C++ Resolve a host IP address from a URL
How can I resolve a host IP address, given a URL in Visual C++?
To use the socket functions under Windows, you have to start by calling WSAStartup, specifying the version of Winsock you want (for your purposes, 1.1 will work fine). Then you can call gethostbyname to get the address of the host. When you're done, you're supposed to call WSACleanup. Putting that all together, you get something like this: #include <windows.h> #include <winsock.h> #include <iostream> #include <iterator> #include <exception> #include <algorithm> #include <iomanip> class use_WSA { WSADATA d; WORD ver; public: use_WSA() : ver(MAKEWORD(1,1)) { if ((WSAStartup(ver, &d)!=0) || (ver != d.wVersion)) throw(std::runtime_error("Error starting Winsock")); } ~use_WSA() { WSACleanup(); } }; int main(int argc, char **argv) { if ( argc < 2 ) { std::cerr << "Usage: resolve <hostname>"; return EXIT_FAILURE; } try { use_WSA x; hostent *h = gethostbyname(argv[1]); unsigned char *addr = reinterpret_cast<unsigned char *>(h->h_addr_list[0]); std::copy(addr, addr+4, std::ostream_iterator<unsigned int>(std::cout, ".")); } catch (std::exception const &exc) { std::cerr << exc.what() << "\n"; return EXIT_FAILURE; } return 0; }
2,151,871
2,151,924
For C++ MacOSX app, what threading library to use?
I'm on MacOSX, writing an app in C++. What threading library should I use? pThreads? or is there something else? Thanks!
On MacOSX, POSIX threads in C/C++ and NSThread in Objective-C/C++ are the recommended solutions - see Thread Management for an overview. In C++ though a cross-platform API as recommended by James is better if portability might ever become an issue.
2,152,002
2,152,042
How do I force a particular instance of a C++ template to instantiate?
See title. I have a template. I want to force a particular instance of a template to instantiate. How do I do this? More specifically, can you force an abstract template class to instantiate? I might elaborate as I have the same question. In my case I am building a library, some of the template implementations are large and include lots of stuff, but are only generated for a couple of types. I want to compile them in the library and export all the methods, but not include the header with the code everywhere. ie: template<class T> OS_EXPORT_DECL class MyTmpl { T *item1; public: inline T *simpleGetT() { return(item1); } /* small inline code in here */ } T *doSomeReallyBigMergeStuff(T *b); // note only declaration here }; // *** implementation source file only seen inside library template<class T> MyTmpl<T>::doSomeReallyBigMergeStuff(T *b) { ... a really big method, but don't want to duplicate it, so it is a template ... } I could of course reference all the methods inside the library which would force them to compile and export but the desire isn't to add un-needed code to the library like the argument formatting for the items and the code to call them etc. ????? specifically I am building the library for several versions of MSC and GCC and intel compilers.
You can't force generic templates to instantiate, the compiler can only generate code if the type is completely known. Forcing an instantiation is done by providing all types explicitly: template class std::vector<int>; Comeaus template FAQ covers the related issues in some detail.
2,152,017
2,154,079
Blowfish-encrypted messages between NSIS and PHP
For a project I'm working on, I need to encrypt and decrypt a string using Blowfish in a compatible way across NSIS and PHP. At the moment I'm using the Blowfish++ plugin for NSIS and the mcrypt library with PHP. The problem is, I can't get them both to produce the same output. Let's start with the NSIS Blowfish++ plugin. Basically the API is: ; Second argument needs to be base64 encoded ; base64_encode("12345678") == "MTIzNDU2Nzg=" blowfish::encrypt "test@test.com***" "MTIzNDU2Nzg=" Pop $0 ; 0 on success, 1 on failure Pop $1 ; encrypted message on success, error message on failure There's no mention of whether it's CBC, ECB, CFB, etc. and I'm not familiar enough with Blowfish to be able to tell by reading the mostly undocumented source. I assume it's ECB since the PHP docs for mcrypt tells me that ECB doesn't need an IV. I've also learned by reading the source code that the Blowfish++ plugin will Base64 decode the second argument to encrypt (I'm not sure why). It also returns a Base64 encoded string. For the PHP side of things, I'm basically using this code to encrypt: $plainText = "test@test.com***"; $cipher = mcrypt_module_open(MCRYPT_BLOWFISH, '', MCRYPT_MODE_ECB, ''); $iv = '00000000'; // Show not be used anyway. $key = "12345678"; $cipherText = ""; if (mcrypt_generic_init($cipher, $key, $iv) != -1) { $cipherText = mcrypt_generic($cipher, $plainText); mcrypt_generic_deinit($cipher); } echo base64_encode($cipherText); However, if I do all these things, I get the following output from each: NSIS: GyCyBcUE0s5gqVDshVUB8w== PHP: BQdlPd19zEkX5KT9tnF8Ng== What am I doing wrong? Is the NSIS plugin not using ECB? If not, what is it using for it's IV?
OK, I've gone through that code and reproduced your results. The problem isn't the cipher mode - NSIS is using ECB. The problem is that the NSIS Blowfish code is simply broken on little-endian machines. The Blowfish algorithm operates on two 32-bit unsigned integers. To convert between a 64 bit plaintext or ciphertext block and these two integers, the block is supposed to be interpreted as two Big Endian integers. The NSIS Blowfish plugin is instead interpreting them in host byte order - so it fails to do the right thing on little-endian hosts (like x86). This means it'll interoperate with itself, but not with genuine Blowfish implementations (like mcrypt). I've patched Blowfish++ for you to make it do the right thing - the modified Blowfish::Encrypt and Blowfish::Decrypt are below, and the new version of blowfish.cpp is here on Pastebin. void Blowfish::Encrypt(void *Ptr,unsigned int N_Bytes) { unsigned int i; unsigned char *Work; if (N_Bytes%8) { return; } Work = (unsigned char *)Ptr; for (i=0;i<N_Bytes;i+=8) { Word word0, word1; word0.byte.zero = Work[i]; word0.byte.one = Work[i+1]; word0.byte.two = Work[i+2]; word0.byte.three = Work[i+3]; word1.byte.zero = Work[i+4]; word1.byte.one = Work[i+5]; word1.byte.two = Work[i+6]; word1.byte.three = Work[i+7]; BF_En(&word0, &word1); Work[i] = word0.byte.zero; Work[i+1] = word0.byte.one; Work[i+2] = word0.byte.two; Work[i+3] = word0.byte.three; Work[i+4] = word1.byte.zero; Work[i+5] = word1.byte.one; Work[i+6] = word1.byte.two; Work[i+7] = word1.byte.three; } Work = NULL; } void Blowfish::Decrypt(void *Ptr, unsigned int N_Bytes) { unsigned int i; unsigned char *Work; if (N_Bytes%8) { return; } Work = (unsigned char *)Ptr; for (i=0;i<N_Bytes;i+=8) { Word word0, word1; word0.byte.zero = Work[i]; word0.byte.one = Work[i+1]; word0.byte.two = Work[i+2]; word0.byte.three = Work[i+3]; word1.byte.zero = Work[i+4]; word1.byte.one = Work[i+5]; word1.byte.two = Work[i+6]; word1.byte.three = Work[i+7]; BF_De(&word0, &word1); Work[i] = word0.byte.zero; Work[i+1] = word0.byte.one; Work[i+2] = word0.byte.two; Work[i+3] = word0.byte.three; Work[i+4] = word1.byte.zero; Work[i+5] = word1.byte.one; Work[i+6] = word1.byte.two; Work[i+7] = word1.byte.three; } Work = NULL; }
2,152,046
2,175,588
Why does autotools create project-File.o on one machine, File.o on another?
I have an autotools project. The same tarball on one machine compiles the files like this: gcc ... File.cpp -o project-File.o and on the other machine: gcc ... File.cpp -o File.o Does anyone know what causes this different behavior? Both machines are identically patched OS X, with the same tool versions.
According to the GNU Automake Documentation, the observed behavior is triggered by some specific variables set during the configuration. You say that both computers are identically patched with the same tools, but what about their environment variables (PATH, Compilation Flags, etc) ?
2,152,285
2,152,306
Does Java have a const reference equivalent?
Here's a snippet of code: //Game board is made up of Squares. A player can place GamePieces on a Square. public class CheckersBoard { public boolean PlaceGamePiece(GamePiece gamePiece, int nRow, int nColumn) { return m_theGameBoard[nRow][nColumn].PlaceGamePiece(gamePiece); } private Square[][] m_theGameBoard; } Let say I'm testing the PlaceGamePiece method (using junit) and I need to access the m_theGameBoard so I can look at it and verify the GamePiece was placed on the correct Square and has the correct data. In C++ I'd either make the test class a friend so it can access the private member m_theGameBoard, or I'd have a function that returns a const GameBoard that cannot be modified (because it's const): const GameBoard& GetGameBoard() const { return m_theGameBoard; } Now I can do what ever checking I want to do on the game board, but I can't modify the game board because it's const. Java doesn't support returning const references or friend classes. So my question is what is the standard Java way of doing this?? Do I have to just provide a bunch of get accessors that allow me check the data on the Square? UPDATE: I ended up writing a GetPiece method as Kaleb Brasee suggested. public GamePiece GetGamePiece(Point pt) { return new GamePiece(m_theGameBoard[pt.GetRow()][pt.GetColumn()]); } Notice I create a new GamePiece object and return that. I'm not returning the GameBoards internal reference, therefore no one can modify the gameboard because they only have a copy! Nice! Thanks for the help guys, some really good advice. FYI: I keep changing the names of the objects when I post them on here, sorry if that confused anyone.
Define the variable as protected, so that if the unit test is in the same package, it can access it. However, I would just add a public method getPiece(int row, int col) that returns the piece on that square (or null if there's no piece there). It's likely you'll need a method like that anyway, and you could use it in your tests.
2,152,355
2,152,468
is it possible to use QtConcurrent::run() with a function member of a class
I can't seem to be able to associate QtConcurrent::run() with a method (function member of a class) only with a simple function. How can I do this? With a regular function I cannot emit signals and its a drag. Why would anyone find this a better alternative to QThread is beyond me and would like some input.
Yes, this is possible (and quite easy). Here is an example (from the Qt documentation): // call 'QStringList QString::split(const QString &sep, SplitBehavior behavior, Qt::CaseSensitivity cs) const' in a separate thread QString string = ...; QFuture<QStringList> future = QtConcurrent::run(string, &QString::split, QString(", "), QString::KeepEmptyParts, Qt::CaseSensitive); ... QStringList result = future.result(); Basically, all you have to do is pass a pointer to the object as the first argument and the address of the method as the second argument (followed by any other arguments). See: https://doc.qt.io/qt-5/qtconcurrentrun.html
2,152,359
2,152,383
Template assertion in C++?
Is there a way to define a template assertInheritsFrom<A, B> such that assertsInheritsFrom<A, B> compiles if and only if class A : public B { ... } // struct A is okay too Thanks!
You can read this section Detecting convertibility and inheritance at compile time from Alexandrescu's book. EDIT: One more link for the same: http://www.ddj.com/cpp/184403750 Look for Detecting convertibility and inheritance
2,152,500
2,152,536
How does c++ auto_ptr relate to managed pointers (Java, C#...)
I come from a managed world and c++ automatic memory management is quite unclear to me If I understand correctly, I encapsulate a pointer within a stack object and when auto_ptr becomes out of scope, it automatically calls delete on the pointed object? What kind of usage should I make of it and how should I naturally avoid inherent c++ problems?
auto_ptr is the simplest implementation of RAII in C++. Your understanding is correct, whenever its destructor is called, the underlying pointer gets deleted. This is a one step up from C where you don't have destructors and any meaningful RAII is impossible. A next step up towards automagic memory management is shared_ptr. It uses reference counting to keep track of whether or not the object is alive. This allows the programmer to create the objects a bit more freely, but still not as powerful as the garbage collection in Java and C#. One example where this method fails is circular references. If A has a ref counted pointer to B and B has a ref counted pointer to A, they will never get destructed, even though no other object is using either. Modern object orianted languages use some sort of variation of mark and sweep. This technique allows managing circular references and is reliable enough for most programming tasks.
2,152,567
2,152,583
Iterating the std::list through a const_iterator
is it possible to iterate through until the end of list in main() function using the const_iterator? I tried using iter->end() but i can't figure it out. #include <list> #include <string> using std::list; using std::string; class list_return { public: list <string>::const_iterator get_list() { _list.push_back("1"); _list.push_back("2"); _list.push_back("3"); return _list.begin(); } private: list <string> _list; }; int main() { list_return lr; list <string>::const_iterator iter = lr.get_list(); //here, increment the iterator until end of list return 0; }
You seem to have 'encapsulated' the list without exposing a way to access the end() method of the list which you need for your iteration to know when to finish. If you add a method that returns _list.end() to your list_return class (I've called it get_list_end) you could do something like this: for (std::list<std::string>::const_iterator iter = lr.get_list(); iter != lr.get_list_end(); ++iter) { //... }
2,152,636
2,152,669
C++ How to I replace this if...else statement?
I have the following C++ code (simplified version): class Shape { bool isCircle = false; bool isSquare = false; } class Circle : public Shape { // some special members/methods } class Square : public Shape { // some special members/methods } class CAD { virtual DrawCircle(Circle * circle) = 0; } class SWX : public CAD { virtual DrawCircle(Circle * circle){// do some stuff that draws circle on SWX system} } class PRO : public CAD { virtual DrawCircle(Circle * circle){// do some stuff that draws circle on PRO system} } int main() { Circle * circle = new Circle(); circle->isCircle = true; Square * sq = new Square; sq->isSquare = true; vector<Shape*> shapes; shapes.push_back(circle); shapes.push_back(sq); SWX * swx = new SWX(); for( int i = 0 ; i < shapes.size() ; ++i ) { if( shapes[i]->isCircle ) { SWX->DrawCircle((Circle*)(shapes[i])); } else if( shapes[i]->isSquare ) { SWX->DrawSquare((Square*)(shapes[i])); } } I wish to remove the need for if...else (if at all possible within the constraints stated below). My constraints right now are: The CAD and derived classes are ginormous classes with various external dependencies. The CAD classes cannot be merged with the Shape and derived classes (that would have been ideal, since then I can use polymorphism to solve my problem), since other projects/classes depend on the Shape classes and cannot depend on the CAD classes. There are more than a dozen Shape-derived classes with a half dozen CAD-derived classes and this if...else is happening in numerous locations - so it would help if any solution is simple to understand (easier to convince my teammates to change legacy code). Any suggestions/comments/solution you have would be most welcome.
The standard solution for this problem, especially given your constraints regarding dependencies, is to use the Visitor Pattern. Here's how Visitor Pattern would work in your case: You need an abstract ShapeVisitor class. It has an abstract Visit method for each concrete subclass of Shape. eg: Visit(Circle*), Visit(Square*), etc. Shape has an abstract AcceptVisitor(ShapeVisitor*) method. Each Shape subclass implements AcceptVisitor as just calling visitor->Visit(this) Each CAD class is a (or has-a, up to you) a ShapeVisitor. The Visit methods do the appropriate drawing for the specific type of Shape. No conditional or casting required. Here's a modified version of your code that uses Visitor Pattern in a pretty low-impact way: class Circle; class Square; class ShapeVisitor { virtual void Visit(Circle *circle) = 0; virtual void Visit(Square *square) = 0; } class Shape { virtual void AcceptVisitor(ShapeVisitor *visitor) = 0; } class Circle : public Shape { // some special members/methods virtual void AcceptVisitor(ShapeVisitor *visitor) { visitor->Visit(this); } } class Square : public Shape { // some special members/methods virtual void AcceptVisitor(ShapeVisitor *visitor) { visitor->Visit(this); } } class CAD : public ShapeVisitor { virtual DrawCircle(Circle *circle) = 0; virtual DrawSquare(Square *square) = 0; virtual void Visit(Circle *circle) { DrawCircle(circle); } virtual void Visit(Square *square) { DrawSquare(square); } } class SWX : public CAD { virtual DrawCircle(Circle *circle){// do some stuff that draws circle on SWX system} } class PRO : public CAD { virtual DrawCircle(Circle * circle){// do some stuff that draws circle on PRO system} } int main() { Circle * circle = new Circle(); Square * sq = new Square; vector<Shape*> shapes; shapes.push_back(circle); shapes.push_back(sq); SWX * swx = new SWX(); for( int i = 0 ; i < shapes.size() ; ++i ) { shapes[i]->AcceptVisitor(SWX); } } In this code I've opted for making CAD actually a subclass of ShapeVisitor. Also, since you've already got virtual methods in CAD to do the drawing, I implemented the Visit methods there (once), rather than once in each subclass. Once you switch clients over to the using AcceptVisitor instead of calling the Draw* methods directly you could make those methods protected, and then eventually move the implementation of the Visit methods down to the subclasses (that is: refactor to remove the extra level of indirection caused by having Visit(Foo*) call DrawFoo(Foo*)).
2,152,774
2,152,799
Indexing text content of html
I want to pull the text out of html files for indexing purposes, and do so as fast as possible. Rather than create something from scratch, I want to see how much I can find already done for me. Currently I'm just piping the output of html2text, which works, but between being python and trying to prettify the text, I'm sure the speed could be improved. So, with Linux/unix being priority, what (c/c++) libraries would be best suited to this kind of task?
To extract the text you can use an HTML parser like htmlcxx or libxml. You can can also use any XML library after tidying up the HTML. For indexing the text you can use CLucene.
2,152,845
2,152,910
How to get address of member function for local class defined in function (C++)
I am trying to do the following: Obtain the address of a member function from a class that was locally defined within a function. class ConnectionBase { }; template class<EventType, SinkType> class ConnectionImpl : public ConnectionBase { public: typedef void (SinkType::*EventCallback)(EventType const&); }; template<class EventType> class Source { template <class SinkType> boost::shared_ptr<ConnectionBase> setupCallback(typename ConnectionImpl<EventType, SinkType>::EventCallback func, SinkType* sink) { // do the actual connecting. } }; class SomeClass { public: void someFunction(int const& event){} } class SomeUnitTest { public: void someTest() { class NestedClass { public: void someFunction(int const& event){} }; NestedClass nc; //Try#1 - This does not work setupCallback<int, NestedClass>(&NestedClass::someFunction, &nc); //Try #2 - This also does not work setupCallback<int, NestedClass>(&SomeUnitTest::someTest::NestedClass::someFunction, &nc); //Try #3 - Following the GCC error output, I tried this setupCallback<int, NestedClass>(&SomeUnitTest::someTest()::NestedClass::someFunction, &nc); SomeClass sc; //This works fine, as expected setupCallback<int, SomeClass>(&SomeClass::someFunction, &sc); } }; Try #2 and #3 utterly confuse GCC, it has no idea what I am trying to do. Try #1 produces a more helpful error message saying no setupCallback exists that takes the form "setupCallback(void (SomeUnitTest::someTest()::NestedClass::SomeFunction::*), etc) Which is how try #3 was born. I can't really find a lot of information about classes defined inside a function, does anyone know the correct syntax for this, and maybe have a resource that discusses this topic? Ok, it appears this is settled, as both posters have pointed out, local classes have no linkage, it can't work. Now knowing this, I found this article that discusses this, for anyone else that runs into this problem and stumbles across this question: http://www.informit.com/guides/content.aspx?g=cplusplus&seqNum=420 Edit: Clarification of setupCallback(), working example with a more regular class Edit #2: Updated wording to change "nested" to "local". Added more detail for setupCallback. Edit #3: Added links to furhter information. Thanks everyone.
I don't know about the syntax problem, the usual access rules should apply - but there is another problem here if that would work as these member functions have no linkage. To accept local types at all, setupCallback() would have to be a template function - but template type arguments with no linkage are not allowed. §3.5/8 says: Names not covered by these rules have no linkage. Moreover, except as noted, a name declared in a local scope (3.3.2) has no linkage. Members of local classes are not covered there. §9.3/3 clarifies that: Member functions of a local class (9.8) have no linkage. Long story cut short: don't use member functions of a local class as callbacks, use a non-local class instead.
2,152,925
2,152,944
Can I undo the effect of "using namespace" in C++?
With using namespace I make the whole contents of that namespace directly visible without using the namespace qualifier. This can cause problems if using namespace occurs in widely used headers - we can unintendedly make two namespaces with identical classes names visible and the compiler will refuse to compile unless the class name is prepended with the namespace qualifier. Can I undo using namespace so that the compiler forgets that it saw it previously?
No, but you can tell your coworkers that you should never have a using directive or declaration in a header.
2,152,986
2,153,160
How do I get the index of an iterator of an std::vector?
I'm iterating over a vector and need the index the iterator is currently pointing at. What are the pros and cons of the following methods? it - vec.begin() std::distance(vec.begin(), it)
I would prefer it - vec.begin() precisely for the opposite reason given by Naveen: so it wouldn't compile if you change the vector into a list. If you do this during every iteration, you could easily end up turning an O(n) algorithm into an O(n^2) algorithm. Another option, if you don't jump around in the container during iteration, would be to keep the index as a second loop counter. Note: it is a common name for a container iterator,std::container_type::iterator it;.
2,153,017
2,153,104
Is it feasible to ascribe pronunciations to distinct source code concepts?
I frequently tutor fellow students in programming, most often in C++ or Java. It is uniquely aggravating to try to verbally convey the essential syntax of a C++ expression. The speaker must give either an idiomatic translation into English, or a full specification of the code in verbal longhand, using explicit yet slow terms such as "opening parenthesis", "bitwise and", et cetera. Neither of these solutions is optimal. In C++, there is a finite set of keywords—63—and operators—54, discounting named operators and treating compound assignment operators and prefix versus postfix auto-increment and decrement as distinct. There are just a few types of literal, a similar number of grouping symbols, and the semicolon. Unless I'm utterly mistaken, that's about it. Would it not then be feasible to ascribe a concise, unique pronunciation to each of these distinct concepts (including one for whitespace, where it is required) and go from there? Programming languages are far more regular than natural languages, so the pronunciation could be standardised.
Instead of creating new "words" to describe them, for things such as "include" you could simply prefix it with "keyword" when saying it aloud. You could use words/phrases commonly known to say other parts as well. As with any new programmer, you have to literally describe everything anyway, so I don't think that requires special attention. I think creating new words is the harder method... So, for example: #include <iostream>; int main() { if (1 < 2) return 1; else return 0; } Could be read out as: (keyword) include iostream new-line (keyword) int main no params start block if number 1 (operator) less than number 2 new-line (keyword) return number 1 new-line (keyword) else new-line (keyword) return number 0 end block Treat words in () as optional descriptive words, most likely to be used in more complex code. You could use the word 'literal' if you want them to actually write the descriptive word. For example (keyword) if literal number (operator) less than literal keyword becomes if (number < keyword) Other words could be given defined meanings as well, such as 'split-line' when you want them to continue on the next line, without closing any currently open parenthesis, etc. I personally find this method quite simple to use and easy to teach. YMMV, as always. Of course, this doesn't solve the internationalisation issue, but at worst, would result in 'new words' being used in the non-English languages, which is no worse than the proposed solution you offered.
2,153,045
2,153,080
C/C++ implementation of an algorithm similar to subset sum
The problem is simpler than knapsack (or a type of it, without values and only positive weights). The problem consists of checking whether a number can be a combination of others. The function should return true or false. For example, 112 and a list with { 17, 100, 101 } should return false, 469 with the same list should return true, 35 should return false, 119 should return true, etc... Edit: subset sum problem would be more accurate for this than knapsack.
An observation that will help you is that if your list is {a, b, c...} and the number you want to test is x, then x can be written as a sum of a sublist only if either x or x-a can be written as a sum of the sublist {b, c, ...}. This lets you write a very simple recursive algorithm to solve the problem. edit: here is some code, taking into account the comments below. Not tested so probably buggy; and not necessarily the fastest. But for a small dataset it will get the job done neatly. bool is_subset_sum(int x, std::list::const_iterator start, std::list::const_iterator end) { // for a 1-element list {a} we just need to test a|x if (start == end) return (x % *start == 0); // if x is small enough we don't need to bother testing x - a if (x<a) return is_subset_sum (x, start+1, end); // the default case. Note that the shortcut properties of || means the process ends as soon as we get a positive. return (is_subset_sum (x, start+1, end) || is_subset_sum (x-a, start, end)); }
2,153,150
2,153,941
Lazy/multi-stage construction in C++
What's a good existing class/design pattern for multi-stage construction/initialization of an object in C++? I have a class with some data members which should be initialized in different points in the program's flow, so their initialization has to be delayed. For example one argument can be read from a file and another from the network. Currently I am using boost::optional for the delayed construction of the data members, but it's bothering me that optional is semantically different than delay-constructed. What I need reminds features of boost::bind and lambda partial function application, and using these libraries I can probably design multi-stage construction - but I prefer using existing, tested classes. (Or maybe there's another multi-stage construction pattern which I am not familiar with).
The key issue is whether or not you should distinguish completely populated objects from incompletely populated objects at the type level. If you decide not to make a distinction, then just use boost::optional or similar as you are doing: this makes it easy to get coding quickly. OTOH you can't get the compiler to enforce the requirement that a particular function requires a completely populated object; you need to perform run-time checking of fields each time. Parameter-group Types If you do distinguish completely populated objects from incompletely populated objects at the type level, you can enforce the requirement that a function be passed a complete object. To do this I would suggest creating a corresponding type XParams for each relevant type X. XParams has boost::optional members and setter functions for each parameter that can be set after initial construction. Then you can force X to have only one (non-copy) constructor, that takes an XParams as its sole argument and checks that each necessary parameter has been set inside that XParams object. (Not sure if this pattern has a name -- anybody like to edit this to fill us in?) "Partial Object" Types This works wonderfully if you don't really have to do anything with the object before it is completely populated (perhaps other than trivial stuff like get the field values back). If you do have to sometimes treat an incompletely populated X like a "full" X, you can instead make X derive from a type XPartial, which contains all the logic, plus protected virtual methods for performing precondition tests that test whether all necessary fields are populated. Then if X ensures that it can only ever be constructed in a completely-populated state, it can override those protected methods with trivial checks that always return true: class XPartial { optional<string> name_; public: void setName(string x) { name_.reset(x); } // Can add getters and/or ctors string makeGreeting(string title) { if (checkMakeGreeting_()) { // Is it safe? return string("Hello, ") + title + " " + *name_; } else { throw domain_error("ZOINKS"); // Or similar } } bool isComplete() const { return checkMakeGreeting_(); } // All tests here protected: virtual bool checkMakeGreeting_() const { return name_; } // Populated? }; class X : public XPartial { X(); // Forbid default-construction; or, you could supply a "full" ctor public: explicit X(XPartial const& x) : XPartial(x) { // Avoid implicit conversion if (!x.isComplete()) throw domain_error("ZOINKS"); } X& operator=(XPartial const& x) { if (!x.isComplete()) throw domain_error("ZOINKS"); return static_cast<X&>(XPartial::operator=(x)); } protected: virtual bool checkMakeGreeting_() { return true; } // No checking needed! }; Although it might seem the inheritance here is "back to front", doing it this way means that an X can safely be supplied anywhere an XPartial& is asked for, so this approach obeys the Liskov Substitution Principle. This means that a function can use a parameter type of X& to indicate it needs a complete X object, or XPartial& to indicate it can handle partially populated objects -- in which case either an XPartial object or a full X can be passed. Originally I had isComplete() as protected, but found this didn't work since X's copy ctor and assignment operator must call this function on their XPartial& argument, and they don't have sufficient access. On reflection, it makes more sense to publically expose this functionality.
2,153,165
2,153,369
I have a problem with visiting network drive on Vista
The step is: I have been running a service program with UAC for mapping network drive using function WNetAddConnection2, then it was successful. I ran another program with privilege of administrator(run as administrator) to call function GetFileAttribute to get network drive's attribute, however, it was returned 0xffffffff and error code was 3(Doesn't find the special path). I also have tried create file on network drive, but it was still failed. Could you please help me to solve this problem? Thanks a lot.
In NT, a "network drive" is a symbolic link from the MS-DOS filesystem namespace to a UNC path. Those symbolic links are maintained per logon session. This also means that an Administrator has its own set of symbolic links. The solution is to call WNetAddConnection2 in each logon session that needs to access the particular UNC network path as a drive letter. This is documented on the MSDN page : On Windows Server 2003 and Windows XP, the WNet functions create and delete network drive letters in the MS-DOS device namespace associated with a logon session because MS-DOS devices are identified by AuthenticationID (a locally unique identifier, or LUID, associated with a logon session.) This can affect applications that call one of the WNet functions to create a network drive letter under one user logon, but query for existing network drive letters under a different user logon.
2,153,184
2,153,247
Copy constructor invokes an infinite loop
I am passing a value to copy constructor as a reference, but an infinite loop is being invoked. Here's my class: class Vector2f{ private: GLfloat x; GLfloat y; public: Vector2f(); Vector2f(const GLfloat _x, const GLfloat _y); Vector2f(const Vector2f &_vector); ~Vector2f(); }; Here's implementation of methods: Vector2f::Vector2f(): x( 0.0f ), y( 0.0f ) { DebugLog("Vector2f constructor"); } Vector2f::Vector2f(const GLfloat _x, const GLfloat _y): x( _x ), y( _y ) { DebugLog("Vector2f constructor(%f, %f)", _x, _y); } Vector2f::Vector2f(const Vector2f &_vector): x( _vector.getX() ), y( _vector.getY() ) { DebugLog("Vector2f copy constructor"); } Vector2f::~Vector2f() { } Here's how I access the class: Vector2f tempVector1 = Vector2f(0.0f, 0.0f); DebugLog("tempVector1 initialized"); Vector2f tempVector2; tempVector2 = Vector2f(0.0f, 0.0f); DebugLog("tempVector2 initialized"); The results I get are: Vector2f constructor(0.000000, 0.000000) tempVector1 initialized Vector2f constructor Vector2f constructor(0.000000, 0.000000) Vector2f copy constructor Vector2f copy constructor Vector2f copy constructor ... Infinite loop occurs when trying to initialize previously created object. If I try to copy tempVector1 into tempVector 2 an infinite loop occurs as well: Vector2f tempVector2; tempVector2 = Vector2f(tempVector1); Why does it happen and how can I prevent it from getting into an infinite loop? Thank you in advance.
I think the problem is in your assignment operator. How does operator= look like? It seems that operator= is calling him self in some way. Is it possible that the code snippet is taken from the body of operator= itself? If it is then the solution is to change the code (inside operator=) such that it uses the copy ctor. The canonical form is as follows: Vector2f temp = Vector2f(arg); swap(*this, temp) // You need to implement a swap method return *this; (See Exceptional C++ by Herb Sutter for more details)
2,153,240
2,153,258
templated member function to boost multi index container
I have a boost multi index container thus. using namespace boost::multi_index; template < typename O > class Container { public: multi_index_container< O, indexed_by< ordered_unique< const_mem_fun< O, std::string, &O::name > > > > _container; }; As you can see, by this design every object I use to create this container has to have a member function returning a string with the name "name". This is obviously not ideal. I tried a couple of ways of passing in the "key" but I can't get any of them to work.. I tried this.. using namespace boost::multi_index; template < typename O, typename KT, typename KM > class Container { public: multi_index_container< O, indexed_by< ordered_unique< const_mem_fun< O, KT, &KM > > > > _container; }; int main( int c, char *v[] ) { Container< Object, std::string, Object::name > container; } but no joy.. the compiler complains that Object::name isn't a type but I'm not sure how to correct this. And even if I work out how to supply a type to the template, I'll still need a concrete instance of "Object::name" to be used by the container.. maybe I have to hand in the types and then and in the member function at construction? but then how do I construct the container .. My head hurts!?! Alexy, below, kindly offered this solution using namespace boost::multi_index; template < typename O, typename KT, KT (O::* KM)() > class Container { public: multi_index_container< O, indexed_by< ordered_unique< const_mem_fun< O, KT, KM > > > > _container; }; int main( int c, char *v[] ) { Container< Object, std::string, &Object::name > container; // <<---- ERROR HERE } However, this produded the following compiler error. Template parameter KM requires an expression of type std::string (Object::*)(). at the line marked.. Ok. It turns out this was my fault by handing in an incorrectly signatured "&Object::name" parameter... I have fixed this..
Change class definition. template < typename O, typename KT, KT (O::* KM)() > class Container //... and use KM instead of &KM.
2,153,318
2,153,376
Aid in building boost asio ssl example
I have been working through the asio ssl examples (linked below). Despite by best efforts I have been unable to link openssl into the boost example. The output from ld is that ld is missing symbols from libssl.a. The thing that I can not figure out is that I found all the symbols in libssl.a with nm that ld says are missing. I suspect I am doing something dumb but I am not familiar enough with c++ to fix it. I have also included my makefile. The source of ssl-client.cpp is verbatim from the link. http://www.boost.org/doc/libs/1_41_0/doc/html/boost_asio/example/ssl/client.cpp INCLUDES = -I /usr/local/boost_1_41_0/ -I /opt/local/include/ LIBS = -L/usr/local/boost_1_41_0/lib/libboost_system.a \ -L/opt/local/lib/libcrypto.a \ -L/opt/local/lib/libssl.a CPP = g++ build: ssl-client ssl-client: ssl-client.cpp $(CPP) $(LIBS) $(INCLUDES) ssl-client.cpp
I think you've misunderstood how the -L option works. -L specifies a path in which to search for libraries. To specify an individual library to link to, use the -l option and omit the "lib" prefix, as follows: LIBS = -L/usr/local/boost_1_41_0/lib -L/opt/local/lib \ -lboost_system -lcrypto -lssl Also, there is usually no space between the -I include path option and the actual path. I'm not sure if a space in there causes problems, but you might try this to be on the safe side: INCLUDES = -I/usr/local/boost_1_41_0/ -I/opt/local/include/ Also, as noted in my comment, you defined the LIBS variable but then used the LIB variable. The call to g++ should be as follows: $(CPP) $(LIBS) $(INCLUDES) ssl-client.cpp
2,153,435
2,153,513
How to get OS language using C++ API?
I am in the process of developing a application which displays dialogs depending on the OS language. How I can get the OS language using C++ or Windows APIs (Windows 2008/Vista/7)?
There are several functions to do this in Windows, depending on what format you want the information in. Prior to Windows Vista, the language information was encoded into a LCID (Locale Id) which includes language, as well as some information about sorting and formatting. For Windows Vista and Windows 7, a more flexible system called Locale Names was devised. GetSystemDefaultLocaleName Use this if you want to work on Win2k and WinXP. GetSystemDefaultLCID
2,153,601
2,153,610
questions about an article introducing C++ interface
I have been reading an article about C++ interfaces (http://accu.org/index.php/journals/233) and I am completely lost at the part where it says all the virtual member functions should be made private (the section titled "Strengthening the Separation"). It just does not make sense to me at all. According to the author, the code is like this: class shape { public: virtual ~shape(); virtual void move_x(distance x) = 0; virtual void move_y(distance y) = 0; virtual void rotate(angle rotation) = 0; //... }; class line : public shape { public: line(point end_point_1, point end_point_2); //... private: virtual ~line(); virtual void move_x(distance x); virtual void move_y(distance y); virtual void rotate(angle rotation); //... }; So we have a pure virtual function which is public, and its implementation (in the line class) which is private. Could anybody explain how the move_x function can be called? Its access specifier is private, it will lead to an error if I try to do this: line my_line(point(0,0), point(1,2)); my_line.move_x(-1); // does not compile Similarly is it correct to say that the drawing interface (see earlier in the article)cannot access these functions either? Thank you.
The idea is that you'd use those methods via a reference or pointer to shape. shape &s = my_line; s.move_x(-1); This could be justified on the grounds of "reveal only what you need to", or as a form of self-documentation. It proves that the methods are only called in the intended way.
2,153,711
2,154,148
How to convert string from cp1250 to utf-8 in Borland C++ Builder 6
I maintain an application written in Borland C++ 6. This app is using SQLite database. I am now extending it, so it can be used by unprivileged users, and so I had to move the database file to the home user directory. Unfortunately some of users have Polish national characters in their names, such as ą,ć,ę and some more. The system codepage is cp1250, but SQLite requires me to pass an utf-8 encoded path. So, basicly I need to convert a cp1250 encoded path: String path = "c:\documents and settings\User Name like Zażółć gęślą Jaźń\Application Data\...\MyDb.sqlite" to utf-8, and then pass it to sqlite with path.c_str(); Does C++ builder have any class to convert charsets, or should I just map the short set of polish national character codes to their utf-8 representations?
I couldn't find the documentation for C++ Builder (the links on Borland's page seem to be broken), but from what I recall, you can directly convert from AnsiString to WideString. Once you have a UTF-16 string, you can use WideCharToMultiByte Windows function, passing CP_UTF8 as a parameter.
2,153,759
2,153,841
Boost, bjam, and symbolic links
I generated some Boost librairies with bjam, and I get many symbolic links. For date_time : libboost_date_time-gcc41-mt-1_39.a libboost_date_time-gcc41-mt-1_39.so -> libboost_date_time-gcc41-mt-1_39.so.1.39.0 libboost_date_time-gcc41-mt-1_39.so.1.39.0 libboost_date_time-gcc41-mt.a -> libboost_date_time-gcc41-mt-1_39.a libboost_date_time-gcc41-mt.so -> libboost_date_time-gcc41-mt-1_39.so.1.39.0 Why don't I just get the .a and .so ? Why these 3 symbolic links ? And why do the original files have a so complicated name for the .so, with the release version mentionned twice ? Isn't it possible to just have : libboost_date_time-gcc41-mt-1_39.a libboost_date_time-gcc41-mt-1_39.so Thanks for help. I don't know what to do of these symbolic links. Note : I am a newbie in Linux.
A symbolic link is a way of sharing the same file between two names. For example if A is linked to B then opening A or B will give the same data to the calling program. In this case you have 2 files libboost_date_time-gcc41-mt-1_39.so.1.39.0 and libboost_date_time-gcc41-mt-1_39.a. The .so files are shared libraries and .a are static libraries. The links without version numbers libboost_date_time-gcc41-mt.so and libboost_date_time-gcc41-mt.a are there so that builds that do not care about the version number can use these libraries. For shared libraries there is a naming convention with version numbers so that the full version number is at the end so the build system can have exact control of the version number. see Boost docs for full explanation
2,153,776
2,153,915
How to use _CrtDumpMemoryLeaks()
I am trying to use _CrtDumpMemoryLeaks() to display memory leaks in my program. But it does not display anything except for returning 0 in case of no memory leaks and 1 in case there is a leak. The link here shows the output should be like: Detected memory leaks! Dumping objects -> D:\VisualC++\CodeGuru\MemoryLeak\MemoryLeak.cpp(67) : {60} normal block at 0x00324818, 4 bytes long. Data: <, > 2C 00 00 00 Object dump complete. Can anyone suggest the correct way of using this function.
Download the sample from the following link. You have to set the following parameters to direct output to console. // Send all reports to STDOUT _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_WARN, _CRTDBG_FILE_STDOUT ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDOUT ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE ); _CrtSetReportFile( _CRT_ASSERT, _CRTDBG_FILE_STDOUT );
2,153,856
2,153,891
Markov C++ read from file performance
I have my 2nd assignment for C++ class which includes Markov chains. The assignment is simple but I'm not able to figure out what is the best implementation when reading chars from files. I have a file around 300k. One of the rules for the assignment is to use Map and Vector classes. In Map (key is only string) and values will be the Vectors. When I'm reading from the file, I need to start collecting key pairs. Example: File1.txt 1234567890 1234567890 If Select Markov k=3, I should have in my Map: key vector 123 -> 4 456 -> 7 789 -> 0 0/n1 -> 2 234 -> 5 567 -> 8 890 -> /n /n -> NULL The professor's suggestion is to read char by char, so my algorithm is the following while (readchar != EOF){ tempstring += readchar increment index if index == Markovlevel { get nextchar if =!EOF insert nextchar value in vector insert tempstring to Map and assign vector unget char } } I omit some other details. My main question is that if I have 318,000 characters, I will be doing the conditional every time which slows down my computer a lot (brand new MAC pro). A sample program from the professor executes this file in around 5 seconds. I'm not able to figure out what's the best method to read fixed length words from a text file in C++. Thanks!
Have you actually timed the program? 318,000 conditionals should be a piece of cake for your brand new MAC pro. That should take only microseconds. Premature optimization is the root of all evil. Make your program work first, optimization comes second.
2,153,901
2,153,998
Forcing 32-bit architecture via configure
What is the best way to force a configure script to build a 32-bit code? I have a 64-bit machine, and trying to build a 32-bit code. Tried setting the --build type with several options, but this just doesn't work. Thanks!
Try to add -m32 to the CFLAGS.
2,154,132
2,154,149
Printing an uninitialized bool using cout (C++)
I have a class with a bool data member that is not initialized by the constructor. If I do cout << x.myBoolDataMember; where x is an object of this class in which the bool has not been initialized, I sometimes get a random number rather than 0 or 1. (I'm using gcc.) Is this behavior compliant with the Standard?
Is this behavior compliant with the standard? Yes! Using garbage values(uninitialized) in your code invokes Undefined Behavior
2,154,319
2,155,153
How to implement you own custom DirectShow renderer?
How to implement you own custom DirectShow renderer that could work a-la or instead of SampleGrabber?
http://www.gdcl.co.uk/AppFilter.zip
2,154,489
2,154,547
So you think you know the priority of operators in c++?
I just ran into a piece of code that not only compiles, but gives the expected result (where x is an integer value): int y = (int)(0.5 * x * x + + + 0.6 * x + 1.2); It took me a while to figure out what happens and I must say it was an interesting operator problem. Without compiling the program, what are the results of the following operations and why? int a = 1; int b = 2; int z = a + + + b; int z1 = a + - + b; int z2 = a + - - b; int z3 = a - - + b; int z4 = a - - - b; int z5 = a +- b; I still have one question, though: does the standard give such results or is it compiler specific? Explanation: Because the + and - operators have spaces between them, the "+ + +" sequence is not compiled as "++ +", but as unary operators on the right member. So int y = (int)(0.5 * x * x + + + 0.6 * x + 1.2); actually gives: int y = (int)(0.5 * x * x + 0.6 * x + 1.2); which was the expected result. So, z = a + + + b = a + + (+b) = a + (+b) = a + b = 3; z1 = a + - + b = a + - (+b) = a + (-b) = a - b = -1; z2 = a + - - b = a + - (-b) = a + (+b) = a + b = 3; z3 = a - - + b = a - - (+b) = a - (-b) = a + b = 3; z4 = a - - - b = a - - (-b) = a - (+b) = a - b = -1; z5 = a +- b = a + (-b) = a - b = -1;
z = 3 z1 = -1 z2 = 3 z4 = 3 z5 = -1 Without compiling, i'd say it's a simple math operator combining I've learned it with this phrase (translated from Brazilian portuguese): Different signs = subtract Equal signs = add So int z = a + + + b; // '+' + '+' = '+' , the resulting '+' + '+' = + again. int z1 = a + - + b; // '+' + '-' = '-' , the resulting '-' + '+' = - again. int z2 = a + - - b; // '+' + '-' = '-' , the resulting '-' + '-' = +. int z3 = a - - + b; // '-' + '-' = '+' , the resulting '+' + '+' = + again. int z4 = a - - - b; // '-' + '-' = '+' , the resulting '+' + '-' = -. int z5 = a +- b; //simple "different signals = subtract" :)
2,154,567
2,154,590
C++ multithreading problem - is mutex the only way?
I have a counter variable which will be accessed by multiple threads which will increment/decrement it. It should not be updated by multiple threads at the same time. I know that you can create a mutex object which has to be obtained before the variable in question can be changed. A critical section in this case is not appropriate because there are more than 1 function which can change the variable in question. Is there another I can do this without using the mutex? Using a mutex does have a performance penalty (see http://www.codeguru.com/forum/showthread.php?t=333192). I believe that in Java, there is a key word you can use in the variable declaration to accomplish that (is it called "synchronized"?), but is there such a thing in C++ at all? I know that volatile is not the keyword I am looking for. Thank you very much.
Most processors have 'atomic' increment and decrement instructions - in a large part, they are how mutexes are implemented at a machine level. You can access these atomic instructions in your own code. Windows provides the InterlockedIncrement() function, and glib provides equivalents. In x86 assembly language, you can use LOCK CMPXCHG and kin directly. C++ does not know anything about these concepts - you must use them yourself; there are no magic keywords for thread safety in C++. See Atomic Instruction
2,154,792
2,155,356
Are there open source audio stream clients or frameworks?
I'm looking for how to play back audio streams in these formats: MP3 Ogg / Vorbis WMA over MMS/ASF AAC / AAC+ target is the mac and iPhone. Maybe there is an open source library that I could look at, to understand how it works, and then port it to the cocoa frameworks somehow.
I'd take a look at FFmpeg. It's the most widely used opensource codec library and can be compiled for the iPhone. It has RTSP support (Microsoft deprecated MMS streams in 2003 and most current mms:// streams are actually just RTSP. You don't actually need to port C/C++ libraries to Cocoa to be able to use them with Cocoa/Objective-C. You can use C libraries directly and C++ ones with Objective-C++ or using a C wrapper. Or are you worrying about the license? Many parts of FFmpeg are LGPL and can be used from proprietary applications.
2,155,159
2,161,234
Boost::bind a method with boost::function parameter
I would like to provide an extra boost::function to a async_write. I want the connections own HandleWrite function to be called first and then call the provided boost::function. Member method of Connection that binds to asio async_write void Connection::HandleWrite( const boost::system::error_code& e, boost::function<void (const boost::system::error_code&)> handler) { // Code removed for clarity if(!handler.empty()) handler(e); }; Trying to bind HandleWrite to a asio async_write and provide another bind as the value for handler. This doesn't compile. What am I doing wrong? void Connection::QueueRequest( boost::shared_array<char> message, std::size_t size, boost::function<void (const boost::system::error_code&)> handler) { // Code hidden for clarity boost::asio::async_write(m_Socket, boost::asio::buffer(buffer), boost::bind(&Connection::HandleWrite, shared_from_this(), boost::asio::placeholders::error, handler ) ); } The error message I get from the compiler is the following: Error 1 error C2825: 'F': must be a class or namespace when followed by '::' boost\bind\bind.hpp 69 Error 2 error C2039: 'result_type' : is not a member of '`global namespace'' boost\bind\bind.hpp 69 Error 3 error C2146: syntax error : missing ';' before identifier 'type' boost\bind\bind.hpp 69 Error 4 error C2208: 'boost::_bi::type' : no members defined using this type boost\bind\bind.hpp 69 Error 5 fatal error C1903: unable to recover from previous error(s); stopping compilation boost\bind\bind.hpp 69
The problem turned out to be in another place that used the same HandleWrite function and wasn't bound correctly. After fixing that it compiled.
2,155,173
2,155,228
functions memory management C++
i have a little bit lame question, but it's time i have this finally clear. consider regular function with some parameters and a return type. My questions are: are there always made some copies of parameters? i mean even if the function expects reference or pointer as parameter, there are actually new references/pointers created, right? when the function is over are there some destructors called for those? is it the same with return values? is the returned value also copied from the context of the actually performed function? or are those just addresses somewhere and the value in the context is destructed too? i probably didn't express it too clearly sooo.. if you just explained in your way how does it work with memory when some function is called i would be thankful. I have just casual idea about function of processors, but i have already dealt with assembler so there is at least something to work with.
C++, like C, is a call-by-value language, so in general copies of parameters are always made. When: void f( int x ) { } is called, a copy of its parameter is made and passed to the function. When: void f( int * x ) { } is called, a copy of the pointer is made and passed to the function. The exception to this is when references are used: void f( int & x ) { } no copy is made, but internally a pointer is (probably) used to pass the address of the parameter - you are not supposed to think about this however. Exactly the same thing applies to return values: int f() { return 1; } a copy of the value 1 is made and returned to the caller. If the function returned a pointer, a copy of the pointer would be made. Once again, references are the exception, in that no copy is made, but internally a pointer is (probably) used to return the value.
2,155,193
2,155,454
Matlab repmat function equivalent in c++
Is there an equivalent in c++(in any API/library) for Matlab repmat function ?
No because there is no standard C++ matrix class to replicate. If you use a third-party matrix library (many exist), you may find it has that function available, but if you roll your own matrix class, you'll need to supply this function too.
2,155,275
2,155,307
How to overload unary minus operator in C++?
I'm implementing vector class and I need to get an opposite of some vector. Is it possible to define this method using operator overloading? Here's what I mean: Vector2f vector1 = -vector2; Here's what I want this operator to accomplish: Vector2f& oppositeVector(const Vector2f &_vector) { x = -_vector.getX(); y = -_vector.getY(); return *this; } Thanks.
Yes, but you don't provide it with a parameter: class Vector { ... Vector operator-() { // your code here } }; Note that you should not return *this. The unary - operator needs to create a brand new Vector value, not change the thing it is applied to, so your code may want to look something like this: class Vector { ... Vector operator-() const { Vector v; v.x = -x; v.y = -y; return v; } };
2,155,280
2,155,284
Two '==' equality operators in same 'if' condition are not working as intended
I am trying to establish equality of three equal variables, but the following code is not printing the obvious correct answer which it should print. Can someone explain, how the compiler is parsing the given if(condition) internally? #include<stdio.h> int main() { int i = 123, j = 123, k = 123; if ( i == j == k) printf("Equal\n"); else printf("NOT Equal\n"); return 0; } Output: manav@workstation:~$ gcc -Wall -pedantic calc.c calc.c: In function ‘main’: calc.c:5: warning: suggest parentheses around comparison in operand of ‘==’ manav@workstation:~$ ./a.out NOT Equal manav@workstation:~$ EDIT: Going by the answers given below, is the following statement okay to check above equality? if ( (i==j) == (j==k))
if ( (i == j) == k ) i == j -> true -> 1 1 != 123 To avoid that: if ( i == j && j == k ) { Don't do this: if ( (i==j) == (j==k)) You'll get for i = 1, j = 2, k = 1 : if ( (false) == (false) ) ... hence the wrong answer ;)
2,155,398
2,155,426
code anaylsis node missing from Visual studio 2008
I want to have a look at the VS code analysis tools. This msdn page suggests: Expand the Configuration Properties node. Expand the Code Analysis node. Unfortnately when I expand the configuration properties node I only have the options: General, Debugging, c/C++, Linker, Manifest tool, XML Document Generator, Browse Information, Build Events and Customer Build step. This is in a win32 console application in Visual Studio Professional Edition v 9.0.21022.8 RTM with .net framework 3.5 SP1. Any one know what I'm missing?
Code analysis is not part of the professional version, but only in the more expensive Team System edition. You can however use FXCop instead.
2,155,464
3,337,265
Are there any easy ways to generate OpenGL code for drawing shapes from a GUI?
I have enjoyed learning to use OpenGL under the context of games programming, and I have experimented with creating small shapes. I'm wondering if there are any resources or apps that will generate code similar to the following with a simple paint-like interface. glColor3f(1.0, 0.0, 0.0); glBegin(GL_LINE_STRIP); glVertex2f(1, 0); glVertex2f(2, 3); glVertex2f(4, 5); glEnd(); I'm having trouble thinking of the correct dimensions to generate shapes and coming up with the correct co-ordinates. To clarify, I'm not looking for a program I can just freely draw stuff in and expect it to create good code to use. Just more of a visual way of representing and modifying the sets of coordinates that you need. I solved this to a degree by drawing a shape in paint and measuring the distances between the pixels relative to a single point, but it's not that elegant.
It sounds like you are looking for a way to import 2d geometry into your application. The best approach in my opinion would be to develop a content pipeline. It goes something like this: You would create your content in a 3d modeling program like Google's Sketchup. In your case you would draw 2d shapes using polygons. You need a conversion tool to get the data out of the original format and into a format that your target application can understand. One way to get polygon and vertex data out of Sketchup is to export to Collada and have your tool read and process it. (The simplest format would be a list of triangles or lines.) Write a geometry loader in your code that reads the data created by your conversion tool. You need to write opengl code that uses vertex arrays to display the geometry.
2,155,491
2,155,779
hide function template, declare specializations
This is a followup to C++ templates: prevent instantiation of base template I use templates to achieve function overloading without the mess of implicit type conversions: declare the function template, define desired specializations (overloads). all is well except wrong code does not produce errors until the link phase: lib.hpp: template<class T> T f(T v); lib.cpp: #include "lib.hpp" template<> long f(long v) { return -v; } template<> bool f(bool v) { return !v; } main.cpp: #include <iostream> #include "lib.hpp" int main() { std::cout << f(123L) << ", " << f(true) << ", " << f(234) << "\n" ; } gcc output: c++ -O2 -pipe -c main.cpp c++ -O2 -pipe -c lib.cpp c++ main.o lib.o -o main main.o(.text+0x94): In function `main': : undefined reference to `int get<int>(int)' I'd like to have it fail during compilation of main.cpp. Can I somehow declare only specializations actually implemented? What are my options? The target is C++03, and I'm mainly interested in gcc-4.x and VC9.
It seems to produce a linker error even if you don't put it in the separate file. However, to produce a compiler error for other instantiations, implement the function and use a compile-time assertion, e.g #include <boost/static_assert.hpp> template <class T> T f(T) { //assert some type-dependent "always-false" condition, //so it won't be triggered unless this function is instantiated BOOST_STATIC_ASSERT(sizeof(T) == 0 && "Only long or bool are available"); } template<> long f(long v) { return -v; } template<> bool f(bool v) { return !v; } int main() { //f(100); f(100L); f(false); } And just for general information, C++0x has a much more elegant way to deal with it: template <class T> T f(T) = delete; template<> long f(long v) { return -v; } template<> bool f(bool v) { return !v; }
2,155,675
2,155,708
Can I pass a parameter to an std::vector sort function?
Consider the class: MyClass { int varA; int varB; }; I have a vector of pointers to MyClass objects: std::vector<MyClass*> Vec; I want to sort the vector according to varA or varB using the same sort function, i.e. : bool SortFunction(const MyClass* obj1, const MyClass* obj2, const short type) { if( type == VARA_ID ) return obj1->varA < obj2->varA; else if( type == VARB_ID ) return obj1->varB < obj2->varB; } AFAICT this is not possible. What would be the most elegant way to this without using external libraries?
class sorter { short type_; public: sorter(short type) : type_(type) {} bool operator()(MyClass const* o1, MyClass const* o2) const { return SortFunction(o1, o2, type_ ); } }; std::sort(Vec.begin(), Vec.end(), sorter(MY_TYPE) );
2,155,678
2,197,072
Decrypt file in C++ with Microsoft Crypt API that was encrypted with TripleDES in C#
I'm trying to decrypt a file in unmanaged C++ that was previously encrypted with C# TripleDESCryptoServiceProvider. Unfortunately I do not have a clue how to do that with the Microsoft Crypt API (advapi32.lib). Here is the C# code that I use to encrypt the data: private static void EncryptData(MemoryStream streamToEncrypt) { // initialize the encryption algorithm TripleDES algorithm = new TripleDESCryptoServiceProvider(); byte[] desIV = new byte[8]; byte[] desKey = new byte[16]; for (int i = 0; i < 8; ++i) { desIV[i] = (byte)i; } for (int j = 0; j < 16; ++j) { desKey[j] = (byte)j; } FileStream outputStream = new FileStream(TheCryptedSettingsFilePath, FileMode.OpenOrCreate, FileAccess.Write); outputStream.SetLength(0); CryptoStream encStream = new CryptoStream(outputStream, algorithm.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); // write the encrypted data to the file encStream.Write(streamToEncrypt.ToArray(), 0, (int)streamToEncrypt.Length); encStream.Close(); outputStream.Close(); } As you can see the Key and the IV is quite simple (just for testing purpose). So my question is, how do I decrypt that file in C++? I know that the TripleDESCryptoServiceProvider is just a wrapper for the Crypt API, so it cannot be that difficult to solve this problem. Does anyone ever did something like that and can help me? Thx Simon
Once you get in the groove of things, CryptoAPI is relatively straightforward to use. The problem is doing it in a way that is compatible with other cryptography libraries (including .NET framework). I have successfully done this before, but it has been a while; the major sticking point is figuring out how to convert a plain text key into a format usable with CryptoAPI (which operates with "key blobs"). Luckily Microsoft has given us a working, if tedious, example. As for the CryptoAPI way of doing things, here is an example: // 1. acquire a provider context. // the Microsoft Enhanced provider offers the Triple DES algorithm. HCRYPTPROV hProv = NULL; if(CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) { // 2. generate the key; see Microsoft KB link above on how to do this. HKEY hKey = NULL; if(ImportPlainTextSessionKey(hProv, lpKeyData, cbKeyData, CALG_3DES, &hKey)) { // 3. set the IV. if(CryptSetKeyParam(hKey, KP_IV, lpIVData, 0)) { // 4. read the encrypted data from the source file. DWORD cbRead = 0; while(ReadFile(hSourceFile, buffer, 8192, &cbRead, NULL) && cbRead) { // 5. decrypt the data (in-place). BOOL bFinal = cbRead < 8192 ? TRUE : FALSE; DWORD cbDecrypted = 0; if(CryptDecrypt(hKey, NULL, bFinal, 0, buffer, &cbDecrypted)) { // 6. write the decrypted data to the destination file. DWORD cbWritten = 0; WriteFile(hDestFile, buffer, cbDecrypted, &cbWritten, NULL); } } } CryptDestroyKey(hKey); hKey = NULL; } CryptReleaseContext(hProv, 0); hProv = NULL; }
2,155,867
2,155,965
GTK : How to set the Height of a VBox?
Hi I'm making an app using GTKMM. The screenshot is below: Screenshot The Problem is, I'm not able to position the "My Label" to align at the top, just below the Search box. I'm packing Name,Search box, Search Button into a HBox, which is packed into a VBox, and then MyLabel is packed into the VBox. I think the problem is that the VBox is assigning equal heights to the two rows, So even though I align MYLabel to the top, but it's top is the middle of the screen 'cuz VBox distributed the heights between the two rows equally. Is there a way to set the Heights of the VBox rows?? or any other way out?
Set the "expand" and "fill" properties of the label to false.
2,155,990
2,156,007
C++: How can 2 classes call each other without redeclaration and without headers calling each other
I have a bit of problem with this. I have a class A which instantiates an object of B and then B which instantiates an object of A. Is this at all possible? I tried adding this in the headers of each #ifndef A #define A class a... #endif but if keeps me in an infinite header loop which it reaches the maximum header includes, so obviously one is calling the other and the other is calling that one. Is there any way to achieve this? edit: Okay this seems like a good answer but now A complains that B doesn't have a Constructor despite the fact that it definitely has a constructor. I can't figure that one out.
You can forward declare the classes, for example: A.h: class B; class A { B* a_; }; B.h: class A; class B { A* a_; }; In your source files where you actually use the classes (that is, create them, destroy them, use their members, etc.), you will need to include both headers so that their definitions are available: #include "A.h" #include "B.h"
2,156,064
2,156,071
Can a pointer of a derived class be type cast to the pointer of its base class?
The pointer of derived class returned by new can be type cast to the pointer of its base class. Is this true or false? I know dynamic_cast can be used to cast downside. Generally, how to cast a pointer of derived class to a pointer of its base class?
Yes. Conversion from a pointer to a derived class to a pointer to a base class is implicit. Thus, the following is perfectly fine: struct B { }; struct D : B { }; D* my_d_ptr = new D; B* my_d_ptr_as_a_b_ptr = my_d_ptr;
2,156,305
2,156,350
Double const declaration
I often see the following function declaration: some_func(const unsigned char * const buffer) { } Any idea why the const is repeated before the pointer name? Thanks.
The first const says that the data pointed to is constant and may not be changed whereas the second const says that the pointer itself may not be changed: char my_char = 'z'; const char* a = &my_char; char* const b = &my_char; const char* const c = &my_char; a = &other_char; //fine *a = 'c'; //error b = &other_char; //error *b = 'c'; //fine c = &other_char; //error *c = 'c'; //error
2,156,349
2,156,398
Including header files style - C++
I have a project which has the following directory structure. root --include ----module1 ----module2 --src ----module1 ----module2 So a file say foo.cpp in src/module1 has to include like, #include "../../include/module1/foo.hpp" This looks messy and tough to write. I found writing include like #include <module1/foo.h> and providing include file search path to root/include when compiling looks neat. However, I am not sure that this style has got any drawbacks. Which one do you prefer and why? Also do you see any problems in organizing files in the above way?
#include "../../include/module1/foo.hpp" Specifying paths should be avoided as much as possible. Compilers provide you with a cleaner alternative to achieve the same. Further, a clean design should see to it that you do not need to juggle relative paths for including headers. A better idea of which one to use (including whether to use quotes or the angle-brackets) can be had from the standard. From my copy of the C++ draft: 16.2 Source file inclusion 2 A preprocessing directive of the form #include <h-char-sequence> new-line` searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined. 3 A preprocessing directive of the form # include "q-char-sequence" new-line causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read #include <h-char-sequence> new-line` with the identical contained sequence (including > characters, if any) from the original directive. 7 Although an implementation may provide a mechanism for making arbitrary source files available to the < > search, in general programmers should use the < > form for headers provided with the implementation, and the " " form for sources outside the control of the implementation.
2,156,424
2,156,608
How should I get the fully qualified domain name of "localhost" in c++ (on ubuntu)?
I've been messing around with getaddrinfo and getnameinfo but the closest I got to useful output was "localhost.localdomain". I'm not sure what to pass in for the "node" or "service" args of getaddrinfo, although I think it's the function I want.
Actually, Zxaos's answer here is pretty much the answer I was looking for (even though it's for C and mine was for C++, it works in both): How do I find the current machine's full hostname in C (hostname and domain information)? So I guess my question was a duplicate...
2,156,426
2,163,622
Selection change event for MFC CListCtrl, caused by mouse/keyboard input only
i am using an mfc ListCtrl, is there anyway to know if a selection change was caused by mouse/keyboard input rather than a programatic change? i am after the same behaviour as ON_LBN_SELCHANGE for a listbox. thanks
You can use GetKeyState() to find out whether a key or mouse button was pressed. Do not use GetAsyncKeyState() because that API will tell you the current state of the keyboard/mouse buttons, which may have changed when you handle the LBN_SELCHANGE message. GetKeyState() however will tell you the state as it was when LBN_SELCHANGE was generated.
2,156,463
2,159,972
How does _ReadWriteBarrier propagate up the call tree?
I'm looking at this bit of text in the documentation for Visual C++'s _ReadWriteBarrier intrinsic: In past versions of the Visual C++ compiler, the _ReadWriteBarrier and _WriteBarrier functions were enforced only locally and did not affect functions up the call tree. In Visual C++ 2005 and later, these functions are enforced all the way up the call tree. I understand what the barrier does within a function, but the "up the call tree" seems to imply that a function foo() calling a function bar() can know whether bar() contains a barrier or not. What actually changed in VC2005 to enable this... the calling convention/ABI, some global analysis done by the compiler, or what ?
MS docs are never great, and this one is a good example of that. There are 2 parts to the _ReadWriteBarrier: telling the CPU to do a memory barrier (ie mfence), telling the compiler not to optimize around the barrier. I suspect the call tree part is referring to #2. ie: int x = 0; void foo() { x = 7; _ReadWriteBarrier(); x = 8; } Without the barrier, x=7 can be completely removed by the compiler. With the barrier, it stays. Now, what about a function that calls foo? void bar() { x = 3; // optimized away? foo(); x = 4; } I think in the past x=3 might have been optimized away (which can be hard for the compiler to tell whether that's allowed or not), but now it will correctly keep the x=3 instructions. I think.
2,156,634
2,156,670
Why is a pure virtual function initialized by 0?
We always declare a pure virtual function as: virtual void fun () = 0 ; I.e., it is always assigned to 0. What I understand is that this is to initialize the vtable entry for this function to NULL and any other value here results in a compile time error. Is this understanding correct or not?
The reason =0 is used is that Bjarne Stroustrup didn't think he could get another keyword, such as "pure" past the C++ community at the time the feature was being implemented. This is described in his book, The Design & Evolution of C++, section 13.2.3: The curious =0 syntax was chosen ... because at the time I saw no chance of getting a new keyword accepted. He also states explicitly that this need not set the vtable entry to NULL, and that doing so is not the best way of implementing pure virtual functions.
2,156,697
2,162,925
Debugger ignores errors in dynamically loaded DLLs
I have a very strange problem related to debugging of self-coded DLLs. I have an MFC-driven dialog-based application, several projects linked statically and several DLL-projects which are loaded at runtime. I build solution in debug, run the application and I can easily debug those DLL-projects. Now the problem. If there is some obvious runtime error in DLL like following int* i = 0; *i = 4; debugger asserts no error, throws no exception and silently returns to idle state with even no (visible) stack returns. It looks like when I'm hitting F10 on the statement *i = 4;, the control returns to main application window and program execution continues as nothing happened! And if there are no errors in the code, it executes fine. But I expect errors to be asserted in this case! And they are - in the main application's code. I use LoadLibrary() function to load my DLL into application. DLL itself has MFC statically linked, same as every other project in solution has. Any ideas? Don't even know what question to google...
Oh, it turned out that problem is caused by OpenGL wglMakeCurrent() call and is experienced only under Windows 7 64-bit with NVIDIA GeForce 8800 graphic card, meanwhile all works fine under Windows Vista 32-bit. I asked new question here. Thanks for your feedback.
2,156,710
2,156,721
C++ : Prevent a Class from Initialization
I have a class and in the class constructor I want to check few parameters that have been passed, if any parameter fails the check, I want to prevent the class from initialisation. How can I do that ? Class MyClass { MyClass(int no); }; MyClass::MyClass(int no) { if(no<0) // Prevent the Class from Initialisation } void main() { MyClass myobj(-1); // How to check if myobj is an objecT??? // if(myobj!=null) ??? }
Throw an exception.
2,156,715
2,156,740
in which case derived class must have its own constructor?
In C++, in what case, the derived class must have its own constructor? what about the three cases: 1) public inheritance; 2) private inheritance; 3) protected inheritance; Thanks a lot.
All classes that are instantiated always have to have at least one constructor. If you don't provide one, the compiler will provide one instead. There aren't any special rules for derived classes.
2,156,832
2,156,841
std::string - get data from start to end
I want to get some data between some 2 indexes. For example, I have string: "just testing..." and I need string from 2 till 6. I should get: 'st tes'. What function can do this for me?
Use substr: std::string myString = "just testing..."; std::string theSubstring = myString.substr(2, 6); Note that the second parameter is the length of the substring, not an index (your question is a bit unclear, since the substring from 2 to 6 is actually 'st t', not 'st tes').
2,156,894
2,157,023
Bizarre thread printing behaviour
Hey - I'm having an odd problem with a little toy program I've written, to try out threads. This is my code: #include <pthread.h> #include <iostream> using std::cout; using std::endl; void *threadFunc(void *arg) { cout << "I am a thread. Hear me roar." << endl; pthread_exit(NULL); } int main() { cout << "Hello there." << endl; int returnValue; pthread_t myThread; returnValue = pthread_create(&myThread, NULL, threadFunc, NULL); if (returnValue != 0) { cout << "Couldn't create thread! Whoops." << endl; return -1; } return 0; } With the first cout in main not commented out, the thread prints fine. However, without it, the thread doesn't print anything at all. Any help?
Try this: #include <pthread.h> #include <iostream> using std::cout; using std::endl; void *threadFunc(void *arg) { cout << "I am a thread. Hear me roar." << endl; pthread_exit(NULL); } int main() { //cout << "Hello there." << endl; int returnValue; pthread_t myThread; returnValue = pthread_create(&myThread, NULL, threadFunc, NULL); if (returnValue != 0) { cout << "Couldn't create thread! Whoops." << endl; return -1; } pthread_join( myThread, NULL); return 0; } The difference between my code and yours is one line - pthread join. This suspends the main thread until the sub-thread has had chance to complete its actions. In your code, execution reaches the first cout and it's processed. Then, you split off another thread and the main thread carries on until the end, which may or may not be reached before the secondary thread is tidied up. That's where the odd behaviour comes in - what you are experiencing is the case where the main program finishes before the sub-thread has had a chance to, so the program has "returned" and the whole lot is cleaned up by the kernel.
2,156,902
2,157,647
How do I wrap CFtpFileFind example, in C++?
Trying to wrap this short example in C++. (and its been a while since I did this). int main(int argc, char* argv[]) { //Objects CFtpConnection* pConnect = NULL; //A pointer to a CFtpConnection object ftpClient UploadExe; //ftpClient object pConnect = UploadExe.Connect(); UploadExe.GetFiles(pConnect); system("PAUSE"); return 0; } .h - class ftpClient { public: ftpClient(); CFtpConnection* Connect(); void GetFiles(CFtpConnection* pConnect); }; .cpp - //constructor ftpClient::ftpClient() { } CFtpConnection* ftpClient::Connect() { // create a session object to initialize WININET library // Default parameters mean the access method in the registry // (that is, set by the "Internet" icon in the Control Panel) // will be used. CInternetSession sess(_T("FTP")); CFtpConnection* pConnect = NULL; try { // Request a connection to ftp.microsoft.com. Default // parameters mean that we'll try with username = ANONYMOUS // and password set to the machine name @ domain name pConnect = sess.GetFtpConnection("localhost", "sysadmin", "ftp", 21, FALSE ); } catch (CInternetException* pEx) { TCHAR sz[1024]; pEx->GetErrorMessage(sz, 1024); printf("ERROR! %s\n", sz); pEx->Delete(); } // if the connection is open, close it MOVE INTO CLOSE FUNCTION // if (pConnect != NULL) // { // pConnect->Close(); // delete pConnect; // } return pConnect; } void ftpClient::GetFiles(CFtpConnection* pConnect) { // use a file find object to enumerate files CFtpFileFind finder(pConnect); if (pConnect != NULL) { printf("ftpClient::GetFiles - pConnect NOT NULL"); } // start looping BOOL bWorking = finder.FindFile("*"); //<---ASSERT ERROR // while (bWorking) // { // bWorking = finder.FindNextFile(); // printf("%s\n", (LPCTSTR) finder.GetFileURL()); // } } So basically separated the connection and file manipulation into 2 functions. The findFile() function is throwing the assert. (Stepping into the findFile() and it is specifically at the first ASSERT_VALID(m_pConnection) in inet.cpp. ) How does the way I am passing the arround CFtpConnection* pConnect look? EDIT - Looks like CObject vfptr is overwritten (0X00000000) in the GetFiles() function. Any help is appreciated. Thanks.
ANSWER: This session object must be allocated in the Connection function, with a pointer declared as a member function of the class. When creating the object within the function, "CInternetSession sess(_T("MyProgram/1.0"));" the object/session will be terminated when the function exits, being thrown off the stack. When that happens, we can't use the pConnect pointer in other functions. There is a hierarchy to WinInet objects, with session being the top. If session is gone nothing else can be used. Thus, we must use new to allocate the object in memory so that it sustains after this function exits.
2,156,913
2,156,996
Does protected inheritance allow the derived class access the private members of its base class?
I am really confused about private inheritance and protected inheritance. 1) in protected inheritance, the public and protected members become protected members in the derived class. In the private inheritance, everything is private. However, the derived class can never access the private members of the base class, is that right? The derived class can access the public and protected members in both cases. Is that right? 2) I noticed that the private members of the base class will never be touched by the derived class. So why are the private members inherited?
You are correct on point #1. Specifying private, protected or public when inheriting from a base class does not change anything access-wise on the derived class itself. Those access specifiers tell the compiler how to treat the base-class members when instances of the derived class are used elsewhere, or if the derived class happens to be used as a base class for other classes. UPDATE: The following may help to illustrate the differences: class Base { private: int base_pri; protected: int base_pro; public: int base_pub; }; For classes derived from base: class With_Private_Base : private Base { void memberFn(); }; class With_Protected_Base : protected Base { void memberFn(); }; class With_Public_Base : public Base { void memberFn(); }; // this would be the same for all of the above 3 classes: void With_PXXX_Base::memberFn() { base_pri = 1; // error: `int Base::base_pri' is private base_pro = 1; // OK base_pub = 1; // OK } For classes derived from the 3 derived classes: class A : public With_Private_Base { void memberFn(); } void A::memberFn() { base_pri = 1; // error: `int Base::base_pri' is private base_pro = 1; // error: `int Base::base_pro' is protected base_pub = 1; // error: `int Base::base_pub' is inaccessible } class B : public With_Protected_Base { void memberFn(); } void B::memberFn() { base_pri = 1; // error: `int Base::base_pri' is private base_pro = 1; // OK base_pub = 1; // OK } class C : public With_Public_Base { void memberFn(); } void C::memberFn() { base_pri = 1; // error: `int Base::base_pri' is private base_pro = 1; // OK base_pub = 1; // OK } External access to the first three derived classes: void main() { With_Private_Base pri_base; pri_base.base_pri = 1; // error: `int Base::base_pri' is private pri_base.base_pro = 1; // error: `int Base::base_pro' is protected pri_base.base_pub = 1; // error: `int Base::base_pub' is inaccessible With_Protected_Base pro_base; pro_base.base_pri = 1; // error: `int Base::base_pri' is private pro_base.base_pro = 1; // error: `int Base::base_pro' is protected pro_base.base_pub = 1; // error: `int Base::base_pub' is inaccessible With_Public_Base pub_base; pub_base.base_pri = 1; // error: `int Base::base_pri' is private pub_base.base_pro = 1; // error: `int Base::base_pro' is protected pub_base.base_pub = 1; // OK }
2,156,920
2,157,012
Directed graph implementation
I need to implement a digraph(Directed graph) in c++ as part of a homework and I'm having some issues with how to represent the vertices and edges data types. Can anybody please point me to a example or a simple c++ class that implements this so I can study it and extend from there? I've googled for a bit but I only found results about using Boost or other libraries, I just need something simple that doesn't rely on any library. Thank you.
There are two major ways of representing digraphs with data structures: Node centric. This method represents each node as an object within your program, and each node contains information about other nodes it links to. The other nodes can be as simple as a list of nodes where there exists a directed edge between the current node and the target node. Edge centric. This method represents each edge as an object within your program, and each edge contains information about which nodes it connects. In a digraph, each edge will have exactly one "source" and "destination" node (which may be the same node if you're considering self-loops). This method is essentially a list of ordered pairs. Depending on the problem you're solving, one of these two basic forms will end up being most appropriate. More specific algorithms might need to add more information to the above basic structures, such as for example a list of all nodes reachable from the current node.
2,156,945
2,156,985
Compilation error - no matching function for call to 'Exception::Exception(Exception)'
I can not solve this problem for a while. I would be glad for some advice. When I try to throw an exception (self created one in Java style) throw Exception (); compiler make a protest: DataTypes/Date.cpp:24: error: no matching function for call to `Exception::Exception(Exception)' DataTypes/Date.cpp:24: error: in thrown expression It does not work with any of the constructors I have. What is the problem? Here is header file of the Exception: class Exception { public: Exception(void); explicit Exception(const char *); explicit Exception(const Exception &); Exception(const char *, const Exception &); virtual ~Exception(); const char * message; const Exception & cause; }; I should mention that when I leave just implicit constructor and the second one it works. Thank you for any help.
Your copy constructor is marked explicit, which means it isn't really a copy constructor. Thrown objects must be copyable. To elaborate: The explicit keyword means that a single-argument constructor cannot be used to implicitly convert a variable of the argument type to an object of the constructed type. You have to do it explicitly with the class name. For example, your constructor from const char* is explicit, so the compiler will never implicitly convert a const char* to a new object of type Exception, without you writing out Exception("some string here"). On the other hand, you do want the compiler to be able to implicitly make one Exception object into another Exception object (that's what a copy constructor does!), so by taking the constructor that would otherwise be the copy constructor and marking it with the explicit keyword, you have completely eliminated its ability to make copies.
2,157,062
2,157,094
What does it mean when a variable appears red in the visual studio C++ debugger?
what does it mean when a variable appears red in the visual studio C++ debugger? I assume not good. Thanks.
Its value changed during the last 'step'. Don't worry, there is nothing wrong.
2,157,149
2,157,450
Runtime typeswitch for typelists as a switch instead of a nested if's?
This is from TTL: //////////////////////////////////////////////////////////// // run-time type switch template <typename L, int N = 0, bool Stop=(N==length<L>::value) > struct type_switch; template <typename L, int N, bool Stop> struct type_switch { template< typename F > void operator()( size_t i, F& f ) { if( i == N ) { f.operator()<typename impl::get<L,N>::type>(); } else { type_switch<L, N+1> next; next(i, f); } } }; It's used for typeswitching on a TypeList. Question is -- they are doing this via a series of nested if's. Is there a way to do this type switch as a single select statement instead? Thanks!
You'll need the preprocessor to generate a big switch. You'll need get<> to no-op out-of-bound lookups. Check the compiler output to be sure unused cases produce no output, if you care; adjust as necessary ;v) . Check out the Boost Preprocessor Library if you care to get good at this sort of thing… template <typename L> struct type_switch { template< typename F > void operator()( size_t i, F& f ) { switch ( i ) { #define CASE_N( N ) \ case (N): return f.operator()<typename impl::get<L,N>::type>(); CASE_N(0) CASE_N(1) CASE_N(2) CASE_N(3) // ad nauseam. } };
2,157,162
2,157,514
C++ template for generating parts of switch statement?
Is it possible to write a template Foo<int n> such that: Foo<2> gives switch(x) { case 1: return 1; break; case 2: return 4; break; } while Foo<3> gives switch(x) { case 1: return 1; break; case 2: return 4; break; case 3: return 9; break; } ? Thanks! EDIT: changed code above to return square, as many have guessed (and I poorly asked)
Yes, make a template with an oversized master switch and hope/help the optimizer turns it into a little switch. See my answer to your other question Runtime typeswitch for typelists as a switch instead of a nested if's?. Also, don't duplicate-post.
2,157,368
2,157,421
Change progress bar with circular wait image
Is it possible to skin the GTK+ progress bar widget such that it shows a custom image (an AJAX style animated gif maybe)? If so how and if not, is there any other option/control which can achieve this effect?
Something like GtkSpinner?
2,157,458
2,157,477
Using 'const' in class's functions
I've seen a lot of uses of the const keyword put after functions in classes, so i wanted to know what was it about. I read up smth at here: http://duramecho.com/ComputerInformation/WhyHowCppConst.html . It says that const is used because the function "can attempt to alter any member variables in the object" . If this is true, then should it be used everywhere, because i don't want ANY of the member variables to be altered or changed in any way. class Class2 { void Method1() const; int MemberVariable1;} So, what is the real definition and use of const ?
A const method can be called on a const object: class CL2 { public: void const_method() const; void method(); private: int x; }; const CL2 co; CL2 o; co.const_method(); // legal co.method(); // illegal, can't call regular method on const object o.const_method(); // legal, can call const method on a regulard object o.method(); // legal Furthermore, it also tells the compiler that the const method should not be changing the state of the object and will catch those problems: void CL2::const_method() const { x = 3; // illegal, can't modify a member in a const object } There is an exception to the above rule by using the mutable modifier, but you should first get good at const correctness before you venture into that territory.
2,157,510
2,157,519
const cast to allow read lock, does this smell bad?
I want to execute a read-only method on an object marked as const, but in order to do this thread-safely, I need to lock a readers-writer mutex: const Value Object::list() const { ScopedRead lock(children_); ... } But this breaks because the compiler complains about "children_" being const and such. I went up to the ScopedRead class and up to the RWMutex class (which children_ is a sub-class) to allow read_lock on a const object, but I have to write this: inline void read_lock() const { pthread_rwlock_rdlock(const_cast<pthread_rwlock_t*>(&rwlock_)); } I have always learned that const_cast is a code smell. Any way to avoid this ?
Make the lock mutable mutable pthread_rwlock_t rwlock; This is a common scenario in which mutable is used. A read-only query of an object is (as the name implies) an operation that should not require non-const access. Mutable is considered good practice when you want to be able to modify parts of an object that aren't visible or have observable side-effects to the object. Your lock is used to ensure sequential access to the object's data, and changing it doesn't effect the data contained within the object nor have observable side-effects to later calls so it is still honoring the const-ness of the object.
2,157,606
2,157,663
about throw() in C++
void MyFunction(int i) throw(); it just tells the compiler that the function does not throw any exceptions. It can't make sure the function throw nothing, is that right? So what's the use of throw() Is it redundant? Why this idea is proposed?
First of all, when the compiler works right, it is enforced -- but at run-time, not compile-time.. A function with an empty exception specification will not throw an exception. If something happens that would create an exception escaping from it, will instead call unexpected(), which (in turn) calls abort. You can use set_unexpected to change what gets called, but about all that function is allowed to do is add extra "stuff" (e.g. cleanup) before aborting the program -- it can't return to the original execution path. That said, at least one major compiler (VC++) parses exception specifications, but does not enforce them, though it can use empty exception specifications to improve optimization a little. In this case, an exception specification that isn't followed can/does result in undefined behavior instead of necessarily aborting the program.
2,157,620
2,158,134
Reading/Writing integer values on a string object
I have the contents of a file assigned into a string object. For simplicity the file only has 5 bytes, which is the size of 1 integer plus another byte. What I want to do is get the first four bytes of the string object and somehow store it into a valid integer variable by the program. Then the program will do various operations on the integer, changing it. Afterward I want the changed integer stored back into the first four bytes of the string object. Could anyone tell me I could achieve this? I would prefer to stick with the standard C++ library exclusively for this purpose. Thanks in advance for any help.
The following code snippet should illustrate a handful of things. Beware of endian differences. Play around with it. Try to understand what's going on. Add some file operations (binary read & write). The only way to really understand how to do this, is to experiment and create some tests. #include <iostream> #include <string> using namespace std; int main(int argc, char *argv[]) { int a = 108554107; // some random number for example sake char c[4]; // simulate std::string containing a binary int *((int *) &c[0]) = a; // use casting to copy the data // reassemble a into b, using indexed bytes from c int b = 0; b |= (c[3] & 0xff) << 24; b |= (c[2] & 0xff) << 16; b |= (c[1] & 0xff) << 8; b |= c[0] & 0xff; // show that all three are equivalent cout << "a: " << a << " b: " << b << " c: " << *((int *) &c[0]) << endl; return 0; }
2,157,629
2,157,700
Linking static libraries to other static libraries
I have a small piece of code that depends on many static libraries (a_1-a_n). I'd like to package up that code in a static library and make it available to other people. My static library, lets call it X, compiles fine. I've created a simple sample program that uses a function from X, but when I try to link it to X, I get many errors about missing symbols from libraries a_1 - a_n. Is there a way that I can create a new static library, Y that contains X and all the functionality needed by X (selected bits from a_1 - a_n), so that I can distribute just Y for people to link their programs to? UPDATE: I've looked at just dumping everything with ar and making one mega-lib, however, that ends up including a lot of symbols that are not needed (all the .o files are about 700 MB, however, a statically linked executable is 7 MB). Is there a nice way to include only what is actually needed? This looks closely related to How to combine several C/C++ libraries into one?.
Static libraries do not link with other static libraries. The only way to do this is to use your librarian/archiver tool (for example ar on Linux) to create a single new static library by concatenating the multiple libraries. Edit: In response to your update, the only way I know to select only the symbols that are required is to manually create the library from the subset of the .o files that contain them. This is difficult, time consuming and error prone. I'm not aware of any tools to help do this (not to say they don't exist), but it would make quite an interesting project to produce one.
2,157,854
2,158,275
virtual function in private or protected inheritance
It's easy to understand the virtual function in public inheritance. So what's the point for virtual function in private or protected inheritance? For example: class Base { public: virtual void f() { cout<<"Base::f()"<<endl;} }; class Derived: private Base { public: void f() { cout<<"Derived::f()"<<endl;} }; Is this still called overriding? What's the use of this case? What's the relationship of these two f()? Thanks!
Private inheritance is just an implementation technique, not an is-a relationship, as Scott Meyers explains in Effective C++: class Timer { public: explicit Timer(int tickFrequency); virtual void onTick() const; // automatically called for each tick ... }; class Widget: private Timer { private: virtual void onTick() const; // look at Widget private data ... }; Widget clients shouldn't be able to call onTick on a Widget, because that's not part of the conceptual Widget interface.
2,157,891
2,158,039
Does dispatching on a Boost variant type take linear time?
How efficient is dispatching on a boost::variant ? If it's a switch statement, it should only take O(1) time, but as far as I know, template metaprogrammign can only generate if's, which would put boost::variant dispatchs at a runtime overhead of O(n), where n = number of types in the variant. Can anyone confirm/deny/enlighten me on this? Thanks!
Looking at the source, it should be constant time. Boost uses Boost.PreProcessor to generate a switch-table, and keeps track of which index it should jump to (via the type being stored).
2,158,088
2,158,161
Slow C++ DirectX 2D Game
I'm new to C++ and DirectX, I come from XNA. I have developed a game like Fly The Copter. What i've done is created a class named Wall. While the game is running I draw all the walls. In XNA I stored the walls in a ArrayList and in C++ I've used vector. In XNA the game just runs fast and in C++ really slow. Here's the C++ code: void GameScreen::Update() { //Update Walls int len = walls.size(); for(int i = wallsPassed; i < len; i++) { walls.at(i).Update(); if (walls.at(i).pos.x <= -40) wallsPassed += 2; } } void GameScreen::Draw() { //Draw Walls int len = walls.size(); for(int i = wallsPassed; i < len; i++) { if (walls.at(i).pos.x < 1280) walls.at(i).Draw(); else break; } } In the Update method I decrease the X value by 4. In the Draw method I call sprite->Draw (Direct3DXSprite). That the only codes that runs in the game loop. I know this is a bad code, if you have an idea to improve it please help. Thanks and sorry about my english.
Try replacing all occurrences of at() with the [] operator. For example: walls[i].Draw(); and then turn on all optimisations. Both [] and at() are function calls - to get the maximum performance you need to make sure that they are inlined, which is what upping the optimisation level will do. You can also do some minimal caching of a wall object - for example: for(int i = wallsPassed; i < len; i++) { Wall & w = walls[i]; w.Update(); if (w.pos.x <= -40) wallsPassed += 2; }
2,158,306
2,158,543
VS2008 Detected Dependencies - Versions
After building my project on two different machines, my setup project seems to inject microsoft_vc90_mfc_x86.asm dependencies with different versions. My local machine uses version 9.0.21022.8 while the build machine uses 9.0.30729.1. I've checked the Visual Studio versions and they are both 9.0.30729.1 SP. The build machine has some hotfixes and my local machine has VS2005 installed as well. Is there any known issue that might cause my local machine to insert the 9.0.21022.8 version? Both installers seem to work on all my test targets, but it makes me nervous that the build machine produces a different sized installer.
Your local machine uses the RTM version, your build machine uses the SP1 version. It really sounds like you don't have SP1 installed on your local machine. Note that both versions are obsolete, the current version is 9.0.30729.4148. A security patch that was distributed last July. You can get it from here.