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...
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 of...
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: ...
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 cleanl...
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 : pu...
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...
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 ...
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. Wit...
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,heig...
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 s...
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 Com...
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 ti...
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....
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, St...
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 FooConstIte...
[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 thi...
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 g...
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 redirec...
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, T...
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:...
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 tak...
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...
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>(); } }; ...
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....
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,...
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 ...
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...
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...
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::setpr...
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 Fundamenta...
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 dashbo...
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...
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...
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 fa...
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...
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...
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 la...
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++ plu...
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 cipherte...
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); } ...
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...
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, QStr...
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 a...
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...
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"); _l...
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::stri...
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; } ...
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(Sq...
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 ...
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...
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. §...
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 ...
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 dur...
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...
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 requir...
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 shou...
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 s...
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 anothe...
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 en...
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 0xffff...
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 parti...
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 implement...
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....
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; }; A...
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 mi...
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 usua...
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 flexib...
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 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 mo...
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 ...
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...
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\Memo...
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 ); _Crt...
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 ...
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 o...
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 + - + ...
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...
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 c...
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 Coc...
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::f...
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/point...
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 ...
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 = -_...
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: c...
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 =...
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 In...
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); glVert...
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....
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 phas...
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" co...
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...
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 streamToEncr...
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...
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 proble...
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 ...
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 ava...
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; /...
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....
#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 (includi...
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 LB...
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 functio...
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; _ReadWr...
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...
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 the...
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 } ...
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 <<...
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_...
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.GetF...
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...
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...
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...
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 ...
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 cu...
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: ...
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...
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& ...
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...
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 ha...
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 i...
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...
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 t...
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...
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 ...
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 ...
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 ...
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, ...
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 req...
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 thi...
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...
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/e...
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 ...
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 mini...
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 m...
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.