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,365,424
3,365,440
Besides Boost, where can I get a single-file smart pointer implementation for C++?
I want to start using smart pointers in my code but I don't really want to use Boost because it's so huge. Can anyone recommend a simple, one-file smart pointer implementation? Thanks, Boda Cydo.
Unfortunately, smart pointers are not all that simple, so the implementation may be quite complicated. Having said that, if you are using g++ you get things like shared_ptr without having to use Boost: #include <memory> using namespace std; int main() { shared_ptr <int> p( new int ); } but you will have to compil...
3,365,515
3,365,554
Is it possible to use libraries build under VC++ in cygwin gcc build?
I have libraries which are build using VC++. I want to use the same libraries in a program and build in cygwin gcc compiler. Is this scenario will work?
Since C++ doesn't have a standardized ABI, and since Visual C++ and g++ in particular almost certainly have different ABIs, I don't think you can do this. Your only real option is to restrict yourself to C, not C++. Edit: If all of the libraries that you're using are straight C (extern "C", in C++ terms), then you oug...
3,365,569
3,365,590
Comparing command parameter with argv[] is not working
I am trying to compare the parameter of command with argv[] but it's not working. Here is my code. ./a.out -d 1 In main function int main (int argc, char * const argv[]) { if (argv[1] == "-d") // call some function here } But this is not working... I don't know why this comparison is not working.
You can't compare strings using ==. Instead, use strcmp. #include <string.h> int main (int argc, char * const argv[]) { if (strcmp(argv[1], "-d") == 0) // call some function here } The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the r...
3,365,651
3,366,893
C++ BOOST: windows shared memory get_size() returns zero
The below is from the official BOOST docs. Why do I always get size of zero when calling region.get_size() ? What am I doing wrong? int main(int argc, char *argv[]) { //Create a native windows shared memory object. windows_shared_memory shm (create_only, "MySharedMemory", read_write, 1000); //Map the whole shar...
I think I got the answer: From boost docs: Native windows shared memory has also another limitation: a process can open and map the whole shared memory created by another process but it can't know which is the size of that memory. This limitation is imposed by the Windows API so the user must somehow tr...
3,365,753
3,385,920
Layout direction for Arabic is not determined based on the locale (Mac and Linux)
Has anyone managed to have the correct layout direction (left-to-right and right-to-left) be inferred from the user’s language settings? I am having trouble localizing my application to the Arabic (Saudi Arabia) locale. Detection of the current locale, and loading and installing the appropriate QTranslators both work f...
As far as I know the layout direction should be set explicitly in Qt. I know that GTK application do this automatically and qt does not and this is good thing. I explain. Suppose you have untranslated application started in Arabic or Hebrew locale, what happens all layout displayed from right to left and everything loo...
3,365,935
3,366,006
How to fix error with sample code for MFC tooltips?
I get this error when compiling the following source from here: Error 1 error C2440: 'static_cast' : cannot convert from 'UINT (__thiscall CStaticLink::* )(CPoint)' to 'LRESULT (__thiscall CWnd::* )(CPoint)' e:\development\tooltips\cqa0311\statlink.cpp 28 The line of code is for the ON_WM_NCHITTEST be...
From here: Thanks for the report. I investigated and found that this change was by design, in MFC for Visual Studio 2005. This introduced a source incompatibility, so you will need to update your OnNcHitTest method to return an LRESULT instead of a UINT. Pat Brenner Visual C++ Libraries Development Now OnNcHitTest...
3,366,292
3,384,978
SQLite copy database destroyed original, Why?
I got this code snippet to copy a file database to a memory database. it works but it destroys the original file database. (By destroys I mean sets the file size to zero) /** * Exec an sql statement in values[0] against * the database in pData. */ int process_ddl_row(void * pData, int nColumns, char **values, char ...
Your code worked fine for me (checked on WinXP). I think you should try running it without specifying VFS object (if possible) - just replace NETBURNER_VFS_NAME with 0 in sqlite3_open_v2 call. This will show whether the problem is in VFS customization or not.
3,366,295
3,366,388
Is there any way to deduce link flags from headers?
Let's say I know that some of my C/CPP files include certain headers - is there any reliable information against which libraries I will have to link, other than guessing ? For example, if I have something like #include "foo.h" and want to find libfoo_abcdef_123.so Is there any 'best practice' how to do that, any pla...
Despite what the other answers here say - no, there isn't. Libraries can (and sometimes do) redefine the same function and the only thing that can attempt to resolve such clashes is the linker, which knows zip about header files.
3,366,778
3,367,552
Adding methods to template specialization
I have a templated C++ class that exposes a number of methods, e.g template<int X, int Y> class MyBuffer { public: MyBuffer<X,Y> method1(); }; Now, I want to expose additional methods to this class if X == Y. I have done this by subclassing MyBuffer, template<int X> class MyRegularBuffer : public MyBuffer<X,X> { ...
You don't need a separate class to represent the special behaviour. Partial specialization allows you to treat some of the MyBuffer <X,Y> cases specially and give them extra methods. Keep your original declaration of MyBuffer<X,Y> and add this: template<int Y> class MyBuffer<Y, Y> { public: MyBuffer<Y,Y> method1();...
3,366,818
3,370,481
Conditional Compile using Boost type-traits
I have a template that I would like to conditionally compile depending on the type of the argument. I only care about differentiating between "Plain Old Data" (POD), i.e., integers, etc or classes/structs. I'm using c++ VS2008 on Windows. template<T> class foo { void bar(T do_something){ #if IS_POD<T> ...
You can do it without enable_if, because all you need is to dispatch depending on type traits. enable_if is used to add/remove template instantiations to/from overload resolution. You may want to use call traits to choose the best method to pass objects to your function. As a rule, objects should be passed by reference...
3,366,880
3,367,504
How can I query remembered UNC connections similar to "net use"?
I understand how to retrieve the UNC path for a mapped drive from the registry (HKEY_CURRENT_USER\Network), but I also have a need to retrieve remote connections to network resources that were not mapped. For example, opening the 'Run' dialog and typing <\server0123\share$>. If I type "net use", I would see this mappi...
Mick, try using the Win32_NetworkConnection WMI Class check this sample program GetWMI_Win32_NetworkConnection; {$APPTYPE CONSOLE} uses SysUtils ,ActiveX ,ComObj ,Variants; Procedure GetWin32_NetworkConnection; var objWMIService : OLEVariant; colItems : OLEVariant; colItem : OLEVariant; ...
3,366,964
3,366,987
Inline speed and compiler optimization
I'm doing a bit of hands on research surrounding the speed benefits of making a function inline. I don't have the book with me, but one text I was reading, was suggesting a fairly large overhead cost to making function calls; and when ever executable size is either negligible, or can be spared, a function should be dec...
The inline keyword is basically useless. It is a suggestion only. The compiler is free to ignore it and refuse to inline such a function, and it is also free to inline a function declared without the inline keyword. If you are really interested in doing a test of function call overhead, you should check the resultant a...
3,366,978
3,367,019
What is wrong with this recursive va_arg code?
I'm trying to make a generic function taking a variable argument list. A part of the design is that some of these functions call each other. Unfortunately it doesn't seem to work. As you can see if you run the simple code below, the call to command() always fails, but the direct call to marshal_size() succeeds in decod...
You have to make marshal_size take a va_list rather than .... See Question 15.12 in the FAQ at c-faq.com.
3,367,030
3,367,077
C++ iterator, do I need to reset after using set find method
Should I need to call reset method or anything, when I try to use c++ stl set find method multiple times?
set::find is a const method, it doesn't change the container. It doesn't work in findfirst/findnext style. You can call it multiple times without any additional actions.
3,367,111
3,367,284
How to design multithreaded application
I have a multithreaded application. Each module is executed in a separate thread. Modules are: - network module - used to receive/send data from network - parser module - encode/decode network data to internal presentation - 2 application module - perform some application logic on the above data one after other - count...
Thread-per-function designs are just naive: they assume that by separating tasks - by module - onto threads, that some kind of scalability will be achieved. This kind of design is inefficient, as very few task breakdowns yield exactly as many tasks as there are CPUs. Far more rational designs are to break tasks down in...
3,367,175
3,367,360
How to write a program that uses user input and tests for the end of file function
I am writing a program that takes letters and converts them to telephone numbers. I am just starting out in c++ and not really familar with classes or members which most of the examples I've seen on the web involve these concepts. I have the switch case portion working but cannot get the end of file part right. I have ...
I would change a number of things, but as a intro CS program, it's not too bad. A few things: Whenever EOF occurs, your cout is going to try to display that EOF and will probably not work correctly. You should at least put an if check on the cout after the while loop checking against cCharacter != EOF to prevent tha...
3,367,323
3,367,336
C++: Error C2064 with STL
I'm trying to use STL, but the following doesn't compile. main.cpp: #include <set> #include <algorithm> using namespace std; class Odp { public: set<int> nums; bool IsOdd(int i) { return i % 2 != 0; } bool fAnyOddNums() { set<int>::iterator iter = find_if(nums.begin(), nums....
It needs to be declared static: static bool IsOdd(int i) Otherwise, you'd be asking find_if to call an instance method without an instance.
3,367,426
3,367,460
Multi-dimensional array and pointers in C++?
int *x = new int[5](); With the above mentality, how should the code be written for a 2-dimensional array - int[][]? int **x = new int[5][5] () //cannot convert from 'int (*)[5]' to 'int **' In the first statement I can use: x[0]= 1; But the second is more complex and I could not figure it out. Should I use somethi...
You can do the initializations separately: int **x = new int*[5]; for(unsigned int i = 0; i < 5; i++) x[i] = new int[5];
3,367,642
3,367,934
std::list remove calling delete on pointer?
I ran valgrind on my program because of a segfault I can't figure out. It detected a problem here... Address 0x75c7670 is 0 bytes inside a block of size 12 free'd at 0x4024851: operator delete(void*) (vg_replace_malloc.c:387) by 0x805F6D8: std::list<Object*, std::allocator<Object*>::remove(O bject* const&) (new_a...
In response to your edit, yes, I think you have diagnosed it correctly. Your code is a bit confusing (mainly because you give the name obj to both an object pointer and the iterator referring to its cell in the list), but this line: m_objGrid[x][y].remove( obj ); where you remove the obj object will invalidate the obj...
3,367,761
3,367,814
Why does this template have an error in Xcode but not Visual Studio?
I am getting an error in Xcode when using templates in C++. Can someone tell me what is wrong? The first version reports an error in Xcode, but not in Visual Studio. // Version 1: Error in Xcode, but not Visual Studio template<typename LengthT, typename VertexT> int MyGraphAlgorithm(...arguments omitted...) { using ...
The reason for the error is that the compiler has no clue what graph_traits<Graph>::vertex_descriptor is. Is it a static member or a type? If it's a type then you must say so: typename graph_traits<Graph>::vertex_descriptor The reason the compiler isn't smart enough to figure it out on its own is because LengthT is a ...
3,368,022
3,368,043
const member isn't explicitly initialized but compiles
I heard that const members must be explicitly intialized, but the following compiles for me: class someClass { int const x; }; int main() { return 0; }
If a class has const-qualified member variables, then for any constructor defined for that class, those variables must be initialized in the constructor initializer list. If any defined constructor does not initialize a const-qualified member variable, the program is ill-formed. In your example code, someClass has no ...
3,368,094
3,368,193
Template instantiation refused with function-local classes
Possible Duplicate: How to use local classes with templates? g++ 4.4 is refusing to compile a call to a template function taking a function-local class as a template parameter. Like so: // Given this: template <typename C> int f(const C& c) { return c.g(); } // This compiles fine: struct C1 { int g() const {...
C++0x will remove this undesirable restriction. For now, you can make C i a proper nested class (inside of h's class, not inside of h).
3,368,121
3,368,136
How does a C/C++ compiler find the definitions of prototypes in header files?
When I declare a function in a header file, and put the definition of that function in some other file, how does the compiler/linker find the definition? Does it systematically search every file in its path for it, or is there a more elegant solution? This has been bugging me for the past few days, and I've been unable...
The compiler doesn't do this, the linker does. While the compiler works on one source file at a time, when the linker is invoked it is passed the names of all of the object files generated by the compiler, as well as any libraries that the user wishes to have linked in. Therefore, the linker has complete knowledge of t...
3,368,400
3,448,676
Is it safe to replace GCC's system-level C++ runtime with a version from newer GCC?
Linux C++ programs build with GCC link against libgcc_s.so.1 and libstdc++.so.6 libraries, each of which contains multiple ABIs: newer versions contain ABIs from previous version plus new ones. GCC ABI policy document says programs build against older runtime should be able to be run with the new runtime. So, theoretic...
Maybe, but I don't recommend it, at least not without extensive testing that would almost certainly eat up any gain. Here's why: "ABI compatible" is not necessarily "bug compatible". Even if ABI compatibility is maintained, your apps might still break in surprising ways if they somehow depended on behavior that was in...
3,368,798
3,368,838
Add C file to Visual Studio
I'm using Microsoft Visual Studio 2010. When I add files to my project, they have a .cpp extension. To work with C, I have to manually rename the files to .c. Is there any way to directly add C files, without renaming anything?
If I'm understanding correctly, you want to directly add a C file to the project. Unfortunately, I don't think VS provides any means to do so; you'll just have to rename newly added files. You can rename a file from within the IDE. Right click the file and hit rename (or click on the file and push F2). Click file, pus...
3,368,842
3,368,875
How are elements stored in containers in .Net?
How are elements stored in containers in .Net? For example, a C++ vector stores in sequential order, while List doesn't. How are they implemented for .Net containers (Array, ArrayList, ...)? Thanks.
It depends on the element. But a C++ Vector is equivalent to a C# List, and a C++ List<T> is equivalent to a C# LinkedList The C# ArrayList is pretty much, a C# List<object> Wikipedia lists many data structures, and I suggest you have a look there, to see how the different ones are implemented. So: C++ C# ...
3,368,966
3,368,992
SDL / C++: How to make this function short(er)?
I have this: void showNumbers(){ nrBtn1 = TTF_RenderText_Blended( fontnrs, "1", sdlcolors[0] ); nrBtn2 = TTF_RenderText_Blended( fontnrs, "2", sdlcolors[1] ); nrBtn3 = TTF_RenderText_Blended( fontnrs, "3", sdlcolors[2] ); nrBtn4 = TTF_RenderText_Blended( fontnrs, "4", sdlcolors[3] ); nrBtn5 = TTF_Re...
You need to use an array. E.g. SDL_Rect rcnrBtn[60]; for(int x = 0; x < 60; x++) { rcnrBtn[x].x = 30 * x + 10; rcnrBtn[x].y = 32; rcnrBtn[x].w = 100; rcnrBtn[x].h = 24; } Arrays always start at 0, and this particular one ends at 59 giving a total of 60 elements.
3,369,063
3,369,109
Turn code into an Array and Display
How can I turn this into an array? I need a board to show blank spaces and when the user enters it gets filled with a X or an O by another function. The current board works I would like to make it into a array[3][3] and display the contents of the array. void showboard(char &squareOne, char &squareTwo, char &squareThre...
You can have the showboard() function accept a reference to a 3x3 array of chars. The odd-looking parameter char (&squares)[3][3] means "reference to a 3x3 array of chars named squares". void showboard(char (&squares)[3][3]) { std::cout << squares[0][0] << "|" << squares[0][1] << "|" << squares[0][2] << ...
3,369,333
3,369,465
Problem printing out linked-list
I am trying to create my own datatype that is like a vector or an array. I am having troubles with my print function; When I go to print the list, it only prints the last item in the list. // LinkedListClass.cpp : Defines the entry point for the console application. #include "stdafx.h" #include <iostream> class Node ...
There are three important errors: push() --- fixed void push(Node* node) { if(firstNode == NULL) { firstNode = node; currentNode = node; // firstNode->next = currentNode; --> this does nothing useful! size++; } else { currentNode->next = node; currentNode = node; //currentNode = node; ...
3,369,691
3,369,722
Confusion over Win32 CreateProcess
I am confused by the first 2 params, module and command-line. I find unless I populate both it doesn't work right, and it seems the documentation says otherwise. I want to call "testApp.exe param1=123" The only way I found that works is: CreateProcess("testApp.exe","testApp.exe param1=123",... I thought either of thes...
The first parameter is the name of the executable to run. The second parameter is the command line. The command-line need not contain the name of the executable, if it doesn't however and you pass something like "param1 param2" then in your program, argv[0] == "param1" and argv[1] == "param2". Therefore, you usually h...
3,369,783
3,369,803
Comma operators and assignment operators - return values
The following code segment get an output of 32, I am kind of confusing why? int i=(j=4,k=8,l=16,m=32); printf(“%d”, i);
Start reading inside the first set of parentheses. The comma operator evaluates each of several expressions subsequently. It returns the return value of the last expression - in this case, it is 32, because the return value of an assignment is the value assigned. http://en.wikipedia.org/wiki/Comma_operator
3,370,004
3,370,136
What is static block in c or c++?
I want to know that what is static block in c or c++ with an example? I know what is static but what is the difference between static and static block?
Another alternative is that you might be looking for the analogy of a static block in Java. A block of code that is run when the application is loaded. There is no such thing in C++ but it can be faked by using the constructor of a static object. foo.cpp: struct StaticBlock { StaticBlock(){ cout << "hello"...
3,370,047
3,370,387
C++ subclassing a form to trap F1 - F12 keys
The main form opens a child form that has a handful of button CONTROLs on it. I need to trap keyboard events so I subclassed one of the controls. All is good until the control loses focus of course. Ideally, as long as this child form is open I would like to assign the focus to this control and thus trap all the keystr...
Assuming that this is within Windows and the Win32 API, one option is to look for messages in your main GetMessage, TranslateMessage, DispatchMessage loop. You can special-case any message within this loop, irrespective of which window it's aimed at. You should probably use IsChild to check that the message is intended...
3,370,185
3,370,244
Sort Order in STL map and set
How are the user defined objects sorted in map and set? As far as I know, map/set are Sorted Associative Containers: the elements being inserted are sorted based on the key that it holds. But map and set internally use operator > to sort their elements. From the SGI site, I have the following examples: struct ltstr { ...
std::map uses a functor to sort elements. By default is it std::less<Key> which uses operator<. In your sample there is an user defined functor ltstr which will help to sort elements according to its keys in alphabetical order.
3,370,203
3,370,275
Handling a variable number of arguments at runtime in a struct
I have to classes, an Executer with these methods: Executer() struct Execute(string s) Lookup(string name, int module, int num, ...) and a Parser: Parser() struct Parse(string s) The Exectuers Execute method calls the Parsers Parse method. The Parser then chucks the string into smaller bits (it explodes the string ...
Use std::vector<> or a simular container that can hold an arbitrary number of entries. struct { std::string commandName; sender_t senderId; std::vector<arg_t> arguments; }; Edit: oh, you can't use std::vector. In that case: use an array and store the length: struct { const char* commandName; sender_t senderI...
3,370,347
3,370,823
C/C++ - posix_memalign()
I did some reading on cache misses optimization and come to know this stdlib function. It does some kind of memory alignment for optimization, but can any1 help me explain what this function really does? It takes 3 arguments: void* * memptr, size_t alignment, size_t size The part that I don't get is what the documentat...
I did some reading on cache misses optimization and come to know this stdlib function. It does some kind of memory alignment for optimization, but can any1 help me explain what this function really does? The main purpose of the function is to allocate a buffer aligned to the page size. That is rarely made for perform...
3,370,353
3,370,441
How do I insert a value into a URL?
I have the following code where I try to insert randomValue into an URL. int randomValue = qrand() % 100; view = new QWebView(this) ; view->load(QUrl("http://blogsearch.google.com/blogsearch?q=C&start="+randomValue+"&num=1&output=rss")); The following error is reported: error: invalid operands of types 'const char*'...
Use QString for this. It is far more capable than std::string and it provides what you need directly. QString baseurl("http://blogsearch.google.com/blogsearch?q=C&num=1&output=rss&start=%1"); view->load(QUrl(baseurl.arg(randomValue))); See QString documentation for more details.
3,370,480
3,370,667
String functions from programming pearls
Here are functions on strings from programming pearls. int wordncmp(char *p, char* q) { int n = k; for ( ; *p == *q; p++, q++) if (*p == 0 && --n == 0) return 0; return *p - *q; } int sortcmp(char **p, char **q) { return wordncmp(*p, *q); } char *skip(char *p, int n) { for ( ; n > 0;...
This is complete guesswork, since I don't have a copy of the book, but it looks like these functions are for working with an unconventional string format consisting of a sequence of "words" separated by null characters. wordncmp() compares the first k words, where k is presumably a global variable to be set before cal...
3,370,539
3,375,124
Global Coordinates Set (UTM Vs Geo)
I got the impression from other programmers that GEO (wgs84) coordinates are not efficient for calculating distance at meters resulotion. My Goal is to calculate accuratly (meters) distance between 2 points (at the same country) by using global coordinates (UTM Or Geodetic(wgs84)) ,in which set of global coordinates yo...
To achieve high precision in your calculations you should convert coordinates from WGS84 to country's local coordinate system. If you tell what country it is I could probably give a hint on what coordinate system is appropriate. UPDATE: This coordinate system should work well for Israel. If you are using .NET you can u...
3,370,575
3,370,973
C/C++ Header guard consistency
I need a utility to check conflicts in header guards. It would be nice if the utility could check if symbols and file names are consistent (using regex or something). Regards, rn141. EDIT: Example 1. Broken header guard. Doesn't protect from multiple inclusion. // my_file1.h #ifndef my_project_my_file1_h__ #define my_p...
How about using #pragma once instead?
3,371,090
3,371,119
C++ - Vector-based Two dimensional array of objects
As suggested here I fixed my 2D array of numbers to make it work with Vector class. Header file: #include <vector> typedef std::vector<int> Array; typedef std::vector<Array> TwoDArray; And here is how it's used: TwoDArray Arr2D; // Add rows for (int i = 0; i < numRows; ++i) { Arr2D.push_back(Array()); } // Fil...
new MyObject() will return a pointer to the newly created an instance of class MyObject. If you have created a vector<MyObject> then you need to do something like push_back(MyObject()).
3,371,197
3,371,257
Read binary file in C# or C++
I have to read a binary file data into a C# winform application. The binary reading is frequent, i.e. many form reads different section of data. I can create a C++ dll to read the binary file and use it in C# application. or I can have the reading logic in C#. The main issue if performance. If I write it into C# wil...
Reading from disk is mostly an I/O bound operation so it will make little difference if you write it in C# or C++. To maximize performance I would suggest reading the entire file into memory in one go (assuming the file is not too large) rather than seeking backwards and forwards in the file to read different sections....
3,371,205
3,371,604
C++ Intellisense with descriptions
Hello is there some IDE or some plugin or any other way that provides a C# Like intellisense for C++ ? like not just only the parameters & overloads but also a small description eg : cout : outputs message to ... ;; just like in C#. & thanks !
As Mohammad already answered, Visual Studio already has nice Intellisense capabilities for C++. If it isn't good enough for you, you can add some plug-ins for VS that will improve the Intellisense (and the whole "coding experience"). A good plugin that can help you is Visual Assist X which can be found at wholetomato.c...
3,371,217
3,371,301
How to convert inline assembler to .asm file
I'm having a problem converting an inline assembler function to .asm file. I need seperate inline assembler code because in x64 architecture doesn't have support for inline assembly. Here is the code, #include <windows.h> #include <string> #include <iostream> #include <tlhelp32.h> using namespace std; int filter...
Probably your best bet is to move the inline assembler listed into a separate function in a separate C source file and then compile the new source file into assembler (remembering that in your header file you will need to use extern "C" { ... }). You can then take the assembler output and modify it for 64 bit. In the g...
3,371,262
3,371,443
Resize Array Template
I need a template Function to resize an Array of any type. Here is my try: class CCommon { template < typename T > static void ResizeArray(T* paArray, int iOldSize, int iNewSize, T tInitValue); } .. template < typename T > void CCommon::ResizeArray(T* paArray, int iOldSize, int iN...
template < typename T > void CCommon::ResizeArray(T* paArray, int iOldSize, int iNewSize, T tInitValue) { T* paTmpArray = new T[iOldSize]; for(int i = 0; i < iOldSize; i++) { paTmpArray[i] = paArray[i]; } delete [] paArray; paArray=new T[iNewSize]; for(int i=0; i < iNewSize; i++) { paArray[i] = tInitValue; ...
3,371,540
3,371,986
C++ enable/disable debug messages of std::couts on the fly
Is there a way to define/undefine debug messages using std::cout whenever inside a program? I am aware that there are such things such as #define, #ifndef, but I was thinking is there a cleaner way to having a variable say: # debug ON That prints all of my debug data (using std::cout). Consequently, we'll have code l...
Some logging libraries are pretty heavy weight unless you have complex logging needs. Here's something I just knocked together. Needs a little testing but might meet your requirements: #include <cstdio> #include <cstdarg> class CLog { public: enum { All=0, Debug, Info, Warning, Error, Fatal, None }; static v...
3,371,792
3,372,206
Inline code when counting data items (using templates)
There is a simple POD data type like struct Item { int value1; double value2; bool value3; } Now I would like to write different count functions like it could be done with the following code (or some std method): typedef bool Selector(const Item& i); int count(const vector<Item>& items, Selector f) { int s...
Replace the typedef with a template parameter, to allow generic functors: template <typename Selector> int count(const vector<Item>& items, const Selector &f) Then replace your functions with function objects: struct someSimpleSelector { bool operator()(const Item& i) const { return i.value1 > 0; } }; You should ...
3,371,968
3,436,304
__attribute__((init_priority(X))) in GCC
I'm using __attribute__((init_priority(X))) in GCC like this: Type1 __attribute__ ((init_priority (101))) name1 = value1; Type2 __attribute__ ((init_priority (102))) name2 = value2; in different source files. Let's say file1.cpp and file2.cpp. If I use this in same library it works as expected, name1 is initialized b...
The gcc documentation (gcc 4.4) says: `init_priority (PRIORITY)' In Standard C++, objects defined at namespace scope are guaranteed to be initialized in an order in strict accordance with that of their definitions in a given translation unit. No guarantee is made for initializations across transl...
3,372,001
3,401,731
Replacement for ViewBox in free for commercial use framework under Windows
I want to develop windows C/C++ program, but i need in it functionality like a Viewbox from .NET WPF. But i don't want buying Visual Studio platform because it has this control. Can anyone tell me something replacment for this? I want to do window, which after resizing, resizes its contents with good proportion (images...
Good news #1 You don't have to buy Visual Studio: Microsoft gives it away for free. Just go to www.microsoft.com/express and download a copy. Microsoft explains in this FAQ that the free Visual Studio version can be used for commercial purposes. I strongly recommend you download a copy of Visual Studio and use it for...
3,372,071
4,258,219
Stick Window to Other Window
I want to develop Windows program who can stick into other window. I searching fastest-way to do this. I can get by WinAPI all information about target window and move my window into good location and after it Sniffing Windows Messages of target window to searching resize or move window and after this doing move my win...
I used DLLInjection to get into target windows process, created some hooks using winapi calls and by XML over Message Pipe transporting this values to other application who stick to this windows.
3,372,260
3,372,298
Why can't I do tupleVar.get(3) or .get<3>()?
I was going over C++0x. As i looked at tuple I saw this example. Why do I need to do get<3>(var)? Why can't I do var.get(index) or var.get<index>()? I prefer these to make code look and feel consistant. typedef tuple< int, double, long &, const char * > test_tuple ; long lengthy = 12 ; test_tuple proof( 18, 6.5, length...
You have to use get<0> because the tuple has a different type for each of its members. Therefore result type of get<0> is int, get<1> is double, get<2> is long& etc. You cannot achieve this when calling get(0) as it has to have a fixed return type. You might also want to have a look at template metaprogramming because ...
3,372,399
3,374,911
WideCharToMultiByte problem
I have the lovely functions from my previous question, which work fine if I do this: wstring temp; wcin >> temp; string whatever( toUTF8(getSomeWString()) ); // store whatever, copy, but do not use it as UTF8 (see below) wcout << toUTF16(whatever) << endl; The original form is reproduced, but the in between form of...
Let's start by me saying that it appears that there is simply no way to output UTF-8 text to the console in Windows via cout (assuming you compile with Visual Studio). What you can do however for your tests is to output your UTF-8 text via the Win32 API fn WriteConsoleA: if(!SetConsoleOutputCP(CP_UTF8)) { // 65001 ...
3,372,487
3,372,966
C++: STL troubles with const class members
It is an open ended question. Effective C++. Item 3. Use const whenever possible. Really? I would like to make anything which doesn't change during the objects lifetime const. But const comes with it own troubles. If a class has any const member, the compiler generated assignment operator is disabled. Without an assign...
As AndreyT pointed out, under these circumstances assignment (mostly) doesn't make a lot of sense. The problem is that vector (for one example) is kind of an exception to that rule. Logically, you copy an object into the vector, and sometime later you get back another copy of the original object. From a purely logical ...
3,372,556
3,372,886
Can you write a polymorphic class to disk and survive?
Firstly, I know that writing a class to disk is bad, but you should see some of our other code. D: My question is: can I write a polymorphic class to disk and then read it in later and not get undefined behaviour? I am going to guess not because of vtables (I think these are generated at runtime and unique to the objec...
I'll suggest you to take a look at Boost Serialization. we use the term "serialization" to mean the reversible deconstruction of an arbitrary set of C++ data structures to a sequence of bytes. Such a system can be used to reconstitute an equivalent structure in another program context. Depending on the context, this mi...
3,372,682
3,372,778
Is there anyway to create a non-type template parameter for a class but not declare using <>?
My original code looks like this: class a{ ... char buff[10]; } and im attempting to make this change to the code: template <int N = 10> class a{ ... char buff[N]; } Is there any thing I can do to keep my existing code creating instances of class a like this: a test; instead of making the change to: a<> test; to ge...
You can't instantiate a template without angle-brackets, and you can't give a type the same name as a template, so you can't do exactly what you want. You could give the template a different name, and typedef a to the default-sized one.
3,372,703
3,375,471
volatile and multithreading?
In the following code: #include <pthread.h> #include <unistd.h> #include <stdio.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int ready = 0; wait() { int i; do { usleep(1000); pthead_mutex_lock(&mutex); i = ready; pthread_mutex_unlock(&mutex); } while (i == 0); ...
Some perspective from the kernel kings: http://kernel.org/doc/Documentation/volatile-considered-harmful.txt
3,372,801
3,372,816
C++ why do I only get the last line?
This is the text of my program: #include <iostream> #include <string> #include <sstream> #include <fstream> using namespace std; int main(){ string line; ifstream inf("grid.txt"); while(!inf.eof()){ getline(inf, line); cout << line; } return 0; } (I'll be using sstream later) This ...
Try adding a std::endl, which will automatically append a newline and flush the buffer. You can also use the istream& getline ( istream& is, string& str, char delim ); signature to specify another delimiter than the default which is newline in case your file doesn't have any.
3,372,824
3,372,852
Windows Application in C
Can anyone tell me how I can create a basic usable Windows application in C (I have a little idea about C++ also) ?
Get Petzold's Programming Windows book; it's a classic and covers Win32 development from its core C roots.
3,372,913
3,373,088
question about locale
please explain purpose of usage of locale in c++? i have read documents but dont uderstand please help
The basic purpose is for localizing applications. For example, in the US a large number with a decimal separator would normally be written like: "1,234.56". Throughout much of Europe the same number would normally be written like: "1.234,56". A locale allows you to isolate information about such formatting (and other t...
3,373,017
3,373,041
Memory structure of a function-only object?
Let's say we have a class that looks like this: class A { public: int FuncA( int x ); int FuncB( int y ); int a; int b; }; Now, I know that objects of this class will be laid out in memory with just the two ints. That is, if I make a vector of instances of class A, there will be ...
All objects in C++ are guaranteed to have a sizeof >= 1 so that each object will have a unique address. I haven't tried it, but I would guess that in your example, the compiler would allocate but not initialize 1 byte for each function object in the array/vector.
3,373,031
3,403,649
Using QtMobility in QtCreator: Setup?
I am trying to set up a development environment to play around with developing Qt apps for Symbian devices. I have succesfully set up the environment and am able to create simple apps such as HelloWorld and get them to run on my device. I would now like to try using the QtMobility package, but I am struggling to get ...
mingw32-make suggests you're building for win32-mingw target environment. To work with Symbian SDKs, you should be building for e.g. symbian-abld instead. The configure.bat script will auto-detect the target you are building for. Just make sure that QT_PATH environment variable points to a location where you have a Sym...
3,373,193
3,373,282
Why is vector deleting destructor being called as a result of a scalar delete?
I have some code that is crashing in a large system. However, the code essentially boils down to the following pseudo-code. I've removed much of the detail, as I have tried to boil this down to the bare bones; I don't think this misses anything crucial though. // in a DLL: #ifdef _DLL #define DLLEXP __declspec(dllexpo...
Sounds like this could be an issue of allocating off of one heap and trying to delete on another. This can be an issue when allocating objects from a dll as the dll has its own heap. From the code you're showing it doesn't seem like this would be the problem but maybe in the simplification something was lost? In the...
3,373,216
3,374,293
Are there any mature distributed caching solutions available for C++ besides memcached?
Most interested in peer-to-peer solutions - without central server. So, I imagine it like a library that brings to my application a functionality of transparent cache management with feature of remote instances synchronization. It should support cache record timeout and forcing invalidation. UPDATE: If not completely p...
The next best thing after Memcached is Redis: (+) it supports more data types; (+) has persistent storage; (-/+) has a few C++ clients that seem active (as of 09/2018) but none of them are "recommended".
3,373,303
3,391,941
C++ Winsock 2 questions
I have read through the documentation for Winsock2 on MSDN, but I still need clarification on a few things, if anyone can help. I planned to make something like the the setup you get when you use WSAAsyncSelect(), but using a separate thread. Can I use WSAEventSelect() to link more than one socket to a single event obj...
No, you cannot link multiple sockets to a single WSAEVENT. You have to call WSACreateEvent() and WSAEventSelect() for each individual socket that you want to receive notifications for. You can use WSAWaitForMultipleEvents() to have a single thread wait for events from multiple sockets, though. As for using completion...
3,374,277
3,374,369
Crash when calling virtual function
Ok this is a really weird problem. I wanna start off by saying that I'm not a beginner in c++ and I'm certainly not advanced. I'm somewhere in the middle. What I'm trying to do is make a C++ OOP wrapper library (dll) of the Win32 API. Here are the classes of my library. I compiled it with Mingw using the command: g++ -...
The problem is here: bool OnInit(void) { Form form; form.Show(); return true; } The form object is destroyed when this method is returned. So the this pointer that you stored when you call Show() is no longer valid. _handle = CreateWindowEx(WS_EX_CLIENTEDGE, "woop", "", WS_OVERLAPPEDWINDOW, ...
3,374,360
3,374,465
Compilation error while using VS 2005 library in VC6
I have a library which is compiled in VS 2005 and I am trying to link it with one of the old VC 6 workspace, while linking I am getting following errors. error LNK2001: unresolved external symbol _sprintf_s error LNK2001: unresolved external symbol _strncpy_s error LNK2001: unresolved external symbol _strcpy_s erro...
I assume the above is a result of you statically linking the executable? The _s functions are "safe" functions that Microsoft added to the runtime library to make it harder to write code with buffer overflows. They were added after VC6 (either in VS.NET or VS2003) and the functions are not present in the VC6 runtime li...
3,374,433
3,374,620
I want to call a C# delegate from C++ unmanaged code. A parameterless delegate works fine , but a delegate with parameters crashed my program
The Following is code of a function from a unmanged dll. It takes in a function pointer as argument and simply returns value returned by the called function. extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()); extern __declspec(dllexport) int _stdcall callDelegate(int (*pt2Func)()) { int r =...
The calling convention for the function pointer is wrong. Make it look like this: int (__stdcall * pt2Func)(args...)
3,374,464
3,374,474
using smart pointers with "this"
I'm learning the use of boost smart pointers but I'm a bit confused about a few situations. Let's say I'm implementing a state machine where each state is implemented by a single update method. Each state could return itself or create a new state object: struct state { virtual state* update() = 0; // The point: I...
You may want to look at enable_shared_from_this, which is there for specificly solving problems similar to yours.
3,374,743
3,374,972
C++ const getter method with lazy initialization
What is the proper way to implement a getter method for a lazily-initialized member variable and maintain const-correctness? That is, I would like to have my getter method be const, because after the first time it is used, it's a normal getter method. It is only the first time (when the object is first initialized) tha...
I propose encapsulating James Curran's answer into a class of its own if you do this frequently: template <typename T> class suspension{ std::tr1::function<T()> initializer; mutable T value; mutable bool initialized; public: suspension(std::tr1::function<T()> init): initializer(init),initialized(false...
3,374,801
3,392,895
The "right" way to add python scripting to a non-python application
I'm currently in the process of adding the ability for users to extend the functionality of my desktop application (C++) using plugins scripted in python. The naive method is easy enough. Embed the python static library and follow any number of the dozens of tutorials scattered around the web describing how to initiali...
One effective way to accomplish this is to use a message-passing/communicating processes architecture, allowing you to accomplish your goal with Python, but not limiting yourself to Python. ------------------------------------ | App <--> Ext. API <--> Protocol | <--> (Socket) <--> API.py <--> Script ------------------...
3,375,459
3,375,472
how to convert WIN32_FIND_DATA to string?
im using WIN32_FIND_DATA to store the data findfirstfile outputs. i want the file location (C:\file) as a string but i don't know how to get it or any other data from it. Edit: here is my code PTSTR pszFileName; PTSTR pszFileName2[100]; if (search_handle) { do { pszFileName = file.cFileName; ...
WIN32_FIND_DATA is a struct. Check out the cFileName member. For example: WIN32_FIND_DATA FindData = {0}; HANDLE hFind = FindFirstFile(pszPattern, &FindData); if (hFind != INVALID_HANDLE_VALUE) { do { PTSTR pszFileName = FindData.cFileName; // TODO: Use pszFileName in some way... } while (FindN...
3,375,652
3,375,720
SFINAE To detect non-member function existence
Does anybody know of a method for specializing a template depending on whether a non-member method is defined? I know there are numerous ways for specializing if a member function exists, but I've never seen a non-member example. The specific problem is specializing the operator<< for shared_ptr to apply the operator<<...
If you are using C++0x, you could simply use decltype. template<typename Char, typename CharTraits, typename T> decltype( *(std::basic_ostream<Char, CharTraits>*)(nullptr) << *(T*)(nullptr) ) That'll certainly cause a substitution failure if a T cannot be output. You could probably do somet...
3,375,710
3,375,778
returning a std::string with an vector
I'm trying to get "CMtoaPlugin::listArnoldNodes()" to return an "array" of strings std::vector<std::string> ArnoldNodes = CMtoaPlugin::listArnoldNodes(); std::vector<std::string>::iterator it; for ( it=ArnoldNodes.begin() ; it < ArnoldNodes.end(); it++ ) { printf("initialize shader %s\n", *it); } ...
Try it like this: for (it = ArnoldNodes.begin() ; it != ArnoldNodes.end(); ++it) { std::cout << "initialize shader " << *it << std::endl; } printf doesn't work with std::string, you need to use cout (or pass it it->c_str()) In an iterator for-loop, it's preferable to use it != vec.end() (since you only need to ch...
3,375,977
3,376,154
Template argument missing for boolean operator?
I'm currently creating a circular doubly-linked list as exercise. The exercise is templating the damn thing, which is proving to be quite a pain. After many, many, many error-removals I get more errors. I'd laugh at that, but I'm quite tired and exhausted now. Node.h template<class T> class Node { public: Node(T v...
You are lacking the comparison operators for std::string. Try adding an #include <string> in your source file which holds main. Including <iostream> gives you a forward declaration of std::string. That's because <iostream> allows you to do a lot of string operations (for instance, it allows you to convert a string fro...
3,376,124
3,376,159
How to add element by element of two STL vectors?
The question is quite dumb, but I need to do it in a very efficient way - it will be performed over an over again in my code. I have a function that returns a vector, and I have to add the returned values to another vector, element by element. Quite simple: vector<double> result; vector<double> result_temp for(int i=0;...
If you are trying to append one vector to another, you can use something like the following. These are from one of my utilities libraries--two operator+= overloads for std::vector: one appends a single element to the vector, the other appends an entire vector: template <typename T> std::vector<T>& operator+=(std::vec...
3,376,512
3,376,622
Storing struct instances in a std::map
I'm trying to map some structs to some other instances, like this: template <typename T> class Component { public: typedef std::map<EntityID, T> instances_map; instances_map instances; Component() {}; T add(EntityID id) { T* t = new T(); instances[id] = *t; return *t; }; ...
Clarify the operations you want to perform on LogicComponent. Assuming you are trying to achieve something like this: Step 1: Add a new entry to the map: LogicComponent comp; EntityID id = 99; UnitInfos info = comp.add(id); Step 2: Initialize the info: info.x = 10.0; info.y = 11.0 // etc Step 3: Get the info object...
3,376,562
3,376,583
Performance difference for multi-thread and multi-process
A few years ago, in the Windows environment, I did some testing, by letting multiple instances of CPU computation intensive + memory access intensive + I/O access intensive application run. I developed 2 versions: One is running under multi-processing, another is running under multi-threading. I found that the performa...
It depends on how much the various threads or processes (I'll be using the collective term "tasks" for both of them) need to communicate, especially by sharing memory: that's easy, cheap and fast for threads, but not at all for processes, so, if a lot of it is going on, I bet processes' performance is not going to beat...
3,376,901
3,401,959
Blink LED using Visual C++
I am new to vc++, I have to create a simple vc++ application so that I can turn off or turn on an LED ( or an electrical bulb powered by a cell), How can I take the control out from my program, I would like to use a USB for connecting the output. Is there any library available for implementing USB integrating in the ...
Have a look into the FTDI FT232RL series of chips. They're so common that the driver is already included in most operating systems. It's a USB-to-serial device, but it has a "bit bang" mode which turns the serial lines into individually addressable IO lines that can be used either as signal lines for your own protocol,...
3,376,923
3,376,965
C++ 5 dimensional vector?
I am trying to make a 5 dimensional vector and I can’t seem to get it to work. I know if I need to write a 3 dimensional vector, I could write it in the following way: vector< vector< vector<string> > > block(27, vector< vector<string> > (27, vector<string>(27))); Then I call it: block[x][y][z] = “hello”; I wrote th...
But you should stop and think if a dictionary would work better. If the data is sparse you'll save a ton of memory. Create a key using the 5 dimensions, and create only the members you need.
3,377,326
3,377,443
C++: Copy containers efficiently
How do you copy your STL containers? // big containers of POD container_type<pod_type> source; container_type<pod_type> destination // case 1 destination = source; // case 2 destination.assign(source.begin(), source.end()); // case 3 assumes that destination.size() >= source.size() copy(source.begin(), source.end(),...
All elements of the destination are destroyed. Then the copy constructor is called as many times as the destination's size. Why? Not sure what you are talking about. assign is usually implemented something as: template<class Iterator> void assign(Iterator first, Iterator last) { erase(begin(), end()); ...
3,377,345
3,377,380
C++ Syntax question regarding constructor's member initialisation list and throw
How do I write a ctor definition which has both throw and a member initialisation list? Is this correct? ClassName::ClassName(int parameter): datamember_(parameter) throw(ExceptionType)
The throw thing is part of the function declarator, therefore it should appear before the initialization list (the :). ClassName::ClassName(int parameter) throw(ExceptionType) : datamember_(parameter) { BTW, exception specification is deprecated in C++0x, and except throw() it is generally useless. See Should I use an...
3,377,827
3,377,867
i want to study win32 programming
i want to study win32 programming(windows form applications) please advise me good sites or good book (language c++)
Window form applications generally refers to .NET (C#, VB.NET, etc). However, if you want to do win32 windows applications, this is a solid introduction, which I used when learning: http://www.charlespetzold.com/pw5/ Edit: Now that I think about it, I also learned Win32 from this source, which is free, and available...
3,377,828
3,378,709
Variadic templates for lambda expressions
What's the correct way to do this with g++: template < typename F > void g (F f); template < typename ... A > void h (A ... a); template < typename ... A > void f (A ... a) { g ([&a] () { h (a...); }); // g++-4.6: error: parameter packs not expanded with »...« }
I think you need to expand the pack a in the capture list as well, like this: template < typename ... A > void f (A ... a) { g ([&, a...] () { h (a...); }); } Here is the relevant text from the C++0x Final Committee Draft, section 5.1.2.23: A capture followed by an ellipsis is a pack expansion (14.5.3). [ Exampl...
3,377,977
3,377,988
Void Pointer Arithmetic
Given a void pointer, if I want to make the void pointer point to x bytes ahead, how will this be best done? Is there a better way than casting to a char pointer?
Is there a better way than casting to a char pointer? No (except having a char * instead of a void * to begin with, so you don't have to cast it at all). If this is not desirable or possible, then the only way is: ptr = static_cast<char *>(ptr) + offset; (Note: if you are doing this sort of stuff in C++, usually t...
3,378,090
3,378,181
Custom Memory Manager
I am trying to implement a custom memory manager and I am wondering if there is a better way to implement this function, as when I am asked about void pointer arithmetic, several people thought that if I had a void* in C++, something was very wrong. // allocates a page of memory. void ObjectAllocator::allocatePage() {...
If you need a block of memory for for storing a string (8-bit ANSI), it makes sense to declare a pointer to that buffer as char and operate on it. In your case, you need a block of memory that is a 'blob', it has no inherent type, so you correctly chose void* to represent that blob. Now you need to increment that point...
3,378,103
3,378,130
How can I assign this pointer to my Iterator class
Having class : template<class T> class Link { Link* myParent_; Link* myLeft_; Link* myRight_; T* myData_; void assign_(Link<T>*& marker, Link<T>*& aLink); void insert_(const T&);//inserts new data into a link void insert_(const T*); void remove...
Either via constructor: Iterator(Link<T> *l) : myData_(l) {} Or via a setter and getter: void setData(Link<T> *d) { myData_ = d; } Link<T>* getData() const { return myData_; }
3,378,128
3,378,160
C++ OpenCV2 cv::Mat::copyTo error in linux
while trying to compile the following code in OpenCV2 in linux, cv::Mat image1, image2; cv::Rect rect1, rect2; ... image1(rect1).copyTo(image2(rect2)); I get the following error: x.cpp: In member function ‘cv::Mat Process(cv::Mat)’: x.cpp:241: error: no matching function for call to ‘cv::Mat::copyTo(cv::Mat)’ cxc...
From what i see here, operator() for Mat needs an argument of type Mat and not Mat&. That seems to be the issue here. Try adding a temporary objet of type Mat. See below. cv::Mat image1, image2; cv::Rect rect1, rect2; ... cv::Mat extractedImage2 = image1(rect2); image1(rect1).copyTo(extractedImage2); But i must say i ...
3,378,401
3,404,908
C++ get call stack from std::exception
how can I print the full call stack when a std::exception raises?
If you're using g++ (gcc) and don't mind the code being non-portable, you could try following the wise words of "tombarta": (shameless copy from tombarta): #include <execinfo.h> void print_trace(FILE *out, const char *file, int line) { const size_t max_depth = 100; size_t stack_depth; void *stack_addrs[max_...
3,378,410
3,378,444
ostream iterator usage in c++
here is code #include <iostream> #include <string> #include <algorithm> #include <vector> #include <fstream> #include <iterator> using std::vector; using std::string; using std::cout; using std::cin; using std::ostream_iterator; using std::cout; int main(){ vector <string> me; string s; while ((cin>>s) ...
ostream_iterator needs a template argument; use ostream_iterator<string> in this case.
3,378,442
3,378,452
Destructing derived class by deleting base class
I have a situation that looks like the following code: #include <iostream> class A { public: A() { std::cout << "A created!" << std::endl; } ~A() { std::cout << "A destroyed!" << std::endl; } virtual const char* Name() { return "A"; } }; class B : public A { public: B() { std::cout << "B created!" <<...
As a rule of thumb, if any of your methods are virtual, the destructor must also be virtual. If it isn't, the declared type of a variable decides which destructor gets called, which is almost never what you want. 99.9% of all cases, you want the destructor from the runtime type.
3,378,520
3,379,321
How to make boost::make_shared a friend of my class
I have written a class with protected constructor, so that new instances can only be produced with a static create() function which returns shared_ptr's to my class. To provide efficient allocation I'd like to use boost::make_shared inside the create function, however the compiler complains that my class constructor is...
You don't need to template the friend part, but you need to signify that the friend function is a template: friend boost::shared_ptr<Connection> boost::make_shared<>(/* ... */); // ^^ That works with Comeau and current GCC versions but fails with VC. Better would be ...
3,378,533
3,378,687
What's all the fuss about C++ copy constructors?
Possible Duplicate: When do we have to use copy constructors? Why exactly are C++ copy constructors so important? I just learned about them and I don't quite see what is the fuss about them. It seems you should always write a copy constructor for your classes if you use pointers, but why? Thanks, Boda Cydo.
Copy constructors and assignment operators are very important in C++ because the language has "copy semantics", that is to say when you pass a parameter or store a value in a container, a copy of the object is passed or stored. How can C++ make a copy or perform an assignment on an object? For native types it knows by ...
3,378,616
3,379,007
"The application failed to initialize properly (0xc000007b)."
I get this error when i try to start a program that I've made in C++. It works fine on my other computer (XP SP3 32bit) but not on my windows 7 64 bit version. When I run Dependency Walker on the program, it tells me that IESHIMS.dll is missing, however it's there in the Internet Explorer folder of both 32 and 64 bit v...
The error code is STATUS_INVALID_IMAGE_FORMAT, "Mumble is either not designed to run on Windows or it contains an error. Try installing the program again using the original installation media or contact your system administrator or the software vendor for support." Which is a bit outdated perhaps for the 64-bit version...
3,378,656
3,378,727
programmatically create a pad sound
Okay this one may be a bit out from left field, but I'm going to try anyways. A pad is a sort of ambient electronic sound that kind of 'hums'. Something like this . How can I produce this in code? Using either Processing, OpenFrameworks, C, Objective-C or C++. Keep in mind I haven't been programming for that long. I ...
I've never heard the term "pad" as applied here, but it sounds like a synth organ sound, playing major chords. As a start, to represent a single note, you could generate sin waves at the fundamental frequency of the note (say 440Hz if we're talking about an A Major) and the next few multiples of that (880, 1760, 3520)...
3,378,699
8,560,458
Methods to convert mathematical formulas into code in Matlab, C++, etc?
I have a basic question for all of the math experts out there. "If I have an academic paper, whats the easiest way to convert a simple mathematical equation into working Matlab (or C++) code?" Ideally, there would be a Latex >> Matlab (or C++) conversion tool. However, failing this, is there a "cheat sheet" which conta...
Use Mathematica Symbolic Computation. You can enter mathematical equations straight into Mathematica, then export the result as C code. Keep tweaking the equation until the rendering looks identical to the original equation in the academic paper. You can then plug your own parameters in, and Mathematica will calculate ...
3,378,759
3,378,883
What exactly happens if you delete an object? (gcc) (When double-delete crashes?)
Please note that I don't want to solve any problem with my question - I was thinking about probabilities of things to happen and thus was wondering about something: What exactly happens if you delete on object and use gcc as compiler? Last week I was investigating a crash, where a race condition lead to an double delet...
It is very dependent on the implementation of the memory allocator itself, not to mention any application dependent failures as overwritting v-table of some object. There are numerous memory allocator schemes all of which differ in capabilities and resistance to double free() but all of these share one common property:...
3,378,796
3,379,262
Solving the mixin constructor problem in C++ using variadic templates
I've recently tackled the constructor problem, where various mixins classes that decorate each other (and a topmost host class) have different constructor signatures. To maintain a single constructor in the resulting decorated class, and without adding init functions, I've found the following solution. The only restric...
You only need something like tuples if you have multiple constructors with differing arity for the mixins (and thus ambiguities). If not you could just handle the parameters for the mixin as usual: template <class... A> M2(const char* p, double d, short s, const A&... a) : B(a...), p_(p), d_(d), s_(s) {}
3,378,974
3,378,989
Does inline assembly mess with portability?
Suppose you've written a portable C++ code which runs smoothly on different platforms. To make some modifications to optimize performance, you use inline assembly inside your code. Is it a good practice (compiler optimization set aside) or will it make troubles for portability?
Obviously the inline assembly isn't even close to portable. To maintain any portability at all, you generally have to use an #ifdef (or something on that order) to determine when to use it at all. My own preference is to segregate the assembly language into a separate file, and in the makefile decide whether to build t...
3,379,004
3,379,039
C++ Includes and Circular dependencies
UPDATE: Let me clarify my files and reiterate my question: main.h #include "other.h" class MyClass { public: void MyMethod(); void AnotherMethod(); OtherClass test; } main.cpp #include "main.h" void MyClass::MyMethod() { OtherClass otherTemp; // <--- instantitate OtherClass object otherT...
Some do one .h/.cpp per class: my.h #ifndef MY_H #define MY_H #include "other.h" class MyClass { public: void MyMethod(); OtherClass test; } #endif // MY_H other.h #ifndef OTHER_H #define OTHER_H class OtherClass { public: void Othermethod(); } #endif // OTHER_H my.cpp #include "my.h" void MyClas...
3,379,193
3,379,214
TRACE system function call in c++
how call TRACE in c++?please explain for example with this simple code int x = 1; int y = 16; float z = 32.0; TRACE( "This is a TRACE statement\n" ); TRACE( "The value of x is %d\n", x ); TRACE( "x = %d and y = %d\n", x, y ); TRACE( "x = %d and y = %x and z = %f\n", x, y, z );
If you mean "How can I trace the execution path of my code?" Then you need to use a source-level symbolic debugger. In Linux this generally means using GDB for which there a number of GUI front ends; using GDB on the command line is arcane and laborious, it can be used through Eclipse or KDevelop for example, or the ...