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
3,240,284
3,240,292
qt example from the book
I have this snippet of the code: #include <QApplication> #include <QFont> #include <QPushButton> #include <QWidget> class MyWidget : public QWidget { public: MyWidget(QWidget *parent = 0); }; MyWidget::MyWidget(QWidget *parent) : QWidget(parent) { setFixedSize(200, 120); QPushButton *qu...
That is an argument to the constructor with a default argument (NULL since NULL is defined as 0 as per the c++ standard). Default meaning passing no parameter is the same as passing NULL. Since Qt's widgets are arranged in a hierarchal system (parent -> child relationships) parent is the widget which is the "owner" or ...
3,240,556
3,241,582
Windows: Get LCID from locale string?
I have string data representing locales, like "fr" or "en". I need to convert it to the appropriate LCID values, like 0x80c or 0x409. Is there a function or macro to do so? I'm using C++ on Windows 7.
Those are LCID values, not sure what LID means. You can get them out of GetLocaleInfoEx(), available in Vista and up. You need to pass a locale name like "en-US", necessary to nail down the language locale. For example: #include "stdafx.h" #include <windows.h> #include <assert.h> int _tmain(int argc, _TCHAR* argv[...
3,240,681
3,240,811
C++ syntax/legality of inheriting from a template while also specifying type
How can I accomplish what is suggested by the following?: template<typename T> class Base{...}; ... class Derived : public Base<int>{...};
Yes, it's legal. Base is a class template, and when provided all its template parameters it can be instantiated, which makes it an instantiated class. So Base<int> is a class name, and you can inherit from it just fine.
3,240,707
3,240,743
Enum vs Macro States C++
(Question is related to my previous questions here, here, here, and here). I am maintaining a very old application that was ported years ago from DOS to Windows, but a lot of the old C conventions still carry forward. The one particular convention is a setBit and clrBit macro: #ifndef setBit #define setBit(word, mask) ...
I think you're confusing the purposes. The enum is about setting up values to use as flags. setBit and clrBit are about operating on data. That data might happen to be a flag, but that's really the only relationship between the two ideas. That being said, macros are certainly NOT the C++ way of doing things. You would ...
3,240,846
3,240,882
Do you know a tool for c++ program that shows which program line allocated how much heap?
I have a c++ program that dies because of out of memory error. Do you know a tool for c++ program that shows which program line allocated how much heap? I would like to figure which part of the program consumes most of the heap. Thanks. Platform: Microsoft C++...Windows By the way, can heap corruption cause excessive m...
You could use something like valgrind on *nix platform or crtdbg checks on windows platform.
3,241,035
3,241,204
Using C++ templates or macros for compile time function generation
I have a code that runs on an embedded system and it has to run really fast. I know C and macros, and this particular project is coded mostly in C but it also uses C++ templates [increasingly more]. There is an inline function: inline my_t read_memory(uint32 addr) { #if (CURRENT_STATE & OPTIMIZE_BITMAP) return re...
The inline function will be parsed once, at the point in the translation unit where it is declared, and the state of the macros at that point will be used. Calling the function multiple times with the macros defined differently will not change the definition of the function. You can do this with a template though --- i...
3,241,190
3,241,395
how to append a matrix to the end of another matrix? (using Boost Libraries in C++)
I have this: using namespace boost::numeric::ublas; matrix<double> m (3, 2); int k = 0; for (int j = 0; j < m.size1 (); j++) { for (int i = 0; i < m.size2 (); i++) m (j, i) = k++; } m = 0 1 2 3 4 5 And I need to append another matrix m2 to m matrix<double> m2...
Well, this is not elegant, but is my first try: m.resize(m.size1(), m.size2()+1, true); column(m, m.size2()) = column(m2, 0); and, of course it needs to be adjusted if m2 has more than one column (or if there are differences in size1 between the two matrices)
3,241,307
3,241,332
About the copy constructor and pointers
I'm reading through an example in primer and something which it talks about is not happening. Specifically, any implicit shallow copy is supposed to copy over the address of a pointer, not just the value of what is being pointed to (thus the same memory address). However, each of the pos properties are pointing to two ...
You're printing the addresses of the pointers, not the address of the string they're pointing to: cout << &blak.pos << endl; cout << &tom.pos << endl; They are two different pointers, so their addresses differ. However, they point to the same string: cout << static_cast<void*>(blak.pos) << endl; cout << static_cast<...
3,241,464
3,241,500
Find count of overlapping 1 bits
I'm trying to find the number of overlapping 1 bits between 2 given numbers. For example, given 5 and 6: 5 // 101 6 // 110 There is 1 overlapping 1 bit (the first bit) I have following code #include <iostream> using namespace std; int main() { int a,b; int count = 0; cin >> a >> b; while (a & b != 0) ...
The problem is that you're just printing out the number of times any of the bits match, as you lop off the least significant bit for each iteration (which will at max be the number of bits set for the smaller number). You're comparing all bits of [a] BITWISE AND [b] each iteration. You could rectify this by masking wit...
3,241,494
3,241,823
ptr_vector - _CrtDumpMemoryLeaks() - memory leaks even though destructor is called
I'm working on a game engine and in an earlier question it was suggested that I start using boost::ptr_vector to maintain a list of pointers. The basic idea is to have several State's, each State has a SceneGraph. Each state has several resources that they initialize, and then stuff its own SceneGraph. The SceneGraph h...
It sure doesn't look like a vector you're leaking. Note that the string is readable, that's at least one hint. If you can get the number between the curly braces stable ("{173}") then you can get a breakpoint when the memory is allocated. Put this in your main() function: _crtBreakAlloc = 173; Use #include <crtdbg.h...
3,241,577
3,241,651
Including extra libraries on the link line
When linking an executable, if it does not make reference to any of the symbols in one of the DLLs on the link line, will it still depend on that DLL at runtime? To make the question concrete, suppose I am building an application from Visual Studio project foo. Under Project Properties > Linker > Input > Additional Dep...
No it is not required. A import library only a library and the EXE will include only the references to functions which are used. By the way to verify this you can use DUMPBIN.EXE utility or dependencies walker (see http://www.dependencywalker.com/) which are part of Visual Studio packages. Just type DUMPBIN.EXE foo.exe...
3,241,634
3,241,672
SIGALRM Timeout -- How does it affect existing operations?
I am currently using select() to act as a timer. I have network receive operations which occur within a loop, and every few seconds a processing operation needs to occur. As a result, the select() statement's timeout constantly changes -- decreasing to zero over time and then restarting at 3. rv = select(selectmonitor+...
Use your SIGALRM handler to set a flag variable. Use sigaction instead of signal to set your signal handler. Do not set the SA_RESTART flag. With SA_RESTART not set your select statement will be interrupted by the signal. Your select will return -1 and errno will be EINTR. Since the signal might happen while your othe...
3,241,645
3,241,745
proper style for interfacing with legacy TCHAR code
I'm modifying someone else's code which uses TCHAR extensively. Is it better form to just use std::wstring in my code? wstring should be equivalent to TString on widechar platforms so I don't see an issue. The rationale being, its easier to use a raw wstring than to support TCHAR... e.g., using boost:wformat. Which st...
If you are only intending on targetting Unicode (wchar_t) platforms, you are better off using std::wstring. If you want to support multibyte and Unicode builds, you will need to use TString and similar. Also note that basic_string defaults the char_traits and allocator to one based on the passed in character type, so o...
3,241,749
3,241,769
boost static_assert with message?
on 1.43 boost it seems that BOOST_STATIC_ASSERT just allows to put a boolean value, is there some alternative that allows me to display a message as well on the compile error?
MPL has BOOST_MPL_ASSERT_MSG. E.g. using GCC 4.2. with this: BOOST_MPL_ASSERT_MSG(false, THIS_DOESNT_WORK, (void)); ... results in: /path/to/file.cpp:42: error: no matching function for call to 'assertion_failed(mpl_::failed************ (function()::THIS_DOESNT_WORK::************)())'
3,241,781
3,241,880
Boost.Statechart - issue with documented method for choice points
As per the example in the documentation I made the following code that fails to compile because custom_reaction<> does not seem to match the concept expected as the third template parameter to state<>. How do I really make choice points? (I also asked this on the boost list) #include <boost/statechart/state_machine.hp...
I think I might have found the answer. I'll wait for verification from the boost list but it looks like the document is just wrong and if you follow the directions in the camera example for making custom reactions it works fine. Namely the choice_point template needs to change to this: // universal choice point base ...
3,241,899
3,241,906
What is the error in the following g++ class construction?
I receive a g++ error (undefined reference to 'SomeClass::SomeClass(int)' and 'SomeClass::~SomeClass') with the following: /* * SomeClass.h * */ #ifndef SOMECLASS_H_ #define SOMECLASS_H_ class SomeClass { public: SomeClass(); SomeClass(int someInt); ~SomeClass(); }; #endif /* SOMECLASS_H_ */ /* * ...
SomeClass::SomeClass someObject(1); First of all that's not valid, because SomeClass::SomeClass names the constructor, and not the class type. Just say SomeClass. Then you probably forget to link against SomeClass.cpp's object file. Be sure to include it in the compiler command line when you compile the executable, or...
3,241,954
3,242,023
Performance of .Net function calling (C# F#) VS C++
Since F# 2.0 has become a part of VS2010 I take an interest in F#. I wondered what's the point of using it. I'd read a bit and I made a benchmark to measure functions calling. I have used Ackermann's function :) C# sealed class Program { public static int ackermann(int m, int n) { if (m == 0) ...
I believe that in this case, the difference between C# and F# is thanks to tail-call optimization. A tail-call is when you have a recursive call that is done as "the last thing" in a function. In this case, F# doesn't actually generate a call instruction, but instead compiles the code into a loop (because the call is t...
3,242,255
3,242,271
Multiple Threads - do i need to lock on reading data?
look at this code: int data=5; void Thread1() { if(data==5) { //nothing } } void Thread2() { if(data==2) { //nothing } } in this case, do i need to use EnterCriticalSection/MutexLock before if(data==..) ?
If you are just reading the data then no locks required. If you are writing the data AND you care about the order data is read then you need to use CS to make sure the ordering is correct. (Note if the object has a more complex state that is not updated in an atomic operation then you may care more about the ordering o...
3,242,256
3,242,553
How does GMP stores its integers, on an arbitrary number of bytes?
2^64 is still far from the "infinity" my ram/hard drive can handle... First I wonder how GMP works with memory/processor since it does some kind of shady optimisations... I was also wondering if there is a way of storing an integer (unsigned, it's easier) on an arbitrary number of bytes. For example, on 50 bytes, I wou...
GMP dynamically allocates space to represent numbers (and reallocates when it needs to grow). This is described in light detail in Integer Internals, in the GMP manual, it describes how it chunks up the representation into "limbs" and stores the limbs in an array. The description of the term "limbs" comes from GMP Basi...
3,242,284
3,242,346
Can I define a type based on the result of some calculation?
I perform some calculations, based on the result, I would like to either use a short int or int for some type of data for the remaining program. Can (/How can) this be done sensibly in C or C++? I don't really care about the amount of memory used (i.e., 2 or 4 bytes), my primary aim is to access generic arrays as if th...
For plain C, you could do this using function pointers: static union { s_int[32]; s_short[64]; s_char[128]; } s; static void set_s_int(int i, int n) { s.s_int[i] = n; } static int get_s_int(int i) { return s.s_int[i]; } static void set_s_short(int i, int n) { s.s_short[i] = n; } static int get_s_short(i...
3,242,475
3,242,586
Controlling how parameters are sent to superclass constructor from subclass constructor declaration (C++)
Can it be done? I am looking for something different than using the member initialization list (because that is present in the definition, not necessarily the declaration). Something like class(args) : superclass(fn of args);
What you are asking makes no sense. In C++ each class has a constructor. For a constructor the declaration defines the parameters. For a constructor the definition defines how the parameters are used (like how they are passed to the base class). Example: Plop.h ============= class Point { public: Point(int x...
3,242,505
3,242,524
How to create service which restarts on crash
I am creating a service using CreateService. The service will run again fine if it happens to crash and I would like to have Windows restart the service if it crashes. I know it is possible to set this up from the services msc see below. How can I programatically configure the service to always restart if it happens t...
You want to call ChangeServiceConfig2 after you've installed the service. Set the second parameter to SERVICE_CONFIG_FAILURE_ACTIONS and pass in an instance of SERVICE_FAILURE_ACTIONS as the third parameter, something like this: int numBytes = sizeof(SERVICE_FAILURE_ACTIONS) + sizeof(SC_ACTION); std::vector<char> buffe...
3,242,555
3,242,564
Overloading operator++ prefix / postfix in terms of each other?
I have a question that may have been answered over 9000 times before but I really don't know how to word it, this is what I am going to try. I've seen in some C++ books and tutorials that when defining your own class which has a iterable value (incrementable) semantics, you can overload operator++ for it (all I'm going...
Boost provides this functionality in the Boost Operators utility library. Its implementation is a little different, but achieves the same result. Can I / Should I use this trick? Use it wherever you can; cutting out redundant and repetitive code is a fundamental principle of refactoring and is a good practice to get...
3,242,662
3,247,502
fftw3 on windows 64-bit
I would like to use FFTW3 on Windows-64 bit. I follow the instructions on FFTW website: download the package, unzip, run lib.exe to create .lib "import libraries". After doing so, I build my application (which runs just fine using FFTW3 dlls 32-bit) and I get the following errors: 1>pyramidTransform.obj : error LNK2...
I found the problem. With FFTW3, since the authors have already compiled the DLLs for Windows, you need to create import libraries (.lib) files from the supplied .def files. You do so by going to the Visual Studio 2008 command prompt: lib /def:libfftw3-3.def Microsoft (R) Library Manager Version 9.00.21022.08 Copyr...
3,242,768
3,246,143
Purging Preprocessing Macros
This is an odd problem, so I have to provide a bit of background. I have a C++ project that I'm working on that I want to clean up a bit. The main issue that I'm dealing with that makes me want to barf is the massive abuse of preprocessor macros that are used in a core component of the project. There's a file with a bu...
this is supposed to be a real-time system that will be dealing with millisecond units of time That's a real problem. [...] that having an if check would adversely affect our performance. That's not a good reason. If your code has been benchmarked for performance and optimized as a result (as it should have ...
3,242,897
3,245,221
Can I configure Visual Studio to use real folders instead of filters in C++ projects?
It's annoying to have to separately maintain a .filters file to make Visual Studio happy, as well as my project's on-disk layout. Is it possible to tell VS to use real folders, like it does for C#?
In the Solution Explorer in Visual Studio, just click the toolbar button called 'Show All Files'. That does exactly what you want. EDIT(Billy O'Neal): Added image for others so they don't have to hunt... (source: billy-oneal.com)
3,243,146
3,243,284
Why does this EXC_BAD_ACCESS happen with long long and not with int?
I've run into a EXC_BAD_ACCESS with a piece of code that deals with data serialization. The code only fails on device (iPhone) and not on simulator. It also fails only on certain data types. Here is a test code that reproduces the problem: template <typename T> void test_alignment() { // allocate memory and record ...
That's actually very annoying, but not so unexpected for those of us bought up in a pre-x86 world :-) The only reason that comes to mind (and this is pure speculation) is that the compiler is "fixing" your code to ensure that the data types are aligned correctly but the sizeof/alignof mismatches are causing problems. I...
3,243,240
3,245,670
Uninstall a J2ME application through J2ME code?
Is there any way to do this? I found some Symbian C++ codes that could do it but nothing in J2ME. I have a J2ME certificate and don't have Symbian C++ certificate. Thanks in advance, Ashish.
Unless the device manufacturer has extensions to allow this, it is not possible to uninstall JavaME midlets from JavaME code.
3,243,401
3,243,479
Passing objects and object oriented design best practices
I'm a university student learning programming. For practice I'm writing a blackjack program. I'm using C++ and doing an object oriented approach to this. I have a Deck class designed that basically builds and shuffles a deck of cards. The deck generated is composed of an array of 52 Card class objects. That's what I h...
My first question is: Is it bad practice to make the array of Card objects public in the Deck class? Yes. In general, data members should always be private. It is good OOP to create an interface with no associated data that defines what operations can be performed on the object, and then to provide a concrete class t...
3,243,454
3,243,463
What is the Linux equivalent to MAXDWORD?
In Microsoft Visual C++, there is a constant called MAXDWORD defined in winnt.h as follows: #define MAXDWORD 0xffffffff It's useful as a high initial value for a 'double' when one is searching for the lowest value in a collection. Google though I might, I can't find the equivalent in standard headers on Linux, but I'...
Standard solution is to use std::numeric_limits. For instance, std::numeric_limits<long>::max(). You could use any standard type instead of long there. You even can to specialize numeric_limits for custom types.
3,243,581
3,243,674
Using getenv function in Linux
I have this following simple program: int main() { char* v = getenv("TEST_VAR"); cout << "v = " << (v==NULL ? "NULL" : v) << endl; return 0; } These lines are added to .bashrc file: TEST_VAR="2" export TEST_VAR Now, when I run this program from the terminal window (Ubuntu 10.04), it prints v = 2. If I r...
On my system (Fedora 13) you can make system wide environment variables by adding them under /etc/profile.d/. So for example if you add this to a file in /etc/profile.d/my_system_wide.sh SYSTEM_WIDE="system wide" export SYSTEM_WIDE and then open a another terminal it should source it regardless of who the user is open...
3,243,649
3,255,124
Dependency injection: do we all need to know that?
One of my friend (he is a .NET/C++ developer, as I am) asked me: Dependency injection: do we all need to know that? Why? Could you please tell: Your opinion: do we really need to know that pattern and how to implement it? Good reference (link) that could explain "why?" Thank you a lot. P.S. I am understanding that ...
Good comments are posted here, but there are no clear answer on the question "Your opinion: do we really need to know that pattern and how to implement it?" From my perspective it should be "yes" if at least one of option is applied to you: you need to write (automated) unit-tests for application; you need to decouple...
3,243,711
3,243,776
Member function cannot access private member
I have got the following code #include <iostream> #include <string> template <typename T> class demo { T data; public: demo(); demo(demo const&k ); demo(const T&k); demo& operator=(const demo &k); template<typename T1> demo(const demo<T1>&k); template<typename T1> demo<T>& oper...
Because demo<T> and demo<T1> are considered different types they may not access each other's private data. Easist way to solve this is by adding a public accessor function and using it: template <typename T> class demo { public: const T &get_data() const { return data; } ... }; template<typename T> template<ty...
3,244,269
3,244,285
C++ : How expensive is ofstream.tellp()?
I want to call it in a tight loop thousands of times per second . Is it an expensive call? I am using Windows Visual C++ .
C++ doesn't mandate the performance (in seconds) of any particular parts of that standard library (although many containers and algorithms have complexity requirements). This means that you are at the mercy of your implementation. The only reliable thing to do is to measure it and see if it is acceptable in your applic...
3,244,681
3,286,966
How to get the Last Active Date of a Process?
I have an assignment were in I have to print the last active date of the process using a COM In Proc Server in C++. I tried doing that with getProcessTimes() function, but that gives me an access violation error. First of all, I want to know if there is anyother command that gives the last active date of the process.. ...
Here is an article that demonstrates how to use GetProcessTimes. It includes sample code. Another option is using WMI and the WIN32_Process class, which also has this information. Here is an example of how you would use WMI.
3,244,741
3,244,980
Need some help writing my results to a file
My application continuously calculates strings and outputs them into a file. This is being run for almost an entire day. But writing to the file is slowing my application. Is there a way I can improve the speed ? Also I want to extend the application so that I can send the results to an another system after some partic...
There are several things that may or may not help you, depending on your scenario: Consider using asynchronous I/O, for instance by using Boost.Asio. This way your application does not have to wait for expensive I/O-operations to finish. However, you will have to buffer your generated data in memory, so make sure ther...
3,244,760
3,246,629
How to get all duplicate symbol linker errors at once?
I am building a C++ project in XCode which uses two libraries. Say for e.g libX.a and libY.a. There are some function definitions common on libX.a and libY.a for which I get duplicate symbol linker error. This is fine, but I get only one error at a time. Once I fix the error, I'll get the next duplicate symbol error an...
You can use the nm command to list all the symbols in the libraries, and sort and uniq -d to print the duplicates. Something like: nm -j test1.o test2.o | sort | uniq -d This will also list the undefined symbols they share in common. You can get a list of those with nm -u. A bit of a hack, but it might get you there...
3,245,048
3,247,607
(student) interview questions - programming for a robotics lab
my robotics lab is looking for programmers to work on some projects we have at the moment. We nailed down the requirements (mainly, c++ and experience with openGL and 3D), but due to obvious money constraints we can't afford to hire Great Developers. Instead we're going to settle for Talented Students, offering them p...
Actually, here's my best advice: Recruit among your students. Since you work for an academic institution I assume that either you or your colleagues teach. This provides you with a wealth of information about what potential recruits are capable of -- how fast they learn, how motivated they are, what they are good and b...
3,245,099
3,245,143
Overloading operator<< to work for string
In the following code: using namespace std; //ostream& operator<< (ostream& out,const string & str) //{ // out << str.c_str(); // return out; //} int _tmain(int argc, _TCHAR* argv[]) { ofstream file("file.out"); vector<string> test(2); test[0] = "str1"; test[1] = "str2"; ...
You do not need to overload operator<< to work with strings, it already knows how to handle them. std::copy( test.begin(), test.end(), std::ostream_iterator<std::string>( file, "\n" ) ); will produce: str1 str2 Is there anything different/special that you want to be done there?
3,245,148
3,245,163
C++ template question
Is there any way to achieve the specified behaviour? If there is some trick or this could be done using traits or enable_if, please let me know. template <typename T> struct Functional { T operator()() const { T a(5); // I want this statement to be tranformed into // plain 'r...
Just specialize for void: template <typename T> struct Functional { T operator()() const { T a(5); return a; } }; template <> struct Functional<void> { void operator()() const { } };
3,245,310
3,245,611
C++ Boost function comparison
I have a class which contains boost::function as one of its arguments. I have to make this class equality comparable but the boost::function is not equality comparable. Is there a easy workaround for this problem? Thanks, Gokul.
boost::function is not eq_compare because there is good way to handle the fact that many functors are not eq_compare. Here is a bit of insight into it: http://www.boost.org/doc/libs/1_35_0/doc/html/function/faq.html#id690470 Unfortunately, the boosties decided not to provide a policy-based approach which would allow us...
3,245,321
3,245,361
C++ variant for Java long?
Is there a C++ variant for the long primitive data-type? A C++ long is only 4 bytes, while a Java long is 8 bytes. So: Is there a non-decimal primitive type with a size of 8 bytes in C++? Maybe with some tricks? Thanks
Microsoft Visual C++ defines an __int64 type that's equivalent to Java's long. gcc has int64_t. There's even a long long int type defined in the ISO C99 standard, however according to the standard it's at least 64 bits wide, but could be wider. But apart from the size, there's also endianness to consider. The Java stan...
3,245,387
3,246,947
Automatically generate a locale csv file for Excel in C++
I want to generate a csv file containing numbers and I want Excel to read that file automatically. However, Excel uses a different csv format depending on the locale settings. For example: English: Text separator: , Decimal separator: . Spanish: Text separator: ; Decimal separator: , Is it possible to automaticall...
I don't think that standard C++ has a notion of "text separator", and that this is Windows-specific. You could thus use GetLocaleInfo with the LOCALE_SLIST flag.
3,245,405
3,245,903
Embedding a Prolog engine in Obj-C projects
I'm looking for a light-weight Prolog engine to be embedded in an Obj-C application under Mac OSX. In Java there are some excellent implementations with the characteristics I need: deployability, lightness, dynamic configurability, integration with Java and ease of interoperability. Can you recommend something similar ...
GProlog supports Mac OS X (Darwin) and there's an installer for Mac OS X Leopard. And here you can read how to call gprolog from C (read also this). Then instead of using gplc, you can use gcc provided that you add the proper options for linking, which could be a bit "trickie" to be found; so you can produce object fil...
3,245,406
3,245,707
Allocating largest buffer without using swap
In C/C++ under Linux, I need to allocate a large (several gigabyte) block of memory, in order to store real-time data from a sensor connected to the ethernet port and streaming data at about 110MB/s. I'd like to allocate the largest amount of memory possible, to maximise the length of data sequence that I can store. Ho...
Well, under linux you can use mlock()/mlockall() to keep an adress range in physical memory and prevent it from being swapped out. The process using mlock needs a couple of privileges to do so, "man mlock" has the details. I am not sure about the maximum mlock'able block (it might differ from what seems to be "free"), ...
3,245,518
3,245,534
Calling delete on two pointers to the same object
I'm having a problem with a couple of event handler classes I'm trying to write. Basically, the idea is to have an event handler class for each logical group of objects. In most cases, the events are between objects and their handler, but in some cases events are also sent between handler objects as well. I've written ...
I've written the code such that the events are placed on a stack and deleted after their information is read and acted upon. There is some confusion here - objects on the stack should not be deleted. Objects created with new (on the heap) should. In general, you should define a clear ownership strategy for your obje...
3,245,552
3,245,576
Why is Erlang said to be more suited for server side programming in webgames than Java and C++?
I don't really understand, how can Erlang be more efficient than C++?
Erlang is far less efficient than C++. Erlang's big strength is scalability, not efficiency. It will linearly scale across multiple CPUs and, due to its programming and communications model, will very easily scale across machine clusters. Just to be clear, Erlang won't scale more than C++; it just scales more easily th...
3,245,914
3,245,990
What field of PE Headers tells that whether a valid PE file or not?
I need to validate whether the given binary is a PE file or not (e.g. if I rename JS/HTML or .class files to .exe or .dll), it won't still be PE files. Parsing PE files would give me info about this problem; what field indicates that a given binary is a valid PE file or not? I have checked the "e_magic" field of FileHe...
Check the Portable Executable/Common Object File Format Specification. There are three magic values for you to check: The MZ header's magic number at the beginning of the file The PE header's magic number "PE\0\0" at the start of the PE header Version identifier for the optional header, IIRC, it's 0x10b for PE files, ...
3,245,955
3,245,970
Defining constants inside a structure
Is there any special significance to defining constant data inside a structure as shown. This is from a 3rd party library. typedef struct { IntVB abc_number; #define ABC_A 0x01 #define ADBC_E 0x02 IntVB asset; } StructA;
Not really. They probably provide better significance to the programmer in that spot of the code. Meaning that those constants are probably related to the items in that struct container, or to the behavior of the struct.
3,246,161
3,246,241
C++ optimization question
I have some mid-large project that is actively using boost libraries and, hence, suffers in terms of Debug application performance (Visual Studio 2008). Solution that I use right now means turning on function inlining even in Debug mode, which brings enough performance, but should definitely have some drawbacks. Does a...
In my opinion, you should probably not be performance-testing your debug release. Save the debug release for unit testing so you can easily find problems but real testing (functionality and performance) should probably be on the release version. That's what your customers will be running after all, right?
3,246,380
3,246,972
On the use (and usefulness) of a pointer to member function vs directly calling the member function
I am new to pointer to member functions, and I would like to know their pros and cons. Specifically, consider this: #include <iostream> #include <list> using namespace std; class VariableContainer; class Variable { public: Variable (int v) : value (v), cb_pointer (0) {} ~Variable () {} void SetCallback (void ...
Depending on what will vary in the future, you can decide: Other functions will be called by the variable's FireCallback => a pointer-to-mf may be useful, but other mechanisms are more c++ish Only the 'Callback' function is going to be called => stick with calling arg->CallBack() directly. A possible solution to the ...
3,246,441
3,246,623
What does "BUS_ADRALN - Invalid address alignment" error means?
We are on HPUX and my code is in C++. We are getting BUS_ADRALN - Invalid address alignment in our executable on a function call. What does this error means? Same function is working many times then suddenly its giving core dump. in GDB when I try to print the object values it says not in context. Any clue where to...
You are having a data alignment problem. This is likely caused by trying to read or write through a bad pointer of some kind. A data alignment problem is when the address a pointer is pointing at isn't 'aligned' properly. For example, some architectures (the old Cray 2 for example) require that any attempt to read an...
3,246,462
3,247,752
Dynamic Creation in Qt of QSlider with associated QLCDNumber
I was wondering what's the best way to go about the following scenario? I am dynamically creating QSliders that I wish to link to an associated QLCDNumber for display. The thing is I would like to have tenths available, so I would like to have a conversion between the QSLider and the QLCDNumber to divide by 10. At this...
This is basically what I ended up using; it seems to work (though it violates the whole object oriented philosophy). signalMapper= new QSignalMapper(this); QObject::connect(tmpSlider, SIGNAL(valueChanged(int)), signalMapper, SLOT(map())); sliderMapper->setMapping(tmpSLider, tmpLCDNumber); QObject::connect(signalMapper,...
3,246,528
3,246,543
Is there a better way to initialize an allocated array in C++?
How to write this in another (perhaps shorter) way? Is there a better way to initialize an allocated array in C++? int main(void) { int* a; a = new int[10]; for (int i=0; i < 10; ++i) a[i] = 0; }
int *a =new int[10](); // Value initialization ISO C++ Section 8.5/5 To value-initialize an object of type T means: — if T is a class type (clause 9) with a user-declared constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor)...
3,246,619
3,247,061
C++ / Objective-C : The two files of a class are called Header and ...?
In languages like C++ or Objective-C a class normally consist of two files. The first is called Header or Interface but what is the "official" name of the other file? In some books it's just called "Codefile" in other "implementation file" or "message file" for Objective-C. Which name is the right name? I need to write...
I always refer to them as "header files" and "implementation files".
3,246,712
3,246,979
C++ - pointer passing question
Does somebody have any idead on how to pass boost::shared_ptr - by value or by reference. On my platform (32bit) sizeof(shared_ptr) equals 8 bytes and it looks like I should pass them by reference, but maybe somebody has another opinion / did a profile / something like that?
You can see this in two ways: a boost::shared_ptr is an object (and should be passed by const &). a boost::shared_ptr models a pointer and should be treated as a pointer. Both of them are valid, and the second option will incur the cost of constructing and destructing the additional instance (which shouldn't be a big...
3,246,761
3,246,795
Protected vs Private Destructor
Is there any difference between a protected and a private destructor in C++? If a base classes destructor is private, I imagine that it is still called when deleting the derived class object.
Taken from here: If the constructor/destructor is declared as private, then the class cannot be instantiated. This is true, however it can be instantiated from another method in the class. Similarly, if the destructor is private, then the object can only be deleted from inside the class as well. Also, it prevents the...
3,246,803
3,247,093
Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?
I have always seen people write class.h #ifndef CLASS_H #define CLASS_H //blah blah blah #endif The question is, why don't they also do that for the .cpp file that contain definitions for class functions? Let's say I have main.cpp, and main.cpp includes class.h. The class.h file does not include anything, so how do...
First, to address your first inquiry: When you see this in .h file: #ifndef FILE_H #define FILE_H /* ... Declarations etc here ... */ #endif This is a preprocessor technique of preventing a header file from being included multiple times, which can be problematic for various reasons. During compilation of your proje...
3,246,895
3,247,156
Can parentheses take arbitrary identifiers as arguments? C++
For example, is (const int)* someInt; valid code? If so, is that statement different than const int* someInt; ?
You can put arbitrarily many parentheses around expressions without changing the meaning. But you cannot do the same with types. In particular, as the others have pointed out, the parenthese in your code change the meaning from a declaration to a cast.
3,246,917
3,246,946
Can I increase int i by more than one using the i++ syntax?
int fkt(int &i) { return i++; } int main() { int i = 5; printf("%d ", fkt(i)); printf("%d ", fkt(i)); printf("%d ", fkt(i)); } prints '5 6 7 '. Say I want to print '5 7 9 ' like this, is it possible to do it in a similar way without a temporary variable in fkt()? (A temporary variable would margi...
"A temporary variable would marginally decrease efficiency, right?" Wrong. Have you measured it? Please be aware that ++ only has magical efficiency powers on a PDP-11. On most other processors it's just the same as +=1. Please measure the two to see what the actual differences actually are.
3,247,030
3,247,309
How to customize the display of a QListView
I have implemented a list of users in my Qt program, using the model/view principle of Qt. My QListView displays a subclass of QAbstractListModel and so far this works just fine. Now I would like to customize the display of my user list (display the name on several line, add IP information, and so on: not really releva...
You need to create a new item delegate class to handle the painting. Here is a good answer to a similar question.
3,247,224
3,247,286
C++ friend operator overload doesn't compile
I have the following (cut-down) class definition, and it has compilation errors. #include <iostream> #include <string> class number { public: friend std::ostream &operator << (std::ostream &s, const number &num); friend std::string &operator << (std::string, const number &num); friend s...
The function signatures are different: friend std::string &operator << (std::string, const number &num); friend std::string &operator >> (std::string, number &num); are declared with a string parameter by value, while std::string & operator >> (std::string &s, number &num) ... std::string & o...
3,247,285
3,247,339
const int = int const?
For example, is int const x = 3; valid code? If so, does it mean the same as const int x = 3; ?
They are both valid code and they are both equivalent. For a pointer type though they are both valid code but not equivalent. Declares 2 ints which are constant: int const x1 = 3; const int x2 = 3; Declares a pointer whose data cannot be changed through the pointer: const int *p = &someInt; Declares a pointer who c...
3,247,344
3,266,742
a way to omit taking names for objects that are used only to construct a final object
Suppose we have following two classes: class Temp{ public: char a; char b; }; class Final{ private: int a; char b; char c; public: Final(Temp in):b(in.a),c(in.b){} //rest of implementation }; suppose the only use of objects of Temp class is to construct objects of Final class, so I wonder if in curren...
there's no such thing as I want in current c++ standard, but in upcoming c++0x standard, to initialize an object of the Final class, we can write: Final obj({'a','b'}); So no naming for initializer object of the Temp class !!!
3,247,632
3,247,731
c++ cout with float producing strange results
Currently I have the following: float some_function(){ float percentage = 100; std::cout << "percentage = " << percentage; //more code return 0; } which gives the output percentage = 100 However when I add some std::endl like so: float some_function(){ float percentage = 100; std::cout << "p...
Your code is perfectly valid. I suspect that you could be smashing your stack or heap in some other part of your code as the most likely cause. 0x6580a8 is too short to be an object address. Also, he would never get the same address in two runs of the same program.
3,247,660
3,247,822
C++ Reading signed 32-bit integer value
I have a multi-byte primitive type called s32 which I want to read from a byte array. The specifications are: It is a 32-bit signed integer value, stored in little-endian order. Negative integers are represented using 2's complement. It uses 1 to 5 bytes depending on the magnitude. Each byte contributes its low seve...
Are you working on a little-endian system? If so following should do the trick. if(!(0x80 & buffer[index])) { if(0x40 & buffer[index]) value = -value; break; } If you need the negative of a little endian value on a big endian system, then it is a bit more tricky, but that requirement would seem very strange to...
3,247,667
3,248,372
Which is the default C++0x mode in Visual C++ 2010 Express?
I have just installed Visual C++ 2010 Express and I have the impression that the default mode includes C++0x features and the std::tr1 library. error C2872: 'is_same' : ambiguous symbol could be 'C:\Program Files\Microsoft Visual Studio 10.0\VC\INCLUDE\type_traits(941) : std::tr1::is_same' Could you confirm th...
YES : VC10 provide some C++0x featrues (auto, decltype, r-value reference, etc) and std::tr1 inside std namespace and it's not optional AFAIK. However, you can still use VS2010 with VC9 (that don't have those features) if you have it installed too. To do this, just change the compiler version in the project setting fro...
3,247,671
3,247,689
Accessing protected members in a derived class
I ran into an error yesterday and, while it's easy to get around, I wanted to make sure that I'm understanding C++ right. I have a base class with a protected member: class Base { protected: int b; public: void DoSomething(const Base& that) { b+=that.b; } }; This compiles and works just fine....
A class can only access protected members of instances of this class or a derived class. It cannot access protected members of instances of a parent class or cousin class. In your case, the Derived class can only access the b protected member of Derived instances, not that of Base instances. Changing the constructor to...
3,247,717
3,248,382
Image sequence transfer using socket, noob question
I am building an C++ application server-client where the client sends an image (170kb) to a server every 200ms. Using UDP, the files uncompressed are over 64kbs allowed by each datagram (I'd like to avoid compressing the files if possible). On the other hand I'm having problems setting a TCP connection, I managed stabl...
First of all, don't use UDP for that. TCP was designed for what you need and does a lot already by itself. From you POV, TCP connections will always somehow work, whereas with UDP, you'll have to take care of packet sequencing, packets missings, etc. For example, an image takes 3 packets to transfer, UDP does not gu...
3,247,837
3,248,418
Strange debugger problem?
I have created this datastructure: class Event { public: Event(EVENT_TYPE type, void* pSender = 0, int content1 = 0, int content2 = 0, int content3 = 0, int content4 = 0); ~Event(void); // ... some functions protected: EVENT_TYPE itsType; void* itsPointerToSender; int itsContent_1; ...
Sounds to me like the debugger is using the wrong .pdb file. Tools + Options, Debugging, General, ensure that "Require source files to exactly match the original version" is checked. While debugging with a breakpoint active, use Debug + Windows + Modules and right-click your executable in the list. Click "Symbol Load...
3,247,861
3,248,017
Example of UUID generation using Boost in C++
I want to generate just random UUID's, as it is just important for instances in my program to have unique identifiers. I looked into Boost UUID, but I can't manage to generate the UUID because I don't understand which class and method to use. I would appreciate if someone could give me any example of how to achieve thi...
A basic example: #include <boost/uuid/uuid.hpp> // uuid class #include <boost/uuid/uuid_generators.hpp> // generators #include <boost/uuid/uuid_io.hpp> // streaming operators etc. int main() { boost::uuids::uuid uuid = boost::uuids::random_generator()(); std::cout << uuid << std::endl; } Ex...
3,248,135
3,248,159
Book about programming in Windows 7
Could anyone recommend good book about programming in windows 7 in C++?
It is not a book in the classical sense, but it is great, extremely comprehensive when it comes to the Windows API (all new Windows 7 technologies are covered), and normative: MSDN.
3,248,255
3,248,354
Why doesn't C++ have virtual variables?
This might have been asked a million times before or might be incredibly stupid but why is it not implemented? class A { public: A(){ a = 5;} int a; }; class B:public A { public: B(){ a = 0.5;} float a; }; int main() { A * a = new B(); cout<<a-...
To access B::a: cout << static_cast<B*>(a)->a; To explicitly access both A::a and B::a: cout << static_cast<B*>(a)->A::a; cout << static_cast<B*>(a)->B::a; (dynamic_cast is sometimes better than static_cast, but it can't be used here because A and B are not polymorphic.) As to why C++ doesn't have virtual variables: ...
3,248,456
3,248,539
Decimal to Binary, strange output
I wrote program to convert decimal to binary for practice purposes but i get some strange output. When doing modulo with decimal number, i get correct value but what goes in array is forward slash? I am using char array for being able to just use output with cout <<. // web binary converter: http://mistupid.com/compute...
It must be array_main[i] = (char) (decimal % 2 + '0'); (note the parentheses). But anyway, the code is horrible, please write it again from scratch.
3,248,469
3,248,483
Returning *this with an assignment operator
I went over making my own copy constructor and it overall makes sense to me. However, on the topic of doing your own assignment operator I need someone to fill in the blank for me. I pretty much don't get why you are returning *this in all the examples, such as the one below: Foo & Foo::operator=(const Foo & f) { //s...
You want to return *this so you can chain =: Foo f, g, h; f = g = h; This is basically assigning h into g, then assigning g (returned by return *this) into f: f = (g = h); Another situation this is sometimes used in is having an assignment in a conditional (considered bad style by many): if ( (f = 3).isOK() ) { Wit...
3,248,554
3,250,303
What's the difference between set<pair> and map in C++?
There are two ways in which I can easily make a key,value attribution in C++ STL: maps and sets of pairs. For instance, I might have map<key_class,value_class> or set<pair<key_class,value_class> > In terms of algorithm complexity and coding style, what are the differences between these usages?
Set elements cannot be modified while they are in the set. set's iterator and const_iterator are equivalent. Therefore, with set<pair<key_class,value_class> >, you cannot modify the value_class in-place. You must remove the old value from the set and add the new value. However, if value_class is a pointer, this doesn't...
3,248,704
3,259,131
C++ vs PHP performance on PCA
May I know whether C++ or PHP is more efficient on running PCA (Principal Component Analysis)? I'm developing a web based system which get uploaded image with php, and then process the image so that I can analyse the image with PCA to find out whether the image match with another image which already stored in database....
Generally speaking, in computationally intensive projects, code doing the same steps is 100 times faster in C (or C++ for that matter) compared to PHP. Optimizing your C will give another 2-10 times increase, depending on the time, effort and knowledge you put in. The point is that PHP is interpreted, and C runs, loose...
3,248,726
3,248,743
Freeing allocated memory
Is this good practice? Or should I just replace the code block between { and } with a function? It could be reusable (I admit) but my only motivation for doing this is to deallocate colsum since it's huge and not required so that I can free the allocated memory. vector<double> C; { vector<double> colsum; A.col_su...
Using brackets to scope automatic variables is fine in my book, but generally if you find yourself doing it a lot, especially multiple times in the same function, your function is probably doing too many different things and should be broken up.
3,248,818
3,434,969
boost::iostreams::zlib::default_noheader seems to be ignored
I'm having trouble getting boost::iostreams's zlib filter to ignore gzip headers ... It seems that setting zlib_param's default_noheader to true and then calling zlib_decompressor() produces the 'data_error' error (incorrect header check). This tells me zlib is still expecting to find headers. Has anyone gotten boost::...
I think what you want to do is something that's described here which is to adjust the window bits parameter. e.g zlib_params p; p.window_bits = 16 + MAX_WBITS; in.push(zlib_decompressor(p)); in.push(ifs); MAX_WBITS is defined in zlib.h I think.
3,248,925
3,261,014
how does OpenID differ between different logins on the same OpenID endpoint
I am trying to implement an own OpenID endpoint based on SMF user accounts. I based my code on phpMyOpenID and some SMF authorization code. It works fine so far. I can use the endpoint to login/register on any site. If I am not logged in on the SMF, it will ask for my login and if that SMF login is successful, it accep...
It seems the first request from the end user I am getting is checkid_setup. On that response, I can specify a unique URL (what I call the unique string in my question) in the openid.identity field. I have done that in my code now and it seems to work. I.e. I can enter the general OpenID endpoint URL (for example on Sou...
3,249,139
3,249,227
Can't Read in two strings separated by a space
I am trying to read in two strings separated by a space. cin>>a; cin>>b; This should technically work. I have also used getline but it doesnt seem to work. It reads in some of the inputs and gets stuck on others Edit: Added C++ tag, kept C tag since it's part of the original post.
This: #include <iostream> #include <sstream> int main() { std::istringstream iss("wrgl zrgl"); std::string s1, s2; iss >> s1 >> s2; std::cout << '"' << s1 << "\" \"" << s2 << "\"\n"; return 0; } compiles, runs, and prints "wrgl" "zrgl" on my machine.
3,249,147
3,249,527
Unexpected const reference behavior
#include <iostream> class A { public: A(){ cerr << "A Constructor" << endl; } ~A(){ cerr << "A Destructor" << endl; } A(const A &o){ cerr << "A Copy" << endl; } A& operator=(const A &o){ cerr << "A Assignment" << endl; return *this; } }; class B : public A { public: B() : A() { cer...
The important verbiage in the current standard (C++03) seems to be in §8.5.3, which explains how references are initialized (In these quotes, T1 is the type of the reference being initialized and T2 is the type of the initializer expression). If the initializer expression is an rvalue, with T2 a class type, and "cv1 T...
3,249,150
3,249,229
Pointer seen by Visual Studio as a void**
something strange is happening to my code. I am using a library which is supposed to work perfectly (nglib from the open-source Netgen mesher). I can link and include everything, but I cannot use this library : The object I want to use is Ng_Mesh* mesh = Ng_NewMesh (); The Ng_NewMesh() method is : DLL_HEADER Ng_Mes...
Here it says: /// Data type for NETGEN mesh typedef void * Ng_Mesh; therefore Ng_Mesh* mesh; is the same as void** mesh;
3,249,358
3,249,425
c++ exception-like message passing
I'm working on developing a fairly robust 2D game engine as a base that other games can be built off of as a for-fun project (I know theres already things that do this, but that's no fun). I'm trying to figure out a good way to do message-passing between classes within the engine. At first I was thinking about using a...
Although this requires explicit registration, this sounds like you want callbacks (eased by e.g. Boost.Function) or signals (like Boost.Signals/Signals2).
3,249,452
3,249,547
C++: speed of std::stack::pop() method
I'm writing a lighter version of some containers from STL for myself. (I know that STL was written by professional programmers and I am too stupid or too ambitious if think that I can write it better than they did. When I wrote my list (only with method I need), it worked few times faster. So, I thought it's a good id...
Because of delete topE. With STL (at least for the SGI implementation), there is no automatic delete on pop(). If you've dynamically allocated the elements in the stack, it's up to you to deallocate before calling pop(). The STL pop just shortens the stack size by one (and destroys the last object - not necessarily a ...
3,249,638
3,249,650
How can private member variables in a superclass be accessed in a subclass?
I want to do something like: /* * Superclass.h * */ class Superclass { const int size; public: Superclass():size(1){} ~Superclass(){} }; /* * Subclass.h * */ #include "Superclass.h" class Subclass : public Superclass { public: Subclass(){size;} ~Subclass(){} };
Use protected instead of private
3,249,738
4,483,294
get_driver_instance() crashes with Qt
I'm trying to User MySQL Connector/C++ with Qt, and had spent hours pulling my hairs on a problem. Here's a SIMPLE code to test out the connection: int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); cout << "aa" << endl; sql::Driver *driver; try { driver = get_driver_instance(); } catch(exception &e...
From the documentation of MySQL Connector: "One problem that can occur is when the tools you use to build your application are not compatible with the tools used to build the binary versions of MySQL Connector/C++. Ideally you need to build your application with the same tools that were used to build the MySQL Connecto...
3,250,044
3,250,262
Switching the "Files of type" pull-down in .NET OpenFileDialog clears the list of files bug
I'm trying to use the .NET class OpenFileDialog in C++ and getting a weird bug. My basic code is below. OpenFileDialog^ openFileDialog = gcnew OpenFileDialog; openFileDialog->InitialDirectory = "c:\\"; openFileDialog->Filter = "Bitmap|*.bmp|All Files|*.*"; openFileDialog->FilterIndex = 1; openFileDialog->RestoreDirecto...
This is pure operating system behavior. The dialog lives in the shell, the .NET wrapper class is a very thin one around GetOpenFileName(). I don't know much about XP x64, except that it was training wheels for Vista x64. It wasn't done with several COM servers not yet translated to x64. And that it didn't get the SP...
3,250,056
3,250,144
C/C++ within Ruby code?
C/C++ would be good option to write some of the performance critical aspects of a Ruby Application. I know this is possible. I would like to know how to add C/C++ code into Ruby code; any other language for that matter. Are there any practical applications of this which you noticed in open source projects or else?
Besides "Extending Ruby", here are two other resources: README.EXT (extension.rdoc) - shows you more about how to build C extensions. A good compliment to "Extending Ruby" Ruby Inline - This is a library that tries to make it easier to build C extensions by having you call methods in ruby to compile C code.
3,250,123
3,250,450
What would a std::map extended initializer list look like?
If it even exists, what would a std::map extended initializer list look like? I've tried some combinations of... well, everything I could think of with GCC 4.4, but found nothing that compiled.
It exists and works well: std::map <int, std::string> x { std::make_pair (42, "foo"), std::make_pair (3, "bar") }; Remember that value type of a map is pair <const key_type, mapped_type>, so you basically need a list of pairs with of the same or convertible types. With unified initialization with std::pai...
3,250,181
3,250,222
Overhead of retrieval of an object compared to storing in local
Suppose you have a private static method called Inst() which allows the class to retrieve the single instance of itself in the application in its static methods. Maybe Inst() is defined something like.. return App::GetApp()->CurrentState()->MyClass(); // Inst returns a reference Compare this... // I prefer this Inst()...
You worry about the wrong things and have answered the question yourself. Profile it and optimize if it's a bottleneck. Anyway: Inst() is probably going to be inlined, so there is no function call overhead and as it is static and the result is not depending on any obvious outside parameters it could be possible for com...
3,250,195
3,250,285
else if string compare problem
I have the following if statements, two of which don't seem to work. I don't get why it works when I try to compare it to a single character "y" or "n" but not when I try to compare it to two characters in one else if statement. The last question I have is if there's a better cleaner way to write this or if this accep...
Unfortunately, the language doesn't give you an easy way to check a variable against a set of possibilities. You have to do each test individually or use a switch statement. So, either of the following code samples would be a valid solution for your problem: else if (somestr == 'y' || somestr == 'Y'){ //do something ...
3,250,217
3,250,246
C++ inheritance question
I have the following problem in application architecture and am willing to solve it (sorry for a lot of text). I am building a game engine prototype and I have base abstract class AbstractRenderer (I will use C++ syntax, but still the problem is general). Assume there are some derived implementations of this renderer, ...
This might be a situation where the template pattern (not to be confused with C++ templates) comes in handy. The public Render in the abstract class should be non-virtual, but have it call a private virtual function (e.g. DoRender). Then in the derived classes, you override DoRender instead. Here's an article that goes...
3,250,339
3,250,812
C++ header file variable scope issue
I've got 3 files that relate to this problem. file.h, file.C and user.C. file.h has a private member, fstream logs. In file.C's constructor it opens logs. It doesn't do this in the constructor, but the constructor calls a function OpenLog(). file.h also has an inline close function: CloseLog() {if (logs) logs.close();...
void user::quitHelpME(item) { helpME* hME = (helpME*) item; This doesn't create an instance, it's using C style casting to cast from whatever item is to a pointer to helpME. if item is NULL then calling a method on it will seq fault. otherwise still not enough detail in your example to give you an answer, the code pre...
3,250,467
3,253,827
What is inside .lib file of Static library, Statically linked dynamic library and dynamically linked dynamic library?
What is inside of a .lib file of Static library, Statically linked dynamic library and dynamically linked dynamic library? How come there is no need for a .lib file in dynamically linked dynamic library and also that in static linking, the .lib file is nothing but a .obj file with all the methods. Is that correct?
For a static library, the .lib file contains all the code and data for the library. The linker then identifies the bits it needs and puts them in the final executable. For a dynamic library, the .lib file contains a list of the exported functions and data elements from the library, and information about which DLL they ...
3,250,579
3,250,647
How do I insert data into a pre-allocated CSV?
Text file (or CSV) is: Data:,,,,,\n (but with 100 ","s) In C or C++ I would like to open the file and then fill in values between the ",". i.e.- Data:,1,2,3,4,\n I'm guessing that I need some sort of search to find the next comma, insert data, find the next comma insert, etc. I was looking at memchr() for...
You can't actually do that in C... if you open in read/write mode you'll overwrite characters, not insert them. http://c-faq.com/stdio/fupdate.html You need to open the file, read the line into memory, write the new line to a temp file. After you're done inserting all the lines, copy the temp file over the original f...
3,250,841
3,251,098
ensure that an iterator dereferences to a certain type
I have to implement a function that takes an iterator. The iterator must dereference to a certain type, say int: template<typename iter> void f(iter i) { // do something here ... int t = *i; // do something here ... } The problem with this code is that if a user calls the function like this vector<string> v; v...
GMan already pointed to a method to solve this via compile time assertions. There is another way to do this, which I prefer (it's my favorite C++ technique). You can put constraints on function arguments in a way that the function is ignored for overload resolution if the constraints don't fit. This is quite terrific,...
3,250,988
3,251,227
How well does the Visual C++ 2008/2010 compiler optimize?
Im just wondering how good the MSVC++ Compiler can optimize code(with Code examples) or what he can't optimize and why. For example i used the SSE-intrinsics with something like this(var is an __m128 value)(it was for an frustrum-culling test): if( var.m128_f32[0] > 0.0f && var.m128_f32[1] > 0.0f && var.m128_f32[2] > 0...
The default for the compiler is set to generate code that wil run on a 'lowest common denominator' CPU - ie one without SSE 4.1 instructions. You can change that by targetting later CPUs only in the build options. That said, the MS compiler is traditionally 'not the best' when it comes to SSE optimisation. I'm not even...
3,251,079
3,251,116
Array stores name retrieved from GetVolumeInformation weirdly in Visual C++?
I would like to use the GetVolumeInformation call to retrieve the name of a removable device. I can retrieve the name just fine and store into a TCHAR array variable szVolNameBuff. Here is my code for that: // Get Volume Information to check for NTFS or FAT TCHAR szFileSys[256]; TCHAR szVolNameBuff[256]; DWORD ...
It looks like you are using the unicode Win32 APIs. You should use _tprintf so that the appropriate function (printf or wprintf) is used according to the character type. If you don't know unicode - here's a quick overview. The reason this is happening is that the unicode for the regular ascii characters is a null byte ...
3,251,167
3,251,181
How to write a pointer to std::cerr?
Given: MY_CLASS* ptr = MY_CLASS::GetSomeInstance(); What is the correct way to output ptr to std::cerr, so I can log its value? Note I don't want to write the class, just the address.
operator<< is overloaded to take a const void*, so you can simply insert the pointer into the stream: std::cerr << ptr; The exception is that if the pointer is a const char*, it will be interpreted as a pointer to a C string. To print the pointer, you need to cast it explicitly to a const void*: std::cerr << static_c...