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
3,625,955
3,625,997
Is there such a thing as a union of unions?
I came across the following code - what is the data type of col_8888 and why does it reference the union _colours? I googled unions, but I can't find a reference to this kind of declaration - it looks to me as though col_8888 is a "union of unions"? union _colours { uint8 c[3][4]; uint32 alignment; }; static ...
The type of col_8888 is union _colours, so it isn't a union of unions: it's just a union. In C, it is necessary to prefix the union name with union to use it. Alternatively you can use a typedef. Thus the following two declarations are equivalent: union _colours { uint8 c[3][4]; uint32 alignment; }; static...
3,625,981
3,626,170
can scoped_ptr and shared_ptr be mixed?
Imagine I create an instance of Foo on the heap in a method/function and pass it to the caller. What kind of smartpointer would I use? smartptr new_foo() { smartptr foo = new Foo(); return foo; } void bar() { smartptr foo = new_foo(); foo->do_something(); // now autodelete foo, don't need it anymor...
boost docs suggest they don't mix If you are transfering ownership then another option at the moment would be auto_ptr e.g. smartptr new_foo() { std::auto_ptr<Foo> foo = new Foo(); return foo; } void bar() { std::auto_ptr<Foo> foo = new_foo(); foo->do_something(); // now autodelete foo, don'...
3,625,998
3,626,099
What is the name and reason for member variable assignment between function name and curly braces?
Look at this code snippet: Size::Size(int iSetWidth, int iSetHeight) :iWidth(iSetWidth), iHeight(iSetHeight) { } Supposedly, this means the same thing as: Size::Size(int iSetWidth, int iSetHeight) { iWidth=iSetWidth; iHeight=iSetHeight; } Why would you use the former or the latter? And what is the name of the...
No, they don't mean exactly the same. When a constructor is executed, before entering the code block (the code between the curly braces), it constructs all object data members. What you do in the initializers (the code after the colon and before the curly braces) is to specify which constructors to use for those member...
3,626,062
3,627,687
dynamically loading static library?
Can a static libary *.a in Linux be dynamically loaded at runtime? I've read here that ...both static and shared libraries can be used as dynamically loaded libraries. How to dynamically load static library?
A static library is more or less just a collection of object files. If you want to use a static library in a program, you have to link the executable with it. The executable will then contain the static library (or the parts that you used). If you want to load a static library at runtime using dlopen, you will have to ...
3,626,213
3,626,315
Problem with my makefile
I think I have a problem with my makefile. I'm writing this program: Q2.cpp contains the main. Agent.cpp Agent.h Timing.cpp Timing.h RandomDouble.cpp RandomDouble.cpp And I'm using the header randoma.h in RandomDouble.cpp. I downloaded the randomaelf64.a file and I wrote this makefile: Q2 : Q2.o Agent.o Timing.o Ran...
You need to link against the library after all your own object files. The linker will only include as much of the library as it needs, and if there are no unresolved references yet, then none of the library will be needed. Change the first rule to: Q2 : Q2.o Agent.o Timing.o RandomDouble.o g++ -Wall -g RandomDoubl...
3,626,483
3,626,541
need some kind of operator.. c++
I want to store a sequence of string in a queue. This seems pretty simple if i use the member function push() queue test; string s0("s0"), s1("s1"); test.push(s0); test.push(s1); I am thinking about adding the strings in the queue in implicitly way. That mean, if I type the following sequence of string the e.g. opera...
While C++ doesn't allow you this, it allows you to do something very similar: test << s0 << s1; However, don't do this! If I see test.push(s0), I know exactly what it does, without even looking at the type of test. If I see test << s0 << s1;, I'd think test is a stream that's written to. Here's my three basic rules y...
3,626,589
3,626,760
Need help understanding operator overloading in C++
I'm trying to implement a structure which is basically a custom made hash table containing either nothing (NULL) or a pointer to a binary search tree object. Anyway, I'm having trouble figuring out how to do some things, such as setting the hash table, which is an array to NULL, and also memcpy'ing BST objects from one...
As I understand it, I think I have to overload the = and == operators to allow setting array elements to NULL, is this correct? No, not at all. You have described an array of BST * pointers, not of BST objects. NULL is already a valid value for a pointer to take, you don't need to change any C++ behaviour: BST ...
3,626,593
3,627,237
QT Qtestlib, Unit Test
If I were to create a unit test for class implementation using QTestlib ( trying to figure it out) how would I do it. (I know unit testing for the simple class below can be done other simple way I trying to understand QTestlib framework and whether its really what I want) Consider a simple class ( just to make things r...
Take a look at https://doc.qt.io/archives/qt-4.8/qtestlib-tutorial.html, it explains step-by-step how to create a test using QTestLib in a very accessible way. For Qt versions >= 5, the official Qt Test tutorial can be found at https://doc.qt.io/qt-5/qtest-tutorial.html.
3,626,625
3,630,264
Getting a buildable Boost extract with bcp
I'm using bcp to extract Boost.Archive from Boost. Unfortunately I can't build this extract. Boost.Archive is not a header-only library. bjam complains Unable to load Boost.Build: could not find "boost-build.jam" Is there any way to tell bcp to make the extract buildable with bjam (copy boost-build.jam to the right pl...
The right place would be any parent directory of the directory where you have extracted Boost.Archive (or that directory itself). That file shall contain a single line: boost-build /path/to/boost/tools/build/v2 ; where /path/to/boost needs to be substituted appropriately. This file tells bjam (the low level build engi...
3,626,948
3,627,077
Macros to avoid heap allocation ? In this case is that bad?
It's my first question there, and it's a noobish question :). I'm facing to a problem with C++ and Qt 4.6, because I want to factorize some of my code which is invoking some public slots of a QObject, through the QMetaMethod::invoke() method. The problem I'm facing to, is that the Q_ARG macro is defined as follow: #def...
And that is my problem, I don't want to do heap allocation in this method, because this will get called thousands of time (this is a request handling module). Don't second guess performances issues. Yes, stack allocation is faster and yes, one should avoid copies when they aren't needed. However, this looks l...
3,627,127
3,627,165
Writing cross-platform C++ Code (Windows, Linux and Mac OSX)
This is my first-attempt at writing anything even slightly complicated in C++, I'm attempting to build a shared library that I can interface with from Objective-C, and .NET apps (ok, that part comes later...) The code I have is - #ifdef TARGET_OS_MAC // Mac Includes Here #endif #ifdef __linux__ // Linux Includes ...
I'll address this specific function: bool probe() { #ifdef TARGET_OS_MAC return probe_macosx(); #elif defined __linux__ return probe_linux(); #elif defined _WIN32 || defined _WIN64 return probe_win(); #else #error "unknown platform" #endif } Writing it this way, as a chain of if-elif-else, eliminates the error b...
3,627,274
3,627,472
Function with variable arguments
Which disadvantages could I have if I want to use the function foo(int num, ...) to implement the variable number of arguments? I do know the first disadvantage that you can only use one data type. Is there any way else to do that?
There are multiple ways NOT to use ellipsis notation. Why ? Because of type safety a hazardous manipulations of the primitives (va_start, va_arg, va_next) that you can't really forward to another function etc... However, contrary to C, C++ provides template methods, which offer type safety and generic behavior, and thi...
3,627,370
3,627,530
How to create a class that is a widget that has a QTextEdit and a QToolBar above the text edit
My intent is to create a QTextEdit with its reach text controls. The controls I want to put in a toolbar. But I have difficulties with controling the layout. The problem is that the overlap if I put a QTextEdit in a QWidget (my class inherits QWidget) which has a toolbar. Another way I tried was the following: my class...
Place your toolbar and QTextEdit in a layout inside your class which inherits QWidget. Layouts (see QVBoxLayout) positions items relative to each other making sure they don't overlap. If you don't use a layout, all child widgets will be created at position (0,0), meaning at the top-left corner of the parent widget. QWi...
3,627,578
3,627,802
What is triple check locking pattern
Reference:- "Modern C++ Design: Generic Programming and Design Patterns Applied" by Andrei Alexandrescu Chapter 6 Implementing Singletons. Even if you put volatile then also it is not guaranteed to make Double Check locking pattern safe and portable.Why it is so? If some one can put any good link that explains what i...
Even if you put volatile then also it is not guaranteed to make Double Check locking pattern safe and portable.Why it is so? I'll try to provide some context. There are three (Boehm & McLaren) portable use cases for volatile in C++ none of which has anything to do with multithreading. Alexandrescu did come up with a...
3,627,738
3,627,780
How to insert an object to a map structure by a certain field?
i have an object - Employee, and i want to know how to insert this object to a map structure sorted by char* lastName field. Thanx. My map need to contain pointers to Employee objects not the objects themselves. the key is the last name of the employee, the map need to be sorted by the employees last name, should i use...
So you've got an std::map with a custom comparator function (you've overloaded the less than operator) and you want to insert objects so that they're in the right order? myMap.insert( make_pair( myKey, myEmployee ) ); where myKey is the key to your map. However, from the sound of your question it actually sounds like...
3,627,773
3,628,167
Splitting a word from a read file
I'm trying to read the contents of a text file into the attributes of a class. The file is structured in such a way that each line contains all the information needed for one object of the class. One line might look like: TYC 9537 00066 1 341.76920751 -88.32499920 8.762 9.294 mc1 hd 210531 0.385 8.80 P F5 5 ...
My suggestion would be to have a look at Boost.Spirit. It will allow you to express the format of your input string naturally, and will make future changes easier if (when!) the input format changes. As a bonus, it'll run much faster at runtime! http://www.boost.org/doc/libs/1_44_0/libs/spirit/doc/html/spirit/introduct...
3,627,941
3,627,979
Global Variable within Multiple Files
I have two source files that need to access a common variable. What is the best way to do this? e.g.: source1.cpp: int global; int function(); int main() { global=42; function(); return 0; } source2.cpp: int function() { if(global==42) return 42; return 0; } Should the declaration of the...
The global variable should be declared extern in a header file included by both source files, and then defined in only one of those source files: common.h extern int global; source1.cpp #include "common.h" int global; int function(); int main() { global=42; function(); return 0; } source2.cpp #i...
3,627,975
3,628,036
Replacement for <conio.h> in Linux
I need to transfer a windows C++ project to linux, however I am currently using MS <conio.h> which is not linux or standards compatible. What header do you recommend to replace it for use in Linux? I would prefer the answer is cross platform too.
There is an replacement version of Conio.h for linux based on NCurses. http://sourceforge.net/projects/linux-conioh/
3,628,040
3,628,195
Marshalling between C# and C++, and the Juggling of Responsibilities
what if I had a native C++ function in which, depending on the result of the function, the responsibility of deleting a certain pointer (delete[]) differs between the caller and the function. I would of course check for the return value and act accordingly in C++. Question is, what if the function was marshalled betwee...
No, simply setting a pointer allocated in native code to null will not free the memory. The CLR can only garbage collect memory that it knows about (aka managed memory). It has no idea about native memory and hence can't collect it. Any native memory which has ownership in a managed type must be explicitly freed. ...
3,628,309
3,661,713
MySQL error 2005 (using MySql C++ Connector):
I am trying to connect to a database using MySQL C++ Connector. I have used this code segment many times: driver = get_driver_instance(); connection = driver->connect("tcp://127.0.0.1:3306", "user", "pass"); and it has worked successfully, but now I am getting this error thrown from this code segment: "Unknown MySQL s...
After much struggling trying to fix character sets, I fixed it by using Connector/NET instead. This forum post: http://www.velocityreviews.com/forums/t713739-mysql-connector-driver-behaviour-with-visual-c-clr-cli-project.html#post4126062 lead me in the right direction.
3,628,345
3,628,523
Where can I find an efficient R-Tree implementation?
I'm looking for an R-Tree implementation, in C, Objective-c and even C++, which shall be efficient for searching the 2d rectangle in which a point falls ( memory efficiency would also be great, but I can sacrifice a bit more memory for time even while I am on an iPhone ). A good documentation will be appreciated too
Check out this page, it provides implementations (in C, C++, Java, etc.) for several variants (R*, R+, etc.).
3,628,364
3,628,564
Count of parameters in a parameter pack? Is there a C++0x std lib function for this?
I was just wondering if there was anything in the C++0x std lib already available to count the number of parameters in a parameter pack? I'd like to get rid of the field_count in the code below. I know I can build my own counter, but it just seems like this would be an obvious thing to include in the C++0x std lib, a...
Yes, you can use sizeof.... From the C++0x FCD (§5.3.3/5): The identifier in a sizeof... expression shall name a parameter pack. The sizeof... operator yields the number of arguments provided for the parameter pack identifier. The parameter pack is expanded (14.5.3) by the sizeof... operator. [Example: template<cla...
3,628,435
3,628,679
How do I check what version of java im using in c++
I have a testing script that checks what version of java the user is using and then executes some commands. But we are trying to convert all of our testing into cxxtests. I would like to know how to convert my version checking script into c++ code. I know I could just use the system() command but I would like that t...
You have to use the system() command, or a C++ library that will use the system() command. This task is much better done in a shell script than C++ code. If necessary, the shell script can call C++ code to do notifications, or whatever it is that's causing the reliance on C++.
3,628,452
3,628,645
Problem with my makefile
I have this Makefile and each line run OK separately, but when I do make I get this error: make: *** No rule to make target `CoalitionManipulation‬‬.cpp', needed by `CoalitionManipulation‬‬.o'. Stop. But I can see the CoalitionManipulation.o file, it means it exists! Bere is the makefile: CoalitionManipulation‬‬ : ‫‪...
make: *** No rule to make target `CoalitionManipulation‬‬.cpp', needed by `CoalitionManipulation‬‬.o'. Stop. Make can't find CoalitionManipulation.cpp. Is it where you told make it is?
3,628,498
3,628,548
How can I compile C++ code using another C++ program?
I want to create a program that modifies another c++ source,compiles it and runs the exe. I mean with something like gcc may be I can but on a windows os gcc may not be present. Is it possible?
I think your options are fairly limited for windows: Check for an install of a compiler (possibly limit this to a short list) and use that compiler Bring along a compiler in your application's install package
3,628,529
3,628,611
Should C++ 'interfaces' have a virtual destructor
Possible Duplicate: Destructors for C++ Interface-like classes Consider a simple example of a C++ abstract class, used to model an interface: class IAnimal { virtual void walk()=0; virtual ~IAnimal(){} }; Is it better to have the destructor, or not? I don't think the destructor can be pure virtual, at least my ...
You should always use a virtual destructor with interfaces. Case in point: IAnimal* animal = new Lion(); delete animal; Now what destructor is it going to use? Definately not the Lion's destructor because the interface doesn't know about Lion's destructor. So, have this if your interface has no memory management: vi...
3,629,073
3,629,135
Error after compiling .IDL file for Firefox accessibility
I've encountered a very annoying problem while working with Firefox MSAA (). I tried to compile IDL file from cmd but it failed. Then I added it to the project and ran build. After VS compiled interface file there were two C files - ISimpleDOMDocument_h.h and ISimpleDOMDocument_i.c I added those to the project. But now...
or the precompiled header is C++ and you are using it from C Which is your problem. Not sure how you got in this pickle, the mumble_i.c file is generated by MIDL and should not contain an #include "stdafx.h" directive. Don't edit the file. Right-click it in Solution Explorer window, Properties, C/C++, Precompiled ...
3,629,131
3,629,161
Do Strong Types prevent Buffer Overflow?
Do strong types, in this case char prevent buffer overflow? char a[100] char b[100] strcpy(a,unknownFunction); // unknownFunction could overflow b // since its length is unknown strcpy(b,a); // can b still overflow a with its now, // potentially overflowed size?
No. strcpy() just keeps going until it finds a null-terminator ('\0'). If b[] doesn't contain one, it will just walk through random memory until it eventually finds one.
3,629,205
3,629,228
What makes this code "endian independent"?
I came across the following code, and was told that it means that COL_8888_RED is "endian independent". Why? What makes this endian independent? (I have asked the original coder but they're not getting back to me ... heck maybe they don't know either.) union _colours { uint8 c[3][4]; uint32 alignment; }; stat...
This code is not "endian-independent" in a sense that platforms with different endianness will give you different values seen through COL_8888_RED. In other words, in the traditional understanding of endian-dependency this code is as endian-dependent as it ever gets. A different question is where is that COL_8888_RED i...
3,629,301
3,629,411
c++ sizeof( string )
#include <cstdlib> #include <iostream> int main(int argc, char *argv[]) { cout << "size of String " << sizeof( string ); system("PAUSE"); return EXIT_SUCCESS; } Output: size of String = 4 Does that mean that, since sizeof(char) = 1 Byte (0 to 255), string can only hold 4 characters?
It isn't clear from your example what 'string' is. If you have: #include <string> using namespace std; then string is std::string, and sizeof(std::string) gives you the size of the class instance and its data members, not the length of the string. To get that, use: string s; cout << s.size();
3,629,321
3,629,365
Try-Catch Block For C++ File-IO Errors Not Working
I'm very new to the world of C++ error handling, but I was told here: Checking for file existence in C++ ...that the best way to checks for file existence was with a try-catch block. From my limited knowledge on the topic, this sounds like sound advice. I located this snippet of code: http://www.java2s.com/Tutorial/C...
In C++ iostreams do not throw exeptions by default. What you need is ifstream myfile("test.txt"); if(myfile) { // We have one } else { // we dont }
3,629,322
3,629,721
linkage .a in eclipse
hi i am using eclipse ide for c++ and i have file.a and i want to do linkage to this file how i do this?
I assume you let eclipse manage your Makefile. Go to Project -> Properties -> C/C++ Build -> Settings ->Tool settings. At the top select [All configurations], to make sure that the library linked in all your builds. In the list select Libraries under the GCC C++ Linker. Add your library there, if your library filename...
3,629,332
3,629,502
boost.serialization and replace existing method of serializing std::wstring
I need to serialize std::wstring by my own method. How to force boost to use my methods of serialization instead of default methods? Thanks.
Untested, but you'd want to specialize boost::serialization::archive for your data type: namespace boost { namespace serialization { template<class Archive> void serialize(Archive & ar, std::wstring& s, const unsigned int version) { for (std::wstring::iterator it = s.begin(); it != s.end(); ++it) ar >> *i...
3,629,553
3,629,573
Dynamic array initialization
I want to make a dynamic array of foo, with the number of items being x. Arguments y and z are to be passed to the constructor of the item foo. I was hoping to do something similar to: Foo* bar = new Foo(y, z)[x]; However that produced the following compiler error: error: expected `;' before '[' token So after speak...
"I want to make a dynamic array" So use a std::vector, it exists for a reason. std::vector<foo> bar(x, foo(y, z)); This creates a dynamic array with x elements initialized to foo(y, z). The above makes copies of the second parameter, x times. If you want to generate values for the vector, use generate_n: std::vector<...
3,629,557
3,631,285
boost shared_from_this<>()
could someone summarize in a few succinct words how the boost shared_from_this<>() smart pointer should be used, particularly from the perspective of registering handlers in the io_service using the bind function. EDIT: Some of the responses have asked for more context. Basically, I'm looking for "gotchas", counter-int...
The biggest "gotcha" I've run into is that it's illegal to call shared_from_this from the constructor. This follows directly from the rule that a shared_ptr to the object must exist before you can call shared_from_this.
3,629,835
3,630,174
Why is std::function not equality comparable?
This question also applies to boost::function and std::tr1::function. std::function is not equality comparable: #include <functional> void foo() { } int main() { std::function<void()> f(foo), g(foo); bool are_equal(f == g); // Error: f and g are not equality comparable } In C++11, the operator== and operator...
Why is std::function not equality comparable? std::function is a wrapper for arbitrary callable types, so in order to implement equality comparison at all, you'd have to require that all callable types be equality-comparible, placing a burden on anyone implementing a function object. Even then, you'd get a narrow con...
3,629,858
3,629,954
Positioning an ifstream in very large files
I have to process very large log files (hundreds of Gigabytes) and in order to speed things up I want to split that processing on all the cores I have available. Using seekg and tellg I'm able to estimate the block sizes in relatively small files and position each thread on the beginning of these blocks but when they g...
The easiest way would be to do the processing on a 64-bit OS, and write the code using a 64-bit compiler. This will (at least normally) give you a 64-bit type for file offsets, so the overflow no longer happens, and life is good.
3,630,018
3,630,106
SDL Alternative with multiple windows and multiple display devices
I'm looking for an alternative to SDL that supports multiple windows on multiple display devices for OpenGL. Is there any mature library that provides this? I'm aware taht SDL 1.3 will support this but it seems that's a bit into the future.
SFML is probably what you are looking for. You should also take a look at OpenSceneGraph. It might seem like overkill, but it really is the best I've come across when it comes to rendering in multiple windows on multiple display devices. It's a complete graphics toolkit/engine, which might not be what you are looking f...
3,630,530
3,630,582
How to terminate program in C++
When I exit my C++ program it crashes with errors like: EAccessViolation with mesage 'Access violation at address 0... and Abnormal Program Termination It is probably caused by some destructor because it happens only when the application exits. I use a few external libraries and cannot find the code that causes it. ...
You should fix the problem. First step: find at check all functions you register with atexit() (not many I hope) Second step: find all global variables and check their destructors. Third Step: find all static function variables check their destructors. But otherwise you can abort. Note: abort is for Abnormal pro...
3,630,669
3,630,760
C++ minimax function
I have searched Google and Stackoverflow for this question, but I still don't understand how a minimax function works. I found the wikipedia entry has a pseudocode version of the function: function integer minimax(node, depth) if node is a terminal node or depth <= 0: return the heuristic value of node ...
That sample from Wikipedia is doing NegaMax with Alpha/Beta pruning. You may be helped by getting the naming straight: The basis is MiniMax, a literal implementation would involve 2 methods that take turns (mutually recursive), 1 for each side. Lazy programmers turn this into NegaMax, one method with a strategically ...
3,631,237
3,631,257
strtok - buffer overrun
c++ function, strtok() cplusplus.com Will this example suffer from buffer overrun if str is not terminated properly? /* strtok example */ /* source - cplusplus.com (see link below) */ #include <stdio.h> #include <string.h> int main () { char str[] ="- This, a sample string."; char * pch; printf ("Splitting strin...
Most string-handling functions will walk off the end if the string is not null-terminated. However, in your code example, str is terminated.
3,631,621
3,631,636
C++ templated function and forward declarations
I'm working on some code that compiles and links (and even has released commercial products) on Windows using MSVC. It doesn't compile with GCC though, I get the following errors: .../CBaseValue.h: In member function 'bool CBaseValue::InstanceOf()': .../CBaseValue.h:90:18: error: invalid use of incomplete type 'struct ...
This is ill-formed by the Standard, but no diagnostic is required. MSVC is fine not diagnosing this particular case (even when instantiation happens!). More specifically, the (C++03) Standard rules at 14.6/7 If a type used in a non-dependent name is incomplete at the point at which a template is defined but is comple...
3,631,655
3,631,720
Do I need to define ">>" operator to Use cin With Int32's?
I need to read exactly 32 bits from a file. I'm using ifstream in the STL. Can I just directly say: int32 my_int; std::ifstream my_stream; my_stream.open("my_file.txt",std::ifstream::in); if (my_stream && !my_stream.eof()) my_stream >> my_int; ...or do I need to somehow override the >> operator to work with int3...
The stream extraction operator (>>) performs formatted IO, not binary IO. You'll need to use std::istream::read instead. You'll also need to open the file as binary. Oh, and checking std::istream::eof is redundant in your code. int32 my_int; std::ifstream my_stream; my_stream.open("my_file.txt",std::ios::in | std::ios...
3,631,672
3,631,724
ADL and friend injection
Consider this code: template <int N> struct X { friend void f(X *) {} }; int main() { f((X<0> *)0); // Error? } compilers seem to heavily disagree. (MSVC08/10 says no, GCC<4.5 says yes, but 4.5 says no, sun 5.1 says yes, intel 11.1 says yes too but comeau says no (both are EDG)). According to "C++ Templates - The c...
The Standard says at 14.7.1/4 A class template specialization is implicitly instantiated if the class type is used in a context that requires a completely-defined object type or if the completeness of the class type affects the semantics of the program; in particular, if an expression whose type is a class template sp...
3,631,855
3,631,913
QT c++ draw point qpainter qgraphicscene
Hell-o all, Im new to qt and I am having trouble drawing one single point. I have a big qMainWindow that eventually calls a QgraphicsScene and inside of it I need to draw a single point, one little pixel, that is all I want, I want to use a QPainter but Im having trouble instantiating one. Any ideas??
Sample code of what you're trying to do would help alot here. QPainter use: Construct your QPainter object pointing at a canvas object, and then call painter_obj.drawPoint(x,y);. Note that the QPainter needs to be created on the stack, not the heap, so that the destructor of the object can kick off the actual drawing....
3,631,858
3,631,868
C++ : Suggest names for mutating and non-mutating versions of a member function
Let's say I have an Image class and I want to provide some operations on the image, like scaling, rotating etc. I want to provide 2 types of functions for each operation. One that modifies the object and other that does not. In Ruby, there are functions that end in ! and indicate that this one is going to modify the ar...
One option would be to use Scale for the mutating version and ScaleCopy for the non-mutating version, since it returns a copy of the original with the operation performed on the copy. Another option would be to make the non-mutating version a non-member function. For example, Image Scale(Image im, double scale_factor)...
3,632,011
3,632,232
What is g++-3 / gcc-3?
Trying to use make from cygwin using g++ I was getting Access Denied error messages. Googling the error message I found a positing referring to g++-3 and gcc-3 http://www.linuxquestions.org/questions/linux-software-2/cygwin-g-3-exe-gcc-3-exe-corrupted-to-g-3-exe-dam-and-gcc-3-exe-dam-769722/)... Changing the compile...
To answer your point in the comment to Pete's answer, the gcc you type on the terminal is just a symlink to the actual gcc binary. It makes it easy to upgrade since you can just point the symlink to something else. $ which gcc /usr/bin/gcc $ ll /usr/bin/gcc lrwxrwxrwx 1 root root 7 2010-09-01 11:10 /usr/bin/gcc -> gc...
3,632,038
3,632,065
Can I use Qt without qmake or Qt Creator?
I want to program using Qt, but I don't want to use special compilers or IDE such as Qt Creator and qmake. I want to write with Kate and compile with g++. Can I compile a program that uses Qt with g++? How do I compile it with g++?
Sure you can. Although it is more convenient with qmake or CMake, you can do: CXXFLAGS += -Ipath_to_your_qt_includes LDFLAGS += -Lpath_to_your_qt_libs LDLIBS += -lqt-mt (for Qt3) or LDLIBS += -lQtCore -lQtGui (for Qt4, add what you need) my_prog: my_prog.cpp (in a makefile) Update - invoking moc: Quote from moc ma...
3,632,203
3,632,304
g++, doubles, optimization and a big WTF
bug in my gcc? bug in my code? both? http://files.minthos.com/code/speedtest_doubles_wtf.cpp Somehow, it manages to "optimize" a function that results in the array of doubles being zeroed out into taking 2.6 seconds on my q6600, instead of the 33 ms the more complex function takes to fill the array with something somew...
Line 99: memcpy(floats, ints, sizeof(floats)); is partially initializing floats[] effectively with floating point garbage. The rest remain zero. This stems from replacing the floats with integer bitmaps and then subsequently interpreting them as doubles. Perhaps the overflows and underflows are affecting performanc...
3,632,327
3,634,304
Proper way to pan and move camera in OpenGL?
Right now I'm panning by glRotating before rendering everything, and i'm moving the camera by gltranslating. I feel as if this is wrong since im essentially moving the scene, not the camera. What is the proper way to move the camera? Thanks
Actually 'moving the scene around the camera' is the proper way in OpenGL. This is due to the fact that OpenGL combines the view and model matrices into the modelview matrix. (look here for more details) Obvious the lookat function (as mentioned above) is an easy way to move a (virtual) camera but i found that it doesn...
3,632,349
3,632,482
Why would a friend function be defined as part of a struct - boost thread_data?
I'm trying to understand some boost code which is causing PC-Lint grief and uses the friend keyword in a way which I didn't think was legal C++ but compiles OK in VS2008. I thought I understood friend as a way to declare classes and functions. I didn't think it was legal to use on a function definition like this. Howev...
It is perfectly fine to define 'friend' functions inside a class definition. In this particular case, since the friend function takes a parameter of type thread_data_base, the friend function definition is visible only in case of ADL (argument dependent lookup) $3.4.2 when called from outside the lexical scope of the c...
3,632,368
3,634,089
Projecting a texture in OpenGL
FIXED by setting near clipping plane to 1, rather than 0 (not sure why it was like that to start with). See the question for skeleton code, and Adrian's answer for how and why this works. I have a few different camera positions, and my scene consists of a single quad. The quad is such that it projects exactly onto the ...
Take a look at the documentation for glTexGen (in your case, you want to use GL_EYE_LINEAR along with an appropriate set of coefficients as described below) and glEnable(GL_TEXTURE_GEN_*). When you enable the texgen feature for particular texture coordinate components (S, T, R and/or Q), the values you specify for thos...
3,632,533
3,632,700
set/get methods in C++
Java programmers and API seems to favor explicit set/get methods. however I got the impression C++ community frowns upon such practice. If it is so,is there a particular reason (besides more lines of code) why this is so? on the other hand, why does Java community choose to use methods rather than direct access? Thank ...
A well designed class should ideally not have too many gets and sets. In my opinion, too many gets and sets are basically an indication of the fact that someone else (and potentially many of them) need my data to achieve their purpose. In that case, why does that data belong to me in the first place? This violates the ...
3,632,746
3,632,753
What does this C++ syntax mean and why does it work?
I was looking through the source of OpenDE and I came across some wierd syntax usage of the array indexing operator '[]' on a class. Here's a simplified example to show the syntax: #include <iostream> class Point { public: Point() : x(2.8), y(4.2), z(9.5) {} operator const float *() const { return...
p is being converted implicitly into a const float* const, which points to x. So *p is x, *(p+1) is y, and so on. It's a pretty weird idea (and confusing!) to do it this way, of course. It's usually preferable to store x, y, and z in an array and have a function to get the entire array if they really want to do things ...
3,632,784
3,633,038
C++ XLST transform not working using MSXML 3.0
I'm new to C++ and inherited the following code that is supposed to transform the given XML using the XSLT file to just spit out the text values. It loads both the XML and XSLT fine and the transformnode() call returns success but no transformation has been applied. The original output at the bottom contains the origin...
Fixed it. It was reassigning m_pXslt to equal the XML is was supposed to be validating. Someone has been copying and pasting.
3,632,818
3,632,826
Forward Declaration vs Include
Consider the following two scenarios (Edited just to complete the whole question and make it clearer) Case 1: (doesnt compile as rightly mentioned below) //B.h #ifndef B_H #define B_H #include "B.h" class A; class B { A obj; public: void printA_thruB(); }; #endif //B.cpp #include...
Case 1 will produce an "incomplete type" error when you compile B.cpp. Because class B contains a class A object, the definition (and in particular the size) of class A is required to be complete before the definition of class B. Alternatively, you could choose to make some_variable a pointer or reference to class A, ...
3,632,994
3,633,009
loading binary data for an encryption program
how do i load a file into my program so it's just binary. i want to read the binary from a file then save it to another one so the file will be a clone of the first file (if it's a exe it will run, etc). i would like to store the data in a array or string so i can edit it before i save it. im using windows 7 , microsof...
Something like: [Edit: added necessary headers: ] #include <fstream> #include <algorithm> #include <vector> #include <ios> // define some place to hold the data: std::vector<char> binary_data; // open the file and make sure we read it intact: std::ifstream file("filename.exe", std::ios::binary); file.unsetf(std::ios_...
3,633,118
3,633,206
getting started with http tunneling
I will soon start work on software which runs on different machines and communicates over the network. I'd like the communication to happen using HTTP tunneling, so no firewall ports need to be opened by the user. This software will be written in C++. My problem is I don't really know where to start looking for resou...
The advantage of using something like WCF is that anomolies of "passing through" some routers are all handled for you. I'm talking about deep-packet inspection that some routers have, that will identify material you send as "not acceptable" if it doesn't look like clean HTML. On the other hand, working with WCF in C++...
3,633,284
3,640,234
Largest representable negative floating-point number
What is a platform-independent way of specifying the largest representable negative floating-point number? We found an algorithm that broke when run on a PS3's SPU, but worked fine when compiled for the PPU: float x = -FLT_MAX; /* stuff */ if (x > 0.0f) { // If x is unchanged, code is executed on SPU } Essentially...
Without knowing what's in /* stuff */, I don't think your problem can be fully addressed here. There's a good set of slides on the problems inherent in floating point calculation here: http://realtimecollisiondetection.net/pubs/GDC07_Ericson_Physics_Tutorial_Numerical_Robustness.ppt - there may be some hint for you in ...
3,633,419
3,633,459
What is the function try block handler?
I came across this question recently - What is function try block handler? Also, where would it be useful?
a function written like this: void fun () try { ..... ..... } catch(SomeException & e) { .... .... } is called a function try block. This is typically used with constructors with initialization lists to catch the exception thrown during the construction of an object constructed in the initialization list.
3,633,477
3,633,482
Implicit Conversion Operator Overloading syntax
I'm an intermediate C++ user and I encountered the following situation. The class definition shown below compiles fine with a g++ compiler. But I cannot put my finger on what exactly the whole syntax means. My guess is that the function operator int() returns an int type. Moreover, I cannot figure out how to use the ...
operator int() is a conversion function that declares a user-defined conversion from A to int so that you can write code like A a; int x = a; // invokes operator int() This is different from int operator()(), which declares a function-call operator that takes no arguments and returns an int. The function-call operato...
3,633,549
3,633,613
Operator overloading '+' operator in C++
I am facing a problem with the code below which is run on Visual Studio 2008. How do I write the function definition for operator + when you have a statement to be overloaded as follows? class Distance { private: int feet,inches; }; main...... Distance Obj, Obj1(2, 2); Obj = 3 + Obj1; // This line here ...
Generally an operator of that form would be declared as: Distance operator+(int lhs, const Distance& rhs) { // Assuming the int value represents feet return Distance(rhs.feet + lhs, rhs.inches); } You'd probably also want to define the symmetric: Distance operator+(const Distance& lhs, int rhs) { // Assuming the...
3,633,705
3,633,860
How to extract selected area of the gui component to PDF in QT
I need to make the tool like Snagit and to take the picture the selected area of the component. I'm searching how to make this tool in Qt. I firstly prefer using Qt native library but if there is no library which fullfills this requirement, any good c++ libray can be accepted for me. Any help will be appr...
I'm not sure to understand exactly what you want. I assume you want to take a screen shot ? and then put this picture into a PDF document. To take a screenshot with Qt, have a look at this : http://doc.qt.nokia.com/4.0/widgets-screenshot.html This will show you how to take a screenshot (using QDesktopWidget) and get a ...
3,633,754
3,633,891
c++ vectors causing break in my game
my works like this i shot airplanes and if the shot toughed an airplane it change there positions(airplane and the shot) than it will delete them. if i toughed an airplane the airplane position gets changed. than it gets deleted than my health reduces. well that works well expect that it breaks when i have about 2-4 ai...
Well I just had a quick look at that monstrosity, and I'm not going to look too far into it but right off the bat I see a problem. I don't know if this is related to this particular problem you are asking about, but this type of thing isn't going to work the way you think: for(long index=0; index < (long)RegularShots.v...
3,634,169
3,634,671
How Can I access Windows Service Object by Another Programme
I have a windows service which is creating a Named Pipe in it's service main Function. The code snippet is below: void WINAPI ServiceMain(DWORD argc, LPTSTR *argv) { DWORD status; DWORD specificError; m_ServiceStatus.dwServiceType = SERVICE_WIN32; m_ServiceStatus.dwCurrentState = SERVICE_START_PENDING; m_Serv...
I hope you not only use CreateNamedPipe but also ConnectNamedPipe. It is also very important to set Security and Access Rights to the pipe (see lpSecurityAttributes parameter of the CreateNamedPipe) to be able to communicate with the pipe created by another user (typical situation if you create pipe inside of a windows...
3,634,203
3,634,493
Why are templates so slow to compile?
Large templated projects are slow to compile, the STL being a main culprit of this it seems from empiric evidence. But, why is it slow to compile? I've optimized builds before by watching for header includes and by combining compilation units, but I don't get why template libraries are quite so slow to compile.
Templated code has to be taken as another language to generate C++ code. In this way of thinking, templated code has to be parsed, executed, then the compiler can generate C++ code that has to be added to the current unit file, and then we can compile the whole C++ code. I've heard that not all compilers do this exactl...
3,634,251
3,634,316
C++ - how to send a HTTP post request using Curlpp or libcurl
I would like to send an http post request in c++. It seems like libcurl (Curlpp) is the way to go. Now, here is a typical request that am sending http://abc.com:3456/handler1/start?<name-Value pairs> The name values pairs will have: field1: ABC field2: b, c, d, e, f field3: XYZ etc. Now, I would like to know how to...
Don't have experience with Curlpp but this is how I did it with libcurl. You can set your target url using curl_easy_setopt(m_CurlPtr, CURLOPT_URL, "http://urlhere.com/"); POST values are stored in a linked list -- you should have two variables to hold the begin and the end of that list so that cURL can add a value to...
3,634,305
3,634,437
Efficient pointer to integer mapping and lookup in C++
I want to map pointer to integer for purpose of serialization. The pointers may be of different types and may point to polymorphic objects possibly using multiple inheritance. I need to query the map to know if the pointer is stored in it and if it is, then what is the associated integral value. What is the correct way...
You are in luck with your initial idea of using map<void*, int>. Although you are right that operator< is not defined for pointers, the predicate used by std::map<> is std::less<> and the C++ standard requires that std::less<T*> also works for arbitrary pointers. Quote from the C++ standard to support this ([lib.compar...
3,634,326
3,634,415
Does endianness have an effect when copying bytes in memory?
Am I right in thinking that endianess is only relevant when we're talking about how to store a value and not relevant when copying memory? For example if I have a value 0xf2fe0000 and store it on a little endian system - the bytes get stored in the order 00, 00, fe and f2. But on a big endian system the bytes get store...
memcpy doesn't know what it is copying. If it has to copy 43 61 74 00, it doesn't know whether it is copying 0x00746143 or 0x43617400 or a float or "Cat"
3,634,417
3,634,486
Question regarding pragma Ident
Can you please explain what is the meaning of each key in the following declaration #pragma ident "%Z% %M% v%I% (c) GEMS %G%" I am using Clearcase Revision Control System
Pragmas are compiler dependent stuff. This one looks specific to Sun Studio's compiler. From the documentation: Use ident to place string in the .comment section of the executable. This would mean the executable will contain a string after suitable transformation of the variables (i.e. %Z% etc).
3,634,482
3,634,608
String array and Arraylist/list in C++
I am new to C++, can anybody provide me some sample program's for String array and Arraylist/list in C++ Thanks in Advance.
You can refer the following urls, 1. String 2. Character Sequence 3. STL
3,634,564
3,634,934
type-safety by using the ellipsis notation
it had been several times discussed in other subjects that it is not recommended to use variadic function because the compiler can't check the type of provided arguments. But what about if the user knows exactly the type can be e.g. std::string. Could anything still go wrong here too? regards
You may only pass "plain old data" (POD) types as variadic arguments. These are basic types (including pointers), and simple aggregates of other POD types; anything with non-trivial constructors, destructor, base classes or virtual functions are not POD. Passing a non-POD type gives undefined behaviour. If you really w...
3,634,660
3,634,703
How are vtables implemented in c++ and c#?
Lets have this situation (in c++, in c# classes A,B are interfaces): class A { virtual void func() = 0; }; class B { virtual void func() = 0; }; class X: public A, public B { virtual void func(){ var = 1; } int var;}; X * x = new X; // from what I know, x have 2 vtables, is this the same in c#? A * a = (A*)x; // a == ...
Not to be overly pedantic, but the C# compiler does not get involved at this level. The Entire type model, inheritance, interface implementation etc. is actually handled by the CLR more specifically the CTS (Common Type System). .NET compilers mostly just generate IL code that represents intent which is later executed ...
3,634,766
3,634,784
"printf" on strings prints gibberish
I'm trying to print a string the following way: int main(){ string s("bla"); printf("%s \n", s); ....... } but all I get is this random gibberish. Can you please explain why?
Because %s indicates a char*, not a std::string. Use s.c_str() or better still use, iostreams: #include <iostream> #include <string> using namespace std; int main() { string s("bla"); std::cout << s << "\n"; }
3,634,781
3,635,461
Android NDK Confusion
I've been playing around with the NDK recently, finding that many of the tutorials available online really don't help. I've been using this tutorial and I've got it running great. However. Is this the correct use of the NDK? I mean if I have a game say with many classes all in C++ that I wish to port over to the androi...
I'd say your way isn't wrong, but be aware that passing data between Java and C/C++ code is a time consuming thing. Because of that I would suggest you write the most of the code actually in C/C++ and just call C/C++ functions from Java if it can't be avoided. For example you will need to pass data back for the GUI. Es...
3,634,834
3,634,850
How to test if a constant fits into a type while compiling?
I'd like to add compile time asserts into the following C++ code (compiled with Visual C++ 9): //assumes typedef unsigned char BYTE; int value = ...; // Does it fit into BYTE? if( 0 <= value && value <= UCHAR_MAX ) { BYTE asByte = static_cast<BYTE>( value ); //proceed with byte } else { //proceed with great...
You can test in the compile-time assert that ( (1 << (sizeof(BYTE)*CHAR_BIT)) - 1 ) == UCHAR_MAX. (I assume that you're not asking how to do a static assert - there are several ways, see here)
3,634,915
3,635,024
What does "data abstraction" exactly mean?
What does data abstraction refer to? Please provide real life examples alongwith.
Abstraction has two parts: Hide details that don't matter from a certain point of view Identify details that do matter from a certain point of view and consider items to be of the the same class if they possess those details. For example, if I am designing a program to deal with inventory, I would like to be able to ...
3,635,260
3,636,074
"filter" higher order function in C++
Does C++ standard library and/or Boost have anything similar to the filter function found in functional languages? The closest function I could find was std::remove_copy_if but it seems to be doing the opposite of what I want. Does boost::lambda have any function to get a negated version of my predicate (similar to not...
Include <functional> for std::not1 and try cont.erase (std::remove_if (cont.begin (), cont.end (), std::not1 (pred ())), cont.end ());
3,635,343
3,635,357
parse an unknown size string
I am trying to read an unknown size string from a text file and I used this code : ifstream inp_file; char line[1000] ; inp_file.getline(line, 1000); but I don't like it because it has a limit (even I know it's very hard to exceed this limit)but I want to implement a better code which reallocates according to the siz...
The following are some of the available options: istream& getline ( istream& is, string& str, char delim ); istream& getline ( istream& is, string& str );
3,635,414
3,635,508
boost::threads execution ordering
i have a problem with the order of execution of the threads created consecutively. here is the code. #include <iostream> #include <Windows.h> #include <boost/thread.hpp> using namespace std; boost::mutex mutexA; boost::mutex mutexB; boost::mutex mutexC; boost::mutex mutexD; void SomeWork(char letter, int index) { ...
If you have two different threads waiting for the lock, it's entirely non-deterministic which one will acquire it once the lock is released by the previous holder. I believe this is what you are experiencing. Assume B10 is holding the lock, and in the mean time threads are spawned for B11 and B12. B10 releases the l...
3,636,115
3,636,234
Uniquely identify PC based on software/hardware
For a requirement to generate per-PC license keys, I need some code which will return a stable and (near) unique key on any PC. It doesn't have to be guaranteed unique, but close. It does need to be reasonably stable though, so that a given PC always generates the same result unless the hardware is substantially change...
I would just go with the MAC address method; when the wireless / LAN cards are turned off they still show up in Network Connections. You should therefore still be able to get the MAC. Consider this: Any time you'd be able to contact your webserver or whatever you're cataloging these IDs with, the user is going to have ...
3,636,421
3,708,522
Install DLL Server on x64 Windows
I need to install a shell extension (64-bit DLL server) for the contextual menu on any version of Windows x64. I'm able to register the extension just fine (regsvr32) if on the target system I have installed the redistributable files for VS 9.0 SP1 x64 (setup file from Microsoft). However I have to make a setup and can...
I resolved my problem by statically linking the required libraries. The size is much smaller than having the executable + dlls. I can do that for my shell extension but not for the main application since there are conflicts with the included libraries. Thanks Billy ONeal for the suggestion, I was ignoring the obvious.
3,636,715
3,636,856
Cross platform sound API for games?
Is there an API only for sound? APIs such as Allegro or SDL provide too much for my needs. I simply need a library that can do something like: InitSound(); Sound *door = LoadSound("door.wav"); PlaySound(door,volume); It would also be great if it could support compressed formats such as Vorbis or MP3.
I'm a big fan of the SFML library. It does provide additional graphics and network features, but what is relevant to this question, is that it also has neat audio package. Audio features are: Uses hardware acceleration whenever possible Can load and save standard sound formats: Ogg, WAV, FLAC, AIFF, Au, RAW, paf, 8SV...
3,636,723
3,636,829
How to format the selected text in a QTextEdit by pressing a button
I want to format a selected text in a QTextEdit by clicking a button. For axample I want to make it bold if it is not-bold, or not-bold if it is bold. Please help me with an example. EDIT: Actually I have found already a code - qt demo for text editor which does what I need: void MyTextEdit::boldText(bool isBold) //thi...
The textCursor() returns a textCursor that contains the position of the cursor you use in the textEdit, see QTextCursor in Qt classes. So by selecting the text that is contained by the cursor start and end position, you have the text that is currently highlited. As for the mergeCharFormat, I guess that it is used to ap...
3,636,820
3,636,882
How can I programmatically distinguish hard links from real files in Windows 7?
I have a difference between files size and used disk space (total file size is even more than disk size). I suppose because there are many hard links exist (to WinSxS components) in Windows 7/Vista. But how can I programmatically distinguish hard links from real files in Windows 7?
You can't, because all files are hard links. No. Really. A file is just a hard link to a data chunk -- a listing in a directory. (Perhaps you mean symlinks? You can distinguish those...) Use the builtin methods Windows provides for calculating used space instead. EDIT: Reference (emphasis mine) The link itself is only...
3,636,885
3,637,006
Assign values to keywords in usertype.dat in visual studio?
I found that if you create a file called "usertype.dat" in visual studio's IDE dir, that you can specify keywords that will appear in blue like "new" or "int". Is there a way to assign values to these? I don't want to have to use "#define [keyword] [value]" in every single file that I use.. Specifically, I would like t...
One option you would have is to go to the project (or file) properties page and add a preprocessor definition of null=0. Having said that, I agree with @AshleysBrain that this is bad form and you're better off using the already defined item.
3,637,065
3,637,799
Win API Interlocked operations for 32-bit int type
If we have: __int32 some_var = 0; What is the best (if any) way to call InterlockedExchange, InterlockedIncrement and other interlocked functions which require LONG* for some_var ? Since, there is guarantee that LONG is 32 bit on any Windows, it's probably safe just to pass (long*) some_var. However, it seems to me qu...
Just do assert(sizeof(LONG) == sizeof(some_var)) and only worry about the problem when the assertion fails. YAGNI. As long as the assertion holds, you can use reinterpret_cast<LONG*>(&some_var).
3,637,236
3,637,292
Array index vs. "user documentation" terminology?
I have an "array" of bytes that is referenced in some high-level client/developer documentation (which does not contain any programming language or environment specific information). In this document, bytes are currently referred to as "byte 3" or "byte 17", etc. The development environment is C/C++ and the bytes are s...
One possibility is to just directly state where you're starting counting. Another possibility is to use things like "first byte", "seventeenth byte", and so on. A third (the one I usually prefer) is to speak in terms of offsets from the base address.
3,637,280
3,637,453
Statc compiling GLUT?
I have gotten the GLUT 3.7 source and opened the MSVC project. I switched DLL to static lib in the project settings and got a lib. I then linked against it in my application, and added the GLUT_STATIC preprocessor definition. It creates the window and renders one frame of my game and that's it. Whereas the game runs ju...
Just an idea: it might be because of a duplicate symbol. Could you try to rename that update function?
3,637,295
3,637,395
C++: how to create thread local/global variable
in this code: int foo() { static int x; } is the x global to all threads or local in each thread? Or does that depends on a compiler flag and/or the compiler, so I cannot really know what it is from the code? Several questions (all of them independent from compiler and compiler flags and OS): How can I create a st...
x is global to all threads. Always, independent of compiler and/or its flags. Independent of whether this is in C++11 or C++03. So if you declare a regular global or static local variable, it will be shared between all threads. In C++11 we will have the thread_local keyword. Until then, you can use thread_specific_ptr ...
3,637,318
3,637,472
Slow shared memory performance when moved to 64-bit OS
I am having an issue with a 32-bit legacy app running on 64-bit windows. The app in question uses CreateFileMapping to create shared memory. When this is run on 64-bit Windows any attempt to access this shared memory from another process takes about 1 second. The shared memory is created using page protection flags: fl...
You are disabling the file system cache with that flag. Yes, that makes an enormous difference, it forces the OS to work with the disk driver and read sectors directly. Cylinders cannot be read and cached, disabling the optimization that makes reading tracks without having to move the read head so cheap. And lazy wr...
3,637,545
3,637,614
How to create an ASN.1 DER-encoded blob simply
Greetings, How can I simply encode some binary data into an ASN.1 DER-encoded blob? I'm using C/C++, and I figure it should be possible to simply prefix the binary blob with some appropriate bytes that signify that the data is of type octet string and is of a given length (and in a sequence of length 1 I guess). Backg...
I would use the ASN.1 Compiler. People abuse ASN.1 because it is a way to encode data structures. Any time you have a C/C++ program working with a data structure that the attacker controls problems like; buffer overflows and integer overflows, come into play. ASN.1 is no more insecure than lets say XML or JSON or ...
3,637,754
3,637,782
Reference Member Required to be Const?
In this simple example, why do I need to make 'member' const in order to get this to compile? struct ClassA { ClassA(int integer) {} }; struct ClassB { ClassB(int integer): member(integer) { } const ClassA& member; }; int main() { ClassB* b = new ClassB(12); return 0; } Otherwis...
The reason why is that what's actually happening here is you're using an implicit conversion from int to ClassA in the initialization of member. In expanded form it is actually doing the following member(ClassA(integer)) This means that the ClassA instance is a temporary. It's not legal to have a reference to a temp...
3,637,918
3,644,804
DES implementation in C/C++/C#
I am looking for existing implementations of different types of DES in C/C++/C##. My running platform is Windows XP/Vista/7. I am trying to write a C# program which will encrypt and decrypt using the DES algorithm. I need some implementations with which i can verify my code output to see if i did the things in right or...
Thanks for the input.. I found these links where in I could calculate the DES values for giving input. http://www.unsw.adfa.edu.au/~lpb/src/DEScalc/DEScalc.html http://www.riscure.com/tech-corner/online-crypto-tools/des.html
3,637,962
3,638,136
storing mem_fun in a standard container
Is there a way to create a vector< mem_fun_t< ReturnType, MyClass > > ? The error i'm seeing is: error C2512: 'std::mem_fun1_t<_Result,_Ty,_Arg>' : no appropriate default constructor available
You certainly can create such a vector. #include <vector> #include <functional> #include <iostream> struct MyClass { int a() { return 1; } int b() { return 2; } }; int main() { std::vector<std::mem_fun_t<int, MyClass> > vec; vec.push_back(std::mem_fun(&MyClass::a)); vec.push_back(std::mem_fun(&M...
3,637,992
3,638,138
datatype info over socket; dynamic initialize?
I have data coming over a socket that looks like this: (h)(int,char,float,int,char)(/h)(d)(2,a,1.32,45,d)(3,d,3.45,32,a)(/d) The datatype of the data arriving is dynamic and is only known when the header is received. I then have to create corresponding std::vectors to store the data. In this case, two int, two char an...
std::vector can't do this by itself. It sounds like you need something that resembles Boost.Any or Boost.Variant, you'll need to decide which. If you have a small number of types, a simple union might work as well.
3,638,237
5,405,221
Polymorphically catching an exception in a -fno-rtti shared library on Mac OS X
I'm building a shared library with f-no-rtti. Internally, this library throws std:invalid_argument and catches std::exception, but the catch clause is never entered. The following code reproduces the problem (g++ 4.2, Mac OS X 10.6): // library.cpp: exports f(), compiled with -fno-rtti #include <stdexcept> #include <io...
Turns out this a bug on Apple's gcc. They've recently replied to my bug report saying it won't be fixed, though.
3,638,269
3,638,298
(Non) Static Object in Loop
In a book there is an example about static/non-static objects. char buf[MAX]; long count=0; int i=0; while(i++<=MAX) if(buf[i]=='\0') { buf[i]='*'; ++count; } assert(count<=i); It is said that sometimes the code will write past the end of the buf array into count and make the assertion to fail...
The example counts on a specific layout of the variables in memory, namely that count comes just after buf. By making count static, it gets placed in a different part of memory and something else gets clobbered instead. The problem didn't go away, the symptoms just changed.
3,638,317
3,638,335
Why does a struct consisting of a char, short, and char (in that order), when compiled in C++ with 4-byte packing enabled, come to a 6-byte struct?
I thought I understood how C/C++ handled struct member alignment. But I'm getting strange results for a particular arrangement in Visual Studio 2008 and 2010. Specifically, I'm finding that a struct consisting of a char, short, and char is compiled into a 6-byte struct, even with 4- or 8-byte packing enabled. I am at a...
From the MSDN documentation for #pragma pack (where n is the value you set): The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller. sizeof(short) is two bytes, which is smaller than the packing value of four bytes that you set, so...
3,638,406
3,638,438
Ensure multiset is reordered when objects change
I have a multiset with a custom predicate function, e.g multiset<MyClass *,MyCompFunc> where MyCompFunc looks at an attribute on the MyClass objects. During the progress of the application, the objects might change in a way that should cause them to be reordered. What's the correct way to get the multiset to become reo...
The usual is to remove, update, and re-insert. Virtually anything else at least temporarily violates the primary invariant of a set/multiset, which clearly isn't a good thing.