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
6,670,423
6,676,817
How to stub a socket in C?
I've written client code that's supposed to send some data through a socket and read back an answer from the remote server. I would like to unit-test that code. The function's signature is something along the lines of: double call_remote(double[] args, int fd); where fd is the file descriptor of the socket to the remo...
If this is a POSIX system, you can use fork() and socketpair(): #define N_DOUBLES_EXPECTED 10 double stub_behaviour(double []); int initialize_stub(void) { int sock[2]; double data[N_DOUBLES_EXPECTED]; socketpair(AF_UNIX, SOCK_STREAM, 0, sock); if (fork()) { /* Parent process */ close...
6,670,450
6,670,885
Thread Terminating Early with Code 255
I'm attempting to run a part of my program in a thread and getting an unusual result. I have updated this question with the results of the changes suggested by Remus, but as I am still getting an error, I feel the question is still open. I have implemented functionality in a dll to tie into a piece of vendor software. ...
Threads that use CRT (and std::list implies CRT) need to be created with _beginthreadex, as documented on MSDN: A thread in an executable that calls the C run-time library (CRT) should use the _beginthreadex and _endthreadex functions for thread management rather than CreateThread and ExitThread; Is not clear how...
6,670,606
6,671,380
how to understand what part of the boost::regex failed to match/search
I am using boost::regex to match (better to say boost::regex_search) a text vs a regular expression. This one doesn't match and my regex is really huge. Do you know if in the library is there any function telling me which part of the regex failed to match? I am using LINUX/gcc std::string text; // whatever b...
There is no tool for that in the library to my knowledge, but I was using Boost version 1.28.0. Did you try to execute (\w+), (\d+) and (\s+) independantly of each other? At least one of them should fail matching.
6,670,738
6,670,753
Is it a good idea to wrap an #include in a namespace block?
I have a C header that was written to compile as both C and C++ (it only uses features from the common subset, and uses that extern "C" thing). Problem is, that header declares stuff in the global namespace. I'd rather avoid that for the usual reasons. I thought about doing this: namespace foo { #include <foo.h> } Is ...
No, it’s a bad idea. With C++ declarations, it's likely to introduce linker errors as identifiers get declared in the wrong namespace. With C declarations, it works, but it may hide clashes between identifiers in the global namespace (which you were trying to avoid, I guess) until link time; it doesn't really put the i...
6,670,779
6,670,804
Using C-style struct/typedef from within C++
I have a project that is mixing C and C++. In a C header file, I have code like this: typedef struct mystruct* mystruct; struct mystruct { // whatever struct needs }; And to use this in the C++ file, I am doing: extern "C" { #include "mystruct.h" } So you see that I am creating an opaque pointer using the same n...
I thought that using the extern "C" would make the compiler treat the C header as C No. The only thing that extern "C" does is control name mangling. The code is still compiled as C++ (though things that require mangled names, such as namespaces or templates, won’t work). In particular, the rule concerning struct ide...
6,671,050
6,671,188
What happens when pthreads wait in mutex_lock/cond_wait?
I have a program that should get the maximum out of my cpu. It is multithreaded via pthreads that do their job well apart from the fact that they "only" get my cores to about 60% load which is not enough in my opinion. I am searching for the reason and am asking myself (and hereby you) if the blocking functions mutex_l...
On a typical modern pthreads implementation, each thread is managed by the kernel not unlike a separate process. Any blocking call like pthread_mutex_lock or pthread_cond_wait (but also, say, read) will yield its time to the system. The system will then find another eligible thread to schedule, whether in your proces...
6,671,117
6,671,395
parameters to Ellipses in C++
Is it possible to pass parameters of different types in Ellipses(...)? I am writing a function to make the SQL query, where I want to add values to the Insert statement through Ellipse and my values are of different type.
As a word of warning, don't be too clever with this. Not that I've suffered greatly for similar endeavors. :)) Sqlite has built in query builders, check those first. What they wont let you do is specify a table name, which is probably what your problem is. boost::format is a good option for this. It's type safe and ...
6,671,167
6,671,315
C++ vector sorting put simply
Ok, I have a vector< vector < long >>, and I want to sort the innermost vectors from smallest to largest - i.e. I expect to have sorted vector < long > looking like 3,7,21 when sorted. This has been asked before, but I want to do this very simply so that non-programmers can understand. I've seen that I can create a fu...
If you want only the internal vectors sorted, then you can simply use the default sorting order: #include <algorithm> #include <vector> using namespace std; int main() { vector<vector<long>> v; for (auto i = v.begin(); i != v.end(); ++i) sort(i->begin(), i->end()); return 0; } This example uses th...
6,671,410
6,671,528
how to execute batch file from C/C++ w/o console window?
I'm executing batch file from a C++ program by system("start /B mybatch.bat") call, where /B is supposed to run batch file w/o console window. But it's still visible. Edit: I resolved the issue by ShellExecute() as was proposed in comments
Why don't you use CreateProcess instead ?
6,671,446
6,671,501
C++ Class inheriting from template class without knowing the type?
I am designing a template class Policy which needs to be able to handle pointers to other classes. template <class P> class Policy { private: const P *state; public: Policy (P const* s) : state(s){}; }; This works fine. Now I want to inherit from the above template class and create new subclasses: class...
Make them template classes: template <typename P> class Greedy : public Policy<P> { // now you know };
6,671,579
6,671,768
calling virtual functions through pointers with and without consulting the VM-table
I want to take the address of a member function of a c++ class, store it in a pointer, and call the virtual function later on. I know some things about it, but do not now how to take the address of a certain implementation of a virtual function that is NOT the implementation of the most descendent class (the actual cl...
Ok: Its doing exactly what it it is supposed to do. But to answer you questions: 1) What is going on here? Why 12 bytes in stead of 4? Why not. The standard does not specify a size. I am not sure why you expect a normal pointer to be 4. If the question is "why is a method pointer larger than a normal pointer?" Becaus...
6,671,642
6,671,903
Help with this casting issue
I'm making a game where pretty much everything inherits from Entity. I also have an IRenderable interface for all entities that need to be rendered. When loading the level, every entity that is IRenderable is placed in a vector of IRenderable* which is then passed to the renderer. When I instance any Entity, I add it t...
This article is the best discussion which I've found on the subject. I recommend it. Otherwise, this may be useful. class IRenderable; class Entity { public: virtual ~Entity() {} virtual IRenderable *getIRenderable() {return 0;} } class IRenderable : public Entity { public: virtual IRenderable *getIRenderable(...
6,671,757
6,683,674
Print the type of a parameter (ParmVarDecl) with clang API
I need to print the type of a parameter in a C++ source file using the clang API. If I have a parameter representation in clang (ParmVarDecl* param) I can print the name of the parameter using param->getNameAsString(). I would need a method param->getTypeAsString(), but there is no such method. So is there another way...
Got the answer to my question in the llvm irc: There is a method std::string clang::QualType::getAsString(SplitQualType split) So this does work for me: ParmVarDecl* param = *someParameter; cout << QualType::getAsString(param->getType().split()) << endl;
6,671,929
6,671,975
Are there SIMD instructions to speed up checksum calculations?
I'm going to have to code a very basic checksum function, something like: char sum(const char * data, const int len) { char sum(0); for (const char * end=data+len ; data<end ; ++data) sum += *data; return sum; } That's trivial. Now, how should I optimize this? First, I should probably use some std:...
Yes, there are such instructions in the MMX instruction set, called "Packed ADD": _mm_add_pi8 in Visual C++ __builtin_ia32_paddb in gcc And in the SSE2 instruction set: _mm_add_epi8 in Visual C++ __builtin_ia32_paddb128 in gcc EDIT: A faster way to add the partial sums: __m128i sums; sums = _mm_add_epi8(sums, _mm_...
6,671,968
6,672,826
why should we go in eye-space coordinates during fragment stage in the OpenGL pipeline?
I'm currently programming a small 3D engine, and I was wondering why I should go in eye-space coordinates in the fragment shader. To do that, I have to put my camera matrix in a uniform to convert light positions in eye-coordinates, and a camera_normal matrix to put the light directions in eye-coordinates. Why is ever...
There are several reasons eye-space is used: It's convenient. It's a well-defined space that exists, and one that you compute on the way to transforming positions anyway. It has the same scale as world space, but doesn't have the problems world space does. Eye space is always (relatively) close to zero (since the eye ...
6,672,056
6,673,355
what is the better way to write iterators for a loop in C++
For a very simple thing, like for example to print each element in a vector, what is the better way to use in C++? I have been using this: for (vector<int>::iterator i = values.begin(); i != values.end(); ++i) before, but in one of the Boost::filesystem examples I have seen this way: for (vec::const_iterator it(v.begi...
for (vector<int>::iterator i = values.begin(); i != values.end(); ++i) ...vs... for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it) For me [the latter, seen in boost] looks more complicated and I don't understand why is it better then the one I have been using. I'd say it would look more c...
6,672,186
6,674,477
Using observer pattern in the context of Qt signals/slots
I am trying to make some design decisions for an algorithm I am working on. I think that I want to use signals and slots to implement an observer pattern, but I am not sure of a few things. Here is the algorithm I am working towards: 1.) Load tiles of an image from a large file 1a.) Copy the entire file to a new locati...
It's not completely clear in your question, but it seems that you want to split up the work into several threads, so that the processing of tiles can begin before you finishing loading the entire set. Consider a multithreaded processing pipeline architecture. Assign one thread per task (loading, copying, processing), a...
6,672,188
6,672,227
"undefined reference to" linking on Ubuntu
I'm relatively new to C & C++ and stuck at compiling (or should I say linking) for the whole 2 days. Anyone gives me an idea would be appreciated. Error message and 3 code files are below. These are what I cut down to minimum from I'm actually working on so that you guys can take a better glimpse at. Env: Ubuntu 10.10,...
You need to put the definition of template<class T> int AdaBoost<T>::readFromFile(char* fName) into AdaBoost.h, and remove AdaBoost.cpp from your build. It's best to put all template code into the header. C++ linkers are required to eliminate duplicate instantiations of template code so you won't get "multiply defined...
6,672,257
6,672,426
How to properly use system() to execute a command in C++?
I am new to C++ programming under Windows. I am trying to execute a command say cuobjdump in C++ code using the system() function: system("C:\\program files\\nvidia gpu computing...\\cuobjdump.exe --dump-cubin C:\\..\\input.exe"); output: Usage : cuobjdump [options] <file> This followed by the list of the options fo...
Give a try with (that is, surrounding cuobjdump.exe path with ", properly escaped in C++ as \"): system("\"C:\\program files\\nvidia gpu computing...\\cuobjdump.exe\" --dump-cubin C:\\..\\input.exe");
6,672,529
6,673,476
Undefined reference linking error when using &MyClass::MyFunction
this just has me stumped, so I thought I'd query here: I have a class as follows: class MyClass { public: void myThreadFunc(); }; That's in the header. In the constructor MyClass::MyClass() { ... boost::thread t(boost::bind(&MyClass::myThreadFunc, this)); ... } As I've seen done. There are NO ...
You need to write a function body for MyClass::myThreadFunc() somewhere. Writing a constructor for MyClass is different from implementing the MyClass::myThreadFunc() member function. If you call a function in C/C++, it must have a function body somewhere. That's why it's a linker error; it's trying to find the function...
6,672,724
6,673,818
Boost ASIO socket read N bytes not more not less and wait until they come or timeout exception?
Creating a simple TCP server based on examples but still do not get how to create a socket that would read some amount of bytes and if there will not be enough would wait. I need this to be NOT asynchronous operation. #include <iostream> #include <boost/asio.hpp> #ifdef _WIN32 #include "Windows.h" #endif using namesp...
Boost 1.47.0 just introduced a timeout feature for basic_socket_iostream, namely, the expires_at and expires_from_now methods. Here's an example based on your snippet: #include <iostream> #include <boost/asio.hpp> using namespace boost::asio::ip; using namespace std; int main(){ int m_nPort = 12345; boost::as...
6,673,000
6,675,498
Can makefile.am set LDADD for a set of target?
I placed unit tests within the same directory of source code. But how could I set the LDADD in Makefile.am for all these unit tests to use specific libraries (e.g google test)?
The contents of LDADD are used for all target unless this variable is overridden with target_LDADD. So if you have many unit tests, and only a few actual programs, you may use LDADD for the unit tests and override it for each program with different linking requirements. LDADD = libtest.a # Used by default for all ta...
6,673,019
6,673,088
c++ inheritance pointer
it's pretty diffecult for me to describe my problem. I have two classes, I would say Base_A and Derived_A. You can see from the names, the class Derived_A is derived from Base_A. Also in my program I have other two classes Base_B and Derived_B (also with inheritance). The class Base_A contains the object of Base_B, an...
"but try to access Base_B* pointer_, which is not exist" If DerivedA does not properly initialise BaseA, then DerivedA does not meet the "isA" rule for inheritance and the design needs changed. On the face of things: Don't re-use names in the derived class such as b_, pointer_. Its just confusing and you gain no value...
6,673,611
6,673,656
R data frame and which.min() equivalent in c++
I'm translating R code to c++ and I'd like to find an equivalent (optimal) structure which would allow the same kind of operations than a data frame, but in c++. The operations are : add elements (rows) remove elements (rows) from index get the index of the lowest value e.g. : a <- data.frame(i = c(4, 9, 3, 1, 8, 2, ...
I think a vector of vectors should do what you want. You would need to implement the min-finding manually (two nested loops), which is the fastest you can do without adding overhead. You can speed up the min-finding by keeping track of the position of the smallest element in each row along with the row.
6,673,612
15,068,614
Qt on Mac -- how to access "search" in help menu
I am porting my Qt app to Mac OS X. On Windows/Linux I've used a QLineEdit to provide a search feature in the Help menu. In Mac OS X, I saw something like this is built-in: How can I access this search bar with Qt (i.e., add my own elements to it)? I looked at QMenuBar in the docs but couldn't find anything relevant. ...
It seems you can't do this directly through Qt, however, you can implement this one feature in Objective-C++/Cocoa. It is possible through the - registerUserInterfaceItemSearchHandler method of NSApplication to register a custom function for querying and returning search items. QtHelp seems to have support for automati...
6,673,760
6,674,276
Convert NT file time to Win32 time
I need to convert the LARGE_INTEGER CreationTime member in this structure to the FILETIME ftCreationTime member in this structure. The times are in different formats so simply casting it does not work, is there any documentation on what format NT API uses for file time and how I could convert it?
They are the same representation, just different structures. You can either memcpy it across or manual assignment: FILETIME ft; LARGE_INTEGER creationTime; memcpy(&ft, &creationTime, sizeof(ft)); or FILETIME ft; LARGE_INTEGER creationTime; ft.dwLowDateTime = creationTime.LowPart; ft.dwHighDateTime = creationTime.Hig...
6,673,762
6,673,775
Why is "!=" used with iterators instead of "<"?
I'm used to writing loops like this: for (std::size_t index = 0; index < foo.size(); index++) { // Do stuff with foo[index]. } But when I see iterator loops in others' code, they look like this: for (Foo::Iterator iterator = foo.begin(); iterator != foo.end(); iterator++) { // Do stuff with *Iterator. } I fi...
All iterators are equality comparable. Only random access iterators are relationally comparable. Input iterators, forward iterators, and bidirectional iterators are not relationally comparable. Thus, the comparison using != is more generic and flexible than the comparison using <. There are different categories of i...
6,673,772
6,673,790
What does here UserArray means?
What does the below syntax represents? typedef UserArray<T,W,L,H> MyType; where: T = type of an array element W = width of an array element, 0 < W < 8 L = low bound of array index (preferably zero) H = high bound of array index Can anyone explain me using example for above declaration? Does this concepts comes under...
UserArray is a class template that takes four template parameters. It's probably defined like that: template<class T, int W, int L, int H> // parameter names might differ class UserArray { // ... }; typedef is used to define aliases for types. This: typedef UserArray<T,W,L,H> MyType; Defines an alias for UserArra...
6,673,938
9,433,570
Using boost::iostreams::mapped_file_source with wide character strings
If I instantiate a mapped_file_source (boost 1.46.1 ) with a narrow character string as in the following I don't have a problem: boost::iostreams::mapped_file_source m_file_( "testfile.txt" ); However if I try to use a wide string: boost::iostreams::mapped_file_source m_file_( L"testfile.txt" ); I get the following c...
With boost 1.48 I can do something like this. #include <boost/filesystem.hpp> #include <boost/iostreams/device/mapped_file.hpp> #include <iostream> int main() { boost::filesystem::path p(L"b.cpp"); boost::iostreams::mapped_file file(p); // or mapped_file_source std::cout << file.data() << std::endl; } or you c...
6,673,973
6,674,109
GJK Algorithm triangle face tests
I am rebuilding my GJK algorithm but I'm having issues with triangular face tests for my tetrahedron. My point and edge tests are complete however. I want to test if the origin is outside of the tetrahedron and closest to a particular triangular face. So far my method was to calculate the normals of a triangular face a...
Let's work with face ABC. Form a normal using N = cross(B-A, C-A). If dot(N, D-A) > 0, then N is inward pointing and needs to be reversed. Finally, normalize N to get a unit normal if needed.
6,674,066
6,674,102
Is complete boost going to be included in C++0x?
Many utilities of boost have been included as part of extended C++ TR1 currently. Is the complete boost library going to be included once the standard is officially out ? In other words, do I need boost library, if I have complete standard conforming C++11 compiler ? If not then any reason for that (Reliability cannot ...
Boost is huge, and of generally high but still varying quality. A lot of the APIs - even the techniques and functionality - are quite "experimental" in the sense that they're still regularly modified as real-world feedback comes in. By way of contrast, the Standard is expected to get it right and need minimal revisi...
6,674,098
6,679,220
making boost::fusion::result_of::as_set<> 's instance doesn't call its elements' constructors
#include <iostream> #include <boost/mpl/front.hpp> #include <boost/mpl/pop_front.hpp> #include <boost/mpl/push_front.hpp> #include <boost/mpl/push_back.hpp> #include <boost/mpl/pop_back.hpp> #include <boost/mpl/fold.hpp> #include <boost/mpl/transform.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/set.hpp> #i...
Possibly typo? Constructors were called when I tested on ideone by adding ::type as the following: /**********create fusion set instance**************/ fusion_set_type::type instance;
6,674,209
6,675,965
How do you read intrinsic and distortion matrixes from file in opencv 2.2
I already have "instinsic.xml" and "distortion.xml" which was produced for my camera. Now I am writing a program using OpenCV 2.2 interface and therefore I am mainly working with cv::Mat data structure as opposed to CvMat. I want to load these two files into corresponding cv::Mat structure. With previous API for OpenCV...
Something like this should be good for you : The code is some sort of a sample. There are others in the samples directory of OpenCV which are really relevant and help a lot in these types of manipulations... //TO WRITE Mat myMat; FileStorage fs(filename,FileStorage::WRITE); fs << "MY_MAT_NAME_IN_THE_XML" << myMat; fs.r...
6,674,211
6,675,037
Blocking cancel of pending async operations in Boost.Asio
I have an object that receives callbacks from a boost::io_service, and for a few reasons I cannot post the callback via a shared pointer (yes, I know it's the official way to handle it), so I bind the handler with a raw pointer. Assume it's a fixed requirement in this situation. Now, if I delete the object, it will, of...
You can't; the information has been lost at that point. You can't even compare the function objects for equality, let alone peek inside and compare some pointer and then decide what to do. So, the question is: why can't you use a shared pointer? The way to do it is to use shared pointers and weak pointers. If you don't...
6,674,447
6,674,465
Why does data get assigned without an extra copy being created, in an initialization list?
Parashift explains initialization lists well, but does not explain why an extra copy of a variable is created before assignment in the ctor body, but no extra copy is created when assigned through an initialization list. I've even come across advice of using ++i instead of i++ because the former avoids creation of a te...
Consider the following: struct C { C() { /* construct the object */ } }; struct X { C member; X() { member = C(); } }; The X() constructor is the same as if you had said: X() : member() { member = C(); } First, the C constructor is called to construct the member data member. Then the body of X is exec...
6,674,506
6,674,588
Lambda expressions : n3290 draft
A point from n3290 ISO draft: Lambda expressions : section 5.1.2, para 6: "The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s f...
The short answer This just means that lambdas not capturing anything can be converted into a function pointer with the same signature: auto func = [](int x) { return x * 2; }; int (*func_ptr)(int) = func; // legal. int y = func_ptr(2); // y is 4. And a capture makes it illegal: int n = 2; auto func = [=](int x) { ret...
6,674,523
6,675,463
Is it possible to express lambda expressions/functions using Templates & Exception Handling?
Shall We can work the Lambda expressions with templates & Exception handling ? Can any one able to show that in terms of an exapmle program please ? Is it possible to express lambda expressions/functions using Templates & Exception Handling ? EDIT: i need an example programs .."Lambda Expression/Functyions using Templ...
You can pass a lambda to a template. The simplest example is with std::for_each: std::vector<int> v; for(int i=0;i<10;++i) { v.push_back(i); } std::for_each(v.begin(),v.end(),[](int& i){i*=2;}); // double each value std::for_each(v.begin(),v.end(),[](int i){std::cout<<i<<std::endl;}); // print each value This wil...
6,674,611
6,674,616
deleting a file with string in the arguments
How can i remove a file from the directory in c++ ? I know this function int remove ( const char * filename ) deletes the file whose file name is specified in the argument. But it accepts only char* . Is there any other function in c++ that accepts string as it's argument ?
If you have a std::string, you can get a const char* from it by calling its c_str() member function. The remove function from <cstdio> is part of the C Standard Library. C has no concept of classes or std::string, hence why the function takes a const char* and not a std::string.
6,674,652
6,676,302
Free DirectShow live stream source filter
I have a DirectShow graph, contains file source filter, splitter filter, decoders for video and audio and renderers. (The data is possibly encrypted, so the splitter just split it to video and audion and the decoders actually decrypts the data). Now, I want to change the graph to work with live streams instead of files...
If by live streams you mean Windows Media over HTTP, you could try this: First define a GUID for CLSID_NetShowSource, something like #include <initguid.h> DEFINE_GUID(CLSID_NetShowSource, 0x6b6d0800, 0x9ada, 0x11d0, 0xa5, 0x20, 0x0, 0xa0, 0xd1, 0x1, 0x29, 0xc0); Then you can use it as follows: IBaseFilt...
6,674,653
6,675,681
Reason for not allowing forward declarations of nested class?
Example: // can't forward declare with class Foo::Bar // actual class class Foo { public: class Bar // or enum Bar { } }; I accept that this is not allowed under the current C++ standards, but I couldn't come up with a good reason of not allowing it though, especially with C++0x, we're now able to forward...
The reason that it is not in the language is simply that nobody has come up with a good proposal on how to include it in the language. Features don't include themselves, someone has to write it up and explain the advantages and that there are no (or very minor) disadvantages. The argument for not forward declaring enum...
6,674,804
6,674,902
Deleting inherited types
I have 2 classes: class A { public: char * x; char * y; char * z; A(); ~A(); } class B: public A { public: char * o; B(); ~B(); } I want to delete[] x, y, and z in class B's destructor (And yes, A's constructor does properly allocate x, y, and z). The code will compile fine, but upon execution it will crash. The prop...
I called A's constructor/destructor as well as B's, so that causes several issues on how I coded it, notably a severe memory leak. Thanks for all of the help guys, I just was confused due to someone telling me that onle constructors were inherited.
6,675,056
6,675,174
Phonegap - C++ Library
I'm planning to write an application for Android and iOS and I want to use Phonegap for it . Now I've heard, that I can write native modules which are then included in the build process I've seen modules which use normal objective c/Java code. Is it possible to write a plugin with a .mm file and a .h file where the .mm...
Yes that is possible. Refer Phonegapdelegate.m, YouAppDelegate.m and .h files for more information. Regarding android, refer Javascript interface in webview.
6,675,098
6,675,241
where to keep typedef's, should i have repeated typedef's
Say i have three files //first.h typedef typename std::map<Vertex_t*,Vd_t> MapVertexVd_t; //the graph class and ... //other useful things related to a graph class //second.h #include "first.h" class analyzeGraph { MapVertexVd_t mapVertexVd; public: void fillMap(); }; //second.cpp #include "second.h" void analyzeGra...
I find that depending on the circumstances these work out well: For typedefs used across a lot of files, put them in a shared header file (probably with forward declarations, etc.) For typedefs used only by a few functions or methods (in the declaration), place them immediately before the first relevant declaration, a...
6,675,393
6,675,470
Diffrence between cin and assignment
Consider the following 2 code snippets: Case 1: #include <iostream> int main() { int i=0; char c='a'; i=c; cout << i << endl; //Retuens ASCII value of 'a' return 0; } Case 2: #include <iostream> int main() { cout << "Enter integer value" << endl; int i=-1; cin >> i; //Assume user enters...
When the user enters 'a', the operator implementation tries to convert this to an integer, and fails. In response to the comment (which seems to be the main point of your question): yes, I understand that cin is failing. What I would like to know is: why cin fails when char is entered, if assignment properly assigns a...
6,675,600
6,675,816
Problem with High speed data read with Settimer method
I am using the hardware with ftdi chip in FIFO mode and D2xx driver for my work. Hardware is sending data bytes at the rate of 19.5KHz to 312.5 KHz for different settings. So my application software(MFC C++) is supposed to read these bytes coming at various speed.I am using Settimer and Ontimer method with value of 10 ...
It will probably be more reliable to keep blocking on Read() in a separate thread. SetTimer() is meant only for low-res work. Its resolution can actually be scaled back depending on power settings in more recent versions of Windows. If you want high-resolution timers, Timer Queues or Multimedia Timers (specifically, t...
6,675,651
6,675,673
When should I use raw pointers over smart pointers?
After reading this answer, it looks like it is a best practice to use smart pointers as much as possible, and to reduce the usage of "normal"/raw pointers to minimum. Is that true?
No, it's not true. If a function needs a pointer and has nothing to do with ownership, then I strongly believe that a regular pointer should be passed for the following reasons: No ownership, therefore you don't know what kind of a smart pointer to pass If you pass a specific pointer, like shared_ptr, then you won't b...
6,675,655
6,675,833
compare topologically sorted list with the original list
i have a vector of vertices from mygraph, and i topologically sort the vertices. typedef typename boost::adjacency_list<boost::listS, boost::vecS, boost::directedS,Vertex_t*> Graph_t; typedef typename boost::graph_traits<Graph_t>::vertex_descriptor Vd_t; Graph_t mygraph; std::vector<Vd_t> v1; //initialize the...
So what is the best way to compare v1 and v2 to test if my original vector of vertices(v1) was 'in order' or 'out of order'. Not comparing the vectors. The test is flawed in that if it succeeds (both vectors are the same) you will know that it was in order, but if it fails (vectors differ) you will not know whether i...
6,675,878
6,676,114
Changing binary file
I have a file on windows. I'm writing in C++. I have a problem where I need to remove some bytes from the end of the file. I am using ifstream, but I don't know how to remove those chars, simple put '\0' in the file or what ?
On linux machines, use truncate(): http://linux.die.net/man/2/truncate On the Windows machines, use SetEndOfFile(): http://msdn.microsoft.com/en-us/library/aa365531%28v=vs.85%29.aspx Both are OS dependent calls.
6,675,882
6,676,217
Calling a glut function exits the program
I'm attempting to use OpenGL with Qt (relatively new to both of them), but whenever the program encounters a glut function like gluSolidCube or similar, it simply exits. I'm sure I'm missing something very basic here, but I have tried putting the dll files everywhere within the solution directories, to no avail. Callin...
GLUT is not part of OpenGL. It's a rather simple framework library and needs to be initialized by glutInit(&argc, argv); in the main entry point function. Without initialization GLUT functions will call exit when invoked, thus terminating your program. Technically I discourage using GLUT for doing something as simple a...
6,676,247
6,676,388
Qt - webkit - how to extract images out of a web page
I am trying to extract the images from the given web page. I have gone through "Simple Selector Example" and "DOM Traversal Example" . But, they refer text-things not image. I have made a code to get a QNetWorkReply by sending QNetworkRequest through QNetworkManager. But, I can't get how to bring images using it. Qt-W...
QWebElement has tagName and attributeNames, you want to search for an img tag with a src attribute. You can download URLs with QNetworkAccessManager.
6,676,365
9,735,925
Is there a way for Flex to access C++ functions from a DLL?
I have an Adobe Flex application that needs to call C++ functions from a dll . Since Flex apps execute within the browser, is there any way to do this ?
We went with Firebreath We created browser plugins with our existing C++ code, using Firebreath and it works great. Firebreath creates both ActiveX and NPAPI plugins in a single .dll.
6,676,525
6,676,928
How to get the absolute library file name corresponding to a relative path given to dlopen?
In my program I have code like the following /* libname may be a relative path */ void loadLib(char const *libname) { void *handle = dlopen(libname); /* ... */ dlclose(handle); } Within /* .. */, I need to read the memory map file /proc/self/maps, to find the virtual memory address at which libname is mapped ...
you could use ... dlinfo(handle, RTLD_DI_LINKMAP, p) p->l_name ... where p is of type Link_map** see man dlinfo for details
6,676,626
6,695,759
algorithm to find best match that may return none
I have some inputs that may be temporarily unavailable and that have an error associated. struct sensorVal { bool available; double error; double val; bool betterThan(const sensorVal* that) const; } I'm looking for an algorithm that will find the best available input. My best attempt so far is to use m...
You can use std::accumulate instead, but I think the solution you already have is better. struct best { std::vector<sensorVal>::const_iterator end; explicit best(std::vector<sensorVal>::const_iterator end) : end(end){} std::vector<sensorVal>::const_iterator operator()(std::vector<sensorVal>::const_iterator l, s...
6,676,764
6,676,865
Disabling "bad function cast" warning
I'm receiving the following warning: warning: converting from 'void (MyClass::*)(byte)' to 'void (*)(byte)' This is because I need to pass as argument a member function instead of an ordinary function. But the program is running correctly. I'd like to disable this warning (Wno-bad-function-cast doesn't work for C++) o...
No. Take this warning seriously. You should rather change your code to handle this scenario. Pointer to member function(void (MyClass::*)(byte)) and normal function pointer (void (*)(byte)) are entirely different. See this link. You cannot cast them just like that. It results in undefined behavior or crash. See here, h...
6,676,779
6,677,167
How to get shortcut target
I need to be able to read the target of a shortcut (a .lnk file). I have Googled this and found numerous results that I have found to be helpful: http://cboard.cprogramming.com/windows-programming/62962-ishelllink-getpath-dev-cplusplus.html http://www.go4answers.com/Example/get-shortcut-target-cpp-win64-216615.aspx htt...
All headers are fine, but you are using wide (wchar_t based) and 'normal' (char based) strings incorrectly: IPersistFile::Load takes a wide string while IShellLinkA::GetPath takes a normal string. Using this should compile: IShellLinkA* psl; //specify the ansi version explicitely CoInitialize( 0 ); //you forgot this, n...
6,677,118
6,681,505
Combining stores/loads of consecutive atomic variables
Referring to a (slightly dated) paper by Hans Boehm, under "Atomic Operations". It mentions that the memory model (proposed at the time) would not prevent an optimizing compiler from combining a sequence of loads, or stores, on the same variable from being combined into a single load. His example is as follows (updated...
The C++0x standard attempts to outlaw this optimization. The relevant words are from 29.3p13: Implementations should make atomic stores visible to atomic loads within a reasonable amount of time. If the thread that is doing the load only ever issues one load instruction then this is violated, as if it misses the writ...
6,677,146
13,253,560
How to suppress runtime errors caused by assert() using google test?
I am using google test in a C++ project. Some functions use assert() in order to check for invalid input parameters. I already read about Death-Tests (What are Google Test, Death Tests) and started using them in my test cases. However, I wonder if there is a way to suppress the runtime errors caused by failing asserti...
Ok, I found the solution myself: You have to select the test-style threadsafe. Just add the following line to your test code: ::testing::FLAGS_gtest_death_test_style = "threadsafe"; You can either do this for all tests in the test-binary or for affected tests only. The latter is faster. I got this from the updated FAQ...
6,677,447
6,677,699
Optimal Code for initialization
Which of the following code would be optimal for initializing array? char szCommand[2048] ={0} char szCommand[2048]; memset(szCommand,0,2048);
For null terminated strings, in my opinion, the optimal initialization is this szCommand[0] = 0;
6,677,916
6,677,968
C++ exception overhead
Why do embedded platform developers continuosly attempt to remove usage C++ exceptions from their SDKs? For example, Bada SDK suggests the following workaround for the exception usage, which looks exceptionally ugly: result MyApp::InitTimer() { result r = E_SUCCESS; _pTimer = new Timer; r = _pTimer->Co...
I can think of a couple of possible reasons: Older versions of the compiler didn't support exceptions, so a lot of code has been written (and conventions have been established) where exceptions are not used Exceptions do have a cost, and it can be as much as 10-15% of your total execution time (they can also be implem...
6,678,056
6,696,494
Open source Multi-Way Radix Tree
I'm looking for a Radix Tree implementation that I can use for keys that are string of binary characters, actually UUID so must support null byte. It'd be used in a commercial product so something with a suitable licence.
There is a java implementation available here http://www.badgenow.com/p/radixtree/
6,678,253
6,678,378
How can writing memory to a filebuffer mutate it?
For a while now, I have been experiencing an extremely odd problem when trying to write memory to a filebuffer in C++. The problem only occurs on MinGW. When I compile under gcc/linux, everything is fine. Debugging Session displaying the problem So basically, I'm writing code from a memory buffer to a filebuffer, and t...
You need to open the file in binary mode. When you open it in text mode on Windows, line feeds (0x0A) will get converted to CR/LF pairs (0x0D, 0x0A). On Linux you don't see this because Linux uses a single LF (0x0A) as the line terminator in text files, so no conversion is done. Pass the ios::binary flag to the ostream...
6,678,286
6,679,541
Speed/Memory usage estimate for different data structures
I'm trying to decide which data structure to use for the following. Lets say I have maybe 10 million keys that contain pointers to unique objects containing some data. The keys are UUID's think of them as 16 byte binary arrays. The UUID's are generated using a good quality random number generator. I've been considerin...
You don't care about ordering Your key is already random 10 million items The short answer A hash table will probably be the best for your case. Speed A hash table (std::unordered_map) will be O( 1 ) if hashing is constant. In your case, O( 1 ) holds because you don't even need to hash—just using the lower 32 bits o...
6,678,396
6,678,435
Can #if pre-processor directives be nested in C++?
I have a question about Pre-processor directives in c++: For example: #ifndef QUESTION //some code here #ifndef QUESTION //some code here #endif #endif Can we use it in this way, and can the C++ compiler match the ifndef and endif in the right way?
Yes, we can. The #endif statement matches to the previous #if #ifdef or #ifndef etc for which there hasn't been a corresponding #endif. e.g. #if ----------| #if -----| | #endif ---| | #endif --------|
6,678,820
6,678,950
including windows.h causes clashing with local variable name
I am including windows.h in one of my h files (in order to use CaptureStackBackTrace), in a Visual-Studio project. At first I got some compiler errors because of the use of min/max std methods and the macro with same name in windows.h, but this seems to be solved by #define NOMINMAX, as I read in other SO posts. (I say...
dlg.h contains the line #define grp1 0x0430 You could exclude it by defining WIN32_LEAN_AND_MEAN.
6,678,861
6,678,953
CMAKE: Creating and building a list within a function -- with directory, or global scope
I am not entirely familiar with the scoping rules of cmake. I need to buildup a list of various files whilst doing RPC code-generation for an IDL. function(generate_rpc file_name) set(PROTO_FILES ${PROTO_FILES} ${file_name}) endfunction(generate_rpc) generate_rpc(BasicProtocol.proto) generate_rpc(dummy.proto) messa...
Using a macro instead of a function seems to do it: macro(generate_rpc file_name) set(PROTO_FILES ${PROTO_FILES} ${file_name}) endmacro(generate_rpc) EDIT: According to http://www.cmake.org/cmake/help/syntax.html (should be in the man page, IMO): CMake functions create a local scope for variables, and macros use th...
6,679,096
6,679,133
Using find_if on a vector of object
I have a vector of that looks like the following: class Foo { //whatever }; class MyClass { int myInt; vector<Foo> foo_v; }; And let's say, in the main: int main (void) { vector<MyClass> myClass_v; } I want to find a object in myClass_v that has myInt == bar. I don't care about foo_v. I thought of us...
That's not how predicates work. You have to supply either a free function bool Comparator(const MyClass & m) { ... }, or build a function object, a class that overloads operator(): struct MyClassComp { explicit MyClassComp(int i) n(i) { } inline bool operator()(const MyClass & m) const { return m.myInt == n; } priv...
6,679,221
6,759,262
Failed CoCreateInstance
I have a function where I am calling CoCreateInstance. This function is called multiple times and it works, however one time the CoCreateInstance fails with the "Bad variable type" error. The thing is the parameters are always the same both when it succedes and when it fails. What could cause this to happen?
I fixed this. The call was made from different threads. When the call succeded, it was called from the main thread. On fail, a different thread was the source and CoInitialize() wasn't called beforehand. Calling CoInitialize solved the problem.
6,679,607
6,679,704
how to write and read a text to and from a LineEdit using QT Creator?
I am working with QT Creator. I have a form that contains a push button and an Line Edit. I would like to print a string that i give programatically in this LineEdit.Secondly I would also like to the from the LineBox a string that I fill in and print it using QMessageBox. How to do it? Need some help. I don't know how ...
You use QLineEdit::setText() to change the text and QLineEdit::text() to read. Your questions are very basic and show a clear lack of studying the documentation and experimenting thing yourself. Qt is one of the better documented frameworks out there and with lots of examples. Please take your time to go through them.
6,679,732
6,679,767
DWORD,LPTSR,LPBYTE,HANDLE what do these terms mean?
I came across these terms recently, while studying a program. I got an idea that they were data types...? Are they really? Could you please explain me what these terms really mean? I have not found their documentation.
Assuming context of Windows development, they are simply data types. See Windows Data Types (from Microsoft).
6,680,240
6,681,144
boost::copy_file copy_option to skip over existing destination file?
I would like to copy a file to an other, and I would like to use Boost::copy_file. It has a paramether called copy_option which can be: BOOST_SCOPED_ENUM_START(copy_option) {none, fail_if_exists = none, overwrite_if_exists}; BOOST_SCOPED_ENUM_END I have found another question regarding the overwrite_if_exists ...
There is no copy_option to just skip the copy if the destination already exists. But if (!exists(path)) copy_file(...) is not the right answer, either, because of the race condition: The file might be created between the time you perform the existence check and the time you attempt the copy. So even when you check fo...
6,680,480
6,680,901
Zooming in on an object in a 2D scene?
Right now, my camera translates to the camera position and then scales by a scale factor. al_identity_transform(&mTransform); al_translate_transform(&mTransform,-mPosition.x, -mPosition.y); al_scale_transform(&mTransform,mScale,mScale); al_use_transform(&mTransform); So if I have an object at 400,400 and...
If the screen is W wide and H tall and the origin is at the upper left hand corner with positive x to the right and positive y downward, then in order to ensure that a pixel rendered at (a,b) is in the center of the screen, you need to translate that point to (W/2,*H/2*). That's pretty easy: al_identity_transform(&mTr...
6,681,255
6,681,967
Cursor vs Iterator pattern
In numerous texts, I've seen the term cursor used interchangeably with the term iterator. However, it doesn't seem right that they are treated as the same thing. To me, an iterator allows iteration of a container with no knowledge of the container itself. A cursor, on the other hand, allows iteration of a container as ...
The Cursor pattern you described is the combination of two patterns: Proxy and Iterator. The reason the standard library is different is to avoid needlessly coupling those two behaviors.
6,681,271
6,681,803
debugging a shared library wrapped by SWIG in perl
I have wrapped my C/C++ code using SWIG in Perl. I have few segmentation fault because of the wrapped code. I am trying to use ddd with the Perl script but unfortunately even if I set a breakpoint on a line of the script ( the one calling C/C++ code ), ddd is not able to step in down to the C/C++ code. Is there any way...
I did a simple thing. I called the gdb directly on perl interpreter. gdb /usr/bin/perl (gdb) r myscript #block the script someway or rerun it (gdb) b whatever_my_function It seems that once the scipt is running shared memory is also loaded in memory. Once this happened I have available all information,...
6,681,492
6,681,973
Using select() and fgets() to access information from a serial port
This is a followup to this question: How to wait for input from the serial port in the middle of a program I am writing a program to control an Iridium modem that needs to wait for a response from the serial port in the middle of the program in order to verify that the correct response was given. In order to accompli...
You aren't using the same file handle for read/write/select, which is somewhat strange. You are not resetting your fd_sets, which are modified by select and would have all of your fds unset in the case of a timeout, making the next call timeout by default (as you are asking for no fds). you are also using buffered IO, ...
6,681,520
6,681,573
"this" Cannot Be Used As A Function
In C++ I'm attempting to emulate how Java handles calls to it's constructor. In my Java code, if I have 2 different constructors and want to have one call the other, I simply use the this keyword. Example: public Constructor1(String s1, String s2) { //fun stuff here } public Constructor2(String s1) { this("Tes...
You can write an init private member function for such job, as shown below: struct A { A(const string & s1,const string & s2) { init(s1,s2); } A(const string & s) { init("Testing", s); } private: void init(const string & s1,const string & s2) { //do the initialization }...
6,681,650
6,685,520
Help with SNMP in C++?
I've been trying to build an application in C++ using WinSNMP, and although I'm slowly making progress, I keep running into issues. So far, my program tries to startup, create, and open an SNMP session, sets a port, and then attempts to listen to that port, then exits. I have it printing out the values of all the varia...
You only pass two arguments to printf: one format string and retranslateMode. Get rid of the parenthesis around your variables in the call and it should work as you expect. Background: The expression (a, b) evaluates a, discards the result, and then yields b. One place where applying this comma operator is useful is co...
6,681,855
6,781,995
How to extract audio/video clips using the libvlc API or FFmpeg API?
I am supporting a C++/Qt application that uses libvlc to playback audio/video streams. My task is to enhance the application to allow the users to extract video clips by setting start / end times and capturing the video in between to a file. I've implemented the start/end markers, and can seek the audio/video to the co...
ffmpeg supports clipping of video file and conversion of clips to desired format. By providing start time (with -ss parameter) and duration (with -t parameter) you can actually clip video within 'ss to t' seconds.
6,681,871
6,682,014
Modifying only a specific element type of VBO buffer data?
I have my VBO using single buffer at the moment, it has vertex, texcoord and color elements. Now, is it possible to update efficiently only the texcoords without updating the vertex/color as well? It should be the same efficiency as having separate buffers updated.
You can map a specific range of your VBO into user memory using glMapBufferRange. Of course, if your vertex, color and texcoord data are interleaved, it will be equivalent to a glMapBuffer. EDIT: If your VBO is: [XYZ XYZ XYZ XYZ RGBA RGBA RGBA RGBA TxTy TxTy TxTy TxTy] You can upload only the texture coordinates by ma...
6,681,978
6,725,802
Entity-attribute-value mode or JSON in database?
I have a database schema where attribute are unlimited, I can have this structure using two ways. Using Entity attribute-value model table 1 id entity table 2 entityid attribute-name attribute-value 2 . Way is to use JSON. like table1 id entity json-attribute {"name":"value-pair"} I have a question wh...
I had chosen json solution. why ? It will avoid writing complex query to fetch data. What about if I need to load any particular attribute ? yes. In JSON solution I have to load all attribute from the database. and then filter for that particular attribute. But in my case I will be loading all attribute every t...
6,682,011
6,682,252
Passing array of strings from c# to c++ - memory management
In my code I have c DLL that accepts array of strings: void Helper::ProcessEvent(PEVENT_RECORD pEvent,wchar_t** OutPutFormattedData) I'm invoking it with this code: [DllImport("Helper.dll", EntryPoint = "ProcessEvent")] internal static extern uint ProcessEvent( [In, Out] ref EVENT_RECORD pEvent, ...
If you allocate a (managed or unmanaged) buffer (or array or chars) in C# and then fill in C++: 1. Deallocate in C#. 2. Buffer should be [in] and not have ref or out in C# signature. If you allocate a buffer (or array of chars) in C++: 1. Pass buffer as [out] out IntPtr. 2. Add deallocate method to C++ signature. 3. C...
6,682,180
6,682,217
Recognizing files with an application
After I save a file in a folder with correct extension, when I go back and look at it, the file is unrecognizable to the application. The file association appears to be lost. I want Windows to be able to recognize all files with a particular extension (*.sp) with my application. How do I do that? and How do I implement...
Deployment and Associations The link includes this text: The deployment tools in Visual Studio include a File Types Editor, which allows you to specify document types and associate them with file extensions. In addition, you can specify the verbs or actions for each document type and specify MIME types for the d...
6,682,286
6,682,412
Understanding a C++ sample - printers, handles, strings
There are few question from the following code which i came across here: // RawDataToPrinter - sends binary data directly to a printer // // szPrinterName: NULL-terminated string specifying printer name // lpData: Pointer to raw data bytes // dwCount Length of lpData in bytes // // Returns: TRUE f...
&hPrinter is the address of the hPrinter variable. You need to pass it so the OpenPrinter function can write in it the actual handle to the printer. _T takes your character string and converts it to the proper ANSI (8bits/character) or Unicode (16bits/character) representation based on your compilation settings. Basic...
6,682,433
6,682,631
Compilers give different answers for Project Euler #22
I'm doing Project Euler #22: Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to...
Here: if(x.compare(y) == -1) You are assuming that std::string::compare will return -1 for a less-than result, but it can in fact return any negative value. You can fix this by using x.compare(y) < 0, but it's better to just write x<y. In fact, you don't even need the strCmp function because the default behavior of st...
6,682,438
6,682,471
Is it possible to manually calculate the byte-offset of a class member?
That is, what is the standard a compiler uses to generate a class? For example, let's say that I have class C with members x, y, and z, and I want to know the offset of z within that class. Can I just add up the data-type sizes of the other members, like I would for a structure?
No You cannot. Compilers are free to align the members as they chose to.It is an implementation detail of the compilers. If you're working with a POD, then you can use the offsetof macro. But If working with a Non-POD, then I suppose there won't be any portable method to do so.
6,682,591
6,682,705
Memberwise Initialization
Possible Duplicate: C++ initialization lists What is the difference between member-wise initialization and direct initialization in a class? What is the difference between the two constructors defined in the class? class A { public: int x; int y; A(int a, int b) : x(a), y(b) {} A(int a, int ...
The theoretical answers have been given by other members. Pragmatically, member-wise initialization is used in these cases : You have a reference attribute (MyClass & mMyClass) in your class. You need to do a member-wise initialization, otherwise, it doesn't compile. You have a constant attribute in you class (const ...
6,683,001
6,767,259
Wormhole Attack Implementation -Sensors
I am trying to implement a wormhole attack detection program for network sensors. I have looked around the internet for source code on this, but have found none. Does anyone know where to find source code for Wormhole sensor Attacks (for simulation purposes) or wormhole detection? If so, where?. It can be in any progr...
The wormhole attack has a lot of cases we should keep in mind. The network is set up and has no plans to add anymore nodes (easy dont let anything connect but i guess with my limited understanding of ah hoc this maybe pointless) The network is setup and nodes are added often (they look like a normal computer i think c...
6,683,217
6,684,030
Command Line Tool Build for Release in Xcode 4, trouble with including images in the build executable
(First off, thanks so much. Stackoverflow has been very helpful to me in the past!) Okay, so I am currently working on a Command Line Tool written in C++ through Xcode. I've done a dozen or so programs in the past like this and had no problem compiling them inside or outside of Xcode. Usually, I just use the terminal's...
The Mac version of SDL sets the working directory to the application bundle's parent directory. You're not creating a Mac application bundle so the operating system can't find the images. A short term fix would be to open the file SDLMain.m and modify the setupWorkingDirectory: method so the working directory is set to...
6,683,356
6,690,034
C++ Templated Producer-Consumer BlockingQueue, unbounded buffer: How do I end elegantly?
I wrote a BlockingQueue in order to communicate two threads. You could say it follows the Producer-Consumer pattern, with an unbounded buffer. Therefore, I implemented it using a Critical Section and a Semaphore, like this: #pragma once #include "Semaphore.h" #include "Guard.h" #include <queue> namespace DRA{ namespa...
You better use events instead of Semaphore. While adding, take lock on CS, and check element count (store into bIsEmpty local variable). Add into queue, then check if number of elements WAS empty, SetEvent! On pop method, lock first, then check if it is empty, then WaitForSingleObject - as soon as WFSO returns you get ...
6,683,411
6,683,500
Is this valid ANSI C++ code? Trying to generate offsets of structure members at compile-time
Possible Duplicates: Does the 'offsetof' macro from <stddef.h> invoke undefined behaviour? dereferencing the null pointer #define _OFFS_OF_MEMBER(p_type, p_member) (size_t)&(((p_type *)NULL)->p_member) struct a { int a, b; }; size_t l = _OFFS_OF_MEMBER(struct a, b); I had a littl...
You're not dereferencing anything invalid here. All that macro does is tell the compiler that a structure of type p_type exists in memory at the address NULL. It then takes the address of p_member, which is a member of this fictitious structure. So, no dereferencing anywhere. In fact, this is exactly what the offsetof ...
6,683,451
6,683,507
Problem Implementing Observer Pattern : "Member reference base type ________ is not a structure or union"
I've been implementing a barebones observer pattern and am stuck on a somewhat cryptic error: "Member reference base type 'Observer *' is not a structure or union". I assume this has something to do with my use of templates, with which I'm still fairly uncomfortable. Here is the offending code (most cons/destructors re...
The problem is with the operator precedence. Instead of: *i->update( this ); Use: (*i)->update( this ); Otherwise, it will be interpreted as *(i->update( this )), which tries to call a method on a pointer, resulting in the error message.
6,683,489
6,684,449
simulate a deterministic pushdown automaton (PDA) in c++
I was reading an exercise of UVA, which I need to simulate a deterministic pushdown automaton, to see if certain strings are accepted or not by PDA on a given entry in the following format: The first line of input will be an integer C, which indicates the number of test cases. The first line of each test case contains ...
You first need a data structure to keep transitions. You can use a vector with a transition struct that contains transition quintuples. But you can use fact that states are integer and create a vector which keeps at index 0, transitions from state 0; at index 1 transitions from state 1 like that. This way you can reduc...
6,683,596
6,683,957
Cross platform open source third party library for WebServices
I'm looking for cross platform open source third party library for web services which support c++. I have generated c++ files using WSMakeStubs utility but it uses Core Foundation data types. I want a library which provide web service call through c++ so that I can use it on Windows and Mac both the platform. I wanted...
I would like to recommend gSoap. In the company I'm working at, we use it for about 7 years now (since version 2.6.0, the actual version is 2.8.3) and only made good experiences with it. Look at the success stories to get an overview of the companies which are using it. Related: C++ and SOAP What is a good platform fo...
6,683,992
6,702,918
Is there a way to compile C++ several files using Clang in one process?
For benchmarking reason, I need to use the Clang (clang++) compiler to compile several C++ files using only one process. Indeed, by default, the compiler use several process to compile the files and that makes my benchmark to not works the way I want. I know this is a uncommon question, but this is only for a special...
Take a look at the result of clang++ file1.cc -c -### (plus whatever flags you need). You should be able to stuff additional input files into the command starting with clang -cc1, and have them all compile without any forking. This mode of operation isn't really supported, but it works as far as I know.
6,683,999
6,686,175
C++ shared_ptr inheritance memory leak
I have a situation where I have a shared_ptr to base of a child class. When the shared_ptr goes to delete the pointer, only the parent destructor is being called. The parents destructor is virtual, the childs is not, although I have experimented in all combinations. I have the program in valgrind, and it show that memo...
There was a dataRead std::function in UserAgent which ended up getting set to a lambda containing a std::shared_ptr to itself stopping it self form destructing. I added a close() method and set the std::function to it default value. Now all is well and it delete fine Thanks for all your help any way
6,684,021
6,684,043
converting string to array of bytes
I wanted to convert string into array of bytes. How can i do that ? Actually i wanted to read from the file and convert all that data into array of bytes . If converted how can i obtain the size of that array ? After obtaining array of bytes i wanted to get the pointer of type LPVOID and make it point to that array of...
You can convert a string to a char* using char* bytes = str.c_str(); The length can be obtained through int len = str.length(); The pointer can simply be casted to LPVOID LPVOID ptr = (LPVOID) bytes;
6,684,114
6,684,144
No matching function to call Std::find?
I am trying to do: std::find(images_map.begin(), images_map.end(), current_rgb)); where: QRgb current_rgb; QMap<QRgb, MI*> images_map; but I get: error: no matching function for call to 'find(QMap<unsigned int, MI*>::iterator, QMap<unsigned int, MI*>::iterator, QRgb&)
Use the QMap::find() method instead.
6,684,176
6,684,268
"undefined reference to" error. (from a member function to static member variable)
I got a following error upon linking. A member variable ClassBB::THR can't be accessed from a function ClassBB::bound(). What's strange is, from ClassBB::setThreshold(T v) function, which seems in the same condition with ClassBB::bound() in that both are template member function, ClassBB::THR is successfully accessed ...
You have to create the storage for the static variable. Just add: template<class T> T ClassBB<T>::THR; Note that for normal member variables, the storage is generated whenever a new instance of the template class is created. But for static members, a "static" place should be defined for them, hence the explicit defini...
6,684,573
6,684,642
Floating point keys in std:map
The following code is supposed to find the key 3.0in a std::map which exists. But due to floating point precision it won't be found. map<double, double> mymap; mymap[3.0] = 1.0; double t = 0.0; for(int i = 0; i < 31; i++) { t += 0.1; bool contains = (mymap.count(t) > 0); } In the above example, contains will alwa...
You could implement own compare function. #include <functional> class own_double_less : public std::binary_function<double,double,bool> { public: own_double_less( double arg_ = 1e-7 ) : epsilon(arg_) {} bool operator()( const double &left, const double &right ) const { // you can choose other way to make de...
6,684,591
6,684,651
shall I delete smart pointer manually?
This might be a dumb question but I'm just not sure about the answer. The following code read a file, and for each line of the file, a smart pointer is created by "new". If the smart pointer will be used in the future, it's stored in a list, otherwise it's not stored. My question is that: if the smart pointer is not s...
As long as you're storing it with a copy of the smart pointer, this will not leak memory. When the aPtr object falls off the stack (at the end of each while loop execution), it will be destroyed. If it is the only holder to the allocated object, it will delete it. But if you stored a copy of aPtr elsewhere, then it is ...
6,684,620
6,684,658
HTTP POST/GET via stdio
Is it possible to communicate with server via raw file IO functions like fprintf() and fscanf()? E.g. this code won't work afaik: #include <stdio.h> int main() { FILE* f = fopen("http://example.com/", "r"); while (!feof(f)) { char *s = new char[255]; fscanf(f, "%s", s); printf("%s\...
No, this won't work, that's not what stdio is for. But I tell you what you can do: Use libcurl Use asio Use your own sockets I don't know about win32, but on Unix you could: Get a socket to that host using connect(2) Use fdopen(3) to associate it with a FILE * Also, those functions aren't "raw" at all; there's quit...