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 |
|---|---|---|---|---|
722,386 | 722,413 | How to get rid of g++ hash_map deprecation warning? | When I compile a c++ application I'm writing that makes use of hash_map, I get this warning on g++ 4.3.2:
You are using the deprecated header . To eliminate this warning, use an ANSI-standard header file or use hte -Wno-deprecated compiler flag.
9> #include <ext/hash_map>
What include replaces this? I've searched for... | My very first Google hit for "g++ hash_map deprecated" takes me to a page that includes a list of things to use instead of the deprecated headers and classes.
For hash_map, the list suggests using unordered_map, in the unordered_map header. The class is new for TR1.
|
722,555 | 798,447 | Unexposing a snapshot in XP (Volume Shadow Copy) | Microsoft provides a way of mounting a read-only snapshot as a volume using their vshadow program. However, it does not provide a way to unmount the snapshot (I wonder what would happen if I deleted the snapshot?). Going through the documentation on MSDN I found UnexposeSnapshot Method, and added the ability to use it ... | Use Windows' built-in mount management utility mountvol.exe.
On API level, you should be able to use DeleteVolumeMountPoint.
|
722,788 | 722,794 | How do I access a C++ subscript operator from within the class in which it resides? | Where, ClassA has an operator as such, that returns ClassB:
class ClassA
{
public:
ClassA();
ClassB &operator[](int index);
}
If I want to access said operator from within ClassA's constructor, as so:
ClassA::ClassA()
{
// How do I access the [] operator?
}
At the moment, as a work-around I'm just using a... | Try the following
(*this)[0] = ...
|
722,801 | 722,870 | fast way to parse a configuration | Say you have
char *= "name:454";
What is the best way to parse name and the number, thus
std:string id would equal to "name";
double d would equal to 454;
STL please, no boost.
| #include <iostream>
#include <sstream>
#include <string>
int main() {
/* output storage */
std::string id;
double d;
/* convert input to a STL string */
std::string s("name:454");
size_t off = std::string::npos;
/* smart replace: parsing is easier with a space */
if ((off = s.find(':')) != std::st... |
722,814 | 722,840 | What is a good multiplatform vector graphics library for C/C++? | I'm looking for a good multiplatform library for vector graphics in C/C++. Any recommendation or thougts?
Thanks
EDIT: Thanks for all your answers!! Could anyone tell me the pros and cons of qt vs cairo, for example? Cairo got more votes, but it seems to be from 5 to 7 times slower according to some benchmarks...
| You can try out Cairo - it's opensource, not too heavy and has a flexible license.
|
722,822 | 722,879 | Correct place to initialize class variables? | Where is the correct place to initialize a class data member?
I have the class declaration in a header file like this:
Foo.h:
class Foo {
private:
int myInt;
};
Then I try to set a value to myInt in the corresponding .cpp file:
Foo.cpp:
int Foo::myInt = 1;
I get a compiler error for redefining myInt. What am I do... | What you have there is an instance variable. Each instance of the class gets its own copy of myInt. The place to initialize those is in a constructor:
class Foo {
private:
int myInt;
public:
Foo() : myInt(1) {}
};
A class variable is one where there is only one copy that is shared by every instance of the cl... |
722,838 | 722,848 | beginner c++: virtual functions in a base class | I'm writing some code where I defined the following base class.
class Chorus{
public:
//Destructor
virtual ~Chorus();
//callback function
virtual int callback( void *outputBuffer, void *notUsed, unsigned int
nBufferFrames, double streamTime, RtAudioStreamStatus status, void *userData );
... | If your intent is for them to be simply place holders for child classes to implement, then make them pure virtual functions by ending with = 0. For example
virtual void destroyDelayBuffer(void) = 0;
This makes the method "abstract" so to speak. The C++ compiler will not look for an actual definition of the method bu... |
722,932 | 722,958 | Complicated error LNK2005: already defined C++ | I'm getting the LNK2005: already defined in (...) error when building my project in Visual Studio 2008. I've referenced other related questions, but mine seems to be a bit more complicated due if nothing else to the number of files I'm working with.
First, I think it will be helpful for me to map out the #include state... | The error is probably that you say you #include Chorus.cpp in AudioHandle.cpp - this is not what you probably want.
The reason is, that all .cpp files (unless you've done something special in your IDE) are compiled separately, then linked. When you #include another .cpp file, the file's text is literally included; ther... |
723,344 | 723,398 | method running on an object BEFORE the object has been initialised? | #include <iostream>
using namespace std;
class Foo
{
public:
Foo(): initialised(0)
{
cout << "Foo() gets called AFTER test() ?!" << endl;
};
Foo test()
{
cout << "initialised= " << initialised << " ?! - ";
cout << "but I expect it to be 0 from the 'initialised(0)' initialiser on Foo()" << endl;
cout <<... | You can't prevent people from coding poorly, really. It works just like it "should":
Allocate memory for Foo (which is the value of the "this" pointer)
Going to Foo::test by doing: Foo::test(this), in which,
It gets the value by this->initialised, which is random junk, then it
Calls Foo's default constructor (because ... |
723,581 | 723,613 | How did I break inheritance? | Refactored from bug_report_view.cc and bug_report_view.h, I extracted send_report(), report_phishing(), a few other smaller functions and BugReport::Cleanup into bug_report.cc and bug_report.h (my versions). Compiling now, I get:
[...]bug_report.cc:196: error: no matching function for call to ‘URLFetcher::URLFetcher(s... | The problem is not the type of the PostCleanup class. The problem is the type of the first parameter to the URLFetcher class constructor. The constructor expects a GURL &, you are passing a std::wstring called post_url. You will need to perform some kind of conversion between the two. Possibly something like this would... |
723,702 | 723,720 | Inheritance vs Specialization | Considering the following two usage scenarios (exactly as you see them, that is, the end-user will only be interested in using Vector2_t and Vector3_t):
[1]Inheritance:
template<typename T, size_t N> struct VectorBase
{
};
template<typename T> struct Vector2 : VectorBase<T, 2>
{
};
template<typename T> struct Vector3... | What you ultimately want, i think, is to have the user type
Vector<T, N>
And depending on N, the user will get slight different things. The first will not fulfill that, but the second will, on the price of code duplication.
What you can do is to invert the inheritance:
template<typename T, size_t N> struct VectorBas... |
723,762 | 723,780 | Programs causing static noise in speakers? | Does anyone know a reason why my programs could be causing my speakers to output some soft static? The programs themselves don't have a single element that outputs sound to anything, yet when I run a few of my programs I can hear a static coming from my speakers. It even gets louder when I run certain programs. Moving ... | Since you say you don't touch sound in your programs, I doubt it's your code doing this. Does it occur if you run any other graphics-intensive programs? Also, what happens if you mute various channels in the mixer (sndvol32.exe on 32-bit windows)?
Not knowing anything else I'd venture a guess that it could be related t... |
723,796 | 723,829 | Linking error in C++ - implementing a indexList | Linking...
Directory.obj : error LNK2019: unresolved external symbol "public: void __thiscall indexList<class entry,100>::read(class std::basic_istream<char,struct std::char_traits<char> > &)" (?read@?$indexList@Ventry@@$0GE@@@QAEXAAV?$basic_istream@DU?$char_traits@D@std@@@std@@@Z) referenced in function _main
Gettin... | What you have is a class template. This means when the compiler needs to call a function, it will look at your template definition and generate the corresponding code as needed.
For example, the following probably has a compile-time error in it if tried to call it:
template <typename T>
void doSomething(const T& x) {
... |
723,973 | 723,974 | Will the initialization list always be processed before the constructor code? | Will the initialization list always be processed before the constructor code?
In other words, will the following code always print <unknown>, and the constructed class will have "known" as value for source_ (if the global variable something is true)?
class Foo {
std::string source_;
public:
Foo() : source_("<unknow... | Yes, it will, as per C++11: 12.6.2 /10 (same section in C++14, 15.6.2 /13 in C++17):
In a non-delegating constructor, initialization proceeds in the following order (my bold):
First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-... |
723,975 | 723,980 | Do I need to use reference parameters for returning values? | If a HANDLE is an output parameter, is it necessary to use a reference to the HANDLE or
use HANDLE directly?
bool fn(HANDLE h_result);
or
bool fn(HANDLE& h_result);
| To return values you can:
Use a reference as a parameter
Use a pointer as a parameter
Actually return the value via return
When you specify the following:
bool fn(HANDLE h_result);
You are making a copy of h_result. So if you change it in your function, you are changing the copy, not the original.
When dealing wit... |
724,060 | 726,519 | How do I render text on to a square (4 vertices) in OpenGL? | I'm using Linux and GLUT. I have a square as follows:
glVertex3f(-1.0, +1.0, 0.0); // top left
glVertex3f(-1.0, -1.0, 0.0); // bottom left
glVertex3f(+1.0, -1.0, 0.0); // bottom right
glVertex3f(+1.0, +1.0, 0.0); // top right
I guess I can't use glutBitmapCharacter, since this is only ideal for 2D ortho.
Simple enough... | The simplest way is to load a font map from a image, such as those generated by the bitmap font builder (I know it's windows but I can't find one for linux), eg:
The example is a 256x256 gif, though you may what to convert it to a png/tga/bmp. It's full ASCII mapped gird, 16x16 characters. Load the texture and use glT... |
724,084 | 724,134 | Howto incorporate -I in makefile | I have no problem compiling specific code the following way:
g++ -I /opt/local/include Code1.cc -o Code1
However when I tried to do that in the makefile:
CXX = g++ -Wall -Werror -gstabs -pedantic -O2 -g
all: Code3 Code2 Code1
Code3: Code3.cc Tools.cc
$(CXX) $^ -o $@
Code2: Code2.cc Tools.cc
$(CXX) $^ -... | -pedantic causes all required warnings to be reported, and -Werror causes warnings to be reported as errors. As C++ does not define the "ULL" long long integer constant syntax (C99 does), this is probably being reported and then promoted to full-on error status by g++.
Try removing -pedantic.
Or try #including <boost/... |
724,096 | 758,222 | Disk Based Dynamic Memory Allocation | I have a program in which I want to be able to store certain data (dynamically allocated blocks), on disk for reduced memory usage and persistence.
My first thought was to write my own custom allocator which managed the content of files on the disk, but I want to see what alternatives there are too.
I've looked into cu... | Your two goals are to reduce memory usage and persist your data. That definitely sounds like a job for a database. But then you say
Because the data is not of a fixed
size, most database implementations
seem not well suited.
I think you'll be interested in this distinctive feature of SQLite (a very lightweight cross-... |
724,156 | 724,166 | Keyboard input hesitation when held down? | Does anyone know why there is some hesitation when you hold down a keyboard key and try to process it? I'm calling a function right in my WinProc(...) that will move an image on the screen (OpenGL) when a key is held down. I press it and get a single response, then there is about .5 seconds of nothing, then it behaves ... | It's a rather standard keyboard setting to have a small delay between when the key was pressed and when repeat messages get generated.
Instead of processing keyboard input in your Windows message handler, you could instead keep an array of 256 bits indicating the current state of the keyboard. When you receive a WM_KE... |
724,347 | 724,392 | Can file pointer change during the process of write or read of a CFile object | I have a CFile object, which can be accessed by multiple threads. There is the possibility that one thread is writing data to this file while another thread is reading data from the file. I want to know is there any unsafety under this policy? Can the file pointer change before the write or read process complete? Is th... | CFile objects are not thread-safe. If you need to access them from multiple threads, you'll need to perform your own synchronization.
From http://msdn.microsoft.com/en-us/library/aa270950.aspx:
Accessing Objects from Multiple Threads
For size and performance reasons, MFC
objects are not thread-safe at the
object l... |
724,465 | 724,544 | How to check for TR1 while compiling? | We are programming a logging library that keeps itself in a .hpp file. We would like to include <tr1/unordered_map> (if the compiler supports TR1,) or the standard <map> otherwise. Is there a standard way of checking at compile time if tr1 is available or not?
I was thinking that the same way that the "__cplusplus" def... | If you are using any configuration tools like autotools you may try to write a test like:
AC_CHECK_HEADER(tr1/unordered_map,[AC_DEFINE([HAVE_TR1],[],["Have tr1"])],[])
AC_CHECK_HEADER(unordered_map,[AC_DEFINE([HAVE_CXX0X],[],["Have C++0x"])],[])
And then use these defines in your code.
Generally speaking __cplusplus m... |
724,536 | 730,868 | Does memory stay allocated when a C++ thread exits? | I'm using the pthread library on Linux.
I'm assigning a string in thread A, and then trying to print the string in thread B. However, the string just prints out empty (I have verified that it works in thread A).
Note: The string resides inside an object, which I suspect may be getting cleaned up or re-instantiated empt... | Turns out, the issue was caused by incorrect use of memory, as expected. I'm 99% sure the following example is accurate; it's pretty much pseudo code, so wont compile, obviously.
Update:
Just added a 3rd solution thanks to nusi.
The wrong way (with stack memory):
std::map<int, MyType1> myMap;
void firstFunctionRunFrom... |
724,765 | 724,838 | Problem using pthread to utilize multiple cores | I’m developing a Ray Tracer in C++ using SDL and Pthread. I’m having issues making my program utilize two cores. The threads work, but they don’t use both cores to 100%. To interface SDL I write directly to it's memory, SDL_Surface.pixels, so I assume that it can't be SDL locking me.
My thread function looks like this:... | This is useless :
pthread_mutex_lock(&frame_mutex);
pthread_cond_wait(&frame_cond, &frame_mutex);
pthread_mutex_unlock(&frame_mutex);
if you wait to wait for a new frame do something like :
int new_frame = 0;
First thread :
pthread_mutex_lock(&mutex);
new_frame = 1;
pthread_cond_signal(&cond);
pthread_mutex_unloc... |
725,040 | 725,066 | Converting (void*) to std::vector<unsigned char> | I have a (void*) buffer that I need to convert to std::vector<unsigned char> before I can pass it on. Unfortunately, my C++ casting skills a little weak. Any suggestions?
| You will need the length of the buffer. Once you do, we can do this:
unsigned char *charBuf = (unsigned char*)voidBuf;
/* create a vector by copying out the contents of charBuf */
std::vector<unsigned char> v(charBuf, charBuf + len);
Okay, the comment got me started on why I did not use reinterpret_cast:
In C++, the... |
725,138 | 725,144 | How to detect 'strict aliasing' at compile time? | 'Strict aliasing' optimization needs special care from the source code, s.a. using a union instead of pointer casts. Is there a way to detect using preprocessor directives (#if/else) whether the compiler is trying to do such optimizations?
I would like to maintain the old and non-strict-aliasing-prepared code path for ... | Completely implementation dependant - you need to check the docs for your specific compiler(s). And when asking questions like this, it's a good idea to mention which compiler(s) you are using.
A semi-portable way to do this is from your Makefile - define different targets for aliased & unaliased versions and define yo... |
725,142 | 725,197 | How does a reference-counting smart pointer's reference counting work? | In other words, how does the implementation keeps track of the count?
Is there a map-like object maintained which is accessible by all the shared_ptr instances whose key is the pointer's address and value is the number of references? If I've to implement a shared_ptr, this is the first idea that's coming to my mind.
Is... | I've seen two different non-intrusive approaches to this:
The smart pointer allocates a small
block of memory to contain the
reference counter. Each copy of the
smart pointer then receives a
pointer to the actual object and a
pointer to the reference count.
In addition to an object pointer,
each smart pointer contains... |
725,375 | 725,531 | Const-correct Notifier in Observer Pattern | I want to implement an Observer of a Model class which does not change the Model. Thus, it should be able to use a const-Reference to access the Model. But the Registering of the Observer prohibits this.
Here is how the observer pattern is implemented in my Project:
//Attributes of type Observable are used by classe... | If you consider the Notifier object not to be part of the Model object which owns it, so that modifying the Notifier doesn't "count" as modifying the Model, then make getNotifier a const method returning a non-const reference:
Notifier& GetNotifier() const //Is const but returns a non-const
{ ... |
726,002 | 726,028 | C2065 undeclared identifier while assigning a define to an int | I have a small problem with a define. I want to assign it to an integer variable but the compiler says it's undeclared.
Here's what the code looks like:
defines.h
#ifndef DEFINES_H
#define DEFINES_H
#define MYDEFINE 2
#endif
myclass.h
namespace mynamespace {
class myClass {
int someFunction();
};
}
myclass.cxx
... | You should check whether the symbol MYDEFINE is really defined.
Check whether the header file where
it is declared is really included
(and compiled). Use #warning near the define to make sure it is compiled for myclass.cxx:
#ifndef DEFINES_H
#define DEFINES_H
#define MYDEFINE 2
#warning My define is defined
... |
726,016 | 726,136 | Windows Explorer like folder tree browser | I am trying to implement a platform independent file/directory tree browser. Basically, I am trying to replicate windows explorer's tree control to browse the computer. However, I can't figure out how to find the "Desktop" or "My Computer" folder string (It changes in every pc and os type, version and language). If I c... | Ignoring portability, what you need is the "PIDL" tree. PIDLs are generalizations of file paths. You can get the PIDLs for special folders with SHGetFolderLocation. The desktop is CSIDL_DESKTOP (not CSIDL_DESKTOPDIRECTORY), My Computer is CSIDL_DRIVES.
To convert the PIDLs to names, have a look at SHGetNameFromIDList
|
726,096 | 726,123 | Accessing private members | Is it appropriate to access a class' private members by casting it to a void pointer and then to a struct?
I don't think I have permissions to modify the class that contains the data members that I need to access. I don't want to take a risk accessing the data members in an indirect way if it is not ethical.
EDIT: H... | "Never say never". I'm sure somewhere in the universe, there's a situation that will force you to have to do this...
But I certainly would cringe if I had to do it. You truly need get lots of opinions on your situation before pulling the trigger. Can you describe your specific situation and maybe we could see if it mak... |
726,119 | 727,013 | How can you make buttons on a MSVS C++ CToolBar larger along with their images? | We have a touch screen, and the toolbar is too small to hit with my meaty fingers. Is there an easy way I can have an option to make the toolbar buttons bigger and easier to hit?
So far I've attempted a few things:
m_toolbar.SetSizes( CSize(64,64), CSize(50,50) );
m_toolbar.SetSizes( CSize(64,64), CSize(50,50) );
m_to... | At toolbar creation time, create an empty CImageList with size 64x64 (let's call it large). Load the original image list from resources (we call it small).
Iterate over each image in small and copy/resize it to large.
Then assign large to your toolbar. Somewhat cumbersome bui should work.
HTH,
|
726,410 | 726,420 | Serialize in C++ then deserialize in C#? | Is there an easy way to serialize data in c++ (either to xml or binary), and then deserialize the data in C#?
I'm working with some remote WINNT machines that won't run .Net. My server app is written entirely in C#, so I want an easy way to share simple data (key value pairs mostly, and maybe some representation of a ... | Protocol Buffers might be useful to you.
Protocol buffers are Google's language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler. You define how you want your data to be structured once, then you can use special generated source code to easil... |
726,456 | 726,492 | C++ template class error with operator == | Error:
error C2678: binary '==' : no operator found which takes a left-hand operand of type 'const entry' (or there is no acceptable conversion)
The function:
template <class T, int maxSize>
int indexList<T, maxSize>::search(const T& target) const
{
for (int i = 0; i < maxSize; i++)
if (elements[i] == t... | Start by reading the error text exactly as it is:
binary '==' : no operator found which takes a left-hand operand of type 'const entry'
It means it can't find any == operator that accepts an entry type as its left operand. This code isn't valid:
entry const e;
if (e == foo)
You've showed us the code for your list cl... |
726,664 | 726,681 | String to enum in C++ | Is there a way to associate a string from a text file with an enum value?
The problem is: I have a few enum values stored as string in a text file which I read on the fly on meeting some condition... Now I want to assign the read value to an enum.
What is the most effective way to do so? It doesn't need to be the si... | You can set up a map that you can use over and over:
template <typename T>
class EnumParser
{
map <string, T> enumMap;
public:
EnumParser(){};
T ParseSomeEnum(const string &value)
{
map <string, T>::const_iterator iValue = enumMap.find(value);
if (iValue == enumMap.end())
... |
726,698 | 726,748 | Timer message in MFC/Win32 | I was just trying the SetTimer method in Win32 with some low values such as 10ms as the timeout period. I calculated the time it took to get 500 timer events and expected it to be around 5 seconds. Surprisingly I found that it is taking about 7.5 seconds to get these many events which means that it is timing out at abo... | Windows is not a real-time OS and can't handle that kind of precision (10 ms intervals). Having said that, there are multiple kinds of timers and some have better precision than others.
|
726,924 | 726,962 | Working with audio in C++ | I need to be able to get the length of an audio file (preferably in milliseconds, the timing is very important for the application), and play back the audio. The application is written in C++ on the windows XP platform. Any suggestions for audio formats/3rd party libraries that would do the trick?
| The Phonon library (part of Qt) is very powerful and comfortable.
It is LGPL.
Downside: it's not as performant as some of the game-oriented libraries such as FMod, SDL_Mixer and OpenAL. However, the latency is generally acceptable for desktop apps.
As for audio formats: use Ogg Vorbis by default. It's an open standa... |
727,050 | 1,850,399 | MagickNet C++ Source Compilation Failure | I'm attempting to compile a working copy of the MagickNet class library (DLL) using the sources from the ImageMagick and MagickNet libraries.
I was unable to obtain a copy of the MagickNet source files from the creator's homepage as it is currently down, so I was forced to obtain the files and C++ project file from her... | I was just able to get past this and was successfully able to compile MagickNET against the latest version of ImageMagick. I had to do several things.
Configured ImageMagick to use StaticMTDll.
Edited magick-config.h to undefine X11 support.
Removed the CORE_xlib project from the ImageMagick solution.
Clean/Rebuild of... |
727,066 | 727,240 | Dynamically change allocation strategy in boost::vector and boost::matrix | In my new project i am building a data management module.I want to give a simple template storage type to upper layers like
template<typename T>
class Data
{
public:
T getValue();
private:
boost::numeric::ublas::matrix<T> data;
}
My aim is, to change allocator of data with some different allocators like Boost.i... | It's not clear what you want, but as a shot in the dark, is the following helpful?
template<typename T>
class IData
{
public:
virtual T getValue() = 0;
virtual ~IData() {}
};
template<typename T, typename Allocator=std::allocator<T> >
class Data : public IData<T>
{
public:
virtual T getValue();
private:
boo... |
727,336 | 728,294 | How to Cross Compile for Cell Linux on the PS3 from Windows? | How can a cross compilation setup be achieved to allow compiling Cell Linux programs on a Windows PC using the cygwin toolchain? The cygwin tools provide a GNU compiler to use in building the cross compiler, and associated tools for the build process e.g. rpm, cpio, make, flex, bison and so on.
I am moderately confiden... | I've never done it, so I can't give you step by step instructions, but I can give you a general idea.
The instructions you linked will serve as a pretty good outline, but there will be definite changes.
For the host PC, you can install gcc and other build tools from MinGW or cygwin. That will give you the windows na... |
727,439 | 727,448 | How do you convert a Visual Studio project from using wide strings to ordinary strings | When I created my visual studio project it defaulted to forcing me to use wide strings for all the functions which take character strings. MessageBox() for example, takes a LPCWSTR rather than a const char*. While I understand that it's great for multi-lingual and portable applications, it is completely unnecessary for... | Right click on your project -> Properties then go to the following tree item:
Configuration Properties -> General
For Unicode select:
Use Unicode Character Strings
For normal multi-byte select:
Use Multi-Byte Character Set
When you put TEXT() or _T() around your strings, you are making it compatible with both of the... |
727,516 | 727,518 | What does the unary plus operator do? | What does the unary plus operator do? There are several definitions that I have found (here and here) but I still have no idea what it would be used for. It seems like it doesn't do anything but there has be a reason for it, right?
| It's there to be overloaded if you feel the need; for all predefined types it's essentially a no-op.
The practical uses of a no-op unary arithmetic operator are pretty limited, and tend to relate to the consequences of using a value in an arithmetic expression, rather than the operator itself. For example, it can be u... |
727,541 | 727,674 | C++/Java Inheritance vs. Delegation vs. etc | I am creating a class library with many different options for possible customizations. For example, you can design your class so that it can perform FeatureX(), or you can design your class so that it can perform FeatureY().
Under normal circumstances, you would simply create an interface IFeatureX with a pure virtual... | If you're not afraid of using templates, you can make your function a template and use SFINAE to check for the two interfaces:
template <class T>
void my_function(const T& data, typename enable_if_c<
is_convertible<T*, IFeatureX*>::value &&
is_convertible<T*, IFeatureY*>::value>::type*=0) {
...
}
This will ... |
727,737 | 727,907 | Why is stringstreams rdbuf() and str() giving me different output? | I have this code,
int main()
{
std::string st;
std::stringstream ss;
ss<<"hej hej med dig"<<std::endl;
std::getline(ss,st,' ');
std::cout <<"ss.rdbuf()->str() : " << ss.rdbuf()->str();
std::cout <<"ss.rdbuf() : " << ss.rdbuf();
return 0;
}
Giving me this output
ss.rdbuf()->str() : hej hej... | ss.rdbuf()->str();
Returns copy of all buffer content.
What doing std::cout << ss.rdbuf();?
See description for
basic_ostream<charT,traits>& operator<<(basic_streambuf<charT,traits>* sb);
It read character by character from buffer and write them to ostream, until eof/fail on writing/exception occurs.
You already... |
727,762 | 727,781 | How should I change this declaration? | I have been given a header with the following declaration:
//The index of 1 is used to make sure this is an array.
MyObject objs[1];
However, I need to make this array dynamically sized one the program is started. I would think I should just declare it as MyObject *objs;, but I figure if the original programmer declar... | You're correct. If you want to dynamically instantiate its size you need to use a pointer.
(Since you're using C++ why not use the new operator instead of malloc?)
MyObject* objs = new MyObject[size];
|
727,918 | 727,935 | What happens when GetTickCount() wraps? | If a thread is doing something like this:
const DWORD interval = 20000;
DWORD ticks = GetTickCount();
while(true)
{
DoTasksThatTakeVariableTime();
if( GetTickCount() - ticks > interval )
{
DoIntervalTasks();
ticks = GetTickCount();
}
}
Eventually, ticks is going to wrap when the value ... | From the docs:
The elapsed time is stored as a DWORD
value. Therefore, the time will wrap
around to zero if the system is run
continuously for 49.7 days. To avoid
this problem, use GetTickCount64.
Otherwise, check for an overflow
condition when comparing times.
However, DWORD is unsigned - so you should b... |
728,068 | 728,070 | How to calculate a time difference in C++ | What's the best way to calculate a time difference in C++? I'm timing the execution speed of a program, so I'm interested in milliseconds. Better yet, seconds.milliseconds..
The accepted answer works, but needs to include ctime or time.h as noted in the comments.
| See std::clock() function.
const clock_t begin_time = clock();
// do something
std::cout << float( clock () - begin_time ) / CLOCKS_PER_SEC;
If you want calculate execution time for self ( not for user ), it is better to do this in clock ticks ( not seconds ).
EDIT:
responsible header files - <ctime> or <time.h>
|
728,126 | 728,134 | What data source could I use for my stock market program? | I would like to make a free open-source C++ application for both Linux and Windows which will create live stock market charts (i.e. they're refreshed frequently).
Please could you give me some pointers on these issues:
What should I use as the data source? Are there free services I can implement? I would like to use t... | As of Nov 2014, these links are dead.
Google Finance API: http://code.google.com/apis/finance/
Yahoo! Finance API: http://developer.yahoo.com/finance/
Cross-platform C++ charts w/ Qt: http://www.int.com/products/2d/carnac/chart_component.htm
|
728,192 | 728,345 | How to remove, reinstall and/or find info about Visual Studio 2008 hotfixes? | Another developer and I are experiencing different behavior in native C++ executables built with Microsoft Visual Studio 2008, Version 9.0.30729.1 SP on different machines.
We are statically linking to the Standard Library so we don't think it's a DLL version issue. We have ruled out differences in our source code and... | The main culprit for causing different behavior in native C++ apps would probably be:
KB958357
This seems to be an earlier version of what is now KB962219. Details are available in this posting on the Visual C++ Team Blog:
http://blogs.msdn.com/vcblog/archive/2008/12/17/vc9-sp1-hotfix-for-the-vector-function-ft-crash.a... |
728,233 | 728,272 | Why are references not reseatable in C++ | C++ references have two properties:
They always point to the same object.
They can not be 0.
Pointers are the opposite:
They can point to different objects.
They can be 0.
Why is there no "non-nullable, reseatable reference or pointer" in C++? I can't think of a good reason why references shouldn't be reseatable.
E... | The reason that C++ does not allow you to rebind references is given in Stroustrup's "Design and Evolution of C++" :
It is not possible to change what a reference refers to after initialization. That is, once a C++ reference is initialized it cannot be made to refer to a different object later; it cannot be re-bound. ... |
728,325 | 728,330 | Can you call a C# DLL from a C DLL? | I've built a DLL in C#. Now I want to use the R Environment to call functions in that DLL. The R environment supports calling unmanaged C/C++ DLL's but not into .NET DLL's. So my question is, can I call functions in a C# DLL from a C/C++ DLL? If so, do you have a link to info about how to do this?
| The most straight forward way of doing this is to expose one of the C# classes in your C# DLL as a COM object, and then create an instance of it from your C/C++ DLL. If that isn't an acceptable option, you'd need to create a mixed-mode C++ DLL (which contains both managed and unmanaged code). Your C/C++ DLL can call ex... |
728,380 | 728,556 | Is there a way to get Asio working without Boost? | I know there is a version of ASIO that is not included in the Boost namespace, but even then ASIO depends on Boost, but I'm wondering if there is a way to get ASIO to work without dependencies on Boost (because I cannot include Boost into the project, for too many reasons).
| No, i don't believe so. ASIO has been using boost for as long as i have heard of it. I think they're very much interconnected. But you may be interested in a tool, bcp, which lets you extract the minimal subset of boost required for the libraries that you want to use.
|
728,416 | 728,441 | Is there any difference between +-ing strings and <<-ing strings in c++? | What is the difference, if any between the effects of the following snippets:
cout << "Some text" << s1 << "some more text\n";
cout << "Some text" + s1 + "some more text\n";
| The result of operator+ on strings is a new string. Therefore, in the example
cout << "Some text" + s1 + "some more text\n";
two new strings are created (implies memory allocation) before the whole thing is written to cout. In your first example, everything is written directly to cout without unnecessary memory alloca... |
728,602 | 728,682 | Windows Mobile Development: Choice of .Net compact vs. Native (c++) code | I work on an experienced and diverse development team and we are preparing to approach our first mobile development which will be for Windows Mobile 6 (platform changes are not an option).
We have skills and experience in both Visual C++ and .Net technologies for Windows desktop and server development.
The mobile dev... | A very similar question was asked and answered just a few days ago. You can find useful information there.
Short answers to your questions:
Native code is faster, but for many applications the speed difference won't be noticeable. Don't use native code just for the speed, unless this is a key factor for your applicati... |
728,972 | 729,603 | Finding all the subsets of a set | I need an algorithm to find all of the subsets of a set where the number of elements in a set is n.
S={1,2,3,4...n}
Edit: I am having trouble understanding the answers provided so far. I would like to have step-by-step explanation of how the answers work to find the subsets.
For example,
S={1,2,3,4,5}
How do you know... | It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.
For n=1, the set of subsets is {{}, {1}}
For n>1, find the set of subsets of 1,...,n-1 and make ... |
728,986 | 729,004 | does assignment operator work with different types of objects? | class A {
public:
void operator=(const B &in);
private:
int a;
};
class B {
private:
int c;
}
sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]
void A::operator=(const B& in)
{
a = in.c;
}
Thanks a lot.
| Yes you can do so.
#include <iostream>
using namespace std;
class B {
public:
B() : y(1) {}
int getY() const { return y; }
private:
int y;
};
class A {
public:
A() : x(0) {}
void operator=(const B &in) {
x = in.getY();
}
void display() { cout << x << endl; }
private:
... |
729,146 | 729,182 | How to programmatically check Internet bandwidth in VC++? | I need to find the bandwidth available at a particular time. The code must be developed in Visual C++ or in .Net family . If anyone knows how, please help me out.
| The only way to check your bandwidth is to actually try to use it, i.e. by downloading a file from somewhere else and measuring the throughput.
Even then it'll only be an approximation, because other network effects will affect the results:
latency
asymmetric upload / download
other traffic
|
729,363 | 729,373 | Is it possible to access private members of a class? | Is it possible to access private members of a class in c++.
provided you don't have a friend
function and You don't have access to
the class definition
| You mean using some pointer arithmetic to gain the access ? It is possible but is definitely dangerous. Take a look at this question also: Accessing private members
|
729,562 | 729,579 | How to compile C# application with C++ static library? | I turned my C++ Dynamic link library into Static library just to acquire more knowledge.
My question is how can I use the .obj file to compile both projects with C# express/MS visual studio?
| No, you can't access static libraries directly from C#. You have to use a DLL.
|
729,652 | 729,690 | Writing a MySQL UDF using C++ STL functionality | There is a statement in the MySQL Docs (http://dev.mysql.com/doc/refman/5.0/en/adding-udf.html) that is bothering me:
"A UDF contains code that becomes part of the running server, so when you write a UDF, you are bound by any and all constraints that otherwise apply to writing server code. For example, you may have pr... | Not having any knowledge at all of libstdc++, but going by the "For example" bit meaning that this warning is applicable to more than libstdc++ I would suggest that this means be wary of standard libraries in general as they may peform things that wouldn't work in a UDF environment.
For example (digging back to C) s... |
729,683 | 730,266 | sizeof(*this) gives wrong value | I have a class, C. C has a member variable declared as: bool markerStart;
From within C a call to sizeof(*this) gives a value of 0x216 bytes.
Elsewhere within C, I do: markerStart = false;
Rather than setting markerStart to false, this call is actually clobbering the start of the next class in memory!
Looking at the di... | As pointed out by Pontus, you probably broken the one definition rule somehow. You've probably included the header file with the definition of class C in two translation units where other code, often in a preceding header file, changes the way the definition of class C is interpreted so that it has a different size in ... |
729,721 | 729,757 | Waiting for pthread_create to finish without using pthread_join | I want to halt one thread till another thread has finished initializing without using pthread_join.
I tried using a join but it leads to a deadlock due to some asynchronous inter-thread communication system that we have.
Right now, I'm using a (custom) lock to achieve this.
In Thread 1:
lock_OfflineWorker.Lock()
if (pt... | You can use a pthread condition to wait until the job reaches the wanted state.
The thread1 waits with pthread_cond_wait() and the thread2 signals it with pthread_cond_signal().
You need :
bool condition ; // or anything else to be tested
pthread_mutex_t mutex ;
pthread_cond_t cond ;
The first thread inits... |
729,792 | 750,745 | bandwidth throttling with Qt | I'm using the QNetworkAccessManager to download files from the web, it provides an easy API to the task. But I wish to add a download rate limit to the class, so all http replies won't exceed that limit (I see no reason to limit the requests).
I've googled abit and found an interesting post here. But what it does is su... | I ended up using the RcTcpSocket and RateController from this article with the QHttp class. Prior to making get/post requests with the QHttp I create a RcTcpSocket, add it to my RateController and use QHttp::setSocket(QTcpSocket*). I still didn't find a solution to keep using QNetworkAccessManager but this is close eno... |
730,125 | 730,203 | Using pthread condition waits in a structure | I previously inquired about synchronizing two threads without using pthread_join and I was able to resolve it using pthread_cond_wait and pthread_cond_signal.
I've written a small struct to bundle this functionality into a single place:
struct ConditionWait
{
int i_ConditionPredicate;
pthread_mu... | This will only work once, after you wake up the thread waiting, the next attempts to wait will all succeed and never block since you never "reset" the condition predicate. If this is what you want (or it doesn't matter in your situation) then yes, this is safe and is how condition variables are typically used.
PS: You ... |
730,134 | 741,541 | How to Enforce C++ compiler to use specific CRT version? | I am using VS2008 for developing a COM dll which by default uses CRT version 9
but I am using TSF (Text service framework) that is not compatible with the new CRT. I think the solution is to use the compatible one so how can I specify the CRT version?
| I whole heartily join the recommendation not to manually change the CRT version you link against. If however, for some reason (which I cannot imagine) this is the right course of action for you, the way to do so is change the manifest for your project.
First make sure a manifest is not generated on every build (on VS20... |
730,253 | 730,277 | Issue with C++ Intellisense and Error Checking | Using Visual C++ 2008. First time, I'm experimenting in crossing over from C# and wanted to try my hand at it. I have not changed base settings much, other than a few things like smart block and maybe a few colors. Because I'm at level ZERO on c++ knowledge all the Googling I've done is over my head.
Part 1 of the prob... | this in C++ is a pointer that is dereferenced by -> not .
Also, intellisense for C++ in VS2008 is not as helpful as in C#, this includes not having error checking. VS2010 will be introducing inline error checking for C++.
There are some very big differences between C# and C++ that you will need to be aware of. It's a b... |
730,400 | 730,413 | gprof and arguments to executable | when using gprof:
$ gprof options [executable-file [profile-data-files...]] [> outfile]
if you have options to pass to the executable like:
gprof a.out --varfred=32
then gprof assumes that I am passing an invalid option to it, instead of to the program being profiled (a.out).
Any way to get around this?
| You don't run your executable with gprof, so you only specify it so gprof can load symbols. You run the executable first, on its own just as normal, and it then emits profiling data.
This data is loaded, along with the executable, by gprof later.
This is all explained in the gprof manual, of course.
|
730,498 | 730,536 | Iterator access performance for STL map vs. vector? | What is the performance difference between using an iterator to loop through an STL map, versus a vector? I'd like to use the map key for insertion, deletion, and some accesses, but I also need to do regular accesses to every element in the map.
| With both map and vector, iterating through the entire collection is O(N). however (like list vs vector) vector stores elements contiguously, so accessing the next element is much cheaper because it will use cache optimally, whereas the map won't.
But since you need to have lookup based on keys, there isn't really an a... |
730,603 | 730,659 | Help with OSSpinLock* usage to replace a while(true) {sleep(1);} | I am maintaining a carbon C++ application on OS X. There is a "spin lock" in one of the objects in the code that looks like this,
while ( mState != RELEASED )
{
sleep( 1 );
}
There is a post render maintenance callback that is fed to AudioUnitAddRenderNotify() that would set the mState of these various objects.
I ... | Don't use a spinlock -- spinlocks waste CPU cycles, looping endlessly until they get the lock. Spinlocks should only be used when the time that the lock will be held will be very short.
A better alternative would be to use a condition variable, such as the ones available in the pthreads library. This way, your thread... |
730,700 | 730,731 | How do you "decode" Visual Studio Link Errors? | I'm not very experienced in C++, and when I have to work with another library and I get link errors, I'm completely in the dark on what the compiler is trying to tell me (other than it can't find something reference somewhere).
Are there any good links that describe, in detail, the meaning of the symbols and characters... | The symbols are the "mangled" versions of the function names. Basically because of c++ overloading (2 functions with different signatures can have the same name). The signature information is encoded into the name.
The message you pasted has both the encoded and plain text versions.
public: __thiscall google::protobuf:... |
730,773 | 731,904 | c++ profiling/optimization: How to get better profiling granularity in an optimized function | I am using google's perftools (http://google-perftools.googlecode.com/svn/trunk/doc/cpuprofile.html) for CPU profiling---it's a wonderful tool that has helped me perform a great deal of CPU-time improvements on my application.
Unfortunately, I have gotten to the point that the code is still a bit slow, and when compile... | If you're on linux, use oprofile.
If you're on Windows, use AMD's CodeAnalyst.
Both will give sample-based profiles down to the level of individual source lines or assembly instructions and you should have no problem identifying "hot spots" within functions.
|
730,913 | 740,626 | Dedicated function for memory allocation causes memory leak? | Hy all,
I believe that the following piece of code is generating memory leak?
/* External function to dynamically allocate a vector */
template <class T>
T *dvector(int n){
T *v;
v = (T *)malloc(n*sizeof(T));
return v;
}
/* Function that calls DVECTOR ... | So, some important concepts discussed here helped me to solve the memory leaking out in my code. There were two main bugs:
The allocation with malloc of my user-defined types was buggy. However, when I changed it to new, leaking got even worse, and that's because one my user-defined types had a constructor calling an ... |
731,032 | 731,048 | Incorporating text files in applications? | Is there anyway I can incorporate a pretty large text file (about 700KBs) into the program itself, so I don't have to ship the text files together in the application directory ? This is the first time I'm trying to do something like this, and I have no idea where to start from.
Help is greatly appreciated (:
| Depending on the platform that you are on, you will more than likely be able to embed the file in a resource container of some kind.
If you are programming on the Windows platform, then you might want to look into resource files. You can find a basic intro here:
http://msdn.microsoft.com/en-us/library/y3sk7e6b.aspx
Wi... |
731,141 | 731,239 | When is it necessary to implement locking when using pthreads in C++? | After posting my solution to my own problem regarding memory issues, nusi suggested that my solution lacks locking.
The following pseudo code vaguely represents my solution in a very simple way.
std::map<int, MyType1> myMap;
void firstFunctionRunFromThread1()
{
MyType1 mt1;
mt1.Test = "Test 1";
myMap[0] = ... | In general, threads might be running on different CPUs/cores, with different memory caches. They might be running on the same core, with one interrupting ("pre-empting" the other). This has two consequences:
1) You have no way of knowing whether one thread will be interrupted by another in the middle of doing something... |
731,208 | 731,370 | What's the best use you've had with pointer to members and member functions? | Pointer to members are not used very much but they are really powerful, how have you used them and what's the coolest things you've done?
Edit:
This is not so much to list things that are possible, for example listing boost::bind and boost::function aren't good. Instead maybe a cool usage with them? I know they're very... | I once was needed to operate with criteria data as pure structure to be able to store the list of all criteria in the queue. And I had to bind the structure with the GUI and other filter elements, etc. So I came up with the solution where pointers to members are used as well as pointers to member functions.
Let's say ... |
731,403 | 731,429 | Why am I getting an error when using vfork()? | This is my code... I don't know why I'm get an error segment... could somebody explain the reason to me?
#include <iostream>
#include <string>
// Required by for routine
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int globalVariable = 2;
main()
{
string sIdentifier;
int iStackVariable... | Is this of use ? Note the caveats surrounding modification of variables.
The vfork() function has the same effect as fork(), except that the behaviour is undefined if the process created by vfork() either modifies any data other than a variable of type pid_t used to store the return value from vfork(), or returns fro... |
731,574 | 732,568 | Saving a IXMLDOMDocument without end tag | Using MSXML via C++, when I call IXMLDOMDocument::save, empty XML elements will get an end tag, like this:
<root>
<child name="first">
</child>
</root>
But I want it saved as this:
<root>
<child name="first" />
</root>
What do I need to do to accomplish that?
| DOM itself does that if there are no child nodes but I don't know why in your case it is doing like this.
If you want to do explicitly call Pretty Print on the DOM pointer.
#include <msxml2.h>
bool FormatDOMDocument (IXMLDOMDocument *pDoc, IStream *pStream)
{
// Create the writer
CComPtr <IMXWriter> pMXWrit... |
731,908 | 731,924 | Why does this compile (used in function before initialized)? | Consider this code (using CString because it's familiar and easy to see when not constructed, but nothing special about the class), tested under Visual Studio 2008:
CString DoSomething( const CString& sString )
{
return sString;
}
CString sTest1 = DoSomething( sTest1 ); // Compiles (no warnings), fails at runtime
... | The behavior you are seeing in sTest1 is undefined in the C++ standard. It's weird and wrong but it compiles on a few compilers.
See litb's answer on the following thread for more details: method running on an object BEFORE the object has been initialised?
|
731,959 | 731,999 | Emacs indentation of the for each statement in C++ | I'm trying to get emacs to correctly format the "for each" construct in c++.
I want the braces to be lined up with the f in for in both of the following examples:
for each(Type a in b)
{ //^c^s shows substatement-open
//... do stuff
}
for( ; ; )
{ //^c^s shows substatement-open
//... ... | Presumably emacs is not recognising "for each" as c++ syntax (I don't either. Is this a microsoft extension? A preprocessor hack? New for the upcoming standard?). So there is no wonder that it is not formatting it "right".
You could hack the mode, or ask the maintainer of the same (I wouldn't expect a possitive respons... |
732,160 | 732,175 | How can I iterate in reverse over a map in C++? | I'm having trouble iterating in reverse over a map in GCC C++. When I use a reverse iterator, it seems I can't assign anything to it - the compiler complains. I'm working around it with some awkward code using a forward iterator, but it's not very elegant. Any thoughts?
| Here's an example of iterating backward through a std::map:
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, std::string> m;
m["a"] = "1";
m["b"] = "2";
m["c"] = "3";
for (auto iter = m.rbegin(); iter != m.rend(); ++iter) {
std::cout << iter->first <<... |
732,602 | 732,632 | Why is the following program 15% slower when compiled with g++? | Updated: The actual resolution that the compile box which served my compile request was different. In the slower instance I was running code compiled on a SuSE 9 but running on a SuSE 10 box. That was sufficient difference for me to drop it and compare apples to apples. When using the same compile box the results we... | When compiled with gcc and g++ the only difference I see is within the first 4 lines.
gcc:
.file "loops.c"
.def ___main; .scl 2; .type 32; .endef
.text
.globl _main
g++:
.file "loops.c"
.def ___main; .scl 2; .type 32; .endef
.text
.align 2
.globl _main
as you ca... |
732,609 | 732,641 | What are some good tools for measuring memory allocations on Windows? | I have an application that keeps using up more and more memory as time goes by (while actively running), but there are no leaks. So I know the program isn't doing something totally wrong, which would be easy to find.
Instead I want to track allocations so I can start tracking down the issue, and on a Mac I'd use Instru... | Memory validator would be ideal for you.
http://www.softwareverify.com/cpp/memory/index.html
|
732,687 | 992,793 | Line Segment container for fast Ray intersection? (2D) | I have a ray, I need to find the closest line segment that it hits. I think it's possible to do this in O(log n) time if I sort the line segments first, but I can't remember how to sort them... I think some sort of tree would work best, but how do I sort them by both start and end point? I would also like fast insertio... | You could take a bounding box of the polygon (min-max x,y coordinates) and build a grid inside the box. Then, for each cell, remember all lines that cross the cell.
Find an intesection like this:
Find out which cell the ray hits first (O(1))
Use Grid traversal algorithm to "draw" a ray through the grid. When you hit n... |
732,893 | 732,948 | Using Borland C++ Code in VC++ | Is there a way to access Borland output in VC++, for method calls and other stuff?
Thanks
| My info may be (way) outdated, but what I had to before was to make sure that Borland output a COFF format OBJ or LIB file to link with VC.
The other option is to have Borland output a DLL, and then use that from VC++. Name mangling and calling conventions may cause a pain. I honestly haven't used a Borland compiler in... |
732,894 | 732,910 | Access violation with malloc() and glDrawPixels()? | Can anyone see what's wrong with this code?
SIZE_BG is 6MB as I am trying to draw a large bitmap image (3366x600). I use malloc to prevent my image from overflowing the stack. I get an access violation error on the call to glDrawPixels(). bgPtr seems to point to the correct data as I checked the first few bytes before... |
SIZE_BG is 6MB
3366 × 600 is approximately 1.92 million pixels
BRGA indicates 4 bytes per pixel
so, 3366 × 600 × 4 is just over 7.7MB
Therefore, your buffer is too small... glDrawPixels() will read past the end into unallocated memory.
|
733,056 | 733,064 | Is there a way to get function name inside a C++ function? | I want to implement a function tracer, which would trace how much time a function is taking to execute. I have following class for the same:-
class FuncTracer
{
public:
FuncTracer(LPCTSTR strFuncName_in)
{
m_strFuncName[0] = _T('\0');
if( strFuncName_in ||
_T(... | VC++ has
__FUNCTION__ for undecorated names
and
__FUNCDNAME__ for decorated names
And you can write a macro that will itself allocate an object and pass the name-yelding macro inside the constructor. Smth like
#define ALLOC_LOGGER FuncTracer ____tracer( __FUNCTION__ );
|
733,537 | 734,061 | Should I be using dynamic_cast<T> for copying? |
Update 1:
Corrected nonsense code! Thanks for comments, I made a hash of the first snippet, oops.
Update 2:
Also updated question title, as the use of dynamic_cast has been pointed out as not necessary by answers.
What I'm trying to achieve here is a deep copy using strong types; I want to be able to copy Class2 to a... | I'm not sure what you are trying to achieve because the code still doesn't make much sense. However, I believe the following should approximate what you're trying to do. Note that I don't use heap memory: it's not necessary and it would leak memory.
template <typename T>
T Class1::Copy()
{
T instance;
CopyTo(&i... |
733,717 | 733,796 | Difference between DECLARE_DYNAMIC and DECLARE_DYNCREATE? | Could you please let me know what is difference between DECLARE_DYNAMIC and DECLARE_DYNCREATE?
Where exactly we can use them?
| The first declares that a class has runtime type info and the second that instances can be created dynamically at runtime. This is described in detail in the MSDN documentation - see links like Run-Time Object Model Services for more info.
|
733,737 | 733,791 | Are inline virtual functions really a non-sense? | I got this question when I received a code review comment saying virtual functions need not be inline.
I thought inline virtual functions could come in handy in scenarios where functions are called on objects directly. But the counter-argument came to my mind is -- why would one want to define virtual and then use obj... | Virtual functions can be inlined sometimes. An excerpt from the excellent C++ faq:
"The only time an inline virtual call
can be inlined is when the compiler
knows the "exact class" of the object
which is the target of the virtual
function call. This can happen only
when the compiler has an actual object
ra... |
733,900 | 733,947 | Force garbage collection/compaction with malloc() | I have a C++ program that benchmarks various algorithms on input arrays of different length. It looks more or less like this:
# (1)
for k in range(4..20):
# (2)
input = generate 2**k random points
for variant in variants:
benchmark the following call
run variant on input array
# (3)
Is it possible to r... | If you want the test runs to start in the same heap states, you can run them in their own processes created by fork().
|
733,971 | 733,977 | Password Information | I want to get the various user account passwords which are stored in my computer programatically using Visual C++. Are there any APIs to help me do this?
| There is no way to retrieve windows passwords nor passwords to most other programs via Win32 APIs.
For Windows passwords you typically have to ask the user to enter their username/password and verify it, all by using LogonUser.
For other programs they are usually stored on disk encrypted by the host application.
|
734,075 | 734,100 | friend class/function in c++ |
Possible Duplicate:
When should you use 'friend' in C++?
I see a lot of people recommending a function/class to be made a friend of another class here in SO though there are other alternatives. Shouldn't friend be sparingly used in C++? I feel other options must be considered before deciding on using the friend fe... | Without specific examples this is hard to decide. While friend isn't strictly necessary it does have its uses. If, as you claim, there are better alternatives then obviously use them, by simple definition of the word “better”. Or maybe the decision which solution is better isn't that clean-cut after all.
Personally, I ... |
734,140 | 734,304 | C# crash when loading C++ dll | My program is written in C# NET 2.0,it's using external functions from a dll written in C++ using Microsoft Visual Studio 2008 SP1.
If I remove the dll from the directory the program is placed,the program crashes at the moment it should use the dll.That's normal.
But the users that are using my program get the same err... | Its most likely the wrong runtime. Make sure you are distributing the correct one. These will always work on your dev box because the runtimes are in the path. For testing software, I use a windows xp virtual machine. I set up the virtual machine as a completely fresh install, install the components I know that I need ... |
734,158 | 734,175 | Does rearranging a conditional evaluation speed up a loop? | Bit of a weird one: I was told a while ago by a friend that rearranging this example for loop from :
for(int i = 0; i < constant; ++i) {
// code...
}
to:
for(int i = 0; constant > i; ++i) {
// code...
}
would slightly increase performance in C++. I don't see how comparing a constant value to a variable is fa... | It's more in the line of C++ folklore, hand micro-optimizations that worked once on a particular version of a particular compiler and get passed down ever after as some kind of lore distinguishing the possessor from the common herd. It's rubbish. Profiling is truth.
|
734,217 | 734,236 | How much of STL is too much? | I am using a lot of STL code with std::for_each, bind, and so on, but I noticed that sometimes STL usage is not good idea.
For example if you have a std::vector and want to do one action on each item of the vector, your first idea is to use this:
std::for_each(vec.begin(), vec.end(), Foo())
and it is elegant and ok,... | Using boost::bind with std::for_each solves this problem in a clean way. Or you can use BOOST_FOREACH.
Example of std::for_each:
std::for_each(v.begin(), v.end(), boost::bind(&C::f, _1, param));
Example of BOOST_FOREACH:
std::list<int> list_int( /*...*/ );
BOOST_FOREACH( int i, list_int )
{
// do something with... |
734,227 | 734,265 | Co-mingling low-level C/C++ code | I am planning to write a code library to access some hardware at a low-level (i.e. flipping register bits and such).
Previously, I wrote everything as C functions and used extern "C" to make the library compile for both C and C++ code. So, both C and C++ users merely had to include the header file and call the functio... | There is some precedent for what you're proposing - Microsoft's MFC classes are just C++ wrappers around the C-compatible Windows API.
Before you start though, you should have some goal in mind beyond just creating busywork for yourself. The C++ should be easier to work with than the C, or you're not gaining anything.
|
734,259 | 734,330 | With OpenGL, how can I use gluOrtho2D properly with default projection? | I'm trying to use gluOrtho2D with glutBitmapCharacter so that I can render text on the screen as well as my 3D objects. However, when I use glOrtho2D, my 3D objects dissapear; I assume this is because I'm not setting the projection back to the OpenGL/GLUT default, but I'm not really sure what that is.
Anyway, this is ... | Your code looks okay. Most likely you've just messed up the matrix stack somewhere.
I suggest that you check if you forgot a glPopMatrix somewhere. To do so you can get the stack depth via glGet(GL_MODELVIEW_STACK_DEPTH). Getters for the other matrix-stacks are available as well.
Also you can take a look at the current... |
734,272 | 758,840 | How to use WinDbg to analyze the crash dump for VC++ application? | How do I use WinDbg for analyzing a dump file?
| Here are some general steps that will get you on your way:
First, you must change your compiler's settings so that it creates PDB files, even for release builds. Later versions of the Visual C++ compiler do this by default, but in many versions of Visual C++ you must do this yourself. Create program database files, and... |
734,551 | 734,899 | How to update a dialog box via SetDlgItemText within a function and have it take effect immediately in windows? | If I call SetDlgItemText() to update the value of a dialog text it seems to only be updated when the function returns. I'm using it to update a status message informing the user of the current progress mid function so I would like it to be updated immediately.
If this can not be done, is there something else I can do ... | I think Processing function is not allowing to call the OnPaint message of the window to which you are setting the message. You can move the processing function to a thread so that main thread handles the UI messages.
|
734,802 | 734,823 | Fixed-width integers in C++ | Occasionally I need to use fixed-width integers for communication with external devices like PLCs. I also use them to define bitmasks and perform bit manipulation of image data. AFAIK the C99 standard defines fixed-width integers like int16_t. However the compiler I use, VC++ 2008 doesn't support C99 and AFAIK Microsof... | Boost has the typedefs for all of the C99 types and more:
"Boost integer library"
|
734,936 | 734,967 | What is the best header structure to use in a library? | Concerning headers in a library, I see two options, and I'm not sure if the choice really matters. Say I created a library, lets call it foobar. Please help me choose the most appropriate option:
Have one include in the very root of the library project, lets call it foobar.h, which includes all of the headers in the l... | stl, boost and others who have a lot of header files to include they provide you with independent tools and you can use them independently.
So if you library is a set of uncoupling tools you have to give a choice to include them as separate parts as well as to include the whole library as the one file.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.