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
4,752,605
4,752,815
Best method for tokenizing / extracting info from a string
I am trying to convert date-times that i am receiving into a particular format to insert into a MySQL database. The program is written in C++, and the following solution works but I feel it is horribly inefficient. The input is : Mon Nov 08 17:41:23 +0000 2010 The desired output format is: YYYY-MM-DD HH:MM:SS So for t...
You're parsing the string and fortunately you can build the output by simple appends. I don't see this getting more efficient. However, it appears as if you can use seekg to position the cursor past day of the week and UTM adjustment. http://www.cplusplus.com/reference/iostream/istream/seekg/
4,752,619
4,752,651
pass smart_pointer to constructor vs raw pointer
Lets say I have a polymorphic class Structure like that class Base { //some implementation }; class Deriv: public Base { //implementation } class Case1 { boost::scoped_ptr<A> a_ //polymorphic data member owned by C public: Case1(A* a):a_(a) { } }; class Case2 { boost::scoped_ptr<A> a_ //polymorphic data me...
You need to pass a smart pointer and you need to name that smart pointer (e.g., it can't be a temporary): std::auto_ptr<Base> p(new Deriv); Case2 c(p); // this constructor would need to take the `auto_ptr` by reference // so that it can steal ownership. In your first example, Case1 c(new Deriv);, the obje...
4,752,708
4,753,583
C++ "delete" is slow. Where should I look first?
I have a C++ application where the "delete" function is slow to run. What might cause this and where should I begin my search for a solution? Background: This C++ code is in an ARX file running inside of AutoCAD, which is basically just a DLL. The specific computer where delete is slow is running AutoCAD 2011, Windows ...
Roughly in the order I'd check them: Other plugins: could that behavior caused by other ARX files? Can they be disabled on bad system? PerfMon: Check if soft/hard page faults or cache misses peak during your delete (I hope you can set that up on the customers computer). HeapQueryInformation: same values in good/bad...
4,753,153
4,753,399
Redirecting std::cout
I need a class that redirects one ostream to another ostream during the lifetime of its object. After some tinkering I came up with this: #include <iostream> #include <fstream> class ScopedRedirect { public: ScopedRedirect(std::ostream & inOriginal, std::ostream & inRedirect) : mOriginal(inOriginal), ...
The reason those lines are the same is because what you're doing is swapping the buffers. (That is, you "redirect" by swapping the original buffer with the redirect buffer; restoration is the swap back.) While this might give you the intended effect with respect to the output stream, it's not correct because the redire...
4,753,299
4,753,336
A collection of template objects with different template parameters
As a kind of factory-method setup I want to register functors which each create objects of a different type, but meet a common interface - i.e all create objects subclassing a core class. Say I have something like: template <class T> struct FactoryMethod { X* create(); } I cannot have (IIRC) std::map<std::string,Fact...
This is known as type erasure and is a fairly common idiom- although your map could of course be made of ownership-enforcing pointers and you could also use a virtual destructor like most sane people.
4,753,341
4,753,436
Converting Deterministic Path Code from C# to C++
Does anyone know how I can convert this (from C#) to C++? string location = Path.GetDirectoryName(Assembly.GetAssembly(typeof(ZigbeeCommUSB)).CodeBase); location = location.Substring(location.IndexOf("\\") + 1); Thanks. EDIT: Additional Information This is to convert from C# to native C++. If there is another way to ...
Substring in C++ Getting path of current directory ( will help you on the way ) How to do IndexOf in C++ You can use Assembly.GetAssembly in C++ if you use Visual C++ Example of Assembly.GetAssembly from the above link Assembly^ SampleAssembly; // Instantiate a target object. Int32 Integer1(0); Type^ Type1; // Set th...
4,753,452
4,753,478
Dijkstra's algorithm without "previous" vector
I am interested about finding the minimum distance between any node in a graph and the root/source. All links have weight. I don't think I need to use previous[], indicated in the Wikipedia article, since I don't need to know the parent of each node. Is that correct? Additionally, if the weights are all equal to one ...
It is entirely possible to implement Dijkstra's algorithm without back pointers; I know this because I've done it myself. :-) The result is that you won't be able to recover the shortest paths once you're done, but if all you need are the path lengths that should be perfectly fine. As for your second question, yes, yo...
4,753,642
4,753,797
C++0x type inference messes with boost::enable_if
I'm trying to write a generic filtering function that performs linear interpolation at a given sampling coordinate in an multi-dimensional array (arbitrary rank). For this, I need a recursive function template that walks through all dimensions of an array until it hits a value and its associated type. I use boost::enab...
The issue is that you passed a T() (and T) to decltype. The types aren't folding down. This is clearly revealed if you compare the return expression to what you passed to decltype- they're inconsistent. template< typename T, std::size_t I > auto test(const T &t) -> typename boost::enable_if_c< (I > 0), decltype(test< T...
4,753,681
4,754,240
how to pan images in QGraphicsView
I am currently able to load my image into a grahpics scene, and then again into a QGraphicsViewer. I am able to implement a zoom feature by dtecting a QEvent::Wheel and then calling the graphicsViews's scale() function. However, I can't seem to figure out how to get the pan functionality working. I basically want to de...
QGraphicsView has build-in mouse-panning support. Set correct DragMode and it will handle the rest. You do need the enable scroll bars for that to work.
4,753,716
72,300,088
Arrays initialization on constructors
I'm trying to convert a program to OOP. The program works with a few arrays: int tipoBilletes[9] = { 500,300,200,100,50,20,10,1,2 }; int cantBilletes[9] = {0}; So for my conversion, I declared in the header file this: int *tipoBilletes; int *cantBilletes; and in the constructor I wrote tipoBilletes = new int[9]; cant...
My question is, is there any way to initialize it like in Java? Yes, starting from C++11 there is a way to do this as shown below. Note that this was proposed in p1009r2. int *tipoBilletes = new int[] { 500,300,200,100,50,20,10,1,2 }; From new expression documentation the above creates an array of type int[9]. Worki...
4,753,829
4,753,902
safety of passing boost::shared_ptr reference
my question is, how fail-safe is the following code snippet which is part of my resource manager: bool Load(std::string name, boost::shared_ptr<Asset::Model>& newModel) { std::map<std::string, boost::scoped_ptr<Asset::Model> >::const_iterator seeker; seeker = models.find(name); if (seeker == models.end()) r...
This usage is safe, in that whatever the shared_ptr<> passed in through the reference will have it's refcount reduced (assuming that the shared_ptr<> returned from seeker->second->Copy() isn't a shared_ptr<> to the same object) and therefore the object it will be pointing to might be deleted. Specifically, you aren't c...
4,754,011
4,754,486
C++ string to double conversion
Usually when I write anything in C++ and I need to convert a char into an int I simply make a new int equal to the char. I used the code(snippet) string word; openfile >> word; double lol=word; I receive the error that Code1.cpp cannot convert `std::string' to `double' in initialization What does the error m...
You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65. With other types things change, beca...
4,754,345
4,754,367
What's the idiomatic way of parsing text by using ifstream?
I'm trying to parse a text file to find a pattern then grab a substring. This code fragment works fine, however can I improve this? Can I minimize copying here? I.e. I get a line and store it in the buf then construct a string, can this copying be eliminated? In short what's the idiomatic way of achieving this? st...
Here's one possible rewrite: std::ifstream f("/file/on/disk"); char buffer[256]; while (f.getline(buffer, sizeof(buf))) { // Use the read operation as the test in the loop. if (strstr(buffer, pattern) != NULL) { // Don't cast to string; costs time // further processing, then break out of the while loop and ...
4,754,414
4,754,441
Getting input from console without cin?
I'm trying to make a little console program that will basically be console pong. So right now I have this: int main() { while(1) { clearScreen(); restThread(100); } return 0; } The only input I need to poll is if the user has pressed the A or D key since the screen was cleared. I will a...
Maybe you want kbhit (non-blocking) or getch (blocking), both from <conio.h>. There's also getchar, from <stdio.h> or <cstdio>. If you want the program to wait for a keyboard press, getch or getchar by themselves will do. If you don't want the program to wait for a keyboard press, kbhit combined with either getch or g...
4,754,577
4,754,593
Double buffering in the console (display)?
I'm trying to create a console pong game but have run into the following issue. I have the following: int main() { while(1) { clearScreen(); std::stringstream sstr; for(int i = 0; i < 20; ++i) { sstr << "Mooooooo \n"; } printf(sstr.str().c_str()); ...
There's the curses/ncurses library, which requires you to refresh the screen before anything is displayed. It's pretty ubiquitous in terms of platform support.
4,754,589
4,757,181
Overriding c++ method in lua and call it back in c++
I once have thought that I can override a class method in lua so that when I call that function in C++, it will do what has overriden in lua. I mean, like this : C++ class class Person { public: Person(); // ctr virtual void shout(); // Meant to be overriden }; Assume that I have that class binded to lua so that ...
What we did in lqt, the automated binding of Qt to Lua, is that for each class that we bind, which has virtual methods, we create a proxy "shell" class, which registers itself into the Lua state. So for your (simplified) class: class Person { public: virtual void shout(); // Meant to be overriden }; We generate the ...
4,754,633
4,754,833
Linux Program can't find Shared Library at run-time
I'm trying to compile a linux program, id3v2, and it says it is can't find the appropriate library: id3v2: error while loading shared libraries: libid3-3.8.so.3: cannot open shared object file: No such file or directory I'm guessing that this is the part that pulls in the lidid3 library? The file DOES exist, however...
Symlinks on libraries work fine, as long as the final target they trace to exists and is accessible. You have built a dynamically-linked executable, that wishes to be linked against libid3-3.8.so.3 at execution time. This was likely linked during the build phase with something like -L/path/to/libid3/directory -lid3. Y...
4,754,763
4,754,779
Object array initialization without default constructor
#include <iostream> class Car { private: Car(){}; int _no; public: Car(int no) { _no=no; } void printNo() { std::cout<<_no<<std::endl; } }; void printCarNumbers(Car *cars, int length) { for(int i = 0; i<length;i++) std::cout<<cars[i].printNo(); } int main() { int userInput = 10; ...
Nope. But lo! If you use std::vector<Car>, like you should be (never ever use new[]), then you can specify exactly how elements should be constructed*. *Well sort of. You can specify the value of which to make copies of. Like this: #include <iostream> #include <vector> class Car { private: Car(); // if you don't ...
4,754,862
5,162,353
Qt - how to map ,map coordinates to image pixel in an scene
I have created an Scene in Qt where i took the an image from open street map[.png] and placed it into the Scene . I have also exported its coordinates in an another file .My Question is how do I map my image pixel with the map coordinates. basically i want to plot the roads in the map into my image .Thank you
here is the answer I was looking for Convert Lat/Longs to X/Y Co-ordinates
4,755,022
4,755,146
putting #warning inside #define's body
In a header that should be able to compile in C and C++ files, in Visual Studio (2010) and MinGW (32-bit - v3.4.5, 64-bit - v4.5.0) I am trying to minimize the size by changing each one of such line (there are many of them): // for symbol A #ifdef __GNUC__ # warning Symbol A is deprecated. Use predefined const cnA inst...
In msvs 2010 there is this : #pragma deprecated( identifier1 [,identifier2, ...] ) don't know about other compilers and microsoft specific: __declspec(deprecated) void func1(int) {} __declspec(deprecated("** this is a deprecated function **")) void func2(int) {} __declspec(deprecated(MY_TEXT)) void func3(int) {}
4,755,105
4,755,147
Making a copy of an object of abstract base class
If I have a pointer to an object that derives from an abstract base class (so I cannot create an new object of that class), and I wish to make a deep copy of said object, is there a more concise way of accomplishing that than to have the abstract base class create a new pure virtual copy function that every inheriting ...
No, but the copy method does not have to be painful: class Derived : public Base { public: Base *copy() const { return new Derived(*this); } }; (assuming you already have a copy constructor, which, if you need a deep copy, you'll have).
4,755,172
4,789,174
Calling LLVM bitcode function in LLVM 2.8
I'm trying to read and call a function parsed from LLVM bitcode in LLVM 2.8. I have everything working apart from the actual call, which crashes the program. First I have this C code: void hello() {} I've compiled this with: llvm-gcc -c -emit-llvm hello.c -o hello.bc Here's a trimmed down version of the code that's s...
I've managed to get this running as expected. I was curious if the problem lay in the above process, but this is obviously not the case. The system I was running this as a part of was causing the crash, and the code above does work on its own.
4,755,192
4,755,250
Vector destructor causing program to crash in C++
I have a vector<vector<Person*>*>* called groups (yes, I know about shared_ptr, but I can't use them in this context), and another one called partialGroups Anyway, at the end of the method I delete all of the inner vector's, but not the people themselves, because I still want them to be valid, so here is the end of the...
If this code snippet is accurate, you're doing all kinds of things with an uninitialized pointer, unsortable. I'm surprised it gets as far as the exit from the method.
4,755,288
4,755,366
How to write this for-loop using std::for_each or std::transform?
This is more of a learning question. Is there a way I can write the following for-loop using std::for_each or std::transform? If not, is there anything in boost that can help on this? The loop simply flattens a vector of vectors into one long vector. vector<vector<int> > int_vectors; // ... fill int_vectors vector<in...
I wouldn't change this to use one of the algorithms unless you have a compiler that supports lambdas. It's completely clear as written. Even if your compiler did support lambdas, I'd probably not change this code. One relatively straightforward option would be to write a flattening iterator. I wrote one for demonstr...
4,755,568
4,755,618
Using a class with a template base class as a base class argument
Am I missing something here? or is there a reason this is not allowed? // the class declaration class MapImage : public MapEntity, public Vector2D {}; // the variable declaration std::vector<MapImage> healthpacks; // the function void DrawItems(SDL_Surface *dest, std::vector<Vector2D> &items, SDL_Surface *image); //...
No. A vector of a base class is not itself a base class of a vector of a derived class. Consider if DrawItems inserted a Vector2D object, one which is not a MapImage, into items: you would have something that isn't a MapImage in a vector<MapImage>. However, since DrawItems has a vector<Vector2D>, that insertion would ...
4,755,913
4,756,110
How to use doxygen to create UML class diagrams from C++ source
I have been searching for some material that describes how to generate simple class diagrams with doxygen, but couldn't find one. Can anybody help? I need to create diagrams as shown below from a set of C++ files. If there are better tools to achieve this easier, please let me know.
Doxygen creates inheritance diagrams but I dont think it will create an entire class hierachy. It does allow you to use the GraphViz tool. If you use the Doxygen GUI frontend tool you will find the relevant options in Step2: -> Wizard tab -> Diagrams. The DOT relation options are under the Expert Tab.
4,755,947
4,812,996
Converting GdiPlus::Bitmap to OpenCV IplImage
I have a 24bpp GdiPlus::Bitmap that i need to convert into IplImage (opencv). Does anyone know how can this be done?
Here is how you can do it. 1.) Create a new target IplImage object with the dimensions of Source image (GdiPlus::Bitmap) 2.) Get the pixeldata handle of Source image using lockbits 3.) Copy the source pixeldata to target imagedata 4.) UnlockBits of source image
4,756,303
4,756,425
Getting notifications regarding internet connection is gone in linux?
In linux , is it possible to get notification when network connection is down ? Is the any OS service for which I have to register for such notifications ? OR is there any DBus Service of it ?
If you're using NetworkManager, it's possible to get status from it (which is, if I remember correctly, done over dbus). But beware that a lot of Linux machines don't use NetworkManager, so you'll have to handle that. And some machines have more than one network connection, etc. Further "network connection is down" may...
4,756,354
4,756,490
Comparative advantages between C vs C++ for new projects
For each new low-level program or library I write on POSIX systems, I always have to start out with the initial decision: do I write it in vanilla C, or do I go with C++? I like to think that each time I'm making a relatively informed decision, but I wonder if there's something I'm missing. This isn't a which is better...
C++ simply has many more features than C. That makes it a more complex language. But the benefit of using these features is that you will have to write (and maintian) less code. You're not required to use templates, stl, exceptions, function overloads, or whatever C++ feature. But if your problem needs just one of the...
4,756,690
4,759,556
finding image silhouette using openCV
as i want to track motion of an object, i require silhouette of sequence of images. does anybody know , how to do this? Silhouette mask is a binary image that has non-zero pixels where the motion occurs
You can use the technique of background subtraction. Here are two ways of doing it. Subtract the previous frame from the current frame. Only pixels in both frames that haven't changed will result in zero. See cvSub, cvAbsDiff. Maintain a running average of the video frames. See the function cvRunningAvg in the Motion ...
4,756,694
4,757,172
Linker script for C++ program for LM3S8962 unhosted using Codesourcery lite toolchain?
Does anyone have a linker script specifically for the Stellaris LM3S8962 board or could explain how to create one? I am using the codesourcery g++ lite toolchain and can successfully create the elf file for the hosted environment using this linker script: Hosted Linker Script This does not work with the unhosted lib...
These are the extra sections in a C++ linker script (from STM32): .preinit_array : { PROVIDE_HIDDEN (__preinit_array_start = .); KEEP (*(.preinit_array*)) PROVIDE_HIDDEN (__preinit_array_end = .); } >FLASH .init_array : { PROVIDE_HIDDEN (__init_array_start = .); KEEP (*(SORT(.init_arra...
4,756,855
4,756,914
Strange code breaks build in MSVC. What does it mean?
I am trying to include rapidxml into my current project. However, it would not build. Visual Studio would complain about this piece of code (rapidxml.hpp:419+451): 419: void *memory = allocate_aligned(sizeof(xml_attribute<Ch>)); 420: xml_attribute<Ch> *attribute = new(memory) xml_attribute<Ch>; The compiler would say ...
This is called "placement new". It instantiates an instance of xml_attribute in memory instead of allocating new memory for it. See: http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10 I'm not sure why VC2010 has a problem with the syntax though.
4,756,944
4,757,105
C++ DLL plugin interface
I'm planning on doing a C++ plugin interface ala How to create some class from dll(constructor in dll)?(с++) but concerns have been raised that if the interface is used to create DLLs via MinGW or Borland and the DLL loader is compiled with MSVC++, there might be problems. Since the only exported function is declared e...
If you want to be compatible across compilers (and Release / Debug) and use C++, you need a little more effort. Basically - you are allowed to pass basic datatypes, and pointer to pure virtual classes. These classes must not contain any data member, their destructor must not be public and they should not have overloade...
4,756,973
4,757,140
C++, Resetting class members without per-member-assignment
In plain C it's common to reset a struct after instantiation: struct MyClass obj; memset( &obj, 0, sizeof(struct MyClass) ); This is convenient - especially when using an object oriented paradigm, since all members are guaranteed to be reset to null etc. no matter how many members are added over time. I'm looking for ...
If you want to assure that you allocated a memory block with zeros you can use a placement new operator: size_t sz = sizeof(MyClass); char *buf = new char[sz]; memset(buf, 0, sz); MyClass* instance = new (buf) MyClass;
4,757,107
4,757,551
Preprocessor directives
When we see #include <iostream>, it is said to be a preprocessor directive. #include ---> directive And, I think: <iostream> ---> preprocessor But, what is meant by "preprocessor" and "directive"?
It may help to think of the relationship between a "directive" and being "given directions" (i.e. orders). "preprocessor directives" are directions to the preprocessor about changes it should make to the code before the later stages of compilation kick in. But, what's the preprocessor? Well, its name reflects that it...
4,757,121
4,757,370
What are good practices regarding shared libraries on Linux?
I recently read a lot about shared libraries on Linux, and here is what I learnt: A shared library should embed a soname including its major version number. Something like: libfoo.so.1 Its real filename should also include a minor version number. Something like: libfoo.so.1.0 When the library file is copied to, say /u...
Suggested reading: Ulrich Drepper's How to write shared libraries: http://www.akkadia.org/drepper/dsohowto.pdf Ulrich Drepper's Good Practices in library design, implementation, and maintenance: http://www.akkadia.org/drepper/goodpractice.pdf dsohowto is much more detailed. goodpractice is a quick read.
4,757,231
4,757,350
How can I run the MSVC preprocessor and compiler in two separate steps?
I'd like to run the Microsoft Visual Studio Compiler cl.exe without invoking the preprocessor. Is this possible? I thought that simply compiling preprocessed source code (using the /c flag) would make the preprocessor run being a no-op, but apparently that's not the case. I did a bit of benchmarking. Here's a little so...
To my knowledge there is no way to run the compiler without the preprocessor (regardless of the fact that it doesn't do anything. However seperating the 2 stages will obviously be slower as you are adding a write to file and then read back of that file. If it doesn't need to do those writes it can hold it in memory an...
4,757,286
4,757,312
const_cast in constructor acceptable
Is this a valid use of a const_cast ? I am using it in a constructor and it looks as follows: KeyLiteObject(const char * extension, const char * swap_suffix) : _extension(extension), _swap_suffix(swap_suffix), _swap_suffix_extension(swap_suffix) { const_cast<std::string*>(&_swa...
Assuming that _swap_suffix_extension is a const std::string then why not just do this: KeyLiteObject(const char * extension, const char * swap_suffix) : _extension(extension), _swap_suffix(swap_suffix), _swap_suffix_extension( std::string( swap_suffix ) + std::string( extension ) ) ...
4,757,387
4,757,522
c++ overload: string literal vs. boost::function ambiguity
my problem code: #include <string> #include <boost/function.hpp> void func (const std::string&) {} void func (const boost::function<void()>&) {} int main() { func (main); // good func ("bad"); return 0; } => error: call of overloaded ‘func(const char [4])’ is ambiguous overload.cpp:4: note: candidates ar...
You can't easily solve this. boost::function<> and std::function<> don't support only functors callable by f(), but also pointer to members callable by (secondArg.*firstArg)() and data members, so their constructors basically slurp everything in, and later decide what to do with the type. It's not trivial at all to wr...
4,757,614
4,763,493
Why doesn't my template accept an initializer list
I have created a template as follows template<typename T> void f(T const& t) { } I wanted for this to be callable by containers but also by initializer lists. I thought it would be initializer_list<int>, when called as follows. f({1, 2, 3}); But GCC behaves as if it's not Standards compliant m.cpp: In function 'int m...
A "thing" like {1,2,3} does not qualify as an expression. It has no type. Therefore, no type deduction is done. But C++0x makes an explicit exception for 'auto', so auto x = {1,2,3}; actually works and decltype(x) will be initializer_list<int>. But this is a special rule that only applies to auto. I guess they wanted ...
4,757,619
4,757,671
Header files vs. forward declaration
http://www.learncpp.com/cpp-tutorial/19-header-files/ It mentions the following as another solution to "forward declaration": A header file only has to be written once, and it can be included in as many files as needed. This also helps with maintenance by minimizing the number of changes that need to be made if a funct...
That is certainly possible. But for a realistically-sized program, there will be a large number of functions that a large number of other files will need to declare. If you put a forward declaration in every file that needs to access another function, you have a multitude of problems: You've just copy-pasted the same ...
4,757,705
4,757,817
Why do functions need to be declared before they are used?
When reading through some answers to this question, I started wondering why the compiler actually does need to know about a function when it first encounters it. Wouldn't it be simple to just add an extra pass when parsing a compilation unit that collects all symbols declared within, so that the order in which they are...
How do you propose to resolve undeclared identifiers that are defined in a different translation unit? C++ has no module concept, but has separate translation as an inheritance from C. A C++ compiler will compile each translation unit by itself, not knowing anything about other translation units at all. (Except that e...
4,757,725
4,757,743
Mathematical set library/header
In what library/header (if any) is mathematical set defined? I need set to have functions like intersection, union etc.
Use <set> and <algorithm>. Then the std provides std::set_union, std::set_intersection and so on. example: #include <set> #include <algorithm> ... std::set<int> s1, s2; for(int i = 0; i < 20; ++i) s1.insert(i); for(int i = 10; i < 30; ++i) s2.insert(i); std::set<int> my_union, my_intersection; std::set_union(s1.begi...
4,757,793
4,758,829
Is there any tool/software available that does porting from C++ to Java
Hi we have a project/product which is written in C++. Now we are planning to convert it into Java for getting benefit of Java. Is there any tool available for doing this porting? What is the best way to start?
I've seen some attempts at automated code conversion, and while it can technically "work", the resulting code is often completely unmaintainable. The major problems are: Some concepts don't translate cleanly, and require some extremely messy (and often slow!) interpretation or wrappers to get the same results. Good J...
4,757,871
4,757,918
gcc failes to compile operator definition with prefixed namespace
I have operators declared for class my_type in namespace my_namespace. namespace my_namespace { class my_type { friend std::ostream& operator << (std::ostream& out, my_type t); } } I'm trying to define these operators in implementation file, but when I write something like that std::ostream& my_namespace::operato...
The error message says it all, actually. You can keep your function definition in the implementation file, but you need to declare it in the namespace first: namespace my_namespace { std::ostream& operator << (std::ostream& out, my_type t); } The C++ standard is quite clear about this: 7.3.1.2/3: Every name fi...
4,757,878
4,757,913
Function declaration in function definintion
Is it legal C++ to have a function declaration in function definition?
It's legal both as a declaration in the immediate block scope, and as a function definition as a member function of a local class. void f() { // this declares the function defined below (enclosing namespace) void g(); g(); } void g() { struct { void help() { ... } } h; h.help(); }
4,757,962
4,760,770
Solving "locally defined symbol" and "unresolved external symbol" that originates from the .lib files
I am trying to compile my project with an open source library GDCM on Visual C++ 2010 on Windows 7 64 bits. I have included required .lib files (gdcmDSED.lib and gdcmMSFF.lib) in my project, however, the compiler complains back more than 100 unresolved external errors. But I see some patterns in the errors. Here: 1>gdc...
Found this on the internet : The problems disappear when creating the gdcm DLL with the BUILD_SHARED_LIBS ON. Does this ring a bell ? see: http://www.creatis.insa-lyon.fr/pipermail/dcmlib/2007-April.txt
4,758,187
4,758,214
C++ issues choosing a function at run time
I'm at a basic level with C++ so please excuse me if I am missing something obvious. I'm planning a program that can run in two modes. The mode it runs in will be decided by a flag in a config file that the program reads when it first starts. After reading this config file the program will drop into a loop that will lo...
On most modern processors, such as x86, there is a "branch predictor". The processor itself observes patterns in whether a conditional branch was taken or not; if you are always making the same decision, then it should be very efficient. The best thing to do is simply to measure. Write your loop code, firstly without...
4,758,257
4,758,280
How to copy a range of data from char array into a vector?
I've read file contents into a char array, and then read some data of it into a vector. How can i copy a range of the char array into the vector? both vector and char array is the same type (unsigned char). Current code goes something like this: int p = 0; for(...){ short len = (arr[p+1] << 8) | arr[p+0]; p+=2...
Appending something to a vector can be done using the insert() member function: vec.insert(vec.end(), arr, arr+len); Of course, there's also an assign(), which is probably closer to what you want to do: vec.assign(arr, arr+len); However, reading your question I wondered why you would first read into a C array just t...
4,758,568
4,758,733
Deploying XBAP with win32 DLL
My XBAP application uses two win32 dlls and as usual many .Net dlls. Since we add .net references to the project itself, that is not a problem, as they all get deployed automatically when publishing the project; only that their names change from mydotnet.dll to mydotnet.dll.deploy. But the problem is, the win32 dlls do...
Can you try: Checking your project properties under the Publish > Application Files section and if your native dlls appear there, making sure they are set to include. Try including the dlls as content files in your project with copy to output directory set to Copy Always (I would think this may make them appear in the...
4,758,669
4,760,847
Managing Fonts, Brushes and Pens in MFC
I am about to start a text-rendering window in MFC. Given that the text-rendering window will allow fonts of differing style (and each window can have a different font), I've been thinking about the management of fonts. Would it make sense to create some kind of a font manager? I was thinking that each time a font is...
This is an okay strategy for fonts, the Windows font mapper isn't that cheap and the number of fonts that a typical program uses is finite. But not for brushes and pens, they are dirt-cheap so just create and destroy them on the fly. The ultimate endorsement for this strategy comes from Microsoft's own code, Winforms ...
4,758,946
4,758,986
comparing enum from templated class - is it safe?
So, a simple question really, illustrated by the example below. When you compile this, the compiler appropriately(?) reports a warning (that we are comparing barfoo<int>::bar with barfoo<foo>::bar), now given bar is an enum - can I safely ignore this warning? #include <iostream> using namespace std; struct foo { }; t...
The numeric representation of the enums will be the same, so it's safe to compare them directly (or even cast between them, although you may need to go through int to satisfy the compiler). If you want to silence the warning, one approach would be to cast them both to ints before doing the comparison: (int)cState.actio...
4,759,068
4,760,253
FCam - low light / HDR photos
I am using FCam to take pictures and right now without modification, the pictures are par for a smartphone camera. FCam advertises HDR and low-light performance, but I don't see any examples of how to use that when taking pictures. How do I take HDR pictures? From my experience with SLRs, you normally take 3 pictures...
The FCam project page includes a complete camera app - FCamera, check the FCam Download Page, last item, which for "HDR Viewfinder" simply averages a long/short exposure image together, and for "HDR Capture" automatically records a burst of suitably-exposed shots. See src/CameraThread.cpp in the sources, I'm not sure h...
4,759,078
4,759,340
Obtaining a pointer to the end of an array
I use the following template to obtain a pointer pointing after the last element of an array: template <typename T, size_t n> T* end_of(T (&array)[n]) { return array + n; } Now I seem to remember that there was some problem with this approach, but I cannot remember what it was. I believe it had something to with t...
Your proposal is not necessarily evaluated at compile time, it depends on optimisation. The following is calculated at compile time: template <typename T, size_t N> char (&array(T(&)[N]))[N]; int main() { int myArray[10]; std::cout << sizeof array(myArray) << std::endl; return 0; } It works by creating an arr...
4,759,274
4,759,426
C++: Generate file on remote machine and transfer to local machine
i am trying to create a C++ program on Windows machine which has to execute a program on remote machine, transfer the generated file to local machine. The remote machine is also windows. Is there any efficient method to implement it without using MFC? Is it possible to do it without server/client component? Regards, Ad...
I don't recommend coding your solution since other solutions already exist. One of them is Rsync, which is pretty popular in *nix circles. A Windows friendly version also exists, and it's called DeltaCopy. Unless you're trying to improve your skills, or have the time, or you believe you can do better, stick with prove...
4,759,775
4,759,908
Somehow display C++ application using double-click on Ubuntu?
I'm totally new to Ubuntu and C++. Anyway, I have PHP experience. I just created very simple application... #include <iostream> int main() { std::cout << "Hello, world!"; return false; } Then compiled it.... g++ hello-world.cpp -o hello-world But I can't open it with double-click on it, like I did on W...
The program you wrote is a console application. In most Linux GUIs, by default if you open a console program from the GUI, the console output will not be displayed. You can either configure the GUI to open a terminal, or you can manually open a terminal and run it yourself. When doing development, I highly recommend ma...
4,760,499
4,760,530
Type information not passed with new/malloc, only size_t
EDITED: reworded question. When new and malloc are called, the size of the block of memory to be allocated is passed: void* malloc(size_t); void* operator new(size_t); is it possible to get type information, i.e. so you could do a sizeof(T) where T was the type the memory was being allocated for: T t = new T; I'd lik...
The new with the std::size_t argument is commonly known as non-placement new. The std::size_t argument is passed in by default to let the operating system know how many bytes to allocate for the object you are creating. You, yourself, don't need to provide it to the new declaration. Edit: In response to your edit. I...
4,760,510
4,760,559
C++ - /tmp/cckpbRW.o:main.cc:(.text+0x9d):undefined reference
Following the example here: http://www.learncpp.com/cpp-tutorial/19-header-files/ Relating to add.h and main.cpp When I try to compile main.cc (I just used another extension), I get the following: /tmp/cckpbRW.o:main.cc:(.text+0x9d):undefined reference to 'add(int, int)' collect2: ld returned 1 exit status How can I f...
Your didn't link your main object to your add one, so when the linker tries to build the executables it cannot find the definition of symbol add(int, int) it uses. You should compile main object, add object and link them together, like this: g++ -c -o main.o main.cpp g++ -c -o add.o add.cpp g++ -o executable main.o add...
4,760,553
4,762,253
Compiler optimization of functions parameters
Function parameters are placed on the stack, but compilers can optimize this task by the use of optional registers. It would make sense that this optimization will kick in if there are only 1-2 parameters, and not when there are 256 (not that one would want to have the max number of parameters). How can one find out th...
Function parameters are placed on the stack, but compilers can optimize this task by the use of optional registers. As FrankH says in his comments and as I'm going to say in my answer, the application binary interface for the system in question determines how arguments are passed to functions - this is called the cal...
4,760,563
5,031,577
Tab Controls and their child windows
I'm using a control tab (Windows class "SysTabControl32") to organize GUI elements in an application I'm developing. In the past I've captured the TCN_SELCHANGE event and then, on a per GUI element basis, decided what should be visible or not. This is quite fine for small applications with only dozens of GUI elements, ...
Thank you Tiib and Tergiver for the answers, unfortunately I just don't like either of those solutions. Here's what I decided to do: When a new tab is added to my tab control, I create a window with the BUTTON class and the BS_OWNERDRAWN style. Then I replace the windows procedures (GWL_WNDPROC) with my own version (fo...
4,760,668
4,760,685
C++ function template question
I was searching on the best way to lcase/ucase a C++ STL class and I came across this post: STL string to lower case One of the solutions given was: #include <algorithm> #include <string> std::string data = “Abc”; std::transform(data.begin(), data.end(), data.begin(), ::tolower); However, transform is defined in s...
This is called Template Argument Deduction. Here is another nice article explaining Template Argument Deduction.
4,760,687
4,760,758
Cancelling a thread using pthread_cancel : good practice or bad
I have a C++ program on Linux (CentOS 5.3) spawning multiple threads which are in an infinite loop to perform a job and sleep for certain minutes. Now I have to cancel the running threads in case a new configuration notification comes in and freshly start new set of threads, for which i have used pthread_cancel. What I...
In general thread cancellation is not a really good idea. It is better, whenever possible, to have a shared flag, that is used by the threads to break out of the loop. That way, you will let the threads perform any cleanup they might need to do before actually exiting. On the issue of the threads not actually cancellin...
4,760,854
4,760,898
function declared in my class is not showing in scope
in my .h: class ImagePixmapItem: public QGraphicsPixmapItem { public: void setSize(qreal size); private: qreal size; }; In my class file I now have two functions: #include "imagepixmapitem.h" #include <QGraphicsSceneWheelEvent> ImagePixmapItem::ImagePixmapItem(const QPixmap &pixmap, QGraphicsItem ...
void wheelEvent ( QGraphicsSceneWheelEvent * event ) should say void ImagePixmapItem::wheelEvent ( QGraphicsSceneWheelEvent * event ) and also add this to the .h protected: void wheelEvent ( QGraphicsSceneWheelEvent * event );
4,760,978
4,761,097
C++ traits example for this class
I haven't used the advanced features of C++ for a while and am refreshing my C++ knowledge.. Having said that, the concept of traits and policy based programming was something that I never really managed to get my head around. I want to change that. I am writing a generic container. I want to enforce a policy that the ...
You can use a little IsDerivedFrom template which can only be instantiated in case a given type 'D' inherits another type 'B' (this implementation was taken from a nice Guru Of The Week article): template<typename D, typename B> class IsDerivedFrom { static void Constraints(D* p) { B* pb = p; // this line only ...
4,761,068
4,761,086
Is there an addressing issue for writing an FTP client that needs to upload files larger than 4 gigs?
If my FTP client intends to upload files over 4 gigs in size, assuming I'm streaming the data, my pointer is going to hit the wall at around 4 gigs, if it's a 32 bit pointer, right? I'm trying to imagine what's going on behind the scenes and am not able to visualize how this could work... however it MUST work, since I...
The client or server should read the data in chunks (I would do a multiple of the page size or something similar) and write the chunks to disk. There is no need to have the whole file in RAM all at once. Something like this psuedo code (error checking and similar omitted) on the receiving end: chunk = new byte[4096]; w...
4,761,226
4,761,256
c++ inheritance, vtable after casting
given the next simple example, #include <iostream> using namespace std; class A { public : void print() { cout<<"A print"<<endl; } }; class B : public A { void virtual print() { cout<<"B print"<<endl; } }; int main() { A* aPointerB=new B(); aPointerB->print(); return ...
It happens because you didn't define print as virtual in A. That means that when calling on A objects, the lookup is not virtual.
4,761,472
4,761,548
Alternative to Fixed-Size Arrays in Java?
[Context: new to Java, 4 months tops; old hand at C++.] I'm working on a library that requires an array of a fixed size ("fixed string") in many places. I'm trying to use Dependency Injection (q.v.) for this particular problem, so I would like something of the form: class Foo { private Bar injectedBar; private...
There is indeed no way to do what you want with a statically guaranteed length, unless you are prepared to have a new class for every length: FixedBarString4, FixedBarString5, etc. (It is possible to create a class for single linked list of chars which uses generics to encode the length. But I doubt you would like to u...
4,761,503
4,761,980
PInvokeStackBalance keeps being detected while the signature is OK
I have a little problem with my code. I've got a unmanaged C++ .dll that I want to use with a C# applaction. The C++ function in the dll looks like this: void EXPORT_API vSetLights(BYTE byLights) { remote.SetLEDs(byLights); } The C# code looks like this: [DllImport("APlugin")] private static extern void vS...
Your stack imbalance is probably caused by a difference in calling convention. The default calling convention in DllImport is WinApi (which in turn defaults to StdCall). It's likely that your C++ function is using the Cdecl calling convention. You'll have to show us the definition of EXPORT_API in order to be sure. ...
4,761,529
4,761,779
Efficient way of reading a file into an std::vector<char>?
I'd like to avoid unnecessary copies. I'm aiming for something along the lines of: std::ifstream testFile( "testfile", "rb" ); std::vector<char> fileContents; int fileSize = getFileSize( testFile ); fileContents.reserve( fileSize ); testFile.read( &fileContents[0], fileSize ); (which doesn't work because reserve doesn...
The canonical form is this: #include<iterator> // ... std::ifstream testFile("testfile", std::ios::binary); std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)), std::istreambuf_iterator<char>()); If you are worried about reallocations then reserve space in the vect...
4,761,585
4,761,638
Vector's weird behavior?
I've a program that just adds two vectors v1 and v2 like this : v1+=v2. At each iteration v2 gets added to v1. Consider the following program: #include <iostream> #include <vector> #include <iterator> using namespace std; typedef vector<double> v_t; int main(){ v_t v1; v_t v2; f...
That's because you are checking ( *(it++) += *(it2++) ) as a loop termination condition. So when it hits the 6th element, zero, it evaluates to to zero, which fails the condition it != end && ( *(it++) += *(it2++) ); and terminates the loop. for(v_t::iterator it(v1.begin()), end(v1.end()); it != end && ( *(it++) += *(...
4,761,605
4,761,729
What decides to deallocate a local allocation on return?
So, I have 2 pieces of code, one that works and one that doesn't. The first piece was just a test to find out if a char pointer would remain valid after it is returned from a local allocation. For some reason this works: char* test(){ char* rawr="what"; return rawr; } But this one doesn't wor...
char* test(){ char* rawr="what"; return rawr; } The string literal "what" is not allocated on the stack - it remains valid throughout the life of the program. However it must NOT be modified. The pointer rawr itself is on the stack, but this is only a problem if you write things like &rawr, getting a pointer...
4,761,612
4,761,942
How to optimize such simple data (event) casting Class?
So I have created compilable prototype for a graph element that can cast its data to subscribed functions. //You can compile it with no errors. #include <iostream> #include <vector> using namespace std ; class GraphElementPrototype { // we should define prototype of functions that will be subscribers to our data...
Implement the program correctly and safely If performance Not Acceptable While Not Acceptable Profile Optimize Done! In my experience, premature optimization is the devil. EDIT: Apparently while I was formatting my answer, another James ninja'd me with a similar answer. Well played.
4,761,721
4,761,849
Dynamic Function Memory? C++
I've been reading through some books, and when it comes to Class/Functions using Pointers/Dynamic Memory (or heap or w/e they call it) I start to get confused. Does anyone have a simple....like easy example they can show, because the books im using are using overly complex examples (large classes or multiple functions)...
Stack allocation: char buffer[1000]; Here the 1000 must be a constant. Memory is automatically freed when buffer goes out of scope. Heap Allocation: int bufsz = 1000; char* buffer = new char[bufsz]; //... delete [] buffer; Here bufsz can be a variable. Memory must be freed explicitly. When to use heap: You don't k...
4,761,919
4,761,976
What is the "-DranSHR3" option for in the mex compiler
I have seen several Matlab contributions at the Mathworks' file exchange site where the authors use the option "-DranSHR3" when compiling with mex. I checked the mex, the GNU GCC and the Microsoft's cl documentations, but found nothing. Any thoughts on what this option is used for? Where can I find more details about...
The option -DranSHR3 defines the preprocessor Symbol ranSHR3 which in turn selects the SHR3 random generator instead of the default one. Here you can read about Matlab's random generators. Here I found a somewhat long comment about SHR3. At least in Matlab R2010b the default generator for random streams is Mersenne Twi...
4,761,957
4,761,982
how to give this variable global scope
In my header file, I have the following: private: ImagePixmapItem *item; In a function, I create a new ImagePixmapItem like so: ImagePixmapItem *item(static_cast<ImagePixmapItem *>(scene.addPixmap(p))); However, this creates a local copy of item. but if I do this: *item(static_cast<ImagePixmapItem *>(scene.addP...
An initialization like item(static_cast<ImagePixmapItem *>(scene.addPixmap(p))); is only allowed within the declaration of your variable (this is in fact your first example with a local variable), or (for member fields) in the constructor initialization list: ViewerMain::ViewerMain() : item(static_cast<ImagePixmapI...
4,762,048
4,762,130
How to enable Exception Handling on XCode 3.2.3?
How to enable exceptions in XCode - 3.2.3. Is there any flag like I should enable for the compiler for exception handling? Tried googling but didn't find enough information on XCode with C++ ! #include <iostream> #include <exception> int main() { try { int i=5,j=0; int res = i/j; } catc...
Dividing by zero does not raise a C++ exception. See this question.
4,762,099
10,962,874
Integrating Stack Blur C++ Port to iPhone SDK
Can anybody give me a pointer as to how to integrate the Stack Blur C++ library to Objective C? http://antigrain.com/index.html It's probably straightforward. I used to be a C programmer long, long time ago and now I'm comfortable enough with Objective C but I completely bypassed C++ so it gives me a headache just look...
Here's an implementation of Stack Blur for iOS somebody else created: https://github.com/tomsoft1/StackBluriOS I'm sure it'll come in handy for some people.
4,762,110
4,762,171
Partial template specialization based on "signed-ness" of integer type?
Given: template<typename T> inline bool f( T n ) { return n >= 0 && n <= 100; } When used with an unsigned type generates a warning: unsigned n; f( n ); // warning: comparison n >= 0 is always true Is there any clever way not to do the comparison n >= 0 when T is an unsigned type? I tried adding a partial templ...
You can use enable_if with the is_unsigned type trait: template <typename T> typename std::enable_if<std::is_unsigned<T>::value, bool>::type f(T n) { return n <= 100; } template <typename T> typename std::enable_if<!std::is_unsigned<T>::value, bool>::type f(T n) { return n >= 0 && n <= 100; } You can find...
4,762,153
4,762,211
sort order of boost::weak_ptr after expiring?
For boost::weak_ptr the operator< is defined, so that it can be used in associative containers. My question is: Is the sort order of several weak_ptr objects stable even when some of them change to a refcount of zero? Doesn't that mess with containers like std::set? Example: using namespace boost; shared_ptr<A> sptrA1(...
In the current implementation of boost::weak_ptr, operator< compares a pointer to an internal reference-count-tracking structure. This structure is not freed until all strong and weak references are removed, so it remains safe to use operator< even if the pointed-to user data has been freed due to a lack of strong refe...
4,762,395
4,762,416
What is stack-based reference?
What is stack-based references? How are they different from references that are members of objects? Does the Standard talk about these? I came across this in an article written by Herb Sutter: Q1: Is the following code legal C++? // Example 1 string f() { return "abc"; } void g() { const string& s = f(); cout << ...
In the given context, stack-based references means a reference that is an automatic object on the stack. That is, in // ... { // ... const foo& x = some_foo; // ... } // ... x is a stack-based object, while the_foo in class bar { // ... foo& the_foo; // ... }; isn't.
4,762,419
4,762,563
CTreeCtrl state image limited to 15 images
I have a CTreeCtrl that uses "state images" to get a second icon next to the normal icon. From the documentation here http://msdn.microsoft.com/en-us/library/fc4e6etb(v=vs.80).aspx: If a state image list is specified, a tree control reserves space to the left of each item's icon for a state image. An application can ...
Implement a custom-drawn tree-view or find such an implementation.
4,762,578
4,886,894
Eclipse Helios - "cannot run program make; unknown reason"
I upgraded Eclipse from Galileo to Helios, and when I try doing "Clean Project", I get an error saying "cannot run program make; unknown reason". I was able to run make in Galileo, so I'm not sure why this is happening, and whether anyone else encountered this.
Add PATH to the environment (Preferences -> C/C++ -> Build -> Environment). I also had to add $ORACLE_HOME to the environment as well (my code uses Pro*C) - looks like CDT isn't picking-up the user's environment variables when it was before. It's annoying, I know...
4,762,602
4,768,589
How to start browser and load url in symbian S60 Qt app?
I just want my app to start a browser and load an URL. I am using this code that compiles and runs on simulator, but nothing happens. #include <QtGui> #include <QDesktopServices> #include <QUrl> int main(int argc, char *argv[]) { QApplication app(argc, argv); QDesktopServices::openUrl(QUrl("http://www.google....
The simulator isn't an emulator - it doesn't emulate the entire OS, so you can't use it test code like this that launches the platform browser, and running the simulator won't give you a home-screen with menus and applications.
4,762,653
4,763,155
intercept mouse events when creating a custom QGraphicsItem
I am using a standard QGraphicsView and QGraphicsScene, but I have subclassed a QGraphicsPixmapItem to my own ImagePixmapItem for the purposes of being able to use the mouse events on the ImagePixmapItem. What do I need to do to be able to capture those events? I have overridden a couple of functions like so: void I...
You can use event filters. http://cartan.cas.suffolk.edu/qtdocs/eventsandfilters.html I would also add that for your original example, be sure to enable mouse tracking on the widgets in question.
4,762,662
25,615,981
Are parentheses around the result significant in a return statement?
Is there a difference between these two statements inside a function? bool returnValue = true; // Code that does something return(returnValue); and this? bool returnValue = true; // Code return returnValue; The former has parentheses around returnValue.
As of C++14, they often are. C++14 adds a fringe case where parentheses around a return value may alter the semantics. This code snippet shows two functions being declared. The only difference is parentheses around the return value. int var1 = 42; decltype(auto) func1() { return var1; } // return type is int, same as d...
4,762,668
4,763,244
How can I initialize a std::vector with a size parameter and have each object constructed independently?
I like creating vectors with a given size and value, for example like this: std::vector<std::string> names(10); However, this a few times this led to unexpected results. For example in the following code each UniqueNumber turns out to have the same value: #include <iostream> #include <string> #include <vector> struc...
generate or generate_n are purpose-designed for just what you want to do. Here's a complete example: #include <algorithm> #include <vector> #include <iterator> #include <iostream> using namespace std; class Foo { public: Foo() : n_(++water_) {}; operator unsigned () const { return n_; } private: static un...
4,762,788
4,762,820
Can a class with all private members be a POD class?
I've heard before that POD types cannot have private data -- but according to the C++0x draft I have the requirement is looser (emphasis mine): has the same access control (Clause 11) for all non-static data members which seems to suggest that private data is okay so long as it's all private. I don't have a copy of C...
C++03 still does not allow non-static private or protected data in POD classes. This requirement is specified in the definition of aggregate An aggregate is an array or a class (clause 9) with no user-declared constructors (12.1), no private or protected non-static data members (clause 11), no base classes (clause 10)...
4,763,067
4,763,092
Difference between `cout << x` and `cout.operator <<(x)`?
I've been trying to use for_each to print a vector of strings to cout. However, when formulating the statement I found that std::ostream::operator<<(const std::string &); is not defined leading to compiler errors. The following code illustrates the problem: #include <iostream> #include <string> int main() { std::...
You're looking for std::ostream& operator<<(std::ostream&, const std::string&);. It's a free function.
4,763,216
4,763,351
Why am I getting a Linker error with template function pointer?
I have a class EventMgr which has a template function to register a listener. But, when I register a listener, linker gives me a "error LNK2019: unresolved external symbol". Appetizer code: class EventMgr { template< class T, class EvenT> void RegisterListener(T* listener, int EventType, void (T::*MemFunc)(EvenT*) )...
If you simply declared the template in a .h file and the implementation is instead in a .cpp file then this is the error you will get, because a C++ compiler works one compile unit at a time. When the compiler finds your code calling a template function that has been just declared it will assume that the concrete inst...
4,763,327
4,763,675
Efficient Packet types/transfer protocol
Using boost::asio in C++, I'm trying to determine the best way to encrypt packets in my program. I thought of defining packets all by myself by type number, each with different fixed packet sizes. The system reads the header (type, and quantity of entries for lists of data) and creates the appropriate structure to rece...
TCP uses streams of data, not packets. I highly suggest thinking of your data transmission as a stream of data instead of sequence of packets. This will make it easier to abstract into your code. Take a look at Boost.Serialization or Google Protocol Buffers. Boost.Asio has SSL encryption capabilities, so it's trivial t...
4,763,455
4,763,466
Data type size impact on performance
I'm running intensive numerical simulations. I often use long integers, but I realized it would be safe to use integers instead. Would this improve the speed of my simulations significantly?
Depends. If you have lots and lots of numbers consecutively in memory, they're more likely to fit in the L2 cache, so you have fewer cache misses. L2 cache misses - depending on your platform - can be a significant performance impact, so it's definitely a good idea to make things fit in cache as much as possible (and p...
4,763,736
4,763,799
VS2010 C++ variadic template example
I have a class template and I can't seem to figure out how to perform a Variadic Template style instantiation. Here is the "code" so far of what I'm looking for: template<typename _Classname, typename... Args> class CFunctorStartExT { friend class CXXFactory; protected: template<typename U> CFunctorStartExT(type...
Visual C++ 2010 does not support variadic templates.
4,763,756
4,763,791
shared_ptr causing segfault
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid. #include <tr1/memory> #include <iostream> class Dataset ; typedef int DataClass; class Dataset_Impl{ friend class Dataset ; DataClass *dc; Dataset_Impl(){dc = new DataClass[10];} public: ...
You haven't created an object; subset2 is a null pointer. You need to create an object for it to manage: std::shared_ptr<Dataset> subset2(new Dataset);
4,763,814
4,763,896
Can boost::smart_ptr be used in polymorphism?
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in polymorphism? class SomeClass { public: SomeClass() { a_ptr.reset(new SubClass); } private: boost::scoped_ptr<SuperClass> a_ptr; }
Yes: #include <string> #include <iostream> using namespace std; #include <boost\shared_ptr.hpp> using namespace boost; class Foo { public: virtual string speak() const { return "Foo"; } virtual ~Foo() {}; }; class Bar : public Foo { public: string speak() const { return "Bar"; } }; int main() { boos...
4,763,906
4,763,937
Can boost::smart_ptr be used in std containers?
Can boost::smart_ptr such as scoped_ptr and shared_ptr be used in std containers such as std::map? class SomeClass { std::map<int,boost::scoped_ptr<SomeOtherClass> > a_map; }; As boost::smart_ptr can be used for polymorphism, is it true in this case as well? Will the destruction of the container, trigger the corre...
scoped_ptr cannot be used in standard containers because it cannot be copied (which is required by the containers' interfaces). shared_ptr may be used, however. If you can't use C++11 and you're using boost already, consider the pointer containers which will perform somewhat better than a container of shared pointers. ...
4,763,953
4,768,368
Getting error " Attempted to read or write protected memory"
This is what is in the header file. /// Creates a new file geodatabase in the specified location. /// @param[in] path The location where the geodatabase should be created. /// @param[out] geodatabase A reference to the newly-created geodatabase. /// @return A long integer indicating whether the method finish...
I see two possible problems: The C++ code is using a wide string, the C# code an ANSI string The C++ code is using the std::wstring class, and not a c style null terminated string I don't think you can fix the second problem easily without changing the API on the C++ side
4,763,992
4,764,725
finding out what portion of a QGraphicsItem is visible in a QGraphicsView
I am trying to figure out how to do the mapping between what pixels i can currently see in a QGraphicsView and the actual pixel in the image that is a QGraphicsItem. For example, if my viewer is 50x50 and my image is 100x100, then when the image loads and is untouched, the 0,0 pixel of the image corresponds to the 0,0 ...
QRect portRect = yourGraphicsView->viewPort()->rect(); QRectF sceneRect = yourGraphicsView->mapToScene(portRect); QRectF itemRect = yourItem->mapRectFromScene(sceneRect); You may want to do an intersection of the resulting rect with your item's actual rect since the viewport may bt larger than the item.
4,764,019
4,764,109
How can I get the window position/size from a different program's window?
What I want to do is create a semi-transparent overlay over another program's window that displays stats on what is happening on the window in the background. I know how to do everything that I want to do with this program except find the properties of window such as position, size, and title so I can position my tran...
In Windows you have to use the Windows API. GetWindowRect can do it. http://msdn.microsoft.com/en-us/library/ms633519%28v=vs.85%29.aspx But first you have to get the another Window hwnd, with something like FindWindow
4,764,048
4,835,416
STL and release/debug library mess
I'm using some 3rd party. I'm using it's shared library version, since the library is big (~60MB) and is used by several applications. Is there a way at application startup to find out that release/debug version of library is used respectively for release/debug version of my application? Longer description The library ...
I believe that you have misread the documentation at the link you provide. In particular, you've misunderstood its purpose -- that section is entitled "Goals", and describes a number of hypothetical designs for a C++ debug library and the consequences of those designs in order to explain the actual design choices that...
4,764,325
4,764,375
C++ standard library - when should I use it and when shouldn't I?
I was wondering how often people actually use much of the standard c++ library, particularly the stuff in the <algorithm> and <numeric> headers. The text books seem to recommend them, but I haven't seen any of them used at all in various projects I've sifted through (coincidence?) and personally it seems easier to jus...
It's possible you're being lazy or stubborn. Personally, I use them all the time in production code. I don't do this to be fancy, and I don't do this because I like writing "space-age code." Rather, I do this because I am a paranoid programmer, and I know that production environments are hostile places that will muti...