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
1,603,251
1,603,282
In C++, how can a class take a const std::string& parameter in the constructor but also handle NULL?
I'm trying to work through ways to create a class with a std::string argument, but which also handles NULL without throwing an exception. Here's an example of the code: class myString { public: myString(const std::string& str) : _str(str) {} std::string _str; }; int main() { myString mystr(NULL); prin...
What actually happens here is that NULL is interpreted as char const* and is being tried to be converted to std::string (you can convert C-strings of type char* into STL strings, right?). To handle it, you may add another constructor class myString { public: myString(const std::string& str) : _str(str) {} myStr...
1,603,300
1,603,613
Xcode 3.2.1 and C++ string fails!
In Xcode 3.2.1 on Mac OS X Snow Leopard, I open a project under: Command Line Tool of type C++ stdc++. I have the following simple code: #include <iostream> #include <string> using namespace std; int main(){ string myvar; cout << "Enter something: " << endl; cin >> myvar; cout << endl << myvar << ...
As far as I can tell, I'm not experiencing this issue in Release mode for x86_64. But I am seeing the issue in Debug x86_64. If I follow the directions given by Howard in this post, I'm able to get it running in debug mode: Project -> Edit Active Target ... Click Build tab Search for "preprocessor" Delete _GLIBCXX_DEB...
1,603,401
1,606,056
CUBLAS memory allocation error
I tried to allocate 17338896 elements of floating point numbers as follows (which is roughly 70 mb): state = cublasAlloc(theSim->Ndim*theSim->Ndim, sizeof(*(theSim->K0)), (void**)&K0cuda); if(state != CUBLAS_STATUS_SUCCESS) { printf("Error allocation video...
Memory can fragment, which means that you can still allocate multiple smaller blocks but not a single large block. Your videocard will obviously need some memory for its normal 2D task. If that happens to break the 128 MB into 2 blocks of almost 64MB, then you'd see this kind of failure.
1,603,834
1,604,031
DllImport a c++ DLL in to a C# app, BYTE * p
I have a exported function in a c++ DLL // C++ DLL (Blarggg.dll) extern "C" { USHORT ReadProperty( BYTE * messsage, USHORT length, BYTE * invokeID ) { if( invokeID != NULL ) { * invokeID = 10 ; } return 0; } } That I would like to make it available to my C# applic...
I pasted your code directly into VS2008 and it runs perfectly on my 32-bit machine (added a .def file to set the exported name). Is your C++ library definitely a pure win32 project? The error message you gave seems to imply that it threw a CLR exception.
1,604,132
1,604,745
How to find location of executable on Linux when normal methods fail?
In another question, the answer states that on Unixes with /proc, the really straight and reliable way is to readlink("/proc/self/exe", buf, bufsize) and it then proceeds to give backup solutions as follows: On Unixes without /proc (i.e. if above fails): If argv[0] starts with "/" (absolute path) this is the path. Oth...
Try looking in /proc from a suid binary.
1,604,176
1,604,216
Size of virtual pointer-C++
What is the size of virtual pointer(VPTR) for a virtual table in C++? Also this is not a homework question...just a question that came to my mind while I was reading a C++ book.
An excellent article related to this topic is Member Function Pointers and the Fastest Possible C++ Delegates. This article delves deeply into the implementation of member function pointers for many different compilers. This article talks about all the nuances of vtable pointers particularly in light of multiple (and v...
1,604,196
1,604,301
STL custom allocators to manage different memory spaces
I would like to use different instances of an STL custom allocator class to manage different memory spaces, and then be able to specify an allocator instance to an STL container such that each container only draws from its assigned memory space. But I don't see how I can do that. I see how I can pass an allocator typ...
Unfortunately STL allocators cannot have state (or at least have to be very careful how that state is used) - each instance of a particular allocator type must be equivalent for STL containers to work effectively with them. I don't recall the details right now, but I know that Scott Meyers discusses this problem at le...
1,604,268
1,604,294
How can I clear a SDL_Surface to be replaced with another one?
Been trying to find this online for a while now. I have a SDL_Surface with some content (in one it's text, in another is a part of a sprite). Inside the game loop I get the data onto the screen fine. But then it loops again and it doesn't replace the old data but just writes over it. So in the case of the text, it beco...
Try something like: SDL_FillRect(screen, NULL, 0x000000); at the beginning of your loop.
1,604,440
1,604,542
How to set selected filter on QFileDialog?
I have a open file dialog with three filters: QString fileName = QFileDialog::getOpenFileName( this, title, directory, tr("JPEG (*.jpg *.jpeg);; TIFF (*.tif);; All files (*.*)") ); This displays a dialog with "JPEG" selected as the default filter. I wanted to put the filter list in alph...
Like this: QString selfilter = tr("JPEG (*.jpg *.jpeg)"); QString fileName = QFileDialog::getOpenFileName( this, title, directory, tr("All files (*.*);;JPEG (*.jpg *.jpeg);;TIFF (*.tif)" ), &selfilter ); The docs are a bit vague about this, so I found this out via guessing.
1,604,582
1,643,777
Timing program runtimes in visual C++
Is there a quick and easy way of timing a section of a program (or the entire thing) without having to setup a timer class, functions, and variables inside my program itself? I'm specifically referring to Visual C++ (Professional 2008). Thanks, -Faken Edit: none of these answers do what i ask for, i would like to be a...
In the Intel and AMD CPUs there is a high speed counter. The Windows API includes function calls to read the value of this counter and also the frequency of the counter - i.e. how many times per second it is counting. Here's an example how to time your time in microseconds: #include <iostream> #include <windows.h> in...
1,604,588
1,604,603
iterate vector, remove certain items as I go
I have a std::vector m_vPaths; I will iterate this vector and call ::DeleteFile(strPath) as I go. If I successfully delete the file, I will remove it from the vector. My question is can I get around having to use two vectors? Is there different data structure that might be better suited for what I need to do? examp...
Check out std::remove_if: #include <algorithm> // for remove_if #include <functional> // for unary_function struct delete_file : public std::unary_function<const std::string&, bool> { bool operator()(const std::string& strPath) const { return ::DeleteFile(strPath.c_str()); } } m_vPaths.erase(std:...
1,604,699
1,604,722
Generators in C++ -- invalid use of nonstatic data member
I sort of understand this, at least the function of generators (I've used them in Python). I understand how the switch statement and its content is formed. However, I get these errors. test.cpp: In constructor 'Foo::descent::descent(int)': test.cpp:46: error: invalid use of nonstatic data member 'Foo::index_' test.cpp...
I'm not entirely sure what you're going for here, but here's where your error is occuring: Let's expand the macros to see how this really looks: class Foo { int index_; std::vector<std::string> bars_; public: Foo() { index_ = 0; bars_.push_back("Foobar"); bars_.push_back("Barfoo"...
1,604,853
1,605,132
Nested class' access to enclosing class' private data members
I'm having trouble implementing a nested class who's constructor is initialized with some of the enclosing class' private data members. Example: Header File: class Enclosing { //...Public members //...Private members int x, int y class Inner; // Declaration for nested class }; Impl. File: // Stuff... class...
Member x and y are non-static data member of Enclosing, which means that they only exist within a concrete object of Enclosing class. Without a concrete object, neither x nor y exist. Meanwhile, you are trying to refer to x and y without an object. That can't be done, which is what the compiler is trying to tell you. I...
1,604,968
1,604,972
What does a colon in a struct declaration mean, such as :1, :7, :16, or :32?
What does the following C++ code mean? unsigned char a : 1; unsigned char b : 7; I guess it creates two char a and b, and both of them should be one byte long, but I have no idea what the ": 1" and ": 7" part does.
The 1 and the 7 are bit sizes to limit the range of the values. They're typically found in structures and unions. For example, on some systems (depends on char width and packing rules, etc), the code: typedef struct { unsigned char a : 1; unsigned char b : 7; } tOneAndSevenBits; creates an 8-bit value, one bit...
1,605,274
1,605,491
Graph in C++ using gnuPlot
I am using gnuPlot library for printing a graph in C++ code. Its printing graph fine, but its printing only in blue color. Does somebody know how can I change the colors? Cheers
Use linestyle for setting a color. Some examples are here.
1,605,400
1,605,426
C++ std::sort with predicate function in Class
I want to sort vector of certain struct with certain order in certain class. I've wrote definition of struct and predicate function in a class and run std::sort in a method of the class with these struct and function. But compilation error has occurred. gcc version is 4.0.1 and OS is Mac OSX. The code is following: cla...
In the first case cmp is declared as a member function of the class sample and hence requires this pointer for calling it. Since the this pointer is not available compiler is complaining about it. You can make it work by declaring cmp as static function since static functions do not require this pointer for calling. I...
1,605,409
1,605,419
function definition does not declare parameters
What's wrong with TextLayoutTransition? Can function pointers not be declared virtual? LCDWrapper.h:23: error: function definition does not declare parameters Here's the class. class LCDInterface { public: // Slots virtual void TextSetSpecialChars() = 0; virtual void LayoutChangeBefore() = 0; virt...
No, you cant.. it doesnt make sense to put virtual on a function pointer. You cant override a variable.
1,605,674
1,605,683
Why/When to use (!!p) instead of (p != NULL)
In the following code, what is the benefit of using (!!p) instead of (p != NULL)? AClass *p = getInstanceOfAClass(); if( !!p ) // do something else // do something without having valid pointer
That's a matter of style, in fact they are equivalent. See this very similar question for discussion. IMO comparing against null pointer is clearer.
1,605,743
1,605,817
MFC/C++ equivalent of VB's AppActivate
AppActivate seems to be what i need, I am fairly sure there must be an c++/mfc equivalent. Is there one?
You can try these: SetForegroundWindow(FindWindow(NULL, "window title")); // or SetForegroundWindow(AfxGetMainWnd());
1,605,807
1,605,994
boost::unordered_map maintains order of insertion?
I am looking for a container which provides std::map like interface but maintains the order in which elements are inserted. Since there will not be too many elements in the map, the lookup performance is not a big issue. Will boost::unordered_map work in this case? i.e. does it maintain the order of insertion. I am ne...
unordered_map doesn't maintain the order of insertion. Unordered in this case means that the observable order of elements (i.e. when you enumerate them) is unspecified and arbitrary. In fact, I would expect that the order of elements in an unordered_map can change during the lifetime of the map, due to rehashing when r...
1,606,299
1,606,344
How does compiler choose between template specializations featuring an array?
I just came across std::tr1::extent template and it puzzled me. I never ever dealt with array type parameters in my life so I don't understand how they work. So, given the code from gcc type_traits template<typename _Tp, unsigned _Uint, std::size_t _Size> struct extent<_Tp[_Size], _Uint> template<typename _Tp, un...
extent<int[], 0>::value == 0 // second one chosen int[] is an incomplete type, the compiler doesn't know its sizeof value. The outermost dimension may stay incomplete, because it's not important for the array to function correctly in most contexts (in particular, indexing will still work). Something like int[1][] woul...
1,606,400
1,760,819
How to sleep or pause a PThread in c on Linux
I am developing an application in which I do multithreading. One of my worker threads displays images on the widget. Another thread plays sound. I want to stop/suspend/pause/sleep the threads on a button click event. It is same as when we click on video player play/pause button. I am developing my application in c++ on...
You can use a mutex, condition variable, and a shared flag variable to do this. Let's assume these are defined globally: pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; int play = 0; You could structure your playback code like this: for(;;) { /* Playback loop */ pt...
1,606,407
1,607,985
Index, assignment and increment in one statement behaves differently in C++ and C#. Why?
Why is this example of code behaving differently in c++ and C#. [C++ Example] int arr[2]; int index = 0; arr[index] = ++index; The result of which will be arr[1] = 1; [C# Example] int[] arr = new int[2]; int index = 0; arr[index] = ++index; The result of which will be arr[0] = 1; I find this very strange. Surely ther...
As others have noted, the behaviour of this code is undefined in C/C++. You can get any result whatsoever. The behaviour of your C# code is strictly defined by the C# standard. Surely there must be some rationale for both languages to implement it differently? Well, suppose you were designing C#, and wished to make t...
1,606,530
1,627,349
PInvoke - how to represent a field from a COM interface
I am referencing a COM structure that starts as follows: [scriptable, uuid(ae9e84b5-3e2d-457e-8fcd-5bbd2a8b832e)] interface nsICacheSession : nsISupports { /** * Expired entries will be doomed or evicted if this attribute is set to * true. If false, expired entries will be returned (useful for offline- ...
The answer you inserted is good. In COM Interop bools are marshaled as VARIANT_BOOL by default so your addition of the MarshalAs attribute to tell the marshaler to use a standard 4 byte BOOL type is correct, though the getter part of the equation needs the attribute added as well. In general, I like to leave propertie...
1,606,596
1,606,622
is this a good way to do a strcmp to return false when strings are empty
I want another condition --still maintaining a fast execution time but safer-- where i return false if either or both strings is empty: int speicial_strcmp(char *str1, char* str2 ) { if(*str1==*str2 =='\0') return 0; return strcmp(str1,str2); }
No, that's not a good way to do it, because it doesn't work. if(*str1==*str2 =='\0') will get evaluated as: bool tmp1 = *str1==*str2; bool tmp2 = tmp1 == '\0'; if (tmp2) In other words, because the bool will get promoted to an integer, your test will return true whenever the strings start with different characters (t...
1,606,738
1,606,975
Why does SFINAE not apply to this?
I'm writing some simple point code while trying out Visual Studio 10 (Beta 2), and I've hit this code where I would expect SFINAE to kick in, but it seems not to: template<typename T> struct point { T x, y; point(T x, T y) : x(x), y(y) {} }; template<typename T, typename U> struct op_div { typedef decltype...
Not 100% sure. It appears that the compiler needs to instantiate both overloads to determine which is better, but while trying to instantiate the other op_div with T = int and U = point<float>, this leads to an error that is not covered by SFINAE (the error is not that op_div doesn't have type in this case, but that ty...
1,606,894
1,606,909
std::pair<int, int> vs struct with two int's
In an ACM example, I had to build a big table for dynamic programming. I had to store two integers in each cell, so I decided to go for a std::pair<int, int>. However, allocating a huge array of them took 1.5 seconds: std::pair<int, int> table[1001][1001]; Afterwards, I have changed this code to struct Cell { int ...
std::pair<int, int>::pair() constructor initializes the fields with default values (zero in case of int) and your struct Cell doesn't (since you only have an auto-generated default constructor that does nothing). Initializing requires writing to each field which requires a whole lot of memory accesses that are relative...
1,606,969
1,609,131
operator new/delete and class hierarchies
Suppose, we have hierarchy of classes and we want to make them allocate/deallocate their memory only throughout our memory manager. What is a classical C++ way to achieve this behavior? Is it a MUST to have additional checks such as: class Foo{ public: virtual ~Foo(){} void* operator new(size_t bytes) ...
No the checks are unnecessary. Have a look at Alexandrescu's Loki's SmallObject allocator, you just inherit from SmallObject and it does all the heavy lifting for you! And do not forget to overload all versions of new and delete: simple version array version placement version Otherwise you might have some troubles.
1,607,188
1,607,233
Why is a type qualifier on a return type meaningless?
Say I have this example: char const * const foo( ){ /* which is initialized to const char * const */ return str; } What is the right way to do it to avoid the compiler warning "type qualifier on return type is meaningless"?
The way you wrote it, it was saying "the returned pointer value is const". But non-class type rvalues are not modifiable (inherited from C), and thus the Standard says non-class type rvalues are never const-qualified (right-most const was ignored even tho specified by you) since the const would be kinda redundant. One ...
1,607,357
1,609,076
warning #411: class foo defines no constructor to initialize the following:
I have some legacy code built with c++ compiler giving the error in the subject line typedef struct foo { char const * const str; } Foo; and a lot of places in the code (meaning I cannot change all of them) use it in a C style initialization: Foo arr[] ={ {"death"}, {"turture"}, {"kill"} } What...
If it works anyway, you might as well disable the warning in the command line for those files. With gcc I think it's something like -wd411. Not so elegant, but if it works and if the code appears to be compliant to the standard (in this order) there's no point sweating over it!
1,607,380
1,626,166
PInvoke - reading the value of a string field - "Attempted to read or write protected memory"
I'm having trouble accessing the some string fields in a COM interface. Calling the integer fields does not result in an error. When attempting call clientID(), deviceID() or key(), I get the old "Attempted to read or write protected memory" error. Here is the source interface code: (code sourced from here) [scriptable...
The strings in this interface are variants on C style strings (char*'s) but COM Interop by default treats strings as BSTRs. You have the marshaller trying to read the wrong kind of string and then free it with the CoTask memory allocator, so it's no surprise you get an access violation. If your strings were [In] parame...
1,607,402
1,607,567
How to Identify a Missing Dependency
We have a legacy 3rd party program that is failing with the error "Class Not Registered" when it tries to execute certain functionality. Is there a way to tell what class it's looking for? Sometimes it says "Catastrophic error" instead. Tried Dependency Walker statically and profiling, Kernal32.exe errors. I'm guess...
It's with a very large probability a COM problem. Here's an article on how to debug it. Basically, use RegMon. It will show COM reading registry keys, tyring to find the class provider.
1,607,409
1,607,436
Why doesn't this while loop work?
Ok, so I'm trying to create a program using a while loop to find the greatest common divisor of two numbers. This is what I came up with. However, from what I can tell, the program just seems to skip the loop entirely when I run it. (opers remains 0, divisor always comes back as equal to num1). Anyone out there that ca...
As soon as one of those modulo returns non 0, the while loop terminates. (So if any of your inputs immediately results in 0 from the modulo, the loop won't be entered) What you probably want: while ( (num1 % divisor != 0 ) || ( num2 % divisor != 0 ) ) { divisor--; opers++; } This continues the loop until both m...
1,607,515
1,607,536
PyQt custom widget in c++
Can I write custom Qt widget in pure C++, compile it and use in PyQt? I'm trying to use the ctypes-opencv with qt and I have performance problems with python's code for displaying opencv's image in Qt form.
You will have to write a Python wrapper for the widget, using the sip library (which is used by PyQt). There is a simple example for a Qt/C++ widget in the documentation.
1,607,678
1,608,358
C++ operator overloading and implicit conversion
I have a class that encapsulates some arithmetic, let's say fixed point calculations. I like the idea of overloading arithmetic operators, so I write the following: class CFixed { CFixed( int ); CFixed( float ); }; CFixed operator* ( const CFixed& a, const CFixed& b ) { ... } It all works. I can write 3 * CFi...
Assuming you'd like the specialized version to be picked for any integral type (and not just int in particular, one thing you could do is provide that as a template function and use Boost.EnableIf to remove those overloads from the available overload set, if the operand is not an integral type. #include <cstdio> #inclu...
1,607,748
1,607,895
template meta-programming OR operation
I have a class that can be decorated with a set of add-on templates to provide additional functionality. Each add-on has an identifying addon_value that the base class needs to know. The code below is an example of what I would like to do. Obviously, the main() function fails to compile. The goal is for CBase::GetValu...
Not sure this is the most elegant way, but the following is fairly straightforward: Add this to CMyClass: enum {AddonsValues = AddOn1<CBase>::addon_value | CMyClass<AddOn2, AddOn3>::AddonsValues}; int GetValueOfAddOns() { // return the result of OR-ing the addon_value of each add-on. return AddonsValues; }; a...
1,607,953
1,608,028
c++ OpenGL coordinate transformation
I just don't seem to be able to figure this out in my head. I'm trying to move an object in 3D space. If I have a point at 5,15,5 and use opengl functions to change the model view.... glTranslatef( 10.0f, 4.0f, 4.0f ); glRotatef( 33.0f, 1.0f, 0.0f, 0.0f ); glTranslatef( 10.0f, 4.0f, 4.0f ); Is there a way I can find o...
Try the following: 1) Push the current matrix into stack; 2) Load identity and apply your transformations; 3) Get the resulting transformation matrix into some temp variable. glGet or something like that will help; 4) Pop the matrix from the stack; Now you have your transformation matrix. Multiply your point by this ma...
1,608,252
1,608,271
C++ features to learn
C++ has too many features, and I can't see how any programmer is able to remember all these features while programming. (We can see how this affected the design of newer languages, such as Java) So, what I need is a list of features that are enough to know, disregarding all the others, to create c++ programs, perhaps c...
This is really an impossible to create list. Every place I work has a different acceptable subset of C++. So its going to be different depending on what you're developing on. I've seen C++ that truly is just C with occasional use of the "class keyword" to very run-time polymorphism oriented code to template meta-progra...
1,608,291
1,608,347
Including header files in Visual Studio
Suppose I have a solution with 3 projects X,Y, and E. E will generate an executable and X and Y will generate static libraries such that Y includes the header files of X and E includes the header files of Y. Now, my question is: why do I have to include the directory of the header files of X in E?
Here's why: It is possible that some function in project Y takes an argument (or returns a value) which is of a type declared in X. If so, the compiler may have to create these argument (or return value) objects while compiling E. If that's the case, header files from X are absolutely needed in E.
1,608,565
1,608,749
Is there a method to procedurally detecting if network router supports DHCP using C/C++?
There is a scenario where an application tells a device on a network to get their IP address from the network router's DHCP server. If a DHCP server is not available, the device's behavior becomes erratic. Is there a method to procedurally detect if the network router supports DHCP? Or, is this something the device ...
DHCP client on the device is doing exactly that. Well, almost that. The DHCP DISCOVERY message is broadcast on the link. Then, if there are any DHCP servers willing to serve this particular MAC address, each one reserves an IP address from its pool, and answers with the OFFER message. The client then picks what server ...
1,608,732
1,608,774
which cast is faster static_cast<int> () or int()
Try to see which cast is faster (not necessary better): new c++ case or old fashion C style cast. Any ideas?
There should be no difference at all if you compare int() to equivalent functionality of static_cast<int>(). Using VC2008: double d = 10.5; 013A13EE fld qword ptr [__real@4025000000000000 (13A5840h)] 013A13F4 fstp qword ptr [d] int x = int(d); 013A13F7 fld qword ptr [d] 013A13FA ca...
1,608,733
1,608,950
ambiguous access when calling a decorated base class
I have a class that can be decorated with a set of add-on templates to provide additional functionality. Each add-on needs to be able to call the base class and the user needs to be able to call the base class (either directly or using the CMyClass as a proxy). Unfortunately, the compiler can't tell which base class I...
Well, since I launched on the Decorator approach, I might as well :) EDIT: let's add the AddOnValues to solve this as well The problem here is the Multi-Inheritance. Tracing such a diagram is not easy but if you look closely you'll see that CMyClass<AddOn_A> inherits twice from CBase. CMyClass<AddOn_A> <-- AddOn_A<CBa...
1,608,909
1,608,955
Why don't structs work in Xcode, when they do in Visual C++? Help needed!
For some reason, this very basic code will compile with no errors in Visual C++, but gives errors in XCode. I will need to know why, in order to continue working in Xcode for my Computer Science class. #include <iostream> #include <string> using namespace std; struct acct { // bank account data int num...
The problem is not actually in your code: while C does require you to prefix your variables with struct in this case, C++ does not. The problem is actually that there is a global function on Unix named acct - it is this that is confusing the compiler. If you renamed your struct to something else, say bank_account, it w...
1,608,953
1,608,978
Very strange char array behaviour
. unsigned int fname_length = 0; //fname length equals 30 file.read((char*)&fname_length,sizeof(unsigned int)); //fname contains random data as you would expect char *fname = new char[fname_length]; //fname contains all the data 30 bytes long as you would expect, plus 18 bytes of random data on the end (intellise...
Sounds like the string in the file isn't null-terminated, and intellisense is assuming that it is. Or perhaps when you wrote the length of the string (30) into the file, you didn't include the null character in that count. Try adding: fname[fname_length] = '\0'; after the file.read(). Oh yeah, you'll need to alloca...
1,608,954
1,608,998
Can the loop continuation condition in for loop be anything that will eventually return a false/null value?
This is out of deitel's c++ book and I'm trying to understand a bit more about why the continuation condition works and how it knows to quit. s1 and s2 are arrays so when s2 tries to assign the '\n' to s1 does it return null? void mystery1( char *s1, const char *s2 ) { while ( *s1 != '\0' ) s1++; for ( ; *s1 = *s2; s...
*s1 = *s2 Is an expression. Expressions in C/C++ evaluates to values, and in this case it returns the value assigned to *s1. When the '\0' is assigned to *s1, the expression evaluates to 0 which is false clearly.
1,609,121
1,609,183
How to have a vector of byvalue and use a vector of pointers in conjunction?
I have some vectors of class A objects: std::vector<A> *V1; std::vector<A> *V2; etc there is a function with a vector of pointers of A: std::vector<A *> *arranged; what I need to do is put the vectors from V1, V2 etc inside arranged without destroying them in the end, so I thought that a vector of pointers to thos...
You could write your own comparator. In this case, the comparator would work on A*. A simple example using int type: void fun(vector<int*>* vec) { ///////// } bool comp(int* lhs, int* rhs) { return *lhs < *rhs; } int main() { vector<int> first, second; vector<int*> vec; for(vector<int>::size_type i...
1,609,127
1,609,198
C++ Serial Port Only Responding Once Using Write()
All the code below works. My device responds, C,7 is a reset. When I run this the second time it doesn't respond. If I manually turn my device off and on, then run this script again it works. But not if I press the button to run the script the second time. RS232: 57600,8,N,1 Any ideas?? Is there any more information ne...
The 1024 may in fact be your problem. The third paramter to the write() function indicates the number of bytes to be written: ssize_t write(int fildes, const void *buf, size_t nbyte); See the man page for write() for details. In your case, the number should be 5, since you are sending 5 characters ('C' ',' '7' '\r' an...
1,609,163
1,609,185
What is the difference between static_cast<> and C style casting?
Is there any reason to prefer static_cast<> over C style casting? Are they equivalent? Is there any sort of speed difference?
C++ style casts are checked by the compiler. C style casts aren't and can fail at runtime. Also, c++ style casts can be searched for easily, whereas it's really hard to search for c style casts. Another big benefit is that the 4 different C++ style casts express the intent of the programmer more clearly. When writin...
1,609,472
1,609,505
friend class with limited access
I want to make a class A friend class of class B. I want to do this as these interact very much and A needs to change internals of class B (which I dont want to expose using public). But I want to make sure it has access to only a few selected functions not all the functions. Example: class A { }; class B { private: ...
It depends on what you mean by "a nice way" :) At comp.lang.c++.moderated we had the same question a while ago. You may see the discussion it generated there. IIRC, we ended up using the "friend of a nested key" approach. Applied to your example, this would yield: class A { }; class B { public: class Key{ ...
1,609,550
1,609,576
looking for an efficient data structure to do a quick searches
I have a list of elements around 1000. Each element (objects that i read from the file, hence i can arrange them efficiently at the beginning) containing contains 4 variables. So now I am doing the following, which is very inefficient at grand scheme of things: void func(double value1, double value2, double value3) { ...
If space isn't too important the easiest thing to do is to create a hash based on "a" Depending on how many conflicts you get on "a" it may make sense to make each node in the hash table point to a binary tree based off of "b" If b has a lot of conflicts, do the same for c. That first index into the hash, depending o...
1,609,606
1,609,617
LNK2001 using a std::vector of a custom struct
I want to have some data cache which contains some objects which I can update over an UpdateCache function. However, I'm getting problems with a LNK2001 followed by a LNK1120. HeaderFile.h #ifndef headerfile_included #define headerfile_included #include <vector> struct MyObject { unsigned int A; unsigned int B;...
You need to add this to a cpp file: std::vector<MyObject> MyClass::myObjectCache; The reason is that as a static exists without a class ever being instantiated it needs to exist whether an instance of the class is instantiated or not. The line above creates the instance of the static and thus it exists whether or not...
1,609,669
1,610,128
Why does new / malloc fail on Win x64 although there is plenty of free RAM?
I have a strongly recursive function, that creates a (very small) std::multimap locally for each function instance using new (which recurses to malloc/calloc in the std lib). After some hundred recursions new fails although i am using a native 64Bit application on Windows XP x64. The machine has 10 GB RAM, The applicat...
Your number suggests an easily defaulted 1MB stacks size (c150K x 8 ). So from a quick look at your code (and that map::insert especially and not providing the for'...' code ) you are running into an interaction with stackoverflow.com :) You are probably hitting it for the OS you're running it on. On Windows use the ...
1,609,975
1,610,606
"Elements of Programming" real world examples?
I'm eager to learn about Stepanov's approach to programming described in the book Elements of Programming. Does anyone here have experience with these methods, or can point me to some online resource where this topic matter is discussed? I've seen the Adobe's Google Tech Talk on A Possible future of software developmen...
I was a proofreader for the book, and my feedback to Alex greatly influenced the style of presentation. I am happy to call myself one of his disciples. I find the material fascinating, and it has totally changed the way I write code, even Java code. Some of Alex's "methods" are radical despite the vague wording I am ...
1,610,029
1,610,065
getters and setters style
(Leaving aside the question of should you have them at all.) I have always preferred to just use function overloading to give you the same name for both getter and setters. int rate() { return _rate; } void rate(int value) { _rate = value; } // instead of int getRate() { return _rate; } void setRate(i...
I would prefer the get/set versions because it is more clear as to what is going on. If I saw rate() and rate(10), how do I know that rate(10) isn't simply using 10 in the calculation to return the rate? I don't, so now I have to start searching to figure out what is going on. A single function name should do one th...
1,610,030
1,610,454
Why does flowing off the end of a non-void function without returning a value not produce a compiler error?
Ever since I realized many years ago, that this doesn't produce an error by default (in GCC at least), I've always wondered why? I understand that you can issue compiler flags to produce a warning, but shouldn't it always be an error? Why does it make sense for a non-void function not returning a value to be valid? An ...
C99 and C++ standards require non-void functions to return a value, except main. The missing return statement in main will be defined (to return 0). In C++ it's undefined behaviour if execution actually reaches the end of a non-void function other than main, while in C it's only UB if the caller uses the return value....
1,610,158
1,610,171
the "this" pointer inside a class
the question is simple... is there any difference in using this->yourvariable or yourvariable directly for some reason? I am not finding any problem with that, but I am using this-> a lot and would like to know if there is any difference before going further. I saw a comment on a post here and I don't remember which th...
No, there is no real difference, it is simply a scope qualifier. However, suppose a method void SetFoo( Foo foo ) { this->foo = foo; } where this->foo is a private member. Here it allows you to take a parameter with the same name as a class/instance variable.
1,610,210
1,610,229
C++ Graphic Drawing Library
Does anyone know what's the best graphic drawing library for C++, I want a lib that can draw basic shapes and can make image editing, gradients and vector or 3D would be great to. The windows drawing functions are complicated and are not very advanced.
May I suggest using Cairo? This vector library is very fast, verbose and powerful! Just look at those pretty examples! There's even integration with OpenGL if you need vectorized 3D textures!
1,610,283
1,610,312
Step execution of release code / post-mortem debugging (VS/C++)
Is there any sense to step-execute release code? I noticed that some lines of code are omitted, i.e. some method calls. Also variable preview doesn't show some variables and shows invalid (not real) values for some others, so it's all quite misleading. I'm asking this question, because loading WinDbg crashdump file int...
Recompile just the file of interest without optimisations :) In general: Switch to interleaved disassembly mode. Single-stepping through the disassembly will enable you to step into function calls that would otherwise be skipped over, and make inlined code more evident. Look for alternative ways of getting at values i...
1,610,551
1,610,631
When or where was the term "Most vexing parse" coined?
There are countless articles and blogs discussing C++'s most vexing parse, but I can't seem to find any with a more substantial reference than "the C++ literature." Where did this term come from?
Scott Meyers book Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library of 2001 might be first published use.
1,610,668
1,610,963
Project level c++ exception handling strategy
Say I have nested methods a, b, c, d, e on each level we return errors in the normal course of operations, but e could also throw an exception (e.g. out of memory on STL insert). The exceptions are very seldom and how fast/slow actual unwinding is happening is not an issue. What is the most appropriate strategy for ex...
Regardless of what you decide here, I would encourage you to pound--or at least gently tap--the notion of exception-safety into the other developers' heads. In my experience, the process of writing exception-safe code has resulted in more cleanly-designed, transactional code. As a benefit, that coding style works rega...
1,610,836
1,610,852
Branchless code that maps zero, negative, and positive to 0, 1, 2
Write a branchless function that returns 0, 1, or 2 if the difference between two signed integers is zero, negative, or positive. Here's a version with branching: int Compare(int x, int y) { int diff = x - y; if (diff == 0) return 0; else if (diff < 0) return 1; else return 2; } ...
int Compare(int x, int y) { return (x < y) + (y < x) << 1; } Edit: Bitwise only? Guess < and > don't count, then? int Compare(int x, int y) { int diff = x - y; return (!!diff) | (!!(diff & 0x80000000) << 1); } But there's that pesky -. Edit: Shift the other way around. Meh, just to try again: int Compare...
1,610,875
1,618,075
Is LLVM an exception to the rule for avoiding dynamic casts?
LLVM has it's own hand rolled alternative to RTTI that is a speed improvement over built-in RTTI and allows dynamic casting to classes with no vtable (dyn_cast). However, it can still be used in exactly the way that dynamic_cast<> is used though it does allow it to be used with more classes. dyn_cast<> template documen...
While performance hits are a reason to avoid dynamic_cast<> for large class hierarchies, it's not the only reason you might want to avoid them. Better performing or not, one should not be more encouraged to use dyn_cast<> because of this claim. On the other hand, there's absolutely nothing wrong with using dynamic_cast...
1,610,906
1,611,001
debugging C++ code with templates and STL with gdb
What do gdb users here think about its capabilities in regards to debugging code with templates and STL? Do you use any tricks to make the debugging any simpler? Perhaps some Python scripts? Or are you satisfied the way it is at present in gdb (ver 6.x, haven't tried 7.x yet)? Thanks.
I am assuming that you mean visualizing STL code better (and not the debug mode which give safe iterators and additional runtime checks). I am not sure if you have looked at these posts: GNU GCC Documentation: Debugging Support Using gdb Starting with version 7.0, GDB includes support for writing pretty-printers in ...
1,611,165
1,611,205
How to use different ifstream modes in c++?
According to the reference, if I use ifstream infile ( "test.txt" , ifstream::in ); it will Allow input operations on the stream. But what are some of the examples of the "input operations"? Is ifstream infile ( "test.txt" , ifstream::in | ifstream::binary ); the right syntax to use multiple flags? Will it make a dif...
According to the reference, if I use ifstream infile ( "test.txt" , ifstream::in ); it will Allow input operations on the stream. But what are some of the examples of the "input operations"? Reading from a file which would mean everything an input stream can support. See istream member functions. Typically,...
1,611,420
1,611,430
ifstream position in c++
I am trying to write a simple UTF-8 decoder for my assignment. I'm fairly new with C++ so bear with me here... I have to determine whether the encoding is valid or not, and output the value of the UTF-8 character in hexadecimal in either case. Say that I have read the first byte and used this first byte to determine th...
I would suggest you use peek() to read the first byte instead. seekg() should work to rewind, but a BUS error is usually caused by your code breaking alignment issues, which points to you doing something else evil in your code.
1,611,526
1,611,602
How do you std::vector in XCode + C++?
For various reasons (and I assure you they are valid, so no "use Cocoa" talk please), I must work with XCode, C++, OpenGL, OpenCL (with a little GLUT on the side) to rebuild a few graphics demos on Mac (coming from XP + Visual Studio 2005 development). The project was built as a Command Line Tool using "c++ stdc++". My...
I'm SO sorry everyone. Mere minutes after posting this, I decided to go on with what I could, saving this issue for later. I found a similar problem occurring with fstream. With this new information available, a Google search brought up this topic, and ultimately the solution. I had defined my own min and max macros in...
1,611,615
1,615,422
boost::spirit and generating different nodes
greetings. i've been interesting in how to force boost::spirit to produce nodes of different classes when parsing the grammar and generating AST. say, i want to have different nodes such as VariableNode (which has name of variable as its member), ValueNode (which has value as its member), etc. it would be very useful w...
I'm not sure I understand your question, do you mean something like this? : typedef boost::variant<VariableNode, ValueNode> AbstractNode; template <typename Iterator> struct NodeGrammar: public boost::spirit::qi::grammar<Iterator, AbstractNode(), boost::spirit::ascii::space_type> { NodeGrammar: NodeGrammar::base_t...
1,611,673
1,611,689
Constant strings address
I have several identical string constants in my program: const char* Ok() { return "Ok"; } int main() { const char* ok = "Ok"; } Is there guarantee that they are have the same address, i.e. could I write the following code? I heard that GNU C++ optimize strings so they have the same address, could I use that fe...
There's certainly no guarantee, but it is a common (I think) optimization. The C++ standard says (2.13.4/2 "String literals): Whether all string literals are distinct (that is, are stored in nonoverlapping objects) is implementation-defined. To be clear, you shouldn't write code that assumes this optimization will ta...
1,611,756
1,611,777
Memory management and realloc
I'm going through my program with valgrind to hunt down memory leaks. Here's one that I'm not sure what to do with. ==15634== 500 (224 direct, 276 indirect) bytes in 2 blocks are definitely lost in loss record 73 of 392 ==15634== at 0x4007070: realloc (vg_replace_malloc.c:429) ==15634== by 0x807D5C2: hash_set_c...
The problem is that if realloc() fails the function will return NULL but the original block will still be allocated. However, you've just overwritten the pointer to that block and can't free (or use) it anymore.
1,611,771
1,611,795
Deleting object with private destructor
How is that possible that it is allowed to delete object with private destructor in the following code? I've reduced real program to the following sample, but it still compiles and works. class SomeClass; int main(int argc, char *argv[]) { SomeClass* boo = 0; // in real program it will be valid pointer delete boo;...
You are trying to delete object of incomplete class type. C++ Standard says that you'll get undefined behavior in this case (5.3.5/5): If the object being deleted has incomplete class type at the point of deletion and the complete class has a non-trivial destructor or a deallocation function, the behavior is undefined...
1,612,031
1,612,051
Is there any danger in calling free() or delete instead of delete[]?
Possible Duplicate: ( POD )freeing memory : is delete[] equal to delete ? Does delete deallocate the elements beyond the first in an array? char *s = new char[n]; delete s; Does it matter in the above case seeing as all the elements of s are allocated contiguously, and it shouldn't be possible to delete only a port...
It's undefined behaviour (most likely will corrupt heap or crash the program immediately) and you should never do it. Only free memory with a primitive corresponding to the one used to allocate that memory. Violating this rule may lead to proper functioning by coincidence, but the program can break once anything is cha...
1,612,058
1,612,075
Building 64bit libraries
I want to build 64bit libraries for some of my C++ components. Is it required to compile/link the libraries in OS running on physical machine directly? Or can i use a OS running as virtual machine in ESX server to build the libraries? Would i need to take care of anything if i am building in a virtual machine? Please a...
If the guest OS is 64-bit and you have a 64-bit compiler, there is not reason why you can't compile and run a 64-bit library/application in your virtualised OS.
1,612,235
1,612,243
Upcasts in COM automatic?
In COM, if I have an interface IBase and an interface IX which inherits from IBase, can I call methods of IBase through an IX pointer, and if not, why can I call Release() and AddRef() on any COM interface pointer without an upcast?
Yes, you can call whatever method of the base through the pointer to the derived. That's exactly why you can call AddRef(), Release() and QueryInterface() through any interface pointer.
1,612,451
1,616,679
Executing external program via system() does not run properly
I try to call a program (ncbi blast, for those who need to know) from my code, via calling the command in a system() call. If I execute the string directly in the shell, it works as intended, but if I try the same string via system(), the program returns much faster, without the intended results. The output file is cre...
The most usual cause of such problems is incorrect environment variable setting in ones ~/.bashrc. You should be able to see what ncbi is unhappy about by executing $SHELL -c '<exact string you pass to system()>' Another common way to debug this is with strace. Execute: strace -fo /tmp/strace.out ./myProgram and look...
1,612,619
1,614,402
Large Xml files are being truncated by MSXML4 / FreeThreadedDOMDocument40 (COM string Interop issue)
I'm using the following code to load a large Xml document (~5 MB): int _tmain(int argc, _TCHAR* argv[]) { ::CoInitialize(NULL); HRESULT hr; CComPtr< IXMLDOMDocument > spXmlDocument; hr = spXmlDocument.CoCreateInstance(__uuidof(FreeThreadedDOMDocument60)), __uuidof(FreeThreadedDOMDocument60); if(FAI...
It appears I was a victim of my own foolishness - the Xml / strings were in fact not being truncated, the viewer in Visual Studio was simply lying to me. Outputting the strings to a file showed that the strings were all as they should be.
1,612,982
1,612,995
How does automatic memory allocation actually work in C++?
In C++, assuming no optimization, do the following two programs end up with the same memory allocation machine code? int main() { int i; int *p; } int main() { int *p = new int; delete p; }
No, without optimization ... int main() { int i; int *p; } does almost nothing - just a couple of instructions to adjust the stack pointer, but int main() { int *p = new int; delete p; } allocates a block of memory on heap and then frees it, that's a whole lot of work (I'm serious here - ...
1,613,041
1,764,696
Embedded console tools functionality in application
I'm currently developing an application that happens to require some file preprocessing before actually reading the data. Doing it externally was not a possibility so I came up with a fork & execve of "cut options filename | sort | uniq -c" etc... and I execute it like that. However I thought that maybe there was alrea...
Arkaitz, the answer no, because of how you've phrased the question. You ask for "another option to reuse all those ancient and good working tools directly in my code and not having to invoke them through a shell" The problem with that is, the proper and accepted way of reusing all those ancient and good working tools i...
1,613,074
1,613,094
In C++, what's the use of having a function void foo(int** p)?
I have been told by my colleague that void foo(int** p) is used like an out parameter in C#. Can someone precisely explain how? I get the idea, but there is something that is missing. I know that if we pass the pointer p itself to foo(*p) and the function body does p = new int(), we might have a dangling modifier! But ...
void foo(int** p) { *p = new int; } void main() { int *p = NULL; foo(&p); //unless you pass the pointer to p, the memory allocated in the //function foo is not available here. foo(p); // lets assume foo is foo(int* p) //when you pass only pointer p to `foo()` then the value of the pointer will be //passed ( pa...
1,613,217
1,616,507
How do I convert from _TCHAR * to char * when using C++ variable-length args?
We need to pass a format _TCHAR * string, and a number of char * strings into a function with variable-length args: inline void FooBar(const _TCHAR *szFmt, const char *cArgs, ...) { //... } So it can be called like so: char *foo = "foo"; char *bar = "bar"; LogToFileA(_T("Test %s %s"), foo, bar); Obviously a simple...
Use %hs or %hS instead of %s. That will force the parameters to be interpretted as char* in both Ansi and Unicode versions of printf()-style functions, ie: inline void LogToFile(const _TCHAR *szFmt, ...) { va_list args; TCHAR szBuf[BUFFER_MED_SIZE]; va_start(args, szFmt); _vstprintf_s(szBuf, BUFFER_MED_SIZE...
1,613,230
1,618,867
Uses of C comma operator
You see it used in for loop statements, but it's legal syntax anywhere. What uses have you found for it elsewhere, if any?
C language (as well as C++) is historically a mix of two completely different programming styles, which one can refer to as "statement programming" and "expression programming". As you know, every procedural programming language normally supports such fundamental constructs as sequencing and branching (see Structured P...
1,613,341
1,613,578
What do the following phrases mean in C++: zero-, default- and value-initialization?
What do the following phrases mean in C++: zero-initialization, default-initialization, and value-initialization What should a C++ developer know about them?
One thing to realize is that 'value-initialization' is new with the C++ 2003 standard - it doesn't exist in the original 1998 standard (I think it might be the only difference that's more than a clarification). See Kirill V. Lyadvinsky's answer for the definitions straight from the standard. See this previous answer a...
1,613,494
1,613,922
Why was wchar_t invented?
Why is wchar_t needed? How is it superior to short (or __int16 or whatever)? (If it matters: I live in Windows world. I don't know what Linux does to support Unicode.)
Why is wchar_t needed? How is it superior to short (or __int16 or whatever)? In the C++ world, wchar_t is its own type (I think it's a typedef in C), so you can overload functions based on this. For example, this makes it possible to output wide characters and not to output their numerical value. In VC6, where wchar_...
1,613,678
1,613,721
Why can't C++ Builder find my headers?
I am required to recompile a C++ builder project, and am come across this problem. one of the unit contains the followings: #include "LMDBaseControl.hpp" #include "LMDBaseGraphicControl.hpp" #include "LMDBaseLabel.hpp" #include "LMDBaseMeter.hpp" #include "LMDControl.hpp" : When I compiled this unit, I ...
You need to add both the path to the library and the path to the H files (2 separate options in the Borland options dialog).
1,614,379
1,615,158
how to determine which files has been changed from those in rcs
I am working with a c++ codebase using rcs repository (agh, old I know), during major code changes, I modify a lot of files, which I sometimes lose track of. So I would like to have a small script which will list the files that are different (those that I changed) from files in the repository. It is sort of unrealist...
Wow. RCS is designed for source control of a single file. It is rarely used directly. CVS is a system that is layered ontop of RCS to extend the functionality to a bunch of files (ie a project). You could do it in the shell with: tcsh foreach a ( `ls *.cpp` ) echo ${a} echo "========================================...
1,614,393
1,680,334
SDL GL program terminates immediately
I'm using Dev-C++ 4.9.9.2 (don't ask why) and SDL 1.2.8. Next I've created new project: SDL&GL. This project contains already some code: #include <SDL/SDL.h> #include <gl/gl.h> int main(int argc, char *argv[]){ SDL_Event event; float theta = 0.0f; SDL_Init(SDL_INIT_VIDEO); SDL_SetVideoMode(600, 300, 0...
I finally found some time to solve this problem. I have completly uninstalled old card graphic drivers and install 9.8 ATI drivers with Catalyst Control Center. Now everything is working. There where no problem in code itself. The problem was something in my system with graphic drivers. Anyway thanks for your answers!
1,614,595
1,614,670
Converting wide char string to lowercase in C++
How do I convert a wchar_t string from upper case to lower case in C++? The string contains a mixture of Japanese, Chinese, German and Greek characters. I thought about using towlower... http://msdn.microsoft.com/en-us/library/8h19t214%28VS.80%29.aspx .. but the documentation says that: The case conversion of towlowe...
If your string contains all those characters, the codeset must be Unicode-based. If implemented properly, Unicode (Chapter 4 'Character Properties') defines character properties including whether the character is upper case and the lower case mapping, and so on. Given that preamble, the towlower() function from <wctyp...
1,614,641
1,614,681
C++ and Windows , CRT
I am developing application application using C++ VS 2008. Now I need to either install respective MSM or install redist on customer machine to get this working. Is there any way in which I can just copy those CRT dlls and get the application running. Private assembly option seems to be complicate.
If you just depend on the CRT, then yes you can simply XCOPY deploy it as a private assembly and it will work just fine. Put it in the same folder as your application. Doing this will prevent your application from taking advantage of servicing releases of the CRT though. This may or may not be an issue for you.
1,614,651
1,615,226
Do sequence points prevent code reordering across critical section boundaries?
Suppose that one has some lock based code like the following where mutexes are used to guard against inappropriate concurrent read and write mutex.get() ; // get a lock. T localVar = pSharedMem->v ; // read something pSharedMem->w = blah ; // write something. pSharedMem->z++ ; // read and write something. mutex....
In short, the compiler is allowed to reorder or transform the program as it likes, as long as the observable behavior on a C++ virtual machine does not change. The C++ standard has no concept of threads, and so this fictive VM only runs a single thread. And on such an imaginary machine, we don't have to worry about wha...
1,614,794
1,614,858
Modify PL/SQL statement strings in C++
This is my use case: Input is a string representing an Oracle PL/SQL statement of arbitray complexity. We may assume it's a single statement (not a script). Now, several bits of this input string have to be rewritten. E.g. table names need to be prefixed, aggregate functions in the selection list that don't use a colu...
Maybe you can use this, it changes an select statement into an xml block: declare cl clob; begin dbms_lob.createtemporary ( cl, true ); sys.utl_xml.parsequery ( user, 'select e.deptno from emp e where deptno = 10', cl ); dbms_output.put_line (cl); dbms...
1,614,867
1,614,878
why would std::vector max_size() function return -1?
I have a std::vector<unsigned char> m_vData; m_vData.max_size() always returns -1. why would that happen?
Probably because you're assigning it to a signed type before viewing. The return value of max_size is typically size_t which is an unsigned type. A straight conversion to say int on many platforms would return -1. Try the following instead std::vector<unsigned char>::size_type v1 = myVector.max_size();
1,614,988
1,615,004
Vector initializing slower than array...why?
I tried 2 things: (pseudo code below) int arr[10000]; for (int i = 0; i < 10000; i++) { for (int j = 0; j < 10000; j++) { arr[j] = j; } } and vector<int> arr(10000); for (int i = 0; i < 10000; i++) { for (int j = 0; j < 10000; j++) { arr[j] = j; } } I ran both the programs and timed it...
For the template, subscripting is done with operator[]. With optimization turned off, that'll usually be generated as a real function call, adding a lot of overhead to something as simple as subscripting into an array. When you turn on optimization, it's generated inline, removing that overhead.
1,615,109
1,615,162
Does Windows 7 render old programs' controls with GDI or the new DWM/WDDM?
In Windows XP the Win32 API renders the controls using GDI/GDI+. Now I'm on 7, so if I use the API's functions, will the rendering automatically be handled by the DWM/WDDM (so by DirectX)? or will it continue to render with GDI? Or likewise, will an old app written with WinAPI, be rendered with GDI also in Windows 7? T...
In my experience, if the Aero display is on everything will render via that system, it just won't be obvious to your application. You'll still render in GDI, but it will be to a back buffer and not directly to the screen buffer (in fact it's more complicated then that). That way your older app can get the benefits of t...
1,615,197
1,615,253
Templates and std::numeric_limits
I have a class called Atomic which is basically an _Atomic_word plus methods that call the gcc atomic builtins. class Atomic{ mutable volatile _Atomic_word value_; public: Atomic(int value = 0): value_(value) {} **** blah blah **** }; I would like std::numeric_limits<Atomic> to instantiate to std::numer...
std::numeric_limits<Atomic> will instantiate with Atomic as the type, you can't subvert that. However you could specialise std::numeric_limits for Atomic like this template<> class numeric_limits< Atomic > : public numeric_limits< Atomic::UnderlyingType > { }; where you obviously expose UnderlyingType as a type in Ato...
1,615,215
1,615,259
Does ASP.NET support C++?
When I go to New -> Web site, in the drop-down menu "Language" there are only 2 languages: Visual C# and Visual Basic. No Visual C++. Maybe, I'm using wrong version of Visual Studio? (mine is 9.0.21022) I tried to google this problem. I found a topic which tells that using C++ in ASP.NET is impossible. But it was post...
Visual Studio generates C# and VB code and that's why it provides you only those options, because the visual designers from which code is generated don't understand C++. There's nothing preventing you from creating a C++ project that uses the managed .NET codebase like the System, System.Web.* namespaces, etc. You won'...
1,615,518
1,615,557
vector.resize function corrupting memory when size is too large
what's happening is i'm reading encryption packets, and I encounter a corrupted packet that gives back a very large random number for the length. size_t nLengthRemaining = packet.nLength - (packet.m_pSource->GetPosition() - packet.nDataOffset); seckey.SecretValues.m_data.resize(nLengthRemaining); In this code m_data ...
I think that vector::max_size() is pretty much always a 'hard coded' thing - it's independent of how much memory the system/library is prepared to dynamically allocate. Your problem seems to be a bug in the vector implementation that corrupts things when an allocation fails. 'Bug' might be too strong of a word. vector:...
1,615,555
1,615,572
Why does my C++ divide program not compile
I tried to make a program that has a correct Divide function. My code was: #include <iostream> using namespace std; double x,y,z,a; double divide(x,y) { if (x >= y) { x=z; z=y; y=x; return(x/y); } else return(y/x); } int main() { double x,y,z ; cout << "En...
You need to specify a proper function signature for the function divide. Specifically, the arguments to the function are missing their types: double divide(double x, double y) { ... } You also need to create a scope for each block in an if statement: if (x > y) { ... } else { ... }
1,615,634
1,864,256
Can anyone recommend a decent DSP/speech library in C++?
Google returns too much results, although SPUC caught my attention. Is there a standard recommended library like OpenCV for vision? The necessary features would be: Free Open Source filter design (Butterworth, Chebyshev, etc) FFT if possible, some speech processing features, like MFCC computation, although that's seco...
The Synthesis Toolkit, https://ccrma.stanford.edu/software/stk/, has a class that can model different Phonemes. It also has tools for all sorts of DSP including different types of filters. I recommend checking it out as it will be a fantastic learning experience no matter what you use it for.
1,615,660
1,615,812
Why this warning from IBM XL C/C++ compiler?
Here's a minimum code example that illustrates the problem: #include <iostream> class Thing { // Non-copyable Thing(const Thing&); Thing& operator=(const Thing&); int n_; public: Thing(int n) : n_(n) {} int getValue() const { return n_;} }; void show(const Thing& t) { std::cout << t.getValue()...
The rules for this are in §8.5.3/5 of the standard. There are three basic situations identified. The first involve the initializer ('3' in your case) being either an lvalue, or having class type. Since neither of those is true, what you have is the third case: initializing a const reference with an rvalue that does not...
1,615,813
1,616,143
How to use C++ classes with ctypes?
I'm just getting started with ctypes and would like to use a C++ class that I have exported in a dll file from within python using ctypes. So lets say my C++ code looks something like this: class MyClass { public: int test(); ... I would know create a .dll file that contains this class and then load the .dll fil...
The short story is that there is no standard binary interface for C++ in the way that there is for C. Different compilers output different binaries for the same C++ dynamic libraries, due to name mangling and different ways to handle the stack between library function calls. So, unfortunately, there really isn't a por...
1,615,902
1,615,917
C++ - "Member function not declared" in derived class
I have a problem in MSVC++ 2008 where VS2008 is throwing this compile error: error C2509: 'render' : member function not declared in 'PlayerSpriteKasua' Now, what's confusing me is that render() is defined, but in an inherited class. The class definition works like this: SpriteBase -Inherited By-> PlayerSpriteBase -In...
In PlayerSpriteKasua.h you need to re-declare whatever methods you're going to override/implement (without the "=0" to say that those methods are not abstract anymore). So you need to write it like follows: class PlayerSpriteKasua : public PlayerSpriteBase { public: virtual void think(); virtual void render(lon...