question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,582,161
2,582,187
Function pointer as parameter
I try to call a function which passed as function pointer with no argument, but I can't make it work. void *disconnectFunc; void D::setDisconnectFunc(void (*func)){ disconnectFunc = func; } void D::disconnected(){ *disconnectFunc; connected = false; }
The correct way to do this is: typedef void (*callback_function)(void); // type for conciseness callback_function disconnectFunc; // variable to store function pointer type void D::setDisconnectFunc(callback_function pFunc) { disconnectFunc = pFunc; // store } void D::disconnected() { disconnectFunc(); // call connected = false; }
2,582,282
2,582,287
How can I catch runtime error in C++
By referring to C++ catching all exceptions try { int i = 0; int j = 0/i; /* Division by 0 */ int *k = 0; std::cout << *k << std::endl; /* De-reference invalid memory location. */ } catch (...) { std::cout << "Opps!" << std::endl; } The above run-time error are unable to be detected. Or, am I having wrong expectation on C++ exception handling feature?
If you dereference a pointer that doesn't point to an object, you don't get an exception, you get undefined behavior. Anything can happen. Usually, if you dereference a null pointer, as you do in your example, the program will crash.
2,582,367
2,582,387
c++ opengl: how to find normalized vectors for a quad?
can anyone assist me in finding the proper formula for quad normalization ? using c++ with opengl. thank you!
Assuming that you want the normal vector for a quad, this pseudo-code works Vector3d vertex[4] = { ... } Vector3d normal(0,0,0) ; for (int i=0; i<4; i++) { normal += cross (vertex[i], vertex[(i+1)%4]) ; // cross product } normalize (normal) ; // normal is the unit normal to the quad This gives you the formula n=A/|A|, where A = v0xv1 + v1xv2 + v2xv3 + v3xv0 and vi=vertex[i]). |A|/2 is also the area of the polygon. This can be generalized to arbitrary polygons, and will even give reasonable results for non-planar polygons, as long as they aren't too non-planar. One reference is http://softsurfer.com/Archive/algorithm_0101/algorithm_0101.htm If you know that the quad/polygon is planar, you only have to calculate the normal of the triangle formed by the first three vertices. This is A1/|A1|, where A1 = (v1-v0)x(v2-v0) = v0xv1 + v1xv2 + v2xv0. If by "quad normalization" you meant something else, just ignore this answer. EDIT: I found this related question: Get the Surface Area of a Polyhedron (3D object)
2,582,415
2,582,422
How do you search a document for a string in c++?
Here's my code so far: #include<iostream> #include<string> #include<fstream> using namespace std; int main() { int count = 0; string fileName; string keyWord; string word; cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ; getline(cin, fileName); cout << endl; cout << "Please input the word you'd like to search for: " << endl; cin >> keyWord; cout << endl; ifstream infile(fileName.c_str()); while(infile.is_open()) { getline(cin,word); if(word == keyWord) { cout << word << endl; count++; } if(infile.eof()) { infile.close(); } } cout << count; } I'm not sure how to go to the next word, currently this infinite loops...any recommendation? Also...how do I tell it to print out the line that that word was on? Thanks in advance!
while(infile >> word) { if(word == keyWord) { cout << word << endl; count++; } } This would do the job. Please read about streams more.
2,582,417
2,583,036
Comparing floats in their bit representations
Say I want a function that takes two floats (x and y), and I want to compare them using not their float representation but rather their bitwise representation as a 32-bit unsigned int. That is, a number like -495.5 has bit representation 0b11000011111001011100000000000000 or 0xC3E5C000 as a float, and I have an unsigned int with the same bit representation (corresponding to a decimal value 3286614016, which I don't care about). Is there any easy way for me to perform an operation like <= on these floats using only the information contained in their respective unsigned int counterparts?
You must do a signed compare unless you ensure that all the original values were positive. You must use an integer type that is the same size as the original floating point type. Each chip may have a different internal format, so comparing values from different chips as integers is most likely to give misleading results. Most float formats look something like this: sxxxmmmm s is a sign bit xxx is an exponent mmmm is the mantissa The value represented will then be something like: 1mmm << (xxx-k) 1mmm because there is an implied leading 1 bit unless the value is zero. If xxx < k then it will be a right shift. k is near but not equal to half the largest value that could be expressed by xxx. It is adjusted for the size of the mantissa. All to say that, disregarding NaN, comparing floating point values as signed integers of the same size will yield meaningful results. They are designed that way so that floating point comparisons are no more costly than integer comparisons. There are compiler optimizations to turn off NaN checks so that the comparisons are straight integer comparisons if the floating point format of the chip supports it. As an integer, NaN is greater than infinity is greater than finite values. If you try an unsigned compare, all the negative values will be larger than the positive values, just like signed integers cast to unsigned.
2,582,523
2,582,537
Suppress the HTTP_X_FORWARDED_FOR http header, c# .net C++
I'm writing an application in C# that uses proxies. The proxies are sending the HTTP_X_FORWARDED_FOR during HTTP requests, and this is unwanted behavior. I am extending the Interop.SHDocVw axWebBrowser (aka Internet Explorer) control right now, but can take another approach if needed for this problem. Is there some way to suppress this header... can this be done in code, on the proxy server, or not at all?
The proxy server, between your C# client and web site, is adding that HTTP_X_FORWARDED_FOR header. So, You cannot suppress that on C# client. But if you have control on proxy server, there should be a setting to turn it off. For example in squid, following could work. header_access X_Forwarded_For deny all Or You may try to find different proxy services, which does not send your ip address.
2,582,524
2,582,554
"Unable to open file", when the program tries to open file in /proc
I try to read file /proc/'pid'/status, using c program. The code is as follows, and even I use sudo to run it, the prompt still keeps throwing "Unable to open file". Please let me know if you have any ideas on how to fix this. thanks Richard ... int main (int argc, char* argv[]) { string line; char* fileLoc; if(argc != 2) { cout << "a.out file_path" << endl; fileLoc = "/proc/net/dev"; } else { sprintf(fileLoc, "/proc/%d/status", atoi(argv[1])); } cout<< fileLoc << endl; ifstream myfile (fileLoc); if (myfile.is_open()) { while (! myfile.eof() ) { getline (myfile,line); cout << line << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; }
Avoid using C strings in C++. You forgot to allocate this one. A stringstream will allocate for you and has sprintf functionality. int main (int argc, char* argv[]) { string line; ostringstream fileLoc; if(argc != 2) { cout << "a.out file_path" << endl; fileLoc << "/proc/net/dev"; } else { fileLoc << "/proc/" << argv[1] << "/status"; } cout<< fileLoc.str() << endl; ifstream myfile (fileLoc.str().c_str());
2,582,529
2,582,533
How can I use an array as map value?
I'm trying to create a map, where the key is an int, and the value is an array as follows: int red[3] = {1,0,0}; int green[3] = {0,1,0}; int blue[3] = {0,0,1}; std::map<int, int[3]> colours; colours.insert(std::pair<int,int[3]>(GLUT_LEFT_BUTTON,red)); // THIS IS LINE 24! colours.insert(std::pair<int,int[3]>(GLUT_MIDDLE_BUTTON,blue)); colours.insert(std::pair<int,int[3]>(GLUT_RIGHT_BUTTON,green)); However, when I try to compile this code, I get the following error: g++ (Ubuntu 4.4.1-4ubuntu8) 4.4.1 In file included from /usr/include/c++/4.4/bits/stl_algobase.h:66, from /usr/include/c++/4.4/bits/stl_tree.h:62, from /usr/include/c++/4.4/map:60, from ../src/utils.cpp:9: /usr/include/c++/4.4/bits/stl_pair.h: In constructor ‘std::pair<_T1, _T2>::pair(const _T1&, const _T2&) [with _T1 = int, _T2 = int [3]]’: ../src/utils.cpp:24: instantiated from here /usr/include/c++/4.4/bits/stl_pair.h:84: error: array used as initializer /usr/include/c++/4.4/bits/stl_pair.h: In constructor ‘std::pair<_T1, _T2>::pair(const std::pair<_U1, _U2>&) [with _U1 = int, _U2 = int [3], _T1 = const int, _T2 = int [3]]’: ../src/utils.cpp:24: instantiated from here /usr/include/c++/4.4/bits/stl_pair.h:101: error: array used as initializer In file included from /usr/include/c++/4.4/map:61, from ../src/utils.cpp:9: /usr/include/c++/4.4/bits/stl_map.h: In member function ‘_Tp& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const _Key&) [with _Key = int, _Tp = int [3], _Compare = std::less<int>, _Alloc = std::allocator<std::pair<const int, int [3]> >]’: ../src/utils.cpp:30: instantiated from here /usr/include/c++/4.4/bits/stl_map.h:450: error: conversion from ‘int’ to non-scalar type ‘int [3]’ requested make: *** [src/utils.o] Error 1 I really can't see where the error is. Or even if there's an error.
You can't copy arrays by value like that. Here are several solutions, but I recommend #4 for your needs: Use an std::vector instead of an array. Use a map of pointers to arrays of 3 elements: int red[3] = {1,0,0}; int green[3] = {0,1,0}; int blue[3] = {0,0,1}; std::map<int,int(*)[3]> colours; colours.insert(std::pair<int,int(*)[3]>(GLUT_LEFT_BUTTON,&red)); colours.insert(std::pair<int,int(*)[3]>(GLUT_MIDDLE_BUTTON,&blue)); colours.insert(std::pair<int,int(*)[3]>(GLUT_RIGHT_BUTTON,&green)); // Watch out for scope here, you may need to create the arrays on the heap. Use boost tuples instead of arrays of 3 elements. Instead of using an array make a new struct that takes 3 elements. Make the map<int, newstructtype>. Or wrap your array in a struct as follows: struct Triple { int color[3]; }; // Later in code Triple red = {1, 0, 0}, green = {0, 1, 0}, blue = {0, 0, 1}; std::map<int,Triple> colours; colours.insert(std::pair<int,Triple>(GLUT_LEFT_BUTTON,red)); colours.insert(std::pair<int,Triple>(GLUT_MIDDLE_BUTTON,blue)); colours.insert(std::pair<int,Triple>(GLUT_RIGHT_BUTTON,green));
2,582,637
2,582,646
Matrix multiplication using pairs
I am looking into alternate ways to do a Matrix Multiplication. Instead of storing my matrix as a two-dimensional array, I am using a vector such as vector<pair<pair<int,int >,int > > to store my matrix. The pair within my pair (pair) stores my indices (i,j) and the other int stores the value for the given (i,j) pair. I thought I might have some luck implementing my sparse array this way. The problem is when I try to multiply this matrix with itself. If this was a 2-d array implementation, I would have multiplied the matrix as follows: for(i=0; i<row1; i++) { for(j=0; j<col1; j++) { C[i][j] = 0; for(k=0; k<col2; k++) C[i][j] += A[i][j] * A[j][k]; } } Can somebody point out a way to achieve the same result using my vector of 'pair of pairs'? Thanks
So far you can store one value at one location. If you want to store several nonzero entries in the matrix, you will need more pairs of pairs in a larger structure. map<pair<int, int>, int> would be the next logical step. Now you can iterate over rows because the first coordinate is more significant in the map's sorting order. To iterate over columns, reverse that precedence: typedef pair<int, int> mx_coord; struct reverse_compare { bool operator() (mx_coord const &l, mx_coord const &r) const { return l.second < r.second? true : r.second < l.second? false : l.first < r.first; } }; typedef map< mx_coord, int > matrix; typedef map< mx_coord, int, reverse_compare > matrix_transpose; To multiply A by B, transpose B and iterate over A and B, multiplying any elements whose less-significant coordinates match, as the ordering naturally lets you go line-by-line and column-by-column. To transpose B: matrix_transpose b_t( b.begin(), b.end() ); // complexity: n log n
2,582,656
2,582,660
C++ dynamic array sizing problem
The basic pseudo code looks like this: void myFunction() { int size = 10; int * MyArray; MyArray = new int[size]; cout << size << endl; cout << sizeof(MyArray) << endl; } The first cout returns 10, as expected, while the second cout returns 4. Anyone have an explanation?
MyArray is only a pointer, which on your system, has a size of four bytes. When you dynamically create an array, you need to keep track of the size yourself. If you created an automatic array or static array, int MyArray[10]; then sizeof(MyArray) would be 40. As soon as the array decays to a pointer, though, e.g. when you pass it to a function, the size information is lost.
2,582,743
2,582,779
autoreferencing this class to use in another for C++
in java we can do this: public class A{ public static void main(String...str){ B b = new B(); b.doSomething(this); //How I do this in c++ ? the this self reference } } public class B{ public void doSomething(A a){ //Importat stuff happen here } } How can I do the same but in c++, I mean the self reference of A to use the method in B ?
First, in a static method there is no this parameter. Anyway, assuming that main() is not static here is how you can do it in C++ class A { public: void f() { B* b = new B(); b->doSomething(this); } void g() { // ... }; }; class B { public: void doSomething(A* a) { // You can now access members of a by using the -> operator: a->g(); } }; In C++ this is a pointer to the "current" Object. Thus if you define doSomething() as taking a pointer to A (that is: doSomething(A* a)), then you will be able to receive the this of A. The -> operator will give you access to the members of the a parameter, as follows: a->g(). Alternatively you can pass *this and define doSomething() to take a reference to A (that is: doSomething(A& a)): class A { public: void f() { B* b = new B(); b->doSomething(*this); } void g() { // ... }; }; class B { public: void doSomething(A& a) { // You can now access members of a by using the . operator: a.g(); } }; To access members of a reference you need to use the . (dot) operator: a.g().
2,582,797
2,582,942
Why pass by const reference instead of by value?
From what I understand: when you pass by value, the function makes a local copy of the passed argument and uses that; when the function ends, it goes out of scope. When you pass by const reference, the function uses a reference to the passed argument that can't be modified. I don't understand, however, why one would choose one over the other, except in a situation where an argument needs to be modified and returned. If you had a void function where nothing is getting returned, why choose one over the other? EDIT: So basically passing by const reference avoids copying the object. So in what situations is copying the object good? I mean, why not just use const references all the time if it optimizes performance all the time?
There are two main considerations. One is the expense of copying the passed object and the second is the assumptions that the compiler can make when the object is a a local object. E.g. In the first form, in the body of f it cannot be assumed that a and b don't reference the same object; so the value of a must be re-read after any write to b, just in case. In the second form, a cannot be changed via a write to b, as it is local to the function, so these re-reads are unnecessary. void f(const Obj& a, Obj& b) { // a and b could reference the same object } void f(Obj a, Obj& b) { // a is local, b cannot be a reference to a } E.g.: In the first example, the compiler may be able to assume that the value of a local object doesn't change when an unrelated call is made. Without information about h, the compiler may not know whether an object that that function has a reference to (via a reference parameter) isn't changed by h. For example, that object might be part of a global state which is modified by h. void g(const Obj& a) { // ... h(); // the value of a might change // ... } void g(Obj a) { // ... h(); // the value of a is unlikely to change // ... } Unfortunately, this example isn't cast iron. It is possible to write a class that, say, adds a pointer to itself to a global state object in its constructor, so that even a local object of class type might be altered by a global function call. Despite this, there are still potentially more opportunities for valid optimizations for local objects as they can't be aliased directly by references passed in, or other pre-existing objects. Passing a parameter by const reference should be chosen where the semantics of references are actually required, or as a performance improvement only if the cost of potential aliasing would be outweighed by the expense of copying the parameter.
2,582,892
2,583,480
Implement a server that receives and processes client request(cassandra as backend), Python or C++?
I am planning to build an inverted index searching system with cassandra as its storage backend. But I need some guidances to build a highly efficient searching daemon server. I know a web server written in Python called tornado, my questions are: Is Python a good choice for developing such kind of apps? Is Nginx(or Sphinx) a good example that I can look inside to learn its architecture to implement a highly efficient server? Anything else I should learn to do this? Thank you~
Python is unlikely to allow you to write the most efficient server possible. However, it may just be that it will be fast enough, because for most applications it is. Therefore, one path you could take is starting with Python. It's a great language for prototyping, much better than C++ for the stage in which you're not even sure which architecture to adopt. As you finish the project, you can see if Python is efficient enough. If it isn't and there's no easy way to make it much faster (such as rewriting a small routine that takes up most of the work in C), you can rewrite it in C++ using the Python prototype as a basis.
2,583,020
2,583,029
Library as dependency for another library
I have a big project compiled into libProject.so-file (shared library), I made some modules (shared libraries too) which use code from all libProject. Can I set libProject as dependence for moduleProject.so file? (gcc)
Sure, just link with it like any other library gcc -L/path/to/lib -lProject -o moduleProject.so
2,583,072
2,583,076
ReSharper/StyleCop-like Visual Studio addon for C/C++
Is there any ReSharper/StyleCop-like Visual Studio addon for C/C++? I'm using ReSharper and StyleCop addons every day. Just recently started a new project which involves C/C++ programming. I miss some features from these addons like code formatting, hints/tips to use cleaner and better code, documentation/uniform code requirements, optimizing includes and so on....
Visual Assist X is pretty much the de-facto for C++ programming in Visual Studio.
2,583,177
2,591,994
Embed WTL App in ATL ActiveX control
Is there a way to somehow Embed a WTL destop application in ATL ActiveX (ie extension)? What I'm trying to achieve is to create an ActiveX control with office files Viewer. As a base I have a desktop WTL application (written some time ago) which uses OOo v3 API to display documents. I have created an ActiveX project, linked necessary libs and includes. I can call WTL and OO Api methods. Some properties and methods have been added to meet requirements of the host application. My ActiveX is properly shown in ie and host application And here my luck (and knowledge?) ended. My control has m_hwnd property but it is always set to 0; I've Googled a bit and found that i Can get parent hwnd with this->m_spInPlaceSite->GetWindow() but it's not working either. Every time I want to create a window runtime ends in IsWindow() method (called from within ATL lib) with parent==null To create and show OOo::DocWindow I need HWND of the parent Window. And here goes the question: Can i somehow embed a WTL Window-based application in ActiveX ie extension? Is it possible without re-writing whole OOo Api wrapper?
Yes, you can. Steps with VS wizard: Create ATL project Add ATL Control, based on some control (button, for example). In this case you'll have message map with some handlers. Then replace CContainedWindow member to your own window and that's all. ATL Samples page, I didn't check it, but hope it helps.
2,583,352
2,583,374
Dynamic Object Not Creating for Privately Inherited Class
What is the reason for the following code that does not let me to create object. class base { public: void foo() { cout << "base::foo()"; } }; class derived : private base { public: void foo() { cout << "deived::foo()"; } }; void main() { base *d = new derived(); d->foo(); } It Gives me error : " 'type cast' : conversion from 'derived *' to 'base *' exists, but is inaccessible" Thanks in advance :)
The problem is that you are using private inheritance; this means that inheritance can only be seen inside your class (in this case, derived). You cannot point a base* to a derived instance outside your class (in this case, in main()) because the inheritance (and hence, the conversion) cannot be accessed. This is exactly the same as trying to access a private member from outside a class. In fact, the name "private inheritance" is quite misleading, since it does not implement real inheritance. In your example, a derived instance is not a base; it is just implemented in terms of a base, and this is what "private inheritance" means. If you are tempted to use private inheritance, you should consider the possibility of using simple aggregation (i.e.: a private pointer to base inside derived) instead. In most cases (most cases, not always), private inheritance offers no advantages and has some subtle problems.
2,583,501
2,590,448
How to call java from C++
I need to run this line from my c++ program: java -jar test.jar text1 text2 the java app will give a float value and give it to the c++ program. How can I do this? I never call a java stuff before from my ms visual studio C++ file.
When I run the java command directly on my command prompt, it works. but when I run the command from the c++ file, the error says "The system cannot execute the specified program" . here's my code, im using ms visual studio 2005 : #include "stdafx.h" #include <conio.h> int _tmain(int argc, _TCHAR* argv[]) { float value; FILE *child = _popen("java -jar c:\simmetrics_jar_v1_6_2_d07_02_07.jar text1 ssdyr445", "r"); if (fscanf(child, "%f", &value) == 1) { fprintf(stdout,"Got Value from simmetrics: %f\n", value); } else { fprintf(stdout,"ERROR\n"); } fclose(child); return 0; }
2,583,749
2,583,805
C++ template type deduction problem
motivation: I would like to create a utility class so that instead of having to write: if( someVal == val1 || someVal == val2 || someVal == val3 ) I could instead write: if( is(someVal).in(val1, val2, val3) ) which is much closer to the mathematical 'a is an element of (b,c,d)' and also would save on a lot of typing when the variable name 'someVal' is long. Here is the code I have so far (for 2 and 3 values): template<class T> class is { private: T t_; public: is(T t) : t_(t) { } bool in(const T& v1, const T& v2) { return t_ == v1 || t_ == v2; } bool in(const T& v1, const T& v2, const T& v3) { return t_ == v1 || t_ == v2 || t_ == v3; } }; However it fails to compile if I write: is(1).in(3,4,5); instead I have to write is<int>(1).in(3,4,5); Which isn't too bad, but it would be better if somehow the compiler could figure out that the type is int with out me having to explicitly specify it. Is there anyway to do this or I am stuck with specifying it explicitly?
If you want to keep this syntax, you can use a helper function like : template<class T> class is_op { private: T t_; public: is_op(T t) : t_(t) { } bool in(const T& v1, const T& v2) { return t_ == v1 || t_ == v2; } bool in(const T& v1, const T& v2, const T& v3) { return t_ == v1 || t_ == v2 || t_ == v3; } }; template< class U > inline is_op<U> is( U const& v ) { return is_op<U>( v ); } int main(int argc, char* argv[]) { is( 1 ).in( 1 , 2 , 4 ); }
2,583,770
2,583,830
Making a shared library from existing object files
I have a project in my IDE. I need to make a shared library of it to use in extensions. I don't want to make a copy of this project with shared-library settings. Is there any way to build a shared library using the object files (.o) from my already existing project? As I understand, I can write a makefile for this.
I assume you're on some sort of Unix and are probably using the GNU toolchain. In that case, to create a proper shared library, you'd need to compile your code using the position-independent code flags (-fpic or -fPIC) before you can create a shared library. Unless your .o files are already compiled with those flags, chances are you won't end up with a working shared lib. If they already are compiled for position independent code, the usual g++ -shared ... should do the trick.
2,583,853
2,584,018
Unformatted output in operator <<
I have a class that contains decoded video frames. I would like my decoder to use an output_iterator to write those frames to different targets. In order to support writing directly to a file, I want to overload operator << for my decoded frame class (for use with ostream_iterator). The problem is, that operator << is meant to be used for formatted output, but I want to do unformatted output with it. Are there any pitfalls to be considered? Is there another solution, or is it OK to just go with that?
std::basic_ostream is indeed mainly to be used for formatted output. (I say "mainly" because it does have a method for unformatted output. But that's not accessible through output iterators.) For unformatted output, use a stream buffer iterator.
2,584,213
2,584,240
How to default-initialize local variables of built-in types in C++?
How do I default-initialize a local variable of primitive type in C++? For example if a have a typedef: typedef unsigned char boolean;//that's Microsoft RPC runtime typedef I'd like to change the following line: boolean variable = 0; //initialize to some value to ensure reproduceable behavior retrieveValue( &variable ); // do actual job into something that would automagically default-initialize the variable - I don't need to assign a specific value to it, but instead I only need it to be intialized to the same value each time the program runs - the same stuff as with a constructor initializer list where I can have: struct Struct { int Value; Struct() : Value() {} }; and the Struct::Value will be default-initialized to the same value every time an instance is cinstructed, but I never write the actual value in the code. How can I get the same behavior for local variables?
You can emulate that behaviour by the following: boolean x = boolean(); or, more general, T x = T(); This will default-initialize x if such a default-initialization exists. However, just writing T x will never do the trick for local variables, no matter what you do. You can also use placement-new to invoke a “constructor”, even for POD: T x; new (&x) T(); Notice that this code produces undefined behaviour for non-POD types (in particular for types that have a non-trivial destructor). To make this code work with user-defined types, we first need to call the object’s destructor: T x; x.~T(); new (&x) T(); This syntax can also be used for PODs (guaranteed by §§5.2.4/12.4.15) so the above code can be used indiscriminately for any type.
2,584,220
2,584,233
Boost.MultiIndex: Are there way to share object between two processes?
I have a Boost.MultiIndex big array about 10Gb. In order to reduce the reading I thought there should be a way to keep the data in the memory and another client programs will be able to read and analyse it. What is the proper way to organize it? The array looks like: struct particleID { int ID;// real ID for particle from Gadget2 file "ID" block unsigned int IDf;// postition in the file particleID(int id,const unsigned int idf):ID(id),IDf(idf){} bool operator<(const particleID& p)const { return ID<p.ID;} unsigned int getByGID()const {return (ID&0x0FFF);}; }; struct ID{}; struct IDf{}; struct IDg{}; typedef multi_index_container< particleID, indexed_by< ordered_unique< tag<IDf>, BOOST_MULTI_INDEX_MEMBER(particleID,unsigned int,IDf)>, ordered_non_unique< tag<ID>,BOOST_MULTI_INDEX_MEMBER(particleID,int,ID)>, ordered_non_unique< tag<IDg>,BOOST_MULTI_INDEX_CONST_MEM_FUN(particleID,unsigned int,getByGID)> > > particlesID_set; Any ideas are welcome. kind regards Arman. EDIT: The RAM and the number of cores are not limited. Currently I have a 16Gb and 8cores. Update The same question I was asking in Boost.Users forum I got an answer from Joaquín M López Muñoz(developer of Boost.MultiIndex). The aswer is Yes. One can share the multi_index between processes using Boost.Interprocess. For more detail you can see in this link
Have you looked at Boost.Interprocess?
2,584,595
8,719,066
Building a python module and linking it against a MacOSX framework
I'm trying to build a Python extension on MacOSX 10.6 and to link it against several frameworks (i386 only). I made a setup.py file, using distutils and the Extension object. I order to link against my frameworks, my LDFLAGS env var should look like : LDFLAGS = -lc -arch i386 -framework fwk1 -framework fwk2 As I did not find any 'framework' keyword in the Extension module documentation, I used the extra_link_args keyword instead. Extension('test', define_macros = [('MAJOR_VERSION', '1'), ,('MINOR_VERSION', '0')], include_dirs = ['/usr/local/include', 'include/', 'include/vitale'], extra_link_args = ['-arch i386', '-framework fwk1', '-framework fwk2'], sources = "testmodule.cpp", language = 'c++' ) Everything is compiling and linking fine. If I remove the -framework line from the extra_link_args, my linker fails, as expected. Here is the last two lines produced by a python setup.py build : /usr/bin/g++-4.2 -arch x86_64 -arch i386 -isysroot / -L/opt/local/lib -arch x86_64 -arch i386 -bundle -undefined dynamic_lookup build/temp.macosx-10.6-intel-2.6/testmodule.o -o build/lib.macosx-10.6-intel-2.6/test.so -arch i386 -framework fwk1 -framework fwk2 Unfortunately, the .so that I just produced is unable to find several symbols provided by this framework. I tried to check the linked framework with otool. None of them is appearing. $ otool -L test.so test.so: /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1) There is the output of otool run on a test binary, made with g++ and ldd using the LDFLAGS described at the top of my post. On this example, the -framework did work. $ otool -L vitaosx vitaosx: /Library/Frameworks/fwk1.framework/Versions/A/fwk1 (compatibility version 1.0.0, current version 1.0.0) /Library/Frameworks/fwk2.framework/Versions/A/fwk2 (compatibility version 1.0.0, current version 1.0.0) /usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 7.9.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 125.0.1) May this issue be linked to the "-undefined dynamic_lookup" flag on the linking step ? I'm a little bit confused by the few lines of documentation that I'm finding on Google. Cheers,
This has nothing to do with the undefined dynamic_lookup but all with distutils. It appends the extra_link_flags to the link flags it chooses for python building. Instead it should prepend it because the -framework listings must come before the objects that use them on the cmdline (AFAIK this is due how gcc gathers symbols for linking). A quick fix that I personally use is building with LDFLAGS="-framework Carbon" python setup.py build_ext --inplace or whatever frameworks you need. LDFLAGS is prepended to distutils own flags. Note that your package will not be pip installable. A proper fix can only come from distutils - imho they should support frameworks like they support libraries. Alternatively, you can also add import os os.environ['LDFLAGS'] = '-framework Carbon' in your setup.py. Your package should then be pip installable.
2,584,856
2,585,213
Splitting Code into Headers/Source files
I took the following code from the examples page on Asio class tcp_connection : public boost::enable_shared_from_this<tcp_connection> { public: typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_service& io_service) { return pointer(new tcp_connection(io_service)); } tcp::socket& socket() { return socket_; } void start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } private: tcp_connection(boost::asio::io_service& io_service) : socket_(io_service) { } void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { } tcp::socket socket_; std::string message_; }; I'm relatively new to C++ (from a C# background), and from what I understand, most people would split this into header and source files (declaration/implementation, respectively). Is there any reason I can't just leave it in the header file if I'm going to use it across many source files? If so, are there any tools that will automatically convert it to declaration/implementation for me? Can someone show me what this would look like split into header/source file for an example (or just part of it, anyway)? I get confused around weird stuff like thistypedef boost::shared_ptr<tcp_connection> pointer; Do I include this in the header or the source? Same with tcp::socket& socket() I've read many tutorials, but this has always been something that has confused me about C++.
Splitting this could look like this: // in the header-file class tcp_connection : public boost::enable_shared_from_this<tcp_connection> { public: typedef boost::shared_ptr<tcp_connection> pointer; static pointer create(boost::asio::io_service& io_service); tcp::socket& socket(); void start(); private: tcp_connection(boost::asio::io_service& io_service); void handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/); tcp::socket socket_; std::string message_; }; // in the cpp-file // #using the namespace in which the class was declared here tcp_connection::pointer tcp_connection::create(boost::asio::io_service& io_service) { return pointer(new tcp_connection(io_service)); } tcp::socket& tcp_connection::socket() { return socket_; } void tcp_connection::start() { message_ = make_daytime_string(); boost::asio::async_write(socket_, boost::asio::buffer(message_), boost::bind(&tcp_connection::handle_write, shared_from_this(), boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)); } tcp_connection::tcp_connection(boost::asio::io_service& io_service) : socket_(io_service) { } void tcp_connection::handle_write(const boost::system::error_code& /*error*/, size_t /*bytes_transferred*/) { } Basically, all the method implementations have been moved to the cpp-file. typedef boost::shared_ptr<tcp_connection> pointer; defines an alias for a type and remains in the header. To understand the rationale of splitting classes, look here and here. To understand the rationale behind not doing it, look here. A reason for not splitting that follows from the previous two is, that this way you do not have to link anything to use the class. You only have to include the header. Hope that gives you a starting point.
2,584,937
2,584,967
Checking the sizeof an integer type in the preprocessor
How can I check the size of an unsigned in the preprocessor under g++? sizeof is out of the question since it is not defined when during preprocessing.
This may not be the most elegant method, but one thing that you may be able to leverage is UINT_MAX defined in "limits.h". That is, ... if UINT_MAX == 65535, then you would know that sizeof (unsigned) = 2 if UINT_MAX == 4294967295, then you would know that sizeof (unsigned) = 4. and so on. As I said, not elegant, but it should provide some level of usability. Hope this helps.
2,585,006
2,585,614
Using the sftp protocol with libcurl -- How do I list the contents of a directory?
I have a little doubt. I need to get a list of the files inside a specific directory on a SFTP server. I will use CUROPT_DIRLISTONLY in order to get just the names, but I'm not sure how to get them. This is the peace of code I have by now: string baseUrl(serverAddr + "/" + __destDir); curl_easy_setopt(anEasyHandle, CURLOPT_URL, (baseUrl).c_str()); curl_easy_setopt(anEasyHandle, CURLOPT_VERBOSE, 1L); curl_easy_setopt(anEasyHandle, CURLOPT_DIRLISTONLY, 1); curl_easy_setopt(anEasyHandle, CURLOPT_QUOTE, commandList); curl_easy_perform(anEasyHandle); curl_easy_reset(anEasyHandle); If I'm right, curl_easy_perform just returns an ERROR_CODE (success or error ir it applies), correct? So where can I get the files list? If I run it on a terminal: curl -u user:pass sftp://server/path/ -l I get the list I want.... Any help would be appreciated. Thanks in advance, George
You need to create a "callback function" with the following signature: size_t function( void *ptr, size_t size, size_t nmemb, void *stream); You then call curl_easy_setopt to set the callback function as your CURLOPT_WRITEFUNCTION. Your function will be called for each chunk of data recieved from the remote server, which should be some form of directory listing. Disclaimer: I have only read the documentation on this, not tried it.
2,585,021
2,585,063
Problems with passing an anonymous temporary function-object to a templatized constructor
I am trying to attach a function-object to be called on destruction of a templatized class. However, I can not seem to be able to pass the function-object as a temporary. The warning I get is (if the comment the line xi.data = 5;): warning C4930: 'X<T> xi2(writer (__cdecl *)(void))': prototyped function not called (was a variable definition intended?) with [ T=int ] and if I try to use the constructed object, I get a compilation error saying: error C2228: left of '.data' must have class/struct/union I apologize for the lengthy piece of code, but I think all the components need to be visible to assess the situation. template<typename T> struct Base { virtual void run( T& ){} virtual ~Base(){} }; template<typename T, typename D> struct Derived : public Base<T> { virtual void run( T& t ) { D d; d(t); } }; template<typename T> struct X { template<typename R> X(const R& r) { std::cout << "X(R)" << std::endl; ptr = new Derived<T,R>(); } X():ptr(0) { std::cout << "X()" << std::endl; } ~X() { if(ptr) { ptr->run(data); delete ptr; } else { std::cout << "no ptr" << std::endl; } } Base<T>* ptr; T data; }; struct writer { template<typename T> void operator()( const T& i ) { std::cout << "T : " << i << std::endl; } }; int main() { { writer w; X<int> xi2(w); //X<int> xi2(writer()); //This does not work! xi2.data = 15; } return 0; }; The reason I am trying this out is so that I can "somehow" attach function-objects types with the objects without keeping an instance of the function-object itself within the class. Thus when I create an object of class X, I do not have to keep an object of class writer within it, but only a pointer to Base<T> (I'm not sure if I need the <T> here, but for now its there). The problem is that I seem to have to create an object of writer and then pass it to the constructor of X rather than call it like X<int> xi(writer(); I might be missing something completely stupid and obvious here, any suggestions?
Looks like a "most vexing parse" issue. Try X<int> xi2 = X<int>(writer()); or X<int> xi2((writer()));
2,585,280
2,585,328
Cross platform millisecond timer lasting more than 49 days?
I'm going to be developing a small dedicated server in C/C++ that will require uptime of forever. I've been looking into some time functions as millisecond timing is required for calculations. I have 2 problems that I'm facing: Using a 32bit integer to store the number of milliseconds since the operation began will wrap around at about the 49 days mark resetting to zero. I have thought about using 64 bit integers, using gettimeofday to retrieve microseconds but this brings me to the second part. There doesn't seem to be any standard system calls for getting elapsed milliseconds that are platform independant What should I do to resolve both these issues?
Use a 64bit integer, presuming that gives you enough time You are correct; there is no standard. One possibility would be to use the Boost DateTime library, alternately find another or roll your own. Good Luck!
2,585,621
2,590,422
how to cout a vector of structs (that's a class member, using extraction operator)
i'm trying to simply cout the elements of a vector using an overloaded extraction operator. the vector contians Point, which is just a struct containing two doubles. the vector is a private member of a class called Polygon, so heres my Point.h #ifndef POINT_H #define POINT_H #include <iostream> #include <string> #include <sstream> struct Point { double x; double y; //constructor Point() { x = 0.0; y = 0.0; } friend std::istream& operator >>(std::istream& stream, Point &p) { stream >> std::ws; stream >> p.x; stream >> p.y; return stream; } friend std::ostream& operator << (std::ostream& stream, Point &p) { stream << p.x << p.y; return stream; } }; #endif my Polygon.h #ifndef POLYGON_H #define POLYGON_H #include "Segment.h" #include <vector> class Polygon { //insertion operator needs work friend std::istream & operator >> (std::istream &inStream, Polygon &vertStr); // extraction operator friend std::ostream & operator << (std::ostream &outStream, const Polygon &vertStr); public: //Constructor Polygon(const std::vector<Point> &theVerts); //Default Constructor Polygon(); //Copy Constructor Polygon(const Polygon &polyCopy); //Accessor/Modifier methods inline std::vector<Point> getVector() const {return vertices;} //Return number of Vector elements inline int sizeOfVect() const {return vertices.size();} //add Point elements to vector inline void setVertices(const Point &theVerts){vertices.push_back (theVerts);} private: std::vector<Point> vertices; }; and Polygon.cc using namespace std; #include "Polygon.h" // Constructor Polygon::Polygon(const vector<Point> &theVerts) { vertices = theVerts; } //Default Constructor Polygon::Polygon(){} istream & operator >> (istream &inStream, Polygon::Polygon &vertStr) { inStream >> ws; inStream >> vertStr; return inStream; } // extraction operator ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr) { outStream << vertStr.vertices << endl; return outStream; } i figure my Point insertion/extraction is right, i can insert and cout using it and i figure i should be able to just...... cout << myPoly[i] << endl; in my driver? (in a loop) or even... cout << myPoly[0] << endl; without a loop? i've tried all sorts of myPoly.at[i]; myPoly.vertices[i]; etc etc also tried all veriations in my extraction function outStream << vertStr.vertices[i] << endl; within loops, etc etc. when i just create a... vector<Point> myVect; in my driver i can just... cout << myVect.at(i) << endl; no problems. tried to find an answer for days, really lost and not through lack of trying! please excuse my lack of comments and formatting also there's bits and pieces missing.
ok, i got the loop working like this..... ostream & operator << (ostream &outStream, const Polygon::Polygon &vertStr) { for (int i = 0; i < vertStr.sizeOfVect(); i++) { outStream << vertStr.vertices.at(i) << endl; } return outStream; } then just cout << mainPoly << endl; in the driver i'm sure i tried that over and over, dont know what i did differently, but hey it works thanks heaps everyone.
2,585,799
2,585,847
Object oriented design suggestion
Here is my code: class Soldier { public: Soldier(const string &name, const Gun &gun); string getName(); private: Gun gun; string name; }; class Gun { public: void fire(); void load(int bullets); int getBullets(); private: int bullets; } I need to call all the member functions of Gun over a Soldier object. Something like: soldier.gun.fire(); or soldier.getGun().load(15); So which one is a better design? Hiding the gun object as a private member and access it with getGun() function. Or making it a public member? Or I can encapsulate all these functions would make the implementation harder: soldier.loadGun(15); // calls Gun.load() soldier.fire(); // calls Gun.fire() So which one do you think is the best?
I would say go with your second option: soldier.loadGun(15); // calls Gun.load() soldier.fire(); // calls Gun.fire() Initially it's more work, but as the system gets more complex, you may find that a soldier will want to do other things before and after firing their gun (maybe check if they have enough ammo and then scream "Die suckers!!" before firing, and mutter "that's gotta hurt" after, and check to see if they need a reload). It also hides from the users of the Soldier class the unnecessary details of how exactly the gun is being fired.
2,585,943
2,586,315
Qt variable re-assignment
I have two examples I have a question about. Let me explain via some code: Question 1: QStringList qsl(); // Create a list and store something in it qsl << "foo"; QString test = "this is a test"; qsl = test.split(" ", QString::SkipEmptyParts); // Memory Leak? What happens when I re-assign the qsl variable what happens to "foo" and the original data allocated on the first line? Question 2: class Foo { QStringList mylist; void MyFunc(QStringList& mylist) { this->m_mylist = mylist; } void AddString(QString str) { mylist << str; } } int main() { Foo f; QStringList *qsl = new QStringList(); f.MyFunc(*qsl); delete qsl; f.AddString("this is a test"); // Segfault? } Here I'm passing a list by reference to a class which is then stored in said class. I then delete the original object. It basically all comes down to what happens when you assign a QObject to a QObject. I assume a copy of the object is made, even if the object was passed in via reference (not via pointer of course, that would just be a pointer copy). I also assume that something like QStringList performs a deepcopy...is this correct?
Assigning to a QStringList variable works the same as assigning to any other variable in C++. For objects, the assignment operator of the object on the left is called to copy the content of the object on the right into the object on the left. Usually this does just a memberwise assignment: struct A { int x; QString y; A& operator=(const A &other) { // do the assignment: x = other.x; y = other.y; return *this; } }; The object on the left of the assignment "adapts itself" to contain the same things as the object on the right. There is no new object allocated, just the existing one is modified. If the class is more complicated and for example contains pointers to dynamically allocated data (like it is probably is the case for QStringList), the assignment operator might be more complicated to implement. But this is an implementation detail of the QStringList class and you should not have to worry about that. The QStringList object on the left of the assignment will be modified to be equal to the object on the right. In Question 2 you assign an object to a member variable, which causes the object in the member variable to be modified so that it contains the same things as the object that is assigned to it. That this other object later is deleted doesn't matter to the member variable. Semantically this is the same as when assigning simple integers: int i, j; i = j; The memory where i is stored is modified, so that it contains the same value as j. What happens to j later on doesn't matter to the value of i.
2,585,951
7,589,763
Getting SIGILL in float to fixed conversion
I'm receiving a SIGILL after running the following code. I can't really figure what's wrong with it. The target platform is ARM, and I'm trying to port a known library (in which this code is contained) void convertFloatToFixed(float nX, float nY, unsigned int &nFixed) { short sx = (short) (nX * 32); short sy = (short) (nY * 32); unsigned short *ux = (unsigned short*) &sx; unsigned short *uy = (unsigned short*) &sy; nFixed = (*ux << 16) | *uy; } Any help on it would be greatly appreciated. Thanks in advance
Some ARM processors have hardware floating-point, and some don't, so it's possible that this function is being compiled for hardware floating-point but your platform lacks a floating-point unit, so the floating-point instructions cause the processor to report an illegal instruction. If this is the first floating-point computation in your test program, that's extremely likely to be the problem. Check your platform's documentation to find which -march option you need to pass to gcc, or look at the compilation options used by some program that already works. This function does not have defined behaviour, and without an indication of what the desired behaviour is it's hard to suggest an improvement. Try something like this for a start:- void convertFloatToFixed(float nX, float nY, unsigned int &nFixed) { assert(nX * 32 < INT_MAX); assert(nY * 32 < INT_MAX); int sx = nX * 32; int sy = nY * 32; unsigned int ux = sx; unsigned int uy = sy; nFixed = (ux << 16) | uy; } I've got rid of the pointer casts, which (as others have pointed out) break the strict aliasing rule. I've also used int instead of short. There's generally no point having short auto variables, since they're widened to ints before computations anyway. (It's a good job they are, as shifting a short by 16 bits would not be very useful.) I've added some checks so your debug builds can find out if the float-to-integer conversion will overflow, which causes undefined behaviour.
2,586,662
2,587,242
Still failing a function, not sure why...ideas on test cases to run?
I've been trying to get this Sudoku game working, and I am still failing some of the individual functions. All together the game works, but when I run it through an "autograder", some test cases fail.. Currently I am stuck on the following function, placeValue, failing. I do have the output that I get vs. what the correct one should be, but am confused..what is something going on? EDIT: I do not know what input/calls they make to the function. What happens is that "invalid row" is outputted after every placeValue call, and I can't trace why.. Here is the output (mine + correct one) if it's at all helpful: http://pastebin.com/Wd3P3nDA Here is placeValue, and following is getCoords that placeValue calls.. void placeValue(Square board[BOARD_SIZE][BOARD_SIZE]) { int x,y,value; if(getCoords(x,y)) { cin>>value; if(board[x][y].permanent) { cout<< endl << "That location cannot be changed"; } else if(!(value>=1 && value<=9)) { cout << "Invalid number"<< endl; clearInput(); } else if(validMove(board, x, y, value)) { board[x][y].number=value; } } } bool getCoords(int & x, int & y) { char row; y=0; cin>>row>>y; x = static_cast<int>(toupper(row)); if (isalpha(row) && (x >= 'A' && x <= 'I') && y >= 1 && y <= 9) { x = x - 'A'; // converts x from a letter to corresponding index in matrix y = y - 1; // converts y to corresponding index in matrix return (true); } else if (!(x >= 'A' && x <= 'I')) { cout<<"Invalid row"<<endl; clearInput(); return false; } else { cout<<"Invalid column"<<endl; clearInput(); return false; } }
If it's printing invalid row after every input, we have to conclude that your code is doing what it says: It thinks that every row is outside the range A-I. Most likely some input got your cin into a frozen state and the cin >> row is actually either sticking a 0 or nothing at all into row, and thus it's constantly failing the check and printing the message.
2,586,681
2,586,712
C++ CIN cin skips randomly
I have this program, but cin in randomly skips.. I mean sometimes it does, and sometimes it doesn't. Any ideas how to fix this? int main(){ /** get course name, number of students, and assignment name **/ string course_name; int numb_students; string assignment_name; Assignment* assignment; cout << "Enter the name of the course" << endl; cin >> course_name; cout << "Enter the number of students" << endl; cin >> numb_students; cout << "Enter the name of the assignment" << endl; cin >> assignment_name; assignment = new Assignment(assignment_name); /** iterate asking for student name and score **/ int i = 0; string student_name; double student_score = 0.0; while( i < numb_students ){ cout << "Enter the name for student #" << i << endl; cin >> student_name; cout << "Enter the score for student #" << i << endl; cin >> student_score; assignment->addScore( Student( student_name, student_score )); i++; } } OK I figured it out. For anyone that would like to know here's the updated code: int main(){ /** get course name, number of students, and assignment name **/ string course_name; int numb_students; string assignment_name; cout << "Enter the name of the course" << endl; getline(cin, course_name); cout << "Enter the number of students" << endl; string temp; getline(cin, temp); numb_students = atoi(temp.c_str()); cout << "Enter the name of the assignment" << endl; getline(cin, assignment_name); Assignment assignment(assignment_name); /** iterate asking for student name and score **/ int i = 0; string student_name; double student_score = 0.0; while( i < numb_students ){ cout << "Enter the name for student #" << i+1 << endl; getline(cin, student_name); cout << "Enter the score for student #" << i+1 << endl; getline(cin, temp); student_score = atof(temp.c_str()); assignment.addScore( Student( student_name, student_score )); i++; }
I would guess that some of your inputs have spaces in them, which the >> operator treats as the end of a particular input item. The iostreams >> operator is really not designed for interactive input, particularly for strings - you should consider using getline() instead. Also, you are needlessly using dynamic allocation: assignment = new Assignment(assignment_name); would much better be written as: Assignment assignment(assignment_name); you should avoid the use of 'new' in your code wherever possible, and instead let the compiler take care of object lifetimes for you.
2,587,135
2,592,087
Using the C Cluster library in Visual C++
Right so i'm trying to use a C library in C++, never actually done this before i thought it would be a case of declaring the header includes under a extern "C" and setting the compile as flag to "default" but i'm still getting linker errors and think that the header file might have to be complied as a DLL. I have no idea really. Is it the library that's the problem or is it me? There are some make files in the cluster-1.47\src, but i don't know how or if they relate to "cluster.h". I've uploaded a visual studio 2008 project for anyone to take a gander, any help would be appreciated as i've been hitting my head against the wall for time now. thanks Stefan Link to Visual Studio 2008 Project
A header file only contains function declarations. You also need the implementation of those functions, which will be contained in the .c files, if the library is distributed as source, or in the .LIB and/or .DLL file if the library is a binary distribution. In either case. the .h files alone are not sufficient.
2,587,235
2,587,304
Choosing between instance methods and free functions?
Adding functionality to a class can be done by adding a method or by defining a function that takes an object as its first parameter. Most programmers that I know would choose for the solution of adding an instance method. However, I sometimes prefer to create a separate function. For example, in the example code below Area and Diagonal are defined as free functions instead of methods. I find it better this way because I think these functions provide enhancements rather than core functionality. Is this considered a good/bad practice? If the answer is "it depends", then what are the rules for deciding between adding method or defining a separate function? class Rect { public: Rect(int x, int y, int w, int h) : mX(x), mY(y), mWidth(w), mHeight(h) { } int x() const { return mX; } int y() const { return mY; } int width() const { return mWidth; } int height() const { return mHeight; } private: int mX, mY, mWidth, mHeight; }; int Area(const Rect & inRect) { return inRect.width() * inRect.height(); } float Diagonal(const Rect & inRect) { return std::sqrt(std::pow(static_cast<float>(inRect.width()), 2) + std::pow(static_cast<float>(inRect.height()), 2)); }
GoTW #84 explored this question with respect to std::string. He tended toward rather the opposite idea: most functions should be global unless they really need to be members. I'd say most modern C++ tends toward the same idea. If you look through Boost, for example, quite a bit is done with free functions.
2,587,349
2,587,458
initializing char and char pointers
What's the difference between these: This one works: char* pEmpty = new char; *pEmpty = 'x'; However if I try doing: char* pEmpty = NULL; *pEmpty = 'x'; // <---- doesn't work! and: char* pEmpty = "x"; // putting in double quotes works! why?? EDIT: Thank you for all the comments: I corrected it. it was supposed to be pEmpty ='x', So, this line doesn't even compile: char pEmpty ='x'; wheras this line works: char* pEmpty ="x"; //double quotes.
The difference is that string literals are stored in a memory location that may be accessed by the program at runtime, while character literals are just values. C++ is designed so that character literals, such as the one you have in the example, may be inlined as part of the machine code and never really stored in a memory location at all. To do what you seem to be trying to do, you must define a static variable of type char that is initialized to 'x', then set pEmpty to refer to that variable.
2,587,423
2,587,720
Emulating a web browser
we are tasked with basically emulating a browser to fetch webpages, looking to automate tests on different web pages. This will be used for (ideally) console-ish applications that run in the background and generate reports. We tried going with .NET and the WatiN library, but it was built on a Marshalled IE, and so it lacked many features that we hacked in with calls to unmanaged native code, but at the end of the day IE is not thread safe nor process safe, and many of the needed features could only be implemented by changing registry values and it was just terribly unflexible. Proxy support JavaScript support- we have to be able to parse the actual DOM after any javascript has executed (and hopefully an event is raised to handle any ajax calls) Ability to save entire contents of page including images FROM THE loaded page's CACHE to a separate location ability to clear cookies/cache, get the cookies/cache, etc. Ability to set headers and alter post data for any browser call Process and/or thread safe would be ideal And for the love of drogs, an API that isn't completely cryptic Languages acceptable C++, C#, Python, anything that can be a simple little background application that is somewhat bearable and doesn't have a completely "untraditional" syntax like Ruby. From my own research, and believe me I am terrible at google searches, I have heard good things about WebKit... would the Qt module QtWebKit handle all these features?
You might try one of these: http://code.google.com/p/spynner/ http://code.google.com/p/pywebkitgtk/
2,587,445
2,588,103
are C functions declared in <c____> headers guaranteed to be in the global namespace as well as std?
So this is something that I've always wondered but was never quite sure about. So it is strictly a matter of curiosity, not a real problem. As far as I understand, whenyou do something like #include <cstdlib> everything (except macros of course) are declared in the std:: namespace. Every implementation that I've ever seen does this by doing something like the following: #include <stdlib.h> namespace std { using ::abort; // etc.... } Which of course has the effect of things being in both the global namespace and std. Is this behavior guaranteed? Or is it possible that an implementation could put these things in std but not in the global namespace? The only way I can think of to do that would be to have your libstdc++ implement every c function itself placing them in std directly instead of just including the existing libc headers (because there is no mechanism to remove something from a namespace). Which is of course a lot of effort with little to no benefit. The essence of my question is, is the following program strictly conforming and guaranteed to work? #include <cstdio> int main() { ::printf("hello world\n"); } EDIT: The closest I've found is this (17.4.1.2p4): Except as noted in clauses 18 through 27, the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C (Clause 7), or ISO/IEC:1990 Programming Languages—C AMENDMENT 1: C Integrity, (Clause 7), as appropriate, as if by inclusion. In the C + + Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std. which to be honest I could interpret either way. "the contents of each header cname shall be the same as that of the corresponding header name.h, as specified in ISO/IEC 9899:1990 Programming Languages C" tells me that they may be required in the global namespace, but "In the C + + Standard Library, however, the declarations and definitions (except for names which are defined as macros in C) are within namespace scope (3.3.5) of the namespace std." says they are in std (but doesn't specify any other scoped they are in).
Here's a nice synopsis of the situation (with some relaity vs. what the standard says) from Stephan T. Lavavej of the MSVC team (http://blogs.msdn.com/vcblog/archive/2008/08/28/the-mallocator.aspx#8904359): > also, <cstddef>, <cstdlib>, and std::size_t etc should be used! I used to be very careful about that. C++98 had a splendid dream wherein <cfoo> would declare everything within namespace std, and <foo.h> would include <cfoo> and then drag everything into the global namespace with using-declarations. (This is D.5 [depr.c.headers].) This was ignored by lots of implementers (some of which had very little control over the C Standard Library headers). So, C++0x has been changed to match reality. As of the N2723 Working Paper, http://open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2723.pdf , now <cfoo> is guaranteed to declare everything within namespace std, and may or may not declare things within the global namespace. <foo.h> is the opposite: it is guaranteed to declare everything within the global namespace, and may or may not declare things within namespace std. In reality and in C++0x, including <cfoo> is no safeguard against everything getting declared in the global namespace anyways. That's why I'm ceasing to bother with <cfoo>. This was Library Issue 456, http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-defects.html#456 . (C++0x still deprecates the headers from the C Standard Library, which is hilarious.) I've never been fond of the <cfoo> headers myself, and found that I've always use <foo.h>. Now I feel like I can stop being anxious about my lack of C++ 'purity' in that regard.
2,587,541
2,587,564
Does C++ have a static polymorphism implementation of interface that does not use vtable?
Does C++ have a proper implementation of interface that does not use vtable? for example class BaseInterface{ public: virtual void func() const = 0; } class BaseInterfaceImpl:public BaseInterface{ public: void func(){ std::cout<<"called."<<endl; } } BaseInterface* obj = new BaseInterfaceImpl(); obj->func(); the call to func at the last line goes to vtable to find the func ptr of BaseInterfaceImpl::func, but is there any C++ way to do that directly as the BaseInterfaceImpl is not subclassed from any other class besides the pure interface class BaseInterface? Thanks. Gil.
Yes. It goes by the moniker CRTP. Have a gander.
2,587,558
2,587,614
Return pointer to nested inner class from generic outer class
I'm new to C++, so bear with me. I have a generic class called A. A has a nested class called B. A contains a method called getB(), which is supposed to return a new instance of B. However, I can't get my code to compile. Here's what it looks like:#include A.h template <class E> class A { public: class B { public: int data; }; B * getB(); }; A.cpp #include "A.h" template <class E> A<E>::B * A::getB() { return new B(); } When I try to compile this, I get the following error: error: expected constructor, destructor, or type conversion before '*' token Does anybody know what I'm doing wrong? Thanks, helixed UPDATE: Thanks for the quick replies everyone. I'm still having a little trouble getting this working. After taking the suggestions listed here, I have something like this: A.h template <class E> class A { public: class B { public: int data; }; B * getB(); }; template <class E> typename A<E>::B * A<E>::getB() { return new B(); } class C { }; However, when I try to use this from main, I get an error. Here's my main method: main.cpp #include "A.h" int main(int argc, char *argv[]) { A<C> *a = new A<C>(); A<C>::B *b = a.getB(); } When I try to compile this, I get the following error: error: request for member 'getB' in 'a', which is of non-class type 'A<C>*' Thanks again for the quick responses. helixed
The compiler isn't smart enough to figure that "B" is a type when "A" is templated. Try using typename. template <class E> typename A<E>::B * A<E>::getB() { return new B(); }
2,587,613
2,587,665
What is the Effect of Declaring 'extern "C"' in the Header to a C++ Shared Library?
Based on this question I understand the purpose of the construct in linking C libraries with C++ code. Now suppose the following: I have a '.so' shared library compiled with a C++ compiler. The header has a 'typedef stuct' and a number of function declarations. If the header includes the extern "C" declaration... #ifdef __cplusplus extern "C" { #endif // typedef struct ...; // function decls #ifdef __cplusplus } #endif ... what is the effect? Specifically I'm wondering if there are any detrimental side effects of that declaration since the shared library is compiled as C++, not C. Is there any reason to have the extern "C" declaration in this case?
This is important so that the compiler doesn't name mangle. C++ uses name mangling to differentiate functions with operator overloads. Run "/usr/bin/nm" against a binary to see what C++ does with your function names: _ZSt8_DestroyIN9__gnu_cxx17__normal_iteratorIPiSt6vectorIiSaIiEEEEiEvT_S7_SaIT0_E extern "C" prevents that name mangling. IIRC, that makes it possible for program to dynamically link in symbols at run time. It's common for "plugin" type architectures.
2,587,625
2,587,724
Warning that callers of a function must handle
I am looking for a way to set a warning that the caller will have to respond to. In a sense I would like to use a late exception mechaninism that occurs after the function already finished executing and returned the wanted value. SomeObject Foo(int input) { SomeObject result; // do something. oh, we need to warn the caller. return result; } void Main() { SomeObject object; object = Foo(1); // after copy constructor is done I would like an exception to be thrown }
You have to make a more concrete decision, I think. It's very unorthodox to (somehow) warn the user of a function while giving them a result. For example, you could return a std::pair<SomeObject, std::string>, where the warning is in the string, if any. But it'll be very easy for people to ignore that. An exception isn't the solution: if you can continue execution in a meaningful way, it's not an exceptional situation. It's possible to come up with some system of letting them finish with an exception "in queue" somewhere, but when should it be thrown? And for what purpose? Surely it will end up cutting of the remainder of the work anyway. I think what you want is an assert. assert that a condition holds true; if it doesn't, the programmer will be notified and can handle the situation accordingly. Remember, assert's are for programmers, exceptions are for the program. Perhaps if you give us a more concrete example, we'd be able to suggest the best course of action.
2,587,708
2,587,744
Am I deleting this properly?
I have some struct: struct A { const char* name_; A* left_; A* right_; A(const char* name):name_(name), left_(nullptr), right_(nullptr){} A(const A&); //A(const A*);//ToDo A& operator=(const A&); ~A() { /*ToDo*/ }; }; /*Just to compile*/ A& A::operator=(const A& pattern) { //check for self-assignment if (this != &pattern) { void* p = new char[sizeof(A)]; } return *this; } A::A(const A& pat) { void* p = new char[sizeof(A)]; A* tmp = new (p) A("tmp"); tmp->~A(); delete tmp;//I WONDER IF HERE I SHOULD USE DIFFERENT delete[]? } int _tmain(int argc, _TCHAR* argv[]) { A a("a"); A b = a; cin.get(); return 0; } I know this is far from ideal and far from finished. But I would like to know if I'm deleting my memory in the proper way (please don't tell me how to do it properly. I'm trying to figure it out myself). This is the link to different question which is really important to me.
void* p = new char[sizeof(A)]; A* tmp = new (p) A("tmp"); tmp->~A(); delete tmp;//I WONDER IF HERE I SHOULD USE DIFFERENT delete[]? No. You have already called the destructor so it is not correct to call delete which will cause another destructor call. You only need to free the memory. e.g. delete[] static_cast<char*>(p); If you are allocating raw memory for use with placement new it is more conventional to directly use an allocation function. e.g. void* p = ::operator new[](sizeof(A)); A* tmp = new (p) A("tmp"); tmp->~A(); ::operator delete[](p); Consider doing something simpler, though. This block could be replaced with a single local variable which would be more robust. A tmp("tmp");
2,588,354
2,588,396
Why does this crash?
I've been banging my head...I can't pretend to be a C++ guy... TCHAR * pszUserName = userName.GetBuffer(); SID sid; SecureZeroMemory(&sid, sizeof(sid)); SID_NAME_USE sidNameUse; DWORD cbSid = sizeof(sid); pLog->Log(_T("Getting the SID for user [%s]"), 1, userName); if (!LookupAccountName(NULL, (LPSTR)pszUserName, &sid, &cbSid, NULL, 0, &sidNameUse)) { pLog->Log(_T("Failed to look up user SID. Error code: %d"),1, GetLastError()); return _T(""); } pLog->Log(_T("Converting binary SID to string SID")); The message 'Getting the SID for user [x] is written' but then the app crashes. I'm assuming is was the LookupAccountName call. EDIT: Whoops userName is a MFC CString
Parameter 6 (cchReferencedDomainName) should point to a DWORD. When the documentation says, "if the ReferencedDomainName parameter is NULL, this parameter must be zero," I believe they mean that the referenced DWORD must be 0. Try adding: DWORD cchReferencedDomainName = 0; if (!LookupAccountName(NULL, (LPSTR)pszUserName, &sid, &cbSid, NULL, &cchReferencedDomainName, &sidNameUse)) ...
2,588,431
2,589,492
How can I get type information at runtime from a DMP file in a Windbg extension?
This is related to my previous question, regarding pulling objects from a dmp file. As I mentioned in the previous question, I can successfully pull object out of the dmp file by creating wrapper 'remote' objects. I have implemented several of these so far, and it seems to be working well. However I have run into a snag. In one case, a pointer is stored in a class, say of type 'SomeBaseClass', but that object is actually of the type 'SomeDerivedClass' which derives from 'SomeBaseClass'. For example it would be something like this: MyApplication!SomeObject +0x000 field1 : Ptr32 SomeBaseClass +0x004 field2 : Ptr32 SomeOtherClass +0x008 field3 : Ptr32 SomeOtherClass I need some way to find out what the ACTUAL type of 'field1' is. To be more specific, using example addresses: MyApplication!SomeObject +0x000 field1 : 0cae2e24 SomeBaseClass +0x004 field2 : 0x262c8d3c SomeOtherClass +0x008 field3 : 0x262c8d3c SomeOtherClass 0:000> dt SomeBaseClass 0cae2e24 MyApplication!SomeBaseClass +0x000 __VFN_table : 0x02de89e4 +0x038 basefield1 : (null) +0x03c basefield2 : 3 0:000> dt SomeDerivedClass 0cae2e24 MyApplication!SomeDerivedClass +0x000 __VFN_table : 0x02de89e4 +0x038 basefield1 : (null) +0x03c basefield2 : 3 +0x040 derivedfield1 : 357 +0x044 derivedfield2 : timecode_t When I am in WinDbg, I can do this: dt 0x02de89e4 And it will show the type: 0:000> dt 0x02de89e4 SomeDerivedClass::`vftable' Symbol not found. But how do I get that inside an extension? Can I use SearchMemory() to look for 'SomeDerivedClass::`vftable'? If you follow my other question, I need this type information so I know what type of wrapper remote classes to create. I figure it might end up being some sort of case-statement, where I have to match a string to a type? I am ok with that, but I still don't know where I can get that string that represents the type of the object in question (ie SomeObject->field1 in the above example).
DOH! It was much simpler than I thought. The virtual function tables are simply other symbols, so I can use GetSymbol() with the address of the field1's vftable. Then simply setup a case statement with the few types I expect, and create the right one for the situation. For example: char buffer[255]; ULONG64 displacement; GetSymbol(0x02de89e4,buffer, &displacement); dprintf("0x%08lx = %s\n", 0x02de89e4, buffer); In WinDbg when I run the extension this outputs: 0x02de89e4 = MyApplication!SomeDerivedClass::`vftable' Simple. Just have to parse that buffer and I should be good to go...
2,588,777
2,588,810
Capturing the input stream as a user types
I am working on a C++ based command line tool and I want to capture the user's keystrokes in real-time without requiring them to hit Return to commit the input. I can't seem to find an iostream call to support this kind of behavior but I recall from my college years that it can be done. Can anyone point me in the right direction?
That is outside of the C++ spec and requires OS specific calls. On Posix, you do this by enabling raw or cbreak mode instead of cooked mode. The easiest way to enable this is via curses.
2,588,803
2,588,852
Best way to insert items from a Derived class's constructor into a Base class's private std::vector?
I have these classes: class Base { ... private: std::vector<X> v; }; class Derived : public Base { Derived(X*, int n); }; where the constructor of Derived is passed an array of item Xs, which I need to insert into my vector v in the Base class. (X is a smart pointer) Currently I see two ways to do this: Create a function in Base: InsertItem(X*) that will insert an item into the vector (1 by 1) Create a vector in Derived that contains the full list, then get it into Base by moving the entire vector. I dont see any advantages to #2, but was wondering if #1 was a good solution, or if there are better ways to do this. Thanks!
There is a third option if you can modify Base. You could make the vector protected which will allow base classes full access: class Base { ... protected: std::vector<X> v; }; Your base class can now directly operate on v. If you need to expose much of the vector functionality to Derived, this is the easiest way. If not, I would just add the one function (i.e. option #1) and would make it protected: class Base { ... protected: void push_back(const X &x) { v.push_back(x); } private: std::vector<X> v; };
2,588,962
2,589,066
push_back of STL list got bad performance?
I wrote a simple program to test STL list performance against a simple C list-like data structure. It shows bad performance at "push_back()" line. Any comments on it? $ ./test2 Build the type list : time consumed -> 0.311465 Iterate over all items: time consumed -> 0.00898 Build the simple C List: time consumed -> 0.020275 Iterate over all items: time consumed -> 0.008755 The source code is: #include <stdexcept> #include "high_resolution_timer.hpp" #include <list> #include <algorithm> #include <iostream> #define TESTNUM 1000000 /* The test struct */ struct MyType { int num; }; /* * C++ STL::list Test */ typedef struct MyType* mytype_t; void myfunction(MyType t) { } int test_stl_list() { std::list<mytype_t> mylist; util::high_resolution_timer t; /* * Build the type list */ t.restart(); for(int i = 0; i < TESTNUM; i++) { mytype_t aItem; aItem->num = i; mylist.push_back(aItem); } std::cout << " Build the type list : time consumed -> " << t.elapsed() << std::endl; /* * Iterate over all item */ t.restart(); std::for_each(mylist.begin(), mylist.end(), myfunction); std::cout << " Iterate over all items: time consumed -> " << t.elapsed() << std::endl; return 0; } /* * a simple C list */ struct MyCList; struct MyCList{ struct MyType m; struct MyCList* p_next; }; int test_simple_c_list() { struct MyCList* p_list_head = NULL; util::high_resolution_timer t; /* * Build it */ t.restart(); struct MyCList* p_new_item = NULL; for(int i = 0; i < TESTNUM; i++) { p_new_item = (struct MyCList*) malloc(sizeof(struct MyCList)); if(p_new_item == NULL) { printf("ERROR : while malloc\n"); return -1; } p_new_item->m.num = i; p_new_item->p_next = p_list_head; p_list_head = p_new_item; } std::cout << " Build the simple C List: time consumed -> " << t.elapsed() << std::endl; /* * Iterate all items */ t.restart(); p_new_item = p_list_head; while(p_new_item->p_next != NULL) { p_new_item = p_new_item->p_next; } std::cout << " Iterate over all items: time consumed -> " << t.elapsed() << std::endl; return 0; } int main(int argc, char** argv) { if(test_stl_list() != 0) { printf("ERROR: error at testcase1\n"); return -1; } if(test_simple_c_list() != 0) { printf("ERROR: error at testcase2\n"); return -1; } return 0; } Oops, Yes. I modified the code, and it show: $ ./test2 Build the type list : time consumed -> 0.163724 Iterate over all items: time consumed -> 0.005427 Build the simple C List: time consumed -> 0.018797 Iterate over all items: time consumed -> 0.004778 So, my question is, why my "push_back" code got bad performance?
Your STL codes create a memory piece twice for each cell. The following is from STL 4.1.1 on x86_64 void push_back(const value_type& __x) { this->_M_insert(end(), __x); } // Inserts new element at position given and with value given. void _M_insert(iterator __position, const value_type& __x) { _Node* __tmp = _M_create_node(__x); // Allocate a new space #### __tmp->hook(__position._M_node); } As you can see, also, push_back() function calls several more functions before returning to the caller, and few pointer-value copying occurs everytime one of the functions is called. Might be neligible because all the parameters are passed by const-reference though.
2,589,197
2,589,220
How do I repass a function pointer in C++
Firstly, I am very new to function pointers and their horrible syntax so play nice. I am writing a method to filter all pixels in my bitmap based on a function that I pass in. I have written the method to dereference it and call it in the pixel buffer but I also need a wrapper method in my bitmap class that takes the function pointer and passes it on. How do I do it? What is the syntax? I'm a little stumped. Here is my code with all the irrelevant bits stripped out and files combined (read all variables initialized filled etc.). struct sColour { unsigned char r, g, b, a; }; class cPixelBuffer { private: sColour* _pixels; int _width; int _height; int _buffersize; public: void FilterAll(sColour (*FilterFunc)(sColour)); }; void cPixelBuffer::FilterAll(sColour (*FilterFunc)(sColour)) { // fast fast fast hacky FAST for (int i = 0; i < _buffersize; i++) { _pixels[i] = (*FilterFunc)(_pixels[i]); } } class cBitmap { private: cPixelBuffer* _pixels; public: inline void cBitmap::Filter(sColour (*FilterFunc)(sColour)) { //HERE!! } };
If I understand what you want: inline void cBitmap::Filter(sColour (*FilterFunc)(sColour)) { _pixels->FilterAll( FilterFunc); } Often dealing with function pointers can be made easier to read if you use a typedef for the function pointer type (yours actually isn't too bad on its own - they can get much worse very easily): struct sColour { unsigned char r, g, b, a; }; typedef sColour (*FilterFunc_t)(sColour); // typedef for a FilterFunc class cPixelBuffer { private: sColour* _pixels; int _width; int _height; int _buffersize; public: void FilterAll(FilterFunc_t FilterFunc); }; void cPixelBuffer::FilterAll(FilterFunc_t FilterFunc) { // fast fast fast hacky FAST for (int i = 0; i < _buffersize; i++) { _pixels[i] = (*FilterFunc)(_pixels[i]); } } class cBitmap { private: cPixelBuffer* _pixels; public: inline void cBitmap::Filter(FilterFunc_t FilterFunc) { _pixels->FilterAll( FilterFunc); } };
2,589,198
2,589,211
How to change this C++ code to make input work better
cout << "Input street number: "; cin >> streetnum; cout << "Input street name: "; cin >> streetname; cout << "Input resource name: "; cin >> rName; cout << "Input architectural style: "; cin >> aStyle; cout << "Input year built: "; cin >> year; The problem with the above code happens if you enter in spaces between words. For example if I enter "Ampitheater Parkway" for streetname, then it puts "Ampitheater" in streetname, skips the prompt for resource name and enters "Parkway" into the next field. How can I fix this?
That's because when you use the extraction operator with a string as the right-hand side, it stops at the first white space character. What you want is the getline free function: std::getline(std::cin, streetnum); // reads until \n You can specify some other delimiter if you want: char c = /* something */; std::getline(std::cin, streetnum, c); // reads until c is encountered Even better is to make a little function to use: void prompt(const std::string& pMsg, std::string& pResult) { std::cout >> pMsg >> ": "; std::getline(std::cin, pResult); } prompt("Street Number", streetnum); prompt("Street Name", streetname); // etc. :)
2,589,282
2,589,354
Templates, and C++ operator for logic: B contained by set A
In C++, I'm looking to implement an operator for selecting items in a list (of type B) based upon B being contained entirely within A. In the book "the logical design of digital computers" by Montgomery Phister jr (published 1958), p54, it says: F11 = A + ~B has two interesting and useful associations, neither of them having much to do with computer design. The first is the logical notation of implication... The second is notation of inclusion... This may be expressed by a familiar looking relation, B < A; or by the statement "B is included in A"; or by the boolean equation F11= A + ~B = 1. My initial implementation was in C. Callbacks were given to the list to use for such operations. An example being a list of ints, and a struct containting two ints, min and max, for selection purposes. There, selection would be based upon B >= A->min && B <= A->max. Using C++ and templates, how would you approach this after having implemented a generic list in C using void pointers and callbacks? Is using < as an over-ridden operator for such purposes... <ugh> evil? </ugh> (or by using a class B for the selection criteria, implementing the comparison by overloading > ?) edit: my implementation of the nodes for the list contains a member for flagging item selection or not. with regards to sets, and uniqueness, the data in the list will likely contain a member specifying position along a time line, given that is one of the main selection criteria, using the term set might be misleading as there is no guaranteed uniqueness regarding position along the time line - that is events can occur simultaneously.
The way this is done all over the place in the standard library is two have a templated parameter that can take a function/functor and that is used for the comparisons: template<typename Predicate> void container::select(Predicate p) { if (p(items[0])) { // something } } Some examples from the standard library would remove_if or lower_bound. (Also be aware that there already is a set class template in the standard library, and algorithms like set_intersection)
2,589,357
2,589,658
Coupling between controller and view
The litmus test for me for a good MVC implementation is how easy it is to swap out the view. I've always done this really badly due to being lazy but now I want to do it right. This is in C++ but it should apply equally to non-desktop applications, if I am to believe the hype. Here is one example: the application controller has to check some URL for existence in the background. It may connect to the "URL available" event (using Boost Signals) as follows: BackgroundUrlCheckerThread(Controller & controller) { // ... signalUrlAvailable.connect( boost::bind(&Controller::urlAvailable,&controller,_1)) } So what does Controller::urlAvailable look like? Here is one possibility: void Controller::urlAvailable(Url url) { if(!view->askUser("URL available, wanna download it?")) return; else // Download the url in a new thread, repeat } This, to me, seems like a gross coupling of the view and the controller. Such a coupling makes it impossible to implement the view when using the web (coroutines aside.) Another possibility: void Controller::urlAvailable(Url url) { urlAvailableSignal(url); // Now, any view interested can do what it wants } I'm partial to the latter but it appears that if I do this there will be: 40 billion such signals. The application controller can get huge for a non-trivial application A very real possibility that a given view accidentally ignores some signals (APIs can inform you at link-time, but signals/slots are run-time) So what do you suggest to remove coupling and also keep complexity down? Thanks in advance.
The litmus test for me for a good MVC implementation is how easy it is to swap out the view. I'll probably draw fire for saying this, but I don't agree with this statement. This looks good on paper, but real-world examples show that a good UI is responsive and interactive, which often times necessitates intertwining the view and controller. Trying to code a completely generic controller to handle unforeseen theoretical views adds a ton of code and complexity to both the controller(s) and the views. Interlinked views/controller worked better in my experience - I think of it as "M(VC)". I would say litmus test for a good MVC implementation is how easily you can "add" another view/controller pair to a model. Are the changes to the model from one view/controller (e.g. desktop operator) propagated out to the other view/controller (e.g. web remote user). Is the model generic enough to support different view/controller paradigms (e.g. desktop GUI, command-line, scheduled/batched input, web-based UI, web service, etc.)? This isn't to say that controller code can't be shared (e.g. derive from a common base), but you do have to find the right line between what should be handled by the controller (external manipulation of the model) and what should be considered part of the behavior of the model (internal transitions of the model). Ditto for view code. I think reading some of the answers under "What goes into the “Controller” in “MVC” would also help with this.
2,589,433
2,589,441
Sub-classing templated class without implementing pure virtual method
I have the following class definition: template<typename QueueItemT> class QueueBC { protected: QueueBC() {} virtual ~QueueBC() {} private: virtual IItemBuf* constructItem(const QueueItemT& item) = 0; } I created the following sub-class: class MyQueue : public QueueBC<MyItemT> { public: MyQueue() {} virtual ~MyQueue() {} }; This compiles fine under VS2005, yet I haven't implemented constructItem() in the MyQueue class. Any idea why?
Try using it: MyQueue m; You can't instantiate an abstract class, but you can define one (obviously, as you defined QueueBC). MyQueue is just as abstract. For example: struct base // abstract { virtual void one() = 0; virtual void two() = 0; }; struct base_again : base // just as abstract as base { }; struct foo : base_again // still abstract { void one() {} }; struct bar : foo // not abstract { void two() {} };
2,589,506
2,589,805
lock file so that it cannot be deleted
I'm working with two independent c/c++ applications on Windows where one of them constantly updates an image on disk (from a webcam) and the other reads that image for processing. This works fine and dandy 99.99% of the time, but every once in a while the reader app is in the middle of reading the image when the writer deletes it to refresh it with a new one. The obvious solution to me seems to be to have the reader put some sort of a lock on the file so that the writer can see that it can't delete it and thus spin-lock on it until it can delete and update. Is there anyway to do this? Or is there another simple design pattern I can use to get the same sort of constant image refreshing between two programs? Thanks, -Robert
Try using a synchronization object, probably a mutex will do. Whenever a process wants to read or write to a file it should first acquire the mutex lock.
2,589,533
2,589,544
What is a Cursor Linked List? [C++]
My professor provided me with a file called CursorList.cpp that implements a "Cursor Linked List". The problem is - I have no idea what that even is! Could anybody give me the gist of it? Thanks!
According to this, here is some background on a cursor linkedlist: some languages do not support pointers use arrays of objects instead start with a Freelist allocate space from Freelist when needed to delete: change pointers, add to Freelist So basically a linked list that is implemented without using pointers. Maybe this implementation is supposed to be "easier" to understand?
2,589,650
2,611,737
Multicolor text in TreeView (Embarcadero RAD studio)
I am writing a piece of software in C++ RAD studio 2010 and got a question about TreeView. Is it possible to use multicolor text in a TTreeView component? I could not find a easy way but to implement custom drawing which seems to be weird nowadays. Are there any straight-forward ways or maybe additional components that can do it for me? UPDATE Ended up doing it with custom drawing. void __fastcall TForm1::TreeView1AdvancedCustomDrawItem(TCustomTreeView *Sender, TTreeNode *Node, TCustomDrawState State, TCustomDrawStage Stage, bool &PaintImages, bool &DefaultDraw) if (Stage == cdPostPaint) { TRect rect(Node->DisplayRect(true)); String redText = "redtext"; String greenText = " greentext"; Sender->Canvas->Font->Color = clRed; Sender->Canvas->Refresh(); Sender->Canvas->TextOut(rect.Left, rect.Top, redText); rect.Left += Sender->Canvas->TextWidth(redText); Sender->Canvas->Font->Color = clGreen; Sender->Canvas->Refresh(); Sender->Canvas->TextOut(rect.Left, rect.Top, greenText); rect.Left += Sender->Canvas->TextWidth(greenText); } It was important to use Refresh so that the method works. Also, after having realized that I needed multiline text to output I switched to VirtualTreeView component from soft-gems
Custom drawing is the only way. There is nothing weird about that. Many controls support custom drawing.
2,589,668
2,589,756
boost::program_options bug or feature?
Very simple example: #include <string> #include <boost/program_options.hpp> namespace po = boost::program_options; int main(int argc, char* argv[]) { po::options_description recipients("Recipient(s)"); recipients.add_options() ("csv", po::value<std::string>(), "" ) ("csv_name", po::value<unsigned>(), "" ) ; po::options_description cmdline_options; cmdline_options.add(recipients); po::variables_map vm; po::store(po::command_line_parser(argc, argv).options(cmdline_options).run(), vm); po::notify(vm); return 0; } And some tests: >Test --csv test in option 'csv_name': invalid option value >Test --csv_name test in option 'csv_name': invalid option value >Test --csv_name 0 >Test --csv text in option 'csv_name': invalid option value >Test --csv 0 >Test --csv_name 0 >Test --csv_name 0 --csv text multiple occurrences Looks like that boost::program_option threats parameter "csv" as "csv_name". Is it a feature or bug?
Yes, this is a "feature" due to default options parsing style. Try with short options, like: recipients.add_options() ("csv,c", po::value<std::string>(), "" ) ("csv_name,C", po::value<unsigned>(), "" ) ; Or play with the basic_command_line_parser::style(int) method. I haven't tried this, so YMMV.
2,589,674
2,589,694
What is the best way to store incremental downloaded data?
Inspired by Chromium's sha1 class, I am thinking to store incrementally downloaded data using std::string // pseudo-code char buff[BUFF_SIZE]; std::string data; do { size = ReadInternetFileTo(buff,BUFF_SIZE); data.append(buff,size); } while (not_finished); Any foreseeable problems with this method or better way to do it?
Should be OK, but you may want to consider rope instead of string. It is more efficient to append to a rope, as it won't promise to keep all bytes consecutive, which will require a reallocation.
2,589,861
2,589,883
C++ template meta-programming, number of member variables?
Is it possible in C++ to determine number of variables/fields in the generic class? for example // suppose I need metaclass number_members determines number of members struct example { int i, j; }; assert(number_members<example>::value==2); I looked through mpl but could not find implementation. thanks.
No. C++ does not provide general introspection into structures. You can try a C++0x std::tuple, which has some of the features of a general POD struct. Or, try to roll your own from the Boost MPL library. That would be a bit advanced if you're just getting started with C++.
2,590,167
2,590,239
What are the advantages and disadvantages of using boost::iterator_facade?
Yep -- the title pretty much sums it up. I've got quite a few types that implement iterator concepts, and I'm wondering if it's worthwhile to pull in this boost header instead of implementing things manually. So far: Advantages Well specified Less likely to have bugs
If maintaining your own iterator types becomes a burden then switch to boost. They are well specified and tested and less likely to have bugs.
2,590,265
2,590,412
Learning Visual C++ 2008 and C++ at the same time? Any resources to recommend?
I am trying to learn Visual C++ 2008 and C++ at the same time to get involved with sourcemod, a server side modding tool for valve games. However I have never touched Visual C++ or C++ in general, and doing some preliminary research I am quite confused on these different versions of C++ (mfc, cli, win32), and why a lot of people seem to hate Visual C++ and use something like Borland instead. I really learn visually, and have used videos from places like Lynda.com with great success. I was wondering if anyone had any exceptional resources they had come across to teach Visual C++ 2k8, with its intricacies and setting up the IDE along with C++ at the same time. Books would be nice, but videos would be preferred, and I don't mind paying for resources. Thanks in advance!
why a lot of people seem to hate Visual C++ and use something like Borland instead You must be looking at old data. Borland's C++ department is essentially defunct nowadays if I'm not mistaken. Their commandline compiler is still available for free, but it seems Borland is happier to focus on Delphi rather than continuing to maintain C++ Builder. (Actually, it seems they don't even own C++ Builder anymore) Visual Studio 6 ha[sd] one of the worst implementations if the Standard Template Library and templates in general, which is why Visual Studio often gets a bad rap in C++ circles. The more recent versions of the compiler, say 2005 and up, should be perfectly fine. VS comes with a whole bunch of libraries you can use like ATL and MFC, but if you're looking to help out on sourcemod you can probably ignore all those goodies. They're helpful if you know what you're doing with them, but if you are working on a simple plugin (like sourcemod is) which does not display any UI then these frameworks are not going to be very helpful for you. (Not to mention I believe sourcemod is cross platform which sort of precludes any platform specific dependencies) Worry less about the intricacies of the IDE itself -- it's there to help you but beyond the simple task of creating a project and hitting Go, most of the time it should not be your focus. Learn how to write correct code first, then go back and look for IDE bells and whistles if you want. For the most part, these bells and whistles don't apply to native C++ development anyway :(
2,590,299
2,590,436
Importing .dll into Qt
I want to bring a .dll dependency into my Qt project. So I added this to my .pro file: win32 { LIBS += C:\lib\dependency.lib LIBS += C:\lib\dependency.dll } And then (I don't know if this is the right syntax or not) #include <windows.h> Q_DECL_IMPORT int WINAPI DoSomething(); btw the .dll looks something like this: #include <windows.h> BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { return TRUE; } extern "C" { int WINAPI DoSomething() { return -1; } }; Getting error: unresolved symbol? Note: I'm not experienced with .dll's outside of .NET's ez pz assembly architechture, definitely a n00b.
Your "LIBS +=" syntax is wrong. Try this: win32 { LIBS += -LC:/lib/ -ldependency } I'm also not sure if having absolute paths with drive letter in your .pro file is a good idea - I usually keep the dependencies somewhere in the project tree and use relative path. EDIT: I suppose that something is wrong in your dll, i.e. the symbols are not exported correctly. I always use template provided by QtCreator: Inside dll project there is mydll_global.h header with code like that: #ifdef MYDLL_LIB #define MYDLL_EXPORT Q_DECL_EXPORT #else #define MYDLL_EXPORT Q_DECL_IMPORT #endif Dll project has DEFINES += MYDLL_LIB inside it's pro file. Exported class (or only selected methods) and free functions are marked with MYDLL_EXPORT inside header files, i.e. class MYDLL_EXPORT MyClass { // ... };
2,590,310
2,590,763
Can I use boost::make_shared with a private constructor?
Consider the following: class DirectoryIterator; namespace detail { class FileDataProxy; class DirectoryIteratorImpl { friend class DirectoryIterator; friend class FileDataProxy; WIN32_FIND_DATAW currentData; HANDLE hFind; std::wstring root; DirectoryIteratorImpl(); explicit DirectoryIteratorImpl(const std::wstring& pathSpec); void increment(); bool equal(const DirectoryIteratorImpl& other) const; public: ~DirectoryIteratorImpl() {}; }; class FileDataProxy //Serves as a proxy to the WIN32_FIND_DATA struture inside the iterator. { friend class DirectoryIterator; boost::shared_ptr<DirectoryIteratorImpl> iteratorSource; FileDataProxy(boost::shared_ptr<DirectoryIteratorImpl> parent) : iteratorSource(parent) {}; public: std::wstring GetFolderPath() const { return iteratorSource->root; } }; } class DirectoryIterator : public boost::iterator_facade<DirectoryIterator, detail::FileDataProxy, std::input_iterator_tag> { friend class boost::iterator_core_access; boost::shared_ptr<detail::DirectoryIteratorImpl> impl; void increment() { impl->increment(); }; bool equal(const DirectoryIterator& other) const { return impl->equal(*other.impl); }; detail::FileDataProxy dereference() const { return detail::FileDataProxy(impl); }; public: DirectoryIterator() { impl = boost::make_shared<detail::DirectoryIteratorImpl>(); }; }; It seems like DirectoryIterator should be able to call boost::make_shared<DirectoryIteratorImpl>, because it is a friend of DirectoryIteratorImpl. However, this code fails to compile because the constructor for DirectoryIteratorImpl is private. Since this class is an internal implementation detail that clients of DirectoryIterator should never touch, it would be nice if I could keep the constructor private. Is this my fundamental misunderstanding around make_shared or do I need to mark some sort of boost piece as friend in order for the call to compile?
You will indeed need to make some boost pieces friend for this. Basically make_shared is calling the constructor and the fact that this is done from within a friend function does not matter for the compiler. The good news though is that make_shared is calling the constructor, not any other piece. So just making make_shared friend would work... However it means that anyone could then create a shared_ptr<DirectoryIteratorImpl>...
2,590,553
2,590,569
Function pointer demo
Check the below code int add(int a, int b) { return a + b; } void functionptrdemo() { typedef int *(funcPtr) (int,int); funcPtr ptr; ptr = add; //IS THIS CORRECT? int p = (*ptr)(2,3); cout<<"Addition value is "<<p<<endl; } In the place where I try to assign a function to function ptr with same function signature, it shows a compilation error as error C2659: '=' : function as left operand
It is very likely that what you intended to write was not: typedef int *(funcPtr) (int,int); but: typedef int (*funcPtr) (int,int);
2,590,668
2,590,977
Customize page number when printing a QTextDocument
I'm trying to print the content of a QTextEdit. For that I'm using QTextDocument::print(QPrinter*). Doing that, a page number is automatically added at the right bottom of the page. Is there any way to change its format / move it / get rid of it? Thanks.
As far as I know that is hard coded into Qt, so you can't change it. Have a look at QTBUG-1688. There you see that this fact has already been reported, but they don't seem to work on it. So you will have to do it yourself, I think.
2,590,677
2,595,226
How do I combine hash values in C++0x?
C++0x adds hash<...>(...). I could not find a hash_combine function though, as presented in boost. What is the cleanest way to implement something like this? Perhaps, using C++0x xor_combine?
Well, just do it like the boost guys did it: template <class T> inline void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); }
2,590,726
3,332,502
How to enable BDS2006's C++ WARN & TRACE macros
I am trying to find out how to enable (& use) Borland's WARN & TRACE macros. My starting point was this link: http://bcbjournal.org/articles/vol2/9809/Debugging_with_diagnostic_macros.htm?PHPSESSID=37bf58851bfeb5c199d1af31d7b2e7ff However, that appears to be for BCB5, and not the 2006 Borland Developer Studio. I've set the two defines (__WARN & __TRACE) I've included the .h file () I've added some macros, and everything compiles & links fine. But when I run the application (in DEBUG mode), no debug output file is created. What am I missing here?
I was investigating this debug TRACE feature too since I use Borland's toolchain. A couple things I noted while I was figure this out. Make sure __TRACE and __WARN are define before #include <checks.h>. You can also remove the #define __TRACE and __WARN from the translation unit and instead pass it to bcc32 using the -D macroname option during compilation. _GetDiagGroupDef is unresolved for BDS2006. It seems the compiler toolchain that comes with BDS2006 and later seems to be missing some function and class implementation that checks.h uses -- in particular _GetDiagGroupDef. I get unresolved references from the linker when compiling a test sample that uses checks.h. This doesn't happen when I use BCB 5.5.1 btw. Using grep/findstr it appears checks.cpp is compiled into the runtime library of BCB5.5.1 but it's missing from BDS2006 toolchain. I'm surprised you didn't run into the same problem, perhaps I didn't install some components. I found a copy of checks.cpp from an older borland toolchain here. Compiling and linking that should fix the unresolved errors. The tutorial says that the outdbg1.txt is a temporary file and it only shows up in the borland IDE -- for that file to actually exist you must save it. This suggest to me that their TRACE/WARN Macros doesn't actually output a debug file. It's probably outputting the debug info to a stderr stream. If that's really the case then redirecting the stderr stream to a file should give what you're looking for. Compile your sample program, then run it with something like this: myprogram.exe 2> outdbg1.txt All in all, you'll probably want to find alternative tools to aid you in the debugging process. Unfortunately, the TRACE & WARN macros provided here are poorly documented and for later versions of borland/embarcadero's toolchain it doesn't even work properly because the rtl doesn't have the needed functions/classes compiled into it. As such, the following is worth investigating: OutputDebugString API. This has the advantage that any monitor program that uses this API can receive debug message strings from your program that's being debugged. xUnit Testing Framework. Google Test is worth checking out. and of course your standard integrated IDE debugger :P
2,590,910
2,590,976
Is there a way to use template specialization to separate new from new[]?
I have an auto pointer class and in the constructor I am passing in a pointer. I want to be able to separate new from new[] in the constructor so that I can properly call delete or delete[] in the destructor. Can this be done through template specialization? I don't want to have to pass in a boolean in the constructor. template <typename T> class MyAutoPtr { public: MyAutoPtr(T* aPtr); }; // in use: MyAutoPtr<int> ptr(new int); MyAutoPtr<int> ptr2(new int[10]);
std::unique_ptr in C++0x will have a specialization for dynamic arrays, somewhat like shown below. However, it will be the user's task to instantiate an appropriate instance. At language level there is no way to distinguish one pointer from another. template <class T> class pointer { T* p; public: pointer(T* ptr = 0): p(ptr) {} ~pointer() { delete p; } //... rest of pointer interface }; template <class T> class pointer<T[]> { T* p; public: pointer(T* ptr = 0): p(ptr) {} ~pointer() { delete [] p; } //... rest of pointer and array interface }; int main() { pointer<int> single(new int); pointer<int[]> array(new int[10]); } Furthermore, it might not be that good to load one class with so various tasks. For example, boost has shared_ptr and shared_array.
2,590,964
2,590,982
Getting started with C++ ( the paradigm shift from Python )
I want to learn C++ so that i can develop C++ Python modules for server-related stuff. I'm a purely dynamic languages developer (Python, PHP, Ruby, etc). I want to learn a fast language, and if I'm going to do this, I'd rather learn a really fast language like C++. Before I even get started though, I understand that suddenly working with static types, a different syntax, and compiling code will be quite the paradigm shift. Is there any advice that a C++ dev who also has dynamic languages experience can give me to me to help me make that shift faster?
I doubt there is any specific advice that can be given, other than that you must read a good book on C++ written by an authoritative author or authors - do not pick the first or cheapest one that comes your way. For a list of books see The Definitive C++ Book Guide and List - I personally would strongly recommend Accelerated C++ - it is written for people with programming experience, though not specifically for those coming from a dynamic language background.
2,591,025
2,591,047
C++ code to class diagram
Is there is a way I can generate a hierachial class diagram from C++ code. My code is spread over 5 to 6 .cpp files. I would like to know if there is any free tool for the same. Regards, AJ
There's e.g. doxygen http://www.doxygen.nl/manual/features.html says: Uses the dot tool of the Graphviz tool kit to generate include dependency graphs, collaboration diagrams, call graphs, directory structure graphs, and graphical class hierarchy graphs. It creates graphs like (from http://www.vtk.org/doc/nightly/html/structvtkKdTree_1_1__cellList.html, an example listed on the doxygen site) Since the question was about class diagrams you might also be interested in the UML_LOOK flag that makes the ouput a bit more uml-like.
2,591,419
2,593,959
Expected output from an RM-1501 RS232 interface?
I have an old RM-1501 digital tachometer which I'm using to try to identify the speed of an object. According to the manual I should be able to read the data over a serial link. Unfortunately, I don't appear to be able to get any sensible output from the device (never gives a valid speed). I think it might be a signalling problem because disconnecting the CTS line starts to get some data through.. Has anyone ever developed anything for one of these / had any success?
I tried every combination of hardware control (both enabled and disabled) I could think of so I think it must be a hardware problem. Removnig the CLS link between PC and the device solved the issue.
2,592,101
2,592,166
Who calls the Destructor of the class when operator delete is used in multiple inheritance
This question may sound too silly, however , I don't find concrete answer any where else. With little knowledge on how late binding works and virtual keyword used in inheritance. As in the code sample, when in case of inheritance where a base class pointer pointing to a derived class object created on heap and delete operator is used to deallocate the memory , the destructor of the of the derived and base will be called in order only when the base destructor is declared virtual function. Now my question is : 1) When the destructor of base is not virtual, why the problem of not calling derived dtor occur only when in case of using "delete" operator , why not in the case given below: derived drvd; base *bPtr; bPtr = &drvd; //DTOR called in proper order when goes out of scope. 2) When "delete" operator is used, who is reponsible to call the destructor of the class? The operator delete will have an implementation to call the DTOR ? or complier writes some extra stuff ? If the operator has the implementation then how does it looks like , [I need sample code how this would have been implemented]. 3) If virtual keyword is used in this example, how does operator delete now know which DTOR to call? Fundamentaly i want to know who calls the dtor of the class when delete is used. <h1> Sample Code </h1> class base { public: base(){ cout<<"Base CTOR called"<<endl; } virtual ~base(){ cout<<"Base DTOR called"<<endl; } }; class derived:public base { public: derived(){ cout<<"Derived CTOR called"<<endl; } ~derived(){ cout<<"Derived DTOR called"<<endl; } }; I'm not sure if this is a duplicate, I couldn't find in search. int main() { base *bPtr = new derived(); delete bPtr;// only when you explicitly try to delete an object return 0; }
The compiler generates all necessary code to call destructors in the right order, whether it be a stack object or member variable going out of scope, or a heap object being deleted.
2,592,155
2,592,190
Testing C++ program with Testing classes over normally used classes
This will probably be a bot of a waffly question but ill try my best. I have a simple c++ program that i need to build testing for. I have 2 Classes i use besides the one i actually am using, these are called WebServer and BusinessLogicLayer. To test my own code i have made my own versions of these classes that feed dummy data to my class to test it functionality. I need to know a way of somehow, via a makefile for instance, how to tell the source code to use the test classes over the normally used classes. The test classes are in a different "tester" c++ file, and the tester c++ file also has its own header file. Regards Paul P.S. This is probably a badly worded question, but i dont know any better way to put my question.
You can define abstract base classes that declare the public interfaces for your components, then wire the objects together at runtime (in main() or something else fairly high up in the food chain). In testing, you simply wire up different objects.
2,592,449
2,592,482
Why is calling close() after fopen() not closing?
I ran across the following code in one of our in-house dlls and I am trying to understand the behavior it was showing: long GetFD(long* fd, const char* fileName, const char* mode) { string fileMode; if (strlen(mode) == 0 || tolower(mode[0]) == 'w' || tolower(mode[0]) == 'o') fileMode = string("w"); else if (tolower(mode[0]) == 'a') fileMode = string("a"); else if (tolower(mode[0]) == 'r') fileMode = string("r"); else return -1; FILE* ofp; ofp = fopen(fileName, fileMode.c_str()); if (! ofp) return -1; *fd = (long)_fileno(ofp); if (*fd < 0) return -1; return 0; } long CloseFD(long fd) { close((int)fd); return 0; } After repeated calling of GetFD with the appropriate CloseFD, the whole dll would no longer be able to do any file IO. I wrote a tester program and found that I could GetFD 509 times, but the 510th time would error. Using Process Explorer, the number of Handles did not increase. So it seems that the dll is reaching the limit for the number of open files; setting _setmaxstdio(2048) does increase the amount of times we can call GetFD. Obviously, the close() is working quite right. After a bit of searching, I replaced the fopen() call with: long GetFD(long* fd, const char* fileName, const char* mode) { *fd = (long)open(fileName, 2); if (*fd < 0) return -1; return 0; } Now, repeatedly calling GetFD/CloseFD works. What is going on here?
If you open a file with fopen, you have to close it with fclose, symmetrically. The C++ runtime must be given a chance to clean up/deallocate its inner file-related structures.
2,592,523
4,692,115
About inconsistent dll linkage
How can I remove this link warning? You can see code segment that causes this warning. static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL }; //bla bla // Exported DLL initialization is run in context of running application extern "C" void WINAPI InitGuiCtrlsDLL() { // create a new CDynLinkLibrary for this app new CDynLinkLibrary(GuiCtrlsDLL); // nothing more to do } warning C4273: 'InitGuiCtrlsDLL' : inconsistent dll linkage I have also export and import definitions, like: #ifdef _GUICTRLS #define GUI_CTRLS_EXPORT __declspec(dllexport) #else #define GUI_CTRLS_EXPORT __declspec(dllimport) #endif
There are multiple possibilities: 1) static AFX_EXTENSION_MODULE GuiCtrlsDLL = { NULL, NULL }; You use AFX_EXTENSION_MODULE. This means that you are implementing an MFC extension DLL. For such extension dlls you have to define the preprocessor _AFXEXT. Set this in the C++ compiler settings of your Visual C++ project see: How To Use _declspec(dllexport) in an MFC Extension DLL: http://support.microsoft.com/kb/128199 AFX_EXTENSION_MODULE Structure: http://msdn.microsoft.com/en-us/library/sxfyk0zk.aspx TN033: DLL Version of MFC: http://msdn.microsoft.com/en-us/library/hw85e4bb.aspx 2) It is likely that you have a duplicated definiton/declaration.
2,592,552
2,592,578
using macro defined in header files
I have a macro definition in header file like this: // header.h ARRAY_SZ(a) = ((int) sizeof(a)/sizeof(a[0])); This is defined in some header file, which includes some more header files. Now, i need to use this macro in some source file that has no other reason to include header.h or any other header files included in header.h, so should i redefine the macro in my source file or simply include the header file header.h. Will the latter approach affect the code size/compile time (I think yes), or runtime (i think no)? Your advice on this!
Include the header file or break it out into a smaller unit and include that in the original header and in your code. As for code size, unless your headers do something incredibly ill-advised, like declaring variables or defining functions, they should not affect the memory footprint much, if at all. They will affect your compile time to a certain degree as well as polluting your name space.
2,592,622
2,627,376
How to control flash movie using activex wrapper?
How to play the flash movie always from the beginning ? Any way to rewind movie ? I have use rewind() method for that but it didn't work. Any help is welcomed....
At first I have tried Rewind() method of activeX wrapper but it didn't work. Another good approach is to Call Flash function from VC++. m_Flash.CallFunction("<invoke name=\"MethodName\"returntype=\"xml\"><arguments></arguments></invoke>");
2,592,653
2,592,720
Trying to create a .NET DLL to be used with Non-.NET Application
I am trying to create a .NET DLL so I can use the cryptographic functions with my non .NET application. I have created a class library so far with this code: namespace AESEncryption { public class EncryptDecrypt { private static readonly byte[] optionalEntropy = { 0x21, 0x05, 0x07, 0x08, 0x27, 0x02, 0x23, 0x36, 0x45, 0x50 }; public interface IEncrypt { string Encrypt(string data, string filePath); }; public class EncryptDecryptInt:IEncrypt { public string Encrypt(string data, string filePath) { byte[] plainKey; try { // Read in the secret key from our cipher key store byte[] cipher = File.ReadAllBytes(filePath); plainKey = ProtectedData.Unprotect(cipher, optionalEntropy, DataProtectionScope.CurrentUser); // Convert our plaintext data into a byte array byte[] plainTextBytes = Encoding.ASCII.GetBytes(data); MemoryStream ms = new MemoryStream(); Rijndael alg = Rijndael.Create(); alg.Mode = CipherMode.CBC; alg.Key = plainKey; alg.IV = optionalEntropy; CryptoStream cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write); cs.Write(plainTextBytes, 0, plainTextBytes.Length); cs.Close(); byte[] encryptedData = ms.ToArray(); return Convert.ToString(encryptedData); } catch (Exception ex) { return ex.Message; } } } } } In my VC++ application, I am using the #import directive to import the TLB file created from the DLL, but the only available functions are _AESEncryption and LIB_AES etc I don't see the interface or the function Encrypt. When I try to instantiate so I can call the functions in my VC++ program, I use this code and get the following error: HRESULT hr = CoInitialize(NULL); IEncryptPtr pIEncrypt(__uuidof(EncryptDecryptInt)); error C2065: 'IEncryptPtr': undeclared identifier error C2146: syntax error : missing ';' before identifier 'pIEncrypt'
You don't appear to have flagged the Interface as visible via COM. I'd expect to see something like: namespace AESEncryption { [Guid("[a new guid for the interface]")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IEncrypt { string Encrypt(string data, string filePath); } [Guid("[a new guid for the class]")] [ComVisible(true)] [ClassInterface(ClassInterfaceType.None)] public class EncryptDecryptInt : IEncrypt { public string Encrypt(string data, string filePath) { // etc. } } }
2,592,746
2,659,679
template specialization of a auto_ptr<T>
Maybe I'm overcomplicating things, but then again, I do sort of like clean interfaces. Let's say I want a specialization of auto_ptr for an fstream - I want a default fstream for the generic case, but allow a replacement pointer? template <> class auto_ptr<fstream> { static fstream myfStream; fstream* ptr; public: auto_ptr() { // set ptr to &myfStream; } reset(fstream* newPtr) { // free old ptr if not the static one. ptr = newPtr }; } Would you consider something different or more elegant? And how would you keep something like the above from propagating outside this particular compilation unit? [The actual template is a boost::scoped_ptr.] EDIT: It's a contrived example. Ignore the fstream - it's about providing a default instance of object for an auto_ptr. I may not want to provide a specialized instance, but would like to keep the auto_ptr semantics for this static default object. class UserClass { public: auto_ptr<fstream> ptr; UserClass() { } } I may not provide an dynamic object at construction time - I still want it to have a meaningful default. Since I'm not looking at ownership-transfer semantics, it really shouldn't matter that my pointer class is pointing to a statically allocated object, no?
This wouldn't end up good. The biggest problem is that std::auto_ptr deletes the underlying object in its destructor. This means your default parameter can't be static. The only choice you can make is to do a lot of hacks there and IMHO the price you'll pay while maintaining all that crappy code isn't worth the small advantage you'd have.
2,592,800
2,592,899
Help with C++ Boost::regex
I'm trying to get all words inside a string using Boost::regex in C++. Here's my input : "Hello there | network - bla bla hoho" using this code : regex rgx("[a-z]+",boost::regex::perl|boost::regex::icase); regex_search(input, result, rgx); for(unsigned int j=0; j<result.size(); ++j) { cout << result[j] << endl; } I only get the first word "Hello".. whats wrong with my code ? result.size() returns 1. thank you.
regex_search only finds the first match. To iterate over all matches, use regex_iterator
2,592,821
2,594,836
Building external code trees with SCons
I'm trying to use SCons for building a piece of software that depends on a library that is available in sources that are installed in system. For example in /usr/share/somewhere/src. *.cpp in that directory should be built into static library and linked with my own code. Library sources have no SConscript among them. Since library is in system directory I have no rights and don't want to put build artefacts somewhere under /usr. /tmp or .build in current working directory is OK. I suspect this can be done easily but I've got entangled by all these SConscripts and VariantDirs. env = Environment() my_things = env.SConscript('src/SConsctipt', variant_dir='.build/my_things') sys_lib = env.SConscript(????) result = env.Program('result', [my_things, sys_lib]) What is intended way to solve the problem with SCons?
You could use a Repository to do this. For example, in your SConstruct you could write: sys_lib = env.SConscript("external.scons", variant_dir=".build/external") Then in the external.scons file (which is in your source tree), you add the path to the external source tree and how to build the library therein. env = Environment() env.Repository("/usr/share/somewhere/src") lib = env.Library("library_name", Glob("*.cpp")) Return("lib")
2,593,137
2,593,492
Tool for finding C-style Casts
Does anyone know of a tool that I can use to find explicit C-style casts in code? I am refactoring some C++ code and want to replace C-style casts where ever possible. An example C-style cast would be: Foo foo = (Foo) bar; In contrast examples of C++ style casts would be: Foo foo = static_cast<Foo>(bar); Foo foo = reinterpret_cast<Foo>(bar); Foo foo = const_cast<Foo>(bar);
If you're using gcc/g++, just enable a warning for C-style casts: g++ -Wold-style-cast ...
2,593,167
2,593,272
Can I specify default value?
Why is it that for user defined types when creating an array of objects every element of this array is initialized with the default constructor, but when I create an array of a built-in type that isn't the case? And second question: Is it possible to specify default value to be used while initializing elements in the array? Something like this (not valid): char* p = new char[size]('\0'); And another question in this topic while I'm with arrays. I suppose that when creating an array of user defined type, every element of this array will be initialized with default value. Why is this? If arrays for built in types do not initialize their elements with their defaults, why do they do it for User Defined Types? Is there a way to avoid/circumvent this default construction somehow? It seems like bit of a waste if I for example have created an array with size 10000, which forces 10000 default constructor calls, initializing data which I will (later on) overwrite anyway. I think that behaviour should be consistent, so either every type of array should be initialized or none. And I think that the behaviour for built-in arrays is more appropriate.
Something like this (not valid): As far as I know that is perfectly valid. Well not completely, but you can get a zero intialized character array: #include <iostream> #include <cstdlib> int main(int argc, char* argv[]) { //The extra parenthesis on the end call the "default constructor" //of char, which initailizes it with zero. char * myCharacters = new char[100](); for(size_t idx = 0; idx != 100; idx++) { if (!myCharacters[idx]) continue; std::cout << "Error at " << idx << std::endl; std::system("pause"); } delete [] myCharacters; return 0; } This program produces no output. And another question in this topic while I'm with arrays. I suppose that when creating an array of user defined type and knowing the fact that every elem. of this array will be initialized with default value firstly why? Because there's no good syntactic way to specialize each element allocated with new. You can avoid this problem by using a vector instead, and calling reserve() in advance. The vector will allocate the memory but the constructors will not be called until you push_back into the vector. You should be using vectors instead of user managed arrays anyway because new'd memory handling is almost always not exception safe. I think that behaviour should be consistent, so either every type of array should be initialized or none. And I think that the behaviour for built-in arrays is more appropriate. Well if you can think of a good syntax for this you can write up a proposal for the standard -- not sure how far you'll get with that. Why is it that for user defined types when creating an array of objects every element of this array is initialized with the default constructor, but when I create an array of a built-in type that isn't the case? and And another question in this topic while I'm with arrays. I suppose that when creating an array of user defined type, every element of this array will be initialized with default value. Why is this? and If arrays for built in types do not initialize their elements with their defaults, why do they do it for User Defined Types? Because a user defined type is never ever valid until its constructor is called. Built in types are always valid even if a constructor has not been called. And second question: Is it possible to specify default value to be used while initializing elements in the array? Something like this (not valid): Answered this above. Is there a way to avoid/circumvent this default construction somehow? It seems like bit of a waste if I for example have created an array with size 10000, which forces 10000 default constructor calls, initializing data which I will (later on) overwrite anyway. Yes, you can use a vector as I described above.
2,593,173
2,593,197
Smart pointers - cases where they cannot replace raw pointers
HI, I have this query about smart pointers. I heard from one of my friends that smart pointers can almost always replace raw pointers. but when i asked him what are the other cases where smart pointers cannot replace the raw pointers,i did not get the answer from him. could anybody please tell me when and where they cannot replace raw pointers?
Passing pointers to legacy APIs. Back-references in a reference-counted tree structure (or any cyclic situation, for that matter). This one is debatable, since you could use weak-refs. Iterating over an array. There are also many cases where you could use smart pointers but may not want to, e.g.: Some small programs are designed to leak everything, because it just isn't worth the added complexity of figuring out how to clean up after yourself. Fine-grained batch algorithms such as parsers might allocate from a pre-allocated memory pool, and then just blow away the whole pool on completion. Having smart pointers into such a pool is usually pointless.
2,593,288
2,593,470
How to use C++ Boost's regex_iterator()
I am using Boost to match substrings in a string. Io iterate over the results, I need to use regex_iterator(). That is the only usage example I have found, but I do not understand the callback. Could someone give me an example uage of the function? Let us assume that my input text is: "Hello everybody this is a sentense Bla bla 14 .. yes date 04/15/1986 " I want to get: "Hello" "everybody" "this" "is" "a" "sentense" "bla" "yes" "date"
If the only part of the example you don't understand is the callback, consider that: std::for_each(m1, m2, &regex_callback); is roughly equivalent to: for (; m1 != m2; ++m1){ class_index[(*m1)[5].str() + (*m1)[6].str()] = (*m1).position(5); } Assuming that, in your case, you want to store all the matches in a vector, you would write something like: //Warning, untested: boost::sregex_iterator m1(text.begin(), text.end(), expression); boost::sregex_iterator m2; std::vector<std::string> tokens; for (; m1 != m2; ++m1){ tokens.push_back(m1->str()). }
2,593,471
2,593,680
Do classes which have a vector has a member have memory issues
I am just starting out C++, so sorry if this is a dumb question. I have a class Braid whose members are vectors. I have not written an assignment operator. When I do a lot of assignments to an object of the type Braid, I run into memory issues :- 0 0xb7daff89 in _int_malloc () from /lib/libc.so.6 #1 0xb7db2583 in malloc () from /lib/libc.so.6 #2 0xb7f8ac59 in operator new(unsigned int) () from /usr/lib/libstdc++.so.6 #3 0x0804d05e in __gnu_cxx::new_allocator<int>::allocate (this=0xbf800204, __n=1) at /usr/lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../include/c++/4.4.3/ext/new_allocator.h:89 #4 0x0804cb0e in std::_Vector_base<int, std::allocator<int> >::_M_allocate (this=0xbf800204, __n=1) at /usr/lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../include/c++/4.4.3/bits/stl_vector.h:140 #5 0x0804c086 in _Vector_base (this=0xbf800204, __n=1, __a=...) at /usr/lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../include/c++/4.4.3/bits/stl_vector.h:113 #6 0x0804b4b7 in vector (this=0xbf800204, __x=...) at /usr/lib/gcc/i686-pc-linux-gnu/4.4.3/../../../../include/c++/4.4.3/bits/stl_vector.h:242 #7 0x0804b234 in Braid (this=0xbf800204) at braid.h:13 #8 0x080495ed in Braid::cycleBraid (this=0xbf8001b4) at braid.cpp:191 #9 0x080497c6 in Braid::score (this=0xbf800298, b=...) at braid.cpp:251 #10 0x08049c46 in Braid::evaluateMove (this=0xbf800468, move=1, pos=0, depth=2, b=...) I suspect that these memory issues are because the vectors are getting resized. What I want to know is whether objects of type Braid automatically expand when its members expand? the code I am writing is really long so I will post the section which is causing the problems. Here is the relevant section of the code :- class Braid { private : vector<int> braid; //Stores the braid. int strands; vector < vector<bool> > history; vector < vector<bool> > CM; public : Braid () : strands(0) {} Braid operator * (Braid); Braid* inputBraid(int,vector<int>); int printBraid(); int printBraid(vector<vector<int>::iterator>); vector<int>::size_type size() const; ..... ..... } Here is the function which causes the issue :- int Braid::evaluateMove(int move,int pos,int depth,Braid b) { int netscore = 0; Braid curr(*this); curr = curr.move(move,pos); netscore += curr.score(b); while(depth > 1) { netscore += curr.evaluateMove(1,0,depth,b); netscore += curr.evaluateMove(2,0,depth,b); for(int i = 0; i < braid.size();++i) { netscore += curr.evaluateMove(3,i,depth,b); netscore += curr.evaluateMove(4,i,depth,b); netscore += curr.evaluateMove(5,i,depth,b); curr = curr.cycleBraid(); netscore += curr.evaluateMove(6,0,depth,b); } --depth; } return netscore; }
Another problem : while(depth > 1) { netscore += curr.evaluateMove(1,0,depth,b); .... --depth; } causes endless recursion when depth >1
2,593,655
2,593,682
Segfault when calling a method c++
I am fairly new to c++ and I am a bit stumped by this problem. I am trying to assign a variable from a call to a method in another class but it always segfaults. My code compiles with no warnings and I have checked that all variables are correct in gdb but the function call itself seems to cause a segfault. The code I am using is roughly like the following: class History{ public: bool test_history(); }; bool History::test_history(){ std::cout<<"test"; //this line never gets executed //more code goes in here return true; } class Game{ private: bool some_function(); public: History game_actions_history; }; bool Game::some_function(){ return game_actions_history.test_history(); } Any tips or advice is greatly appreciated! EDIT: I edited the code so there is no more local_variable and the value returns directly. But it still segfaults. As for posting the actual code, it's fairly large, what parts should I post?
From what I can see there's nothing wrong with the code you've displayed. However, segfaults often are a good indication that you've got corrupted memory. It's happening some place else besides what you've shown and only happens to impact the code here. I'd look any place you're dealing with arrays, pointers, or any manual memory interactions.
2,594,092
2,594,356
How to set configuration properties in VS once and for all?
In VS 2010RC I have to specify configuration properties and specifically included path every time I'm creating new project. Is there a way to do it just once for all future projects? I'm asking this for a reason that I'm starting to use Boost libraries and I have to specify all those paths every time I'm creating project which is bit tedious.
The VC++ Directories (which is what I think you're looking to configure) have been moved to a property sheet to make them more MSBuild-friendly. A snippet from http://blogs.msdn.com/vsproject/archive/2009/07/07/vc-directories.aspx: If you open up the Property Manager view to see the property sheets associated with your project, you’ll see that one of the property sheets is named Microsoft.Cpp.Win32.User. This property sheet is actually stored in LocalAppData, just as VCComponents.dat file was, in the directory %LocalAppData%\Microsoft\VisualStudio\10.0. Using the property editor on the property sheet (just right-click on this property sheet node and select Properties…), you can see that you are able to make edits directly to this file. Since all projects, by default, import this property sheet, you are effectively editing the VC++ directories in the same way you were able to do before. See the following for more details on property sheets in VC++ 2010: http://blogs.msdn.com/vsproject/archive/2009/06/23/inherited-properties-and-property-sheets.aspx
2,594,114
2,595,640
Using deprecated binders and C++0x lambdas
C++0x has deprecated the use of old binders such as bind1st and bind2nd in favor of generic std::bind. C++0x lambdas bind nicely with std::bind but they don't bind with classic bind1st and bind2nd because by default lambdas don't have nested typedefs such as argument_type, first_argument_type, second_argument_type, and result_type. So I thought std::function can serve as a standard way to bind lambdas to the old binders because it exposes the necessary typedefs. However, using std::function is hard to use in this context because it forces you to spell out the function-type while instantiating it. auto bound = std::bind1st(std::function<int (int, int)>([](int i, int j){ return i < j; }), 10); // hard to use auto bound = std::bind1st(std::make_function([](int i, int j){ return i < j; }), 10); // nice to have but does not compile. I could not find a convenient object generator for std::function. Something like std::make_fuction would be nice to have. Does such a thing exist? If not, is there any other better way of binding lamdas to the classic binders?
Never tried to do such thing, and I don't have the time to provide a full answer, but I guess that something could be done with Boost.FunctionTypes. Here's a rough, incomplete and untested draft to give you an idea: template <typename T> struct AdaptedAsUnary : T { namespace bft = boost::function_types; namespace bmpl = boost::mpl; typedef typename bft::result_type<T>::type result_type; typedef typename bmpl::front<typename bft::parameter_types<T>::type>::type argument_type; AdaptedAsUnary(T t) : T(t) {} }; template <typename T> AdaptedAsUnary<T> AdaptAsUnary(T t) { return AdaptedAsUnary<T>(t); }
2,594,151
2,595,268
error: 'void Base::output()' is protected within this context
I'm confused about the errors generated by the following code. In Derived::doStuff, I can access Base::output directly by calling it. Why can't I create a pointer to output() in the same context that I can call output()? (I thought protected / private governed whether you could use a name in a specific context, but apparently that is incomplete?) Is my fix of writing callback(this, &Derived::output); instead of callback(this, Base::output) the correct solution? #include <iostream> using std::cout; using std::endl; template <typename T, typename U> void callback(T obj, U func) { ((obj)->*(func))(); } class Base { protected: void output() { cout << "Base::output" << endl; } }; class Derived : public Base { public: void doStuff() { // call it directly: output(); Base::output(); // create a pointer to it: // void (Base::*basePointer)() = &Base::output; // error: 'void Base::output()' is protected within this context void (Derived::*derivedPointer)() = &Derived::output; // call a function passing the pointer: // callback(this, &Base::output); // error: 'void Base::output()' is protected within this context callback(this, &Derived::output); } }; int main() { Derived d; d.doStuff(); } Edit: I'd love to know where this is in the stardard, but mostly I'm just trying to wrap my head around the concept. I think my problem is that callback doesn't have access to protected members of Derived, but it is able to call Derived::output if you pass it a pointer. How is a protected member of Derived that comes from Derived different from a protected member of Derived that comes from Base?
In short, it's "because the standard says so." Why? I don't know, I've emailed a couple of the standards guys, but haven't received a response, yet. Specifically, 11.5.1 (from C++0x FCD): An additional access check beyond those described earlier in Clause 11 is applied when a non-static data member or non-static member function is a protected member of its naming class (11.2)114 As described earlier, access to a protected member is granted because the reference occurs in a friend or member of some class C. If the access is to form a pointer to member (5.3.1), the nested-name-specifier shall denote C or a class derived from C. All other accesses involve a (possibly implicit) object expression (5.2.5). In this case, the class of the object expression shall be C or a class derived from C. Edit: Also, you'll see that you change the code to the following, according to what the standard specifies, it will compile (and run) cleanly: void (Base::*derivedPointer)() = &Derived::output;
2,594,172
2,594,254
invalid conversion from ‘char*’ to ‘char’
I have a, int main (int argc, char *argv[]) and one of the arguements im passing in is a char. It gives the error message in the title when i go to compile How would i go about fixing this? Regards Paul
When you pass command line parameters, they are all passed as strings, regardless of what types they may represent. If you pass "10" on the command line, you are actually passing the character array { '1', '0', '\0' } not the integer 10. If the parameter you want consists of a single character, you can always just take the first character: char timer_unit = argv[2][0];
2,594,178
2,594,222
Why do you need "extern C" for C++ callbacks to C functions?
I find such examples in Boost code. namespace boost { namespace { extern "C" void *thread_proxy(void *f) { .... } } // anonymous void thread::thread_start(...) { ... pthread_create(something,0,&thread_proxy,something_else); ... } } // boost Why do you actually need this extern "C"? It is clear that the thread_proxy function is private internal and I do not expect that it would be mangled as "thread_proxy" because I actually do not need it mangled at all. In fact, in all my code that I had written and that runs on many platforms, I never used extern "C" and this had worked as-is with normal functions. Why is extern "C" added? My problem is that extern "C" functions pollute the global namespace and they are not actually hidden as the author expects. This is not a duplicate! I'm not talking about mangling and external linkage. It is obvious in this code that external linkage is unwanted! Answer: The calling conventions of C and C++ functions are not necessarily the same, so you need to create one with the C calling convention. See 7.5 (p4) of C++ standard.
It is clear that the thread_proxy function is private internal and I do not expect that it would be mangled as "thread_proxy" because I actually do not need it mangled at all. Regardless, it's still going to be mangled. (Had it not been extern "C") That's just how the compiler works. I agree it's conceivable a compiler could say "this doesn't necessarily need to be mangled", but the standard says nothing on it. That said, mangling doesn't come into play here, as we aren't trying to link to the function. In fact, in all my code that I had written and that runs on many platforms, I never used extern "C" and this had worked as-is with normal functions. Writing on different platforms has nothing to do with extern "C". I expect all standard C++ code to work on all platforms that have a standard C++ compliant compiler. extern "C" has to do with interfacing with C, which pthread is a library of. Not only does it not mangle the name, it makes sure it's callable with the C calling convention. It's the calling convention that needs to be guaranteed, and because we can't assume we are running on a certain compiler, platform, or architecture, the best way to try and do that is with the functionality given to us: extern "C". My problem is that extern "C" functions pollute the global namespace and they are not actually hidden as the author expects. There's nothing polluting about the above code. It's in an unnamed namespace, and not accessible outside the translation unit.
2,594,423
2,594,614
What's a good way to detect wrap-around in a fixed-width message counter?
I'm writing a client application to communicate with a server program via UDP. The client periodically makes requests for data and needs to use the most recent server response. The request message has a 16-bit unsigned counter field that is echoed by the server so I can pair requests with server responses. Since it's UDP, I have to handle the case where server responses arrive out of order (or don't arrive at all). Naively, that means holding on to the highest message counter seen so far and dropping any incoming message with a lower number. But that will fail as soon as we pass 65535 messages and the counter wraps back to zero. Is there a good way to detect (with reasonable probability) that, for example, message 5 actually comes after message 65,000? The implementation language is C++.
If I understand things correctly, you may be able to use some windowing, if you are not already. That is, do not accept an message that is outside your window. For example, if your counter is at 1000, you may limit your range of incoming counter IDs you will accept to 1000...1031 inclusive. Thus anything outside that range is too much for you to handle (forcing you to initiate some resend protocol). Once you get 1000, your upper limit will go to 1032. Then once you get your lower limit counter of 1001, your upper limit will be 1033, and so on. What you end up with is a sliding window. If such a scenario is acceptable, then all you have to check is that your incoming counter ID is within your accepted window. This will be a subset of the 16 bit counter, so you can test ... incomingCounterID - lowerLimitCount < windowSize As long as you are dealing with unsigned variables, you should be fine. Hope this helps (and makes sense).
2,594,502
2,594,548
Count white spaces to the left of a line in a text file using C++
I am just trying to count the number of white spaces to the LEFT of a line from a text file. I have been using count( line.begin(), line.end(), ' ' ); but obviously that includes ALL white spaces to the left, in between words and to the right. So basically what I'm wanting it to do is once it hits a non-space character stop it from counting the white spaces. Thanks everyone.
Assuming line is a std::string, how about: #include <algorithm> #include <cctype> #include <functional> std::string::const_iterator firstNonSpace = std::find_if(line.begin(), line.end(), std::not1(std::ptr_fun<int,int>(isspace))); int count = std::distance(line.begin(), firstNonSpace);
2,594,772
2,601,110
Loading a RSA private key from memory using libxmlsec
I'm currently using libxmlsec into my C++ software and I try to load a RSA private key from memory. To do this, I searched trough the API and found this function. It takes binary data, a size, a format string and several PEM-callback related parameters. When I call the function, it just stucks, uses 100% of the CPU time and never returns. Quite annoying, because I have no way of finding out what is wrong. Here is my code: d_xmlsec_dsig_context->signKey = xmlSecCryptoAppKeyLoadMemory( reinterpret_cast<const xmlSecByte*>(data), static_cast<xmlSecSize>(datalen), xmlSecKeyDataFormatBinary, NULL, NULL, NULL ); data is a const char* pointing to the raw bytes of my RSA key (using i2d_RSAPrivateKey(), from OpenSSL) and datalen the size of data. My test private key doesn't have a passphrase so I decided not to use the callbacks for the time being. Has someone already done something similar ? Do you guys see anything that I could change/test to get forward on this problem ? I just discovered the library on yesterday, so I might miss something obvious here; I just can't see it. Thank you very much for your help.
I changed the format of data to PEM, using the OpenSSL function PEM_write_bio_RSAPrivateKey() and changed the third argument to the call to xmlSecCryptoAppKeyLoadMemory() so it matches the new format. The new code is: d_xmlsec_dsig_context->signKey = xmlSecCryptoAppKeyLoadMemory( reinterpret_cast<const xmlSecByte*>(data), // data is now in PEM format static_cast<xmlSecSize>(datalen), xmlSecKeyDataFormatPem, // Updated NULL, NULL, NULL ); And since then, everything works: the call does no longer get stuck.
2,594,913
2,594,953
Getting the fractional part of a float without using modf()
I'm developing for a platform without a math library, so I need to build my own tools. My current way of getting the fraction is to convert the float to fixed point (multiply with (float)0xFFFF, cast to int), get only the lower part (mask with 0xFFFF) and convert it back to a float again. However, the imprecision is killing me. I'm using my Frac() and InvFrac() functions to draw an anti-aliased line. Using modf I get a perfectly smooth line. With my own method pixels start jumping around due to precision loss. This is my code: const float fp_amount = (float)(0xFFFF); const float fp_amount_inv = 1.f / fp_amount; inline float Frac(float a_X) { return ((int)(a_X * fp_amount) & 0xFFFF) * fp_amount_inv; } inline float Frac(float a_X) { return (0xFFFF - (int)(a_X * fp_amount) & 0xFFFF) * fp_amount_inv; } Thanks in advance!
If I understand your question correctly, you just want the part after the decimal right? You don't need it actually in a fraction (integer numerator and denominator)? So we have some number, say 3.14159 and we want to end up with just 0.14159. Assuming our number is stored in float f;, we can do this: f = f-(long)f; Which, if we insert our number, works like this: 0.14159 = 3.14159 - 3; What this does is remove the whole number portion of the float leaving only the decimal portion. When you convert the float to a long, it drops the decimal portion. Then when you subtract that from your original float, you're left with only the decimal portion. We need to use a long here because of the size of the float type (8 bytes on most systems). An integer (only 4 bytes on many systems) isn't necessarily large enough to cover the same range of numbers as a float, but a long should be.
2,595,634
2,595,649
Idiomatic STL: Iterating over a list and inserting elements
I'm writing an algorithm that iterates over a list of points, calculates the distance between them and inserts additional points if the distance is too great. However I seem to be lacking the proper familiarity with STL to come up with an elegant solution. I'm hoping that I can learn something, so I'll just show you my code. You might have some hints for me. for (std::list<PathPoint>::iterator it = ++points_.begin(); it != points_.end(); it++) { Vector curPos = it->getPosition(); Vector prevPos = (--it)->getPosition(); Vector vecFromPrev = curPos - prevPos; float distance = vecFromPrev.abs(); it++; if (distance > MAX_DISTANCE_BETWEEN_POINTS) { int pointsToInsert = (int)(distance / MAX_DISTANCE_BETWEEN_POINTS); Vector curPos = prevPos; for (int i = 0; i < pointsToInsert; i++) { curPos += vecFromPrev / pointsToInsert; it = points_.insert(it, PathPoint(curPos, false)); it++; } } }
Consider using adjacent_find to find an iterator position where the distance between consecutive elements is too large, then inserting pointsToInsert items. http://www.sgi.com/tech/stl/adjacent_find.html In addition, you could use generate with a functor to fill in the intermediate points. http://www.sgi.com/tech/stl/generate.html Not sure how deep you want to go into STL :)
2,595,701
2,595,734
What is the role of asserts in C++ programs that have unit tests?
I've been adding unit tests to some legacy C++ code, and I've run into many scenarios where an assert inside a function will get tripped during a unit test run. A common idiom that I've run across is functions that take pointer arguments and immediately assert if the argument is NULL. I could easily get around this by disabling asserts when I'm unit testing. But I'm starting to wonder if unit tests are supposed to alleviate the need for runtime asserts. Is this a correct assessment? Are unit tests supposed to replace runtime asserts by happening sooner in the pipeline (ie: the error is caught in a failing test instead of when the program is running). On the other hand, I don't like adding soft fails to code (e.g. if (param == NULL) return false;). A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug.
A runtime assert at least makes it easier to debug a problem in case a unit test missed a bug. This is a pretty fundamental point. Unit tests are not meant to replace assertions (which IMHO are a standard part of producing good quality code), they're meant to complement them. Secondly, lets say you have a function Foo which asserts that it's parameters are valid. In your unit test for Foo you can make sure you only supply valid parameters, so you think you're alright. 6 months down the track some other developer is going to call Foo from some new piece of code (which may or may not have unit tests), and at that point you'll be very grateful you put those asserts in there.