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,217,425
3,217,432
Breaking a "for" loop using "break" considered harmful?
Some days ago I started a quick open source project and, when some mates looked at the code on svn, one of them told me that using break statement inside a for loop is considered harmful and shouldn't be done. He added, though, that I would find several cases of break statements inside for loops on Linux kernel source...
I see no problem with using breaks. There will always be circumstances where you want to stop processing a loop, and using a break; makes much more sense (and makes it more readable!) than setting your loop counter up to a value that would make your loop stop at the next iteration.
3,217,441
3,217,473
Why does my C++ subclass need an explicit constructor?
I have a base class that declares and defines a constructor, but for some reason my publicly derived class is not seeing that constructor, and I therefore have to explicitly declare a forwarding constructor in the derived class: class WireCount0 { protected: int m; public: WireCount0(const int& rhs) { m = rhs; ...
All the derived classes must call their base class's constructor in some shape or form. When you create an overloaded constructor, your default compiler generated parameterless constructor disappears and the derived classes must call the overloaded constructor. When you have something like this: class Class0 { } clas...
3,217,581
3,220,929
Why is this array selection causing such a glitchy phenomenon?
I was loading a image in openGl with the Glaux library when I came across a very strange phenomenon with a array. Some example of what I tried and if they succeeded or not are below. The curFreeId variable is global. The extra variables I created to test with are local to the function. Since when does this effect the f...
Okay... I just went through the entire project looking for all relations to curFreeId. I managed to find a random addition sign someplace. curFreeId++; I hate the simple bugs... Thanks for your help guys. I managed to fix a few other bugs because of your suggestions.
3,217,722
3,217,754
Continously Read/Write Data with Pipes Win32
I am trying to write a GUI program for a command line program in Win32 using WinAPI (so please no MFC). In my current attempt, I am creating an input pipe and an output pipe to read/write data. However, my problem comes in when I attempt to continuously read from a program or to simply write after a single read due to ...
You need to use Asynchronous I/O.
3,217,842
3,217,854
C++ program converts fahrenheit to celsius
Can someone help me understand why this gives an output of 0? #include <iostream> using namespace std; int main() { float celsius; float fahrenheit; cout << "Enter Celsius temperature: "; cin >> ce...
(5/9) will by default be computed as an integer division and will be zero. Try (5.0/9)
3,217,925
3,218,294
Enable Exception C++
I am trying to make APP native code for Android. The Native code is in cplusplus. Whenever I try to make, the following error appears. H236Plus.cpp:135: error: exception handling disabled, use -fexceptions to enable How do I use -fexceptions to enable exception handling, and where do i use it?
You need to build with CrystaX's custom NDK. It has full libstdc++, RTTI and exceptions support. It's generally the best tool for Android development I know.
3,217,944
3,217,955
when to use new in C++?
What's a good policy for when to use "new" to make an instance of a class? I've been hobby programming C++ for a while but I'm still not for sure when is the best time to do this: MyClass thing(param1, param2); over this: MyClass* thing; thing = new MyClass(param1, param2); Any advice?
MyClass thing(param1, param2); //memory for thing is allocated on the process stack(static allocation) MyClass* thing; thing = new MyClass(param1, param2); //memory is allocated dynamically on the heap(free store) for thing The difference lies here: int main() { { MyClass thing(param1, param2); //thing i...
3,218,069
3,218,119
How to make my private class visible for STD containers?
This is the code: #include <map> class Hidden { private: friend class Visible; Hidden(); { /* nothing */ } }; class Visible { public: void f() { std::map<int, Hidden> m; m[1] = Hidden(); // compilation error, class Hidden is private } }; The code doesn't compile because the constructor of class Hidden ...
Add the map as a friend class: #include <map> class Hidden { private: friend class Visible; friend class std::map<int, Hidden> ; Hidden() {} }; class Visible { public: void f() { std::map<int, Hidden> m; m[1] = Hidden(); // compilation error, class Hidden is private } }; Of course, it means you have ...
3,218,097
3,218,603
OpenGl VBO technicalities in C++
I'm a little confused as to the proper usage of VBOs in an OpenGL program. I want to create a terrain paging algorithm, using a map called from a 4096x4096 greyscale heightmap as the "whole" map. From what I've read, each vertex stored in the VBO will take up 64 bytes. The problem I have is that most sources state that...
From what I've read, each vertex stored in the VBO will take up 64 bytes. It can take as many bytes as you want, depending on vertex format. position + normal + texcoords = 4*(3+3+2) = 32 bytes per vertex position + normal + texcoords + tangent vector (for bump) = 4*(3+3+2+3) = 44 bytes That's not including that e...
3,218,187
3,218,193
Confusing std::map insert behavior
I get some strange behavior when inserting values into a map: I always insert at the end of the map, but sometimes the entries get out of order. If I do a straight forward test, then I get no problems- the numbers are correctly ordered: map<int,int> testMap; for(int i = 0; i < 100; ++i) { // everything is ordered c...
A std::map is an ordered container, this is what allows it the look-up times it has. If you need both the mapping and listing, consider using Boost.MultiIndex.
3,218,304
3,218,326
question on string iterators
I have following code #include <iostream> #include <string> #include <algorithm> using namespace std; int main(){ string d="georgia is nice country": string::iterator my; for (my=d.begin();my!=d.end();my++) { cout<<*my<<endl; } return 0; } but it causes a compiler error saying "my is undefined". What i...
You need to put a semicolon instead of a colon after the string. string d="georgia is nice country"; // <-- semicolon!
3,218,414
3,218,423
Question about strcmp
For example we have two strings: string s = "cat"; string s1 = "dog"; Is it correct to write the following method? int a = strcmp(s, s1); Or what will be correct form?
C++'s std::string can be compared directly, so you could just write e.g. if (s == s1) cout << "the strings are equal" << endl; else if (s < s1) cout << "the first string is smaller" << endl; else ... But if you really need the integer value, you could use the .compare method. int a = s.compare(s1);
3,218,426
3,218,449
Differences between build and make?
Recently, I downloaded a copy of mysql source code from their source tree. but i am not sure how can i compile the code. i do not quite understand the different processes involved in c++ software building. after i have built the code, how can i install it? or do i need to make? or how do i even know if the 'build' is s...
Well, make program is used to build entire program. It controls how compiler will compile MySQL. If you are using *NIX OS, standard way of doing things is ./configure which will customize makefile used by make to your system. Then goes make which will make program. In the end, if you want to install it for ev...
3,218,498
3,218,623
any building tool can automatically understand file dependencies in C++ project?
I have a project with 50+ .h files and 50+ .cpp files. I'm using make to build a project, which looks something like this (it's just a piece of an entire file): HEADERS := $(shell find $(INCLUDE) -name "*.h") %.obj: %.cpp $(HEADERS) $(CPP) $(CPPFLAGS) -fPIC -o $@ -g -c $< When I'm making changes to one .h file, th...
Simplest way: depend: g++ -M *.cpp >.depends -include .depends Better way: SRC=foo.cpp bar.cpp ... OBJ=$(patsubst %.cpp,%.o,$(SRC)) DEPS=$(patsubst %.o,.deps/%.o.dep,$(OBJ)) all: .deps .deps: mkdir -p .deps .cpp.o: $(CXX) $(CXXFLAGS) -MD -MF .deps/$@.dep -c -o $@ $< -include $(DEPS) So compiler wil...
3,218,745
3,218,897
set variable to cmd.exe
Greeting earthmen, Here is my question: How can I create a program which sets variable to current session of cmd.exe e.g. c:\> set myvar Environment variable myvar not defined c:\>myexe.exe c:>set myvar myvar=myvalue The only similar topic that I've found is this - How can I change Windows shell (cmd.exe) environment...
Check out this article: Three Ways to Inject Your Code into Another Process. Also you probably will need a handle to your parent process (to determine the target process whose environment to change). A way to get it is described here. Just keep in mind that injection may not work, depending on user account privileges, ...
3,218,821
3,218,853
C++0x Lambda overhead
Is there any overhead associated with using lambda expressions in C++0x (under VS2010)? I know that using function objects incurs overhead, but I'm referring to expressions that are passed to STL algorithms, for example. Does the compiler optimize the expression, eliminating what seems to appear like a function call? ...
You "know" that function objects incur overhead? Perhaps you should recheck your facts. :) There is typically zero overhead to using a STL algorithm with a function object, compared with a hand-rolled loop. A naive compiler will have to repeatedly call operator() on the functor, but that is trivial to inline and so in ...
3,218,858
3,218,947
Writing cross-platform application with a complex GUI
I’d like to develop an application with a complex GUI (combobox with animation, charts with spline, transparent layers, …). I have good experience with C# 2.0 and I’m studying WPF, but I read that, unfortunately, there is no plan to port WPF to Mono. If I stick with C# and create custom GUI controls using OpenGL (via ...
I would go with Qt. Take a look at http://qt.nokia.com/products/ . If you are afraid of C++ (but there is no reason to be afraid of it), you can try with Java Swing. I think that those are the best options to go with multi platform desktop GUI development.
3,219,073
3,219,083
C++, console Application, reading files from directory
I have a directory and I want to read all the text files in it using C++ and having windows OS also using console application I don't know the files' names or their number thanks in advance
Take a look at Boost.Filesystem, especially the basic_directory_iterator.
3,219,112
3,219,120
Checking whether two numbers are permutation of each other?
Given two numbers a, b such that 1 <= a , b <= 10000000000 (10^10). My problem is to check whether the digits in them are permutation of each other or not. What is the fastest way of doing it? I was thinks of using hashing but unable to find any suitable hash function. Any suggestions? For e.g - 123 is a valid per...
If you mean the characters of the numbers (such as 1927 and 9721), there are (at least) a couple of approaches. If you were allowed to sort, one approach is to simply sprintf them to two buffers, sort the characters in the buffers, then see if the strings are equal. However, given your desire to not sort the digits, an...
3,219,251
3,219,256
Memory deallocation in c++ issue (Visual Studio 2010)
I am trying to learn C++, in the process I tried to write a function that gets two char pointers and concatenate the second one to the first one (I know there is strcat for this). But - what I want to accomplish is to modify the first parameter pointer so it will point to the result. for this reason I used a reference ...
You can only delete things that were allocated with new - if your code looked like this: str_cat( "foo", "bar" ); it would be illegal. Basically, your function as it stands is completely unsafe. A better design would be to return the new string via the function's return value. Even better, forget the whole idea and us...
3,219,449
3,219,450
How to write this loop better?
I have a code that does something like this: while (doorIsLocked()) { knockOnDoor(); } openDoor(); but I want to be polite and always knock on the door before I open it. I can write something like this: knockOnDoor(); while (doorIsLocked()) { knockOnDoor(); } openDoor(); but I'm just wondering if there's a be...
You can use a do-while instead of a while-do loop: do { knockOnDoor(); } while (doorIsLocked()); openDoor(); Unlike a while-do loop, the do-while executes the body once before checking the termination condition. See also Wikipedia/Do while loop Pre-test and post-test loops The do-while loop -- sometimes called...
3,219,469
3,219,472
C++ builtin to swap two numerical values?
Does C++ have a built in such as part of STL to swap two numerical values instead of doing: int tmp = var1; var1 = var2; var2 = tmp; Something like this: std::swapValues(var1, var2); Where swapValues is a template.
Use std::swap std::swap(var1, var2);
3,219,611
3,219,792
How can I pass map<string,string> into py with API?
C/C++ can use python API to load py. But, only simple type is supported. How can I pass map into py to be a dict with API? Or, which methods are better?
The Python C API supports C-level functionality (not C++ level one) -- basically, you can easily expose to Python things you could put in an extern C block (which doesn't include std::map &c) -- for other stuff, you need a bit more work. The nature of that work depends on what you're using to wrap your C++ code for Py...
3,219,645
3,222,369
QGLWidget::renderText bounding box
Is it possible to get the bounding box of the output of QGLWidget::renderText() in logical or window coordinates? How?
You can try to use QFontMetrics::boundingRect(). Also maybe you'll need to consider how it handles the newline character (\n). There's an overloaded QFontMetrics::boundingRect() that returns the bounding rect of the given text within a specified rectangle as well.
3,219,771
3,219,809
Pointer help in C/C++
I want to know about the pointer in C and C++ - how does it help in saving memory? I searched but did not get a satisfactory answer. Please help me out.
If you compare the following two pieces of code: foo() { large_struct x; bar(x); } bar(large_struct x) { //do some funny things } and foo() { large_struct* x; bar(x); } bar(large_struct* x) { //do some funny things } In the first piece, the large struct x is copied in memory, while in the sec...
3,219,959
3,219,967
Does such an optimization exist in g++?
Consider the following code snippet: list<someClass>& method(); .... list<someClass> test = method(); What will the behavior of this be? Will this code: Return a reference to the someClass instance returned by return value optimization from method(), and then perform someClass's copy constructor on the reference? ...
The copy constructor will have to be called, because this code must make a copy: the method() function returns a reference to some object, a copy of which must be stored in the variable test. Since you are returning a reference and not an object, there is no need for return value optimization. If you do not want to ma...
3,220,009
23,333,727
Is this key-oriented access-protection pattern a known idiom?
Matthieu M. brought up a pattern for access-protection in this answer that i'd seen before, but never conciously considered a pattern: class SomeKey { friend class Foo; SomeKey() {} // possibly make it non-copyable too }; class Bar { public: void protectedMethod(SomeKey); }; Here only a friend of th...
Thanks to your other question it looks like this pattern is now known as the "passkey" pattern. In C++11, it gets even cleaner, because instead of calling b.protectedMethod(SomeKey()); you can just call: b.protectedMethod({});
3,220,159
3,220,167
C++ : automatic const?
When I compile this code: class DecoratedString { private: std::string m_String; public: // ... constructs, destructors, etc std::string& ToString() const { return m_String; } } I get the following error from g++: invalid initialization of reference of type 'std::string&" from expressi...
m_String is treated as const because it is accessed as this->m_String and this is const because the member function, ToString() is const-qualified.
3,220,224
3,220,274
Is the gettimeofday function thread safe in Linux?
The current time must be stored globally in order for gettimeofday to work, however I am not sure if the function modifies any global state so that concurrent execution is undefined.
gettimeofday is thread safe. The (posix) functions listed here might not be, gettimeofday is not one of them.
3,220,287
3,220,316
Assign std::string from an object using operator=
I'd really like to be able to assign a std::string object from a DecoratedString object that I'm writing. class DecoratedString { private: std::string m_String; public: DecoratedString(const std::string& initvalue) : m_String(initvalue) { } const std::string& ToString() const { ...
The operator = you have defined is for assigning decorated strings to other decorated strings and returning an std::string from that assignment. What you want is a member "conversion operator" that automatically converts a decorated string to an std::string whenever required, like this: operator std::string const &() c...
3,220,459
3,220,637
SSE Alignment with class
Having some really weird problem and as beginner with c++ I don't know why. struct DeviceSettings { public: ....somevariables DXSize BackbufferSize; ....somemethods }; struct DXPoint; typedef DXPoint DXSize; __declspec(align(16)) struct DXPoint { public: union { struct { int x...
The align declspec only guarantees that the __m128i is aligned relative to the start of the data structure. If your memory allocator creates objects that aren't 16-byte aligned in the first place, the __m128i will be carefully misaligned. Many modern memory allocators give only 8-byte alignment. You'll need to overloa...
3,220,477
3,220,503
How to use clock() in C++
How do I call clock() in C++? For example, I want to test how much time a linear search takes to find a given element in an array.
#include <iostream> #include <cstdio> #include <ctime> int main() { std::clock_t start; double duration; start = std::clock(); /* Your algorithm here */ duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC; std::cout<<"printf: "<< duration <<'\n'; }
3,220,715
3,220,725
Running time of program
The program listed below outputs 0 on the screen. Why? Does it mean that my computer is fast or something is wrong in the code? #include <iostream> #include <cstdio> #include <ctime> using namespace std; int main(){ int j=0; clock_t start=clock(); for (int i=0;i<22220;i++){ i++; j++; ...
Note that clock() doesn't return wall clock time, instead it has to do with the processing time in which sleep does nothing practically(it yields control to the operating system). Try to remove sleep, and increase the loop count.
3,220,734
3,220,751
Output _CrtDumpMemoryLeaks() to a String
Is it possible to output the contents of the memory leak dump to a String (not a console)? Hopefully yes :) _CrtDumpMemoryLeaks(); // to-string?
No. But you can have _CrtDumpMemoryLeaks output to a file (using _CrtSetReportMode and _CrtSetReportFile) and then read that file into a string.
3,220,877
3,220,895
from console application to windows form GUI problem
i wrote a console application in visual c++, and now i want to add a GUI to it using windows form. I am new to Windows form. and i have following questions I dont know how to include classes from other .h files in windows form. is library like #include <stdio.h>, #include <stdlib.h>, #include <iostream> in my origin...
You have a great article from Microsoft about this subject, http://msdn.microsoft.com/en-us/library/aa290064(VS.71).aspx. 1) I did not understand your question here, but i'm pretty sure you will find the answer in the article above. 2) I don't see why you can't use your original project, so it should probably not be a ...
3,220,948
3,220,970
my program skips over a return statement
My program has this function: vector<itemPtr> Level::getItemsAt(const Point& pt) { vector<itemPtr> vect(items.size()); // copy all items at pt's position to vect remove_copy_if(items.begin(), items.end(), vect.begin(), boost::bind(matchesPosition<itemPtr>, _1, pt))...
C++ source code does not have to correspond to resulting object code one-to-one as long as the behavior is preserved. What's happening here is that the compiler rearranges the code, and probably invokes Return Value Optimization. Edit: Add this to the GCC options: -fdump-tree-nrv to see NRVO applications by the compile...
3,221,203
3,221,221
GNU ld cannot find library which is there
The packages I'm toying with here are rather unknown, but nevertheless the problem is rather generic. Basically, I'm trying to compile Python module (called rql) with C++ extension. The extension uses external framework called gecode, which contains several libraries. I compiled gecode and installed locally. Now, let t...
LD_LIBRARY_PATH is for runtime linker/loader (same effect could be achieved with ldconfig ). What you need is the -L flag: -L/home/red/usr/lib on the compiler command line. Edit: And - thanks to @bjg for reminding me - you can use LIBRARY_PATH if you don't want to mess with compiler options.
3,221,327
3,221,371
Help with Asynchronous I/O
I have been doing a lot of searching and still can't seem to figure out how to fix my issue. I am writing a GUI program (in WinAPI so no MFC please) to communicate with another program (command line based). I am using anonymous pipes since everything is local (but perhaps named pipes would be better?) which then I use ...
That looks like synchronous code. With asynchronous (OVERLAPPED) I/O, you can't use the buffer until the operation completes. Set the hEvent member of the OVERLAPPED structure, and change your main loop from PeekMessage to MsgWaitForMultipleObjects so that your program can respond to I/O events. Then you can wait on...
3,221,397
3,221,402
public char * member of a class/struct inaccessible?!?!?!po
Code snippet to follow. I have a struct (example code has class, tried both, same effect) that will store a number of char *. I made a constructor for the class that initializes most of them to = ""; Upon attempting to modify that member of an instance of the class, strncpy et all report access denied. These function...
B = new char[32]; B = ""; You first assign the pointer returned by new to B, then you assign a pointer to the string literal "" to B, effectively overwriting the pointer returned by new. As Jonathan Leffler explains, string literals are read-only, so you encounter an error when you try to write to the string literal ...
3,221,426
3,221,445
converting a for loop to a std::for_each
I've got this for loop: std::vector<itemPtr>::iterator it; for(it=items.begin(); it!=items.end(); ++it) { investigators.addToLeaderInventory(*it); } I'd like to convert it to something like this: std::for_each(items.begin(), items.end(), investigators.addToLeaderInventory); However, that line ...
for_each takes a callable entity of some kind. In order to call a member function on another object, you need to use mem_fun, which wraps the member function so that it can be called like an ordinary function, then you need to bind it to the object instance on which it should be called using bind1st: std::for_each(ite...
3,221,448
3,221,556
Win32 -- how to manage my mouse hook thread
I have successfully gotten my low-level mouse hook code to work, but there are some behaviors I'm observing that I don't quite understand. Everything works fine if I spawn a thread which installs the mouse hook. When i no longer need it running, I let the thread get destroyed automatically as I exit the program, and I ...
In your stop() routine, after setting the willQuit variable, you will also need to POST any message to the thread running MouseProcessingProc, so GetMessage will return. See PostThreadMessage API. EDIT: You could also use an event, or other sync object, instead of using windows messages and the message pump. So the m...
3,221,449
3,221,705
How can I get a least recently used algorithm to work with multiple threads?
I'm using a memory pool to store image data in a ray tracer and I'm using a least-recently-used algorithm to deal with freeing blocks of memory. This works fine when there is only one thread. When I add more threads, the LRU code breaks. I'm using a linked list to store the history of which blocks have been accessed an...
You can try using critical sections. See the wiki page here: http://en.wikipedia.org/wiki/Critical_section If you are using ATL or MFC, they have their own classes which wrap around the low level objects which you might find easier to use. For MFC: CCriticalSection. For ATL: CComAutoCriticalSection. You can just put al...
3,221,451
3,223,471
Learning OpenGL while practicing TDD (unit testing)
I have started a new game project, and have decided to learn and use OpenGL for it (project is being simultaneously developed on Windows and Linux). At the same time, I am also very interested in Test Driven Development, and am trying to put my best effort into writing my unit tests to lead design before any actual cod...
Properly testing rendering is not worth the effort. However, you can still use TDD for everything else and while designing your application. Here's a great article about TDD, games, and OpenGL.
3,221,453
3,221,627
Information on implementing game multiplayer?
I'm building a game and I'm looking for a good way to implement multiplayer. It is a sandbox game with Box2D physics. I was thinking of making it so the client only sends input to the server and receives which sprites to draw and where. Would this be a good idea? What might be ideal for a game with Physics like this? T...
There's a few approaches you could take. The one you mention is what I think of as a "thin-client" style aproach - the server is responsible for most of the processing, and the client is responsible for only basic user input and output. This has the advantage of making cheating difficult, since the client has no access...
3,221,553
3,222,745
Problem with a custom drawn list view
I created a list view class that uses Custom Draw for its rendering. It all works well except that it doesn't render anything. I subclassed its parent window to catch the NM_CUSTOMDRAW notification as a WM_NOTIFY message. However, it appears that WM_NOTIFY is only triggered a few times during creation of the control an...
I needed to call ShowWindow(mHandle, SW_SHOW); after creating the list view. Doh!
3,221,563
3,221,593
Permanent Memory Address
With my basic knowledge of C++, I've managed to whip together a simple program that reads some data from a program (using ReadProcessMemory) and sends it to my web server every five minutes, so I can see the status of said program while I'm not at home. I found the memory addresses to read from using a program designed...
There are ways to do it such as being able to recognise memory patterns around the thing you're looking for. Crackers can use this to find memory locations to patch even with software that "moves around", so to speak (as with operating systems that provide randomisation of address spaces). For example, if you know that...
3,221,635
3,221,641
PIMPL and stack allocation
So I've been thinking about PIMPL and stack allocation. I've been writing a library and decided to use PIMPL to hide the private member of the class. That means I would have a class declared like this class Foo { private: class Handle; std::tr1::shared_ptr<Handle> handle; public: Foo(); }; It's pretty stra...
Is this the trade-off you have to live with when using PIMPL? Effectively, yes, though there are techniques, such as those discussed by Herb Sutter in "The Fast Pimpl Idiom," that can be used to eliminate or speed up the heap allocation, at the cost of greater complexity. I thought of releasing the documentation wit...
3,221,812
3,221,813
How to sum up elements of a C++ vector?
What are the good ways of finding the sum of all the elements in a std::vector? Suppose I have a vector std::vector<int> vector with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?
Actually there are quite a few methods. int sum_of_elems = 0; C++03 Classic for loop: for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it) sum_of_elems += *it; Using a standard algorithm: #include <numeric> sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0); Important...
3,221,896
3,221,914
How can I guarantee full macro expansion of a parameter before paste?
I have a general macro: #define mSwitch( Root, Case ) Root##_Case_##Case #define mSpecialDisplay( what, Val ) mSwitch(mSpecialDisplay,what)(Val) #define mSpecialDisplay_Case_Int(Val) ...do stuff #define mSpecialDisplay_Case_Float(Val) ...do stuff ...more special cases how do I guarantee that the variable Case i...
This is the usual idiom for this: #define mSwitch(Root, Case) mSwitch_(Root, Case) #define mSwitch_(Root, Case) Root##_Case_##Case All of the arguments to a C preprocessor macro are fully expanded before the macro itself is expanded, unless the # or ## operator is applied to them; then they're not expanded. So to get...
3,221,969
3,221,984
Is repeatedly calling size() on a container (during loop) bad?
For efficiency reasons, I always avoid writing loops like this: for(std::size_t i = 0; i < vec.size(); ++i) { ... } where vec is an STL container. Instead, I either do const std::size_t vec_size = vec.size(); for(std::size_t i = 0; i < vec_size; ++i) { ... } or use the container iterators. But how bad is the first s...
vector::size() is constant-time and usually implemented as a trivial inline function that is optimised away. Don't bother hand-optimising it.
3,222,131
3,543,090
Why does std::basic_ios overload the unary logical negation operator?
The C++ IO streams' base class std::basic_ios defines operator void*() to return !fail() and operator!() to return fail(). That makes me wonder why we need the operator!() at all. Certainly, !is would also work by implicitly calling operator void*() and negating its result. Am I missing something here or is it purely ...
With old (read: not long after cfront) C++ compilers, the compiler was not guaranteed to implicitly call typecast operators on objects when needed. If iostream didn't have an operator ! declared, then you couldn't expect !cout to work in all cases. C++89 (or whatever the pre-C++98 standard was called) simply left the ...
3,222,137
3,224,389
How can I configure Visual Studio 2010 to build ANTLR grammars for C++ projects?
The .rules files provided with the distribution aren't recognized by VS2010, and I'd really like to avoid having to write a whole MSBuild task and all that for what should be a simple tool. Currently I've been using the pre-build event and making the commandline manually... but that kind of sucks when there's more than...
Well, I got no answers to this, so I read up on a whole bunch of MSBuild related stuff and wrote my own crappy little task for it: http://antlrmsbuild.codeplex.com/ . Hope this helps someone else.
3,222,177
3,222,186
Where to delete an object created by factory?
If I have a factory, that creates an object and returns a pointer to it, what will be a better way to delete it: By delete call in the "user" code, or by a new DestructObject function which I should have together with the factory?
In the general case, the factory might not use plain old new to allocate the object. It may use object and/or page pooling, malloc with placement new, or something even more exotic (memory mapping?). There are at least three ways to handle this that I can think of: Have the factory supply a recycle method to be called...
3,222,312
3,222,721
Problem debugging C++ with an Eclipse based IDE
This is a weird question in that I'm not sure where to start looking. First of all, I haven't done any C++ programming for the last 10 years so it could be me thats forgotten a few things. Secondly, the IDE I'm using is Eclipse based (which I've never used) and customized for Samsung bada based mobile development (it k...
Ok, problem solved. The idea is to first new up an instance of Image like so... _decoder = new Osp::Media::Image(); And then do _decoder->Construct(). Funny enough, this seems blatantly obvious to me now coming from the C# world, though why the code I posted for workingDecoder works is still somewhat mysterious to me. ...
3,222,351
3,222,472
Forward-declaring library names
An excerpt from "Exceptional C++": "In the old days, you could just replace "#include " with "class ostream;" in this situation, because ostream used to be a class and it wasn't in namespace std. Alas, no more. Writing "class ostream;" is illegal for two reasons: ostream is now in namespace std, and programmers aren't ...
The part in bolds just says you can't forward declare ostream like this: class ostream; because ostream now is a typedef, and the details of declaration may or may not vary on different implementations. because programmers are not allowed to declare anything in namespace std (though it will work on the majority of co...
3,222,427
3,223,118
how to use malloc() in C++
How to use malloc() in C++ program?
Question 1: "How do I call malloc from C++?" One of these two: #include <cstdlib> ... int *iptr = (int*) std::malloc(sizeof(*iptr)); #include <stdlib.h> ... int *iptr = (int*) malloc(sizeof(*iptr)); As with C, you could use sizeof(int) if you prefer, rather than sizeof(*iptr). Note however the (theoretical) need...
3,222,462
3,224,889
Static const initialization iPhone/Release
I have a cross platform library that has strange problem only on iPhone and only under release. // .h class cColor { public: static const cColor Red; static const cColor Green; static const cColor Blue; u8 r; u8 g; u8 b; u8 a; inline cColor(...) : ... { } }; // .cpp const cColor cColor::Red(...
I'm convinced that this is a linker bug. I just found a work around which is really stupid. I moved one inlined function from the cColor class to the cColor.cpp. I had nothing else in the cColor.cpp except the static const initialization. My guess is that because nothing else is in the translation unit in some cases th...
3,222,507
3,222,514
circular class member pointer?
I am not sure if I can describe the problem, but I will try my best. Here is the situation: If I can want a class1 has a pointer as a member variable pointing to another class, class2. Meanwhile, I want class2 also has a pointer as a member variable pointing to class1. Is that possible? class Class1 { private: Clas...
You need a forward declaration. Either: class Class1 { private: class Class2* classptr; ... ... public: ... ... }; or: class Class2; class Class1 { private: Class2* classptr; ... ... public: ... ... };
3,222,572
3,222,587
Convert a single character to a string?
Simple question (in C++): How do I convert a single character into a string. So for example, I have string str = "abc"; And I want to extract the first letter, but I want it to be a string as opposed to a character. I tried string firstLetter = str[0] + ""; and string firstLetter = & str[0]; Neither works. Ideas?
Off the top of my head, if you're using STL then do this: string firstLetter(1,str[0]);
3,222,675
3,222,780
Always creating instance of class?
I have a class that has only one function "Print()" and two properties "age, sex". And i am trying to understand when is object creating on memory? i can always access to object's props and functions even i didn't call it's constructor function. Isn't there any rule for the creating object from the class? In C# this ...
In C# this willn't create object on memory: ClassName cls; But this will create: ClassName cls = new ClassName(); In C++ is there any way to not create object in memory until i need to call it's constructor function? The equivalent to your C# example, using C++, is as follows: //pointer to ClassName, not initialized ...
3,222,723
3,222,813
how to place .o files into a separate directory, with Makefile rule
I have the following Makefile rules: DIR = src SOURCES = $(shell find $(DIR) -name "*.cpp") OBJS := $(SOURCES:.cpp=.o) With this definition all my .o files are located in the same directories (and sub-directories) as their .cpp counterparts. Such allocation principle turns the project directory into a mess very soon (...
I'm not sure if you can specify patterns with these modification directly, but you always can use macros (at least in GNU make). An example could be this: define export_rule objects/$(patsubst %.cpp,%.o,$(subst /,-,$(1))) : $(1) <<your rules here>> endef SOURCES = $(shell find $(DIR) -name "*.cpp") $(foreach s,$...
3,222,890
3,222,902
Call-stack for exceptions in C++
Today, in my C++ multi-platform code, I have a try-catch around every function. In every catch block I add the current function's name to the exception and throw it again, so that in the upmost catch block (where I finally print the exception's details) I have the complete call stack, which helps me to trace the except...
No, it is deeply horrible, and I don't see why you need a call stack in the exception itself - I find the exception reason, the line number and the filename of the code where the initial exception occurred quite sufficient. Having said that, if you really must have a stack trace, the thing to do is to generate the cal...
3,222,926
3,222,955
std::list< std::unique_ptr<T> >: passing it around
Say I have a std::list of class T's: std::list<T> l; When passing it into functions, I would use a reference: someFunction( std::list<T> &l ) What is the best way to pass around (the elements) of a std::list of unique_ptrs? std::list< std::unique_ptr<T> > l; Like this: someFunction( std::unique_ptr<T> ptr ) Or thi...
In order of best to worse: someFunction(const T&); someFunction(T&); someFunction(const std::unique_ptr<T>&); someFunction(std::unique_ptr<T>&); The first one is the best because it does not modify the object it and it will work with the object no matter how you have allocated it (for example, you could switch to sha...
3,223,238
3,223,274
Android-ndk with eclipse: How to force reinstallation of apk
I'm developing a library in c++ using the android NDK. Actually i created my project in android with both java and c++ sources. I can compile and run my project and all works fine. Now i would like to force eclipse to reinstall the apk on the phone even if the java code is unchanged but something changed on the c++ sid...
I have encountered this problem too. To solve this, you could touch a random java file in your project each time you compile the NDK project (easiest is to add it to the NDK makefile). This way Eclipse is "fooled" into re-creating the APK. Open the Eclipse Workspace containing your project and then enable Window | Pref...
3,223,302
3,223,311
C++: insert char to a string
so I am trying to insert the character, which i got from a string, to another string. Here I my actions: 1. I want to use simple: someString.insert(somePosition, myChar); 2. I got an error, because insert requires(in my case) char* or string 3. I am converting char to char* via stringstream: stringstream conversion; ...
There are a number of overloads of std::string::insert. The overload for inserting a single character actually has three parameters: string& insert(size_type pos, size_type n, char c); The second parameter, n, is the number of times to insert c into the string at position pos (i.e., the number of times to repeat the ...
3,223,416
3,224,421
How to structure this tree of nodes?
I'm writing a program in C++ that uses genetic techniques to optimize an expression tree. I'm trying to write a class Tree which has as a data member Node root. The node constructor generates a random tree of nodes with +,-,*,/ as nodes and the integers as leaves. I've been working on this awhile, and I'm not yet clea...
I think a standard Binary Tree should do... here is an example of a (binary) expression tree node: const int NUMBER = 0, // Values representing two kinds of nodes. OPERATOR = 1; struct ExpNode { // A node in an expression tree. int kind; // Which type of node is this? // ...
3,223,497
3,223,546
Post-Initialize stringstream inside map?
How can I post-initialize an stringstream inside a map? Is it even possible or do I have to create a stringstream*? std::map<std::string, std::stringstream> mapTopics; if(mapTopics.end() == mapTopics.find(Topic)) { mapTopics[Topic] = std::stringstream(""); // Post Initialize <--- } std::map<std::string, std::stri...
How can I post-initialize an stringstream inside a map? You cannot. STL containers require their data elements to be copyable, and streams are not copyable. Why do you want to have streams in a map? Can't you store the strings? If you are really desperate, you will have to store pointers to (most likely dynamically...
3,223,732
3,223,826
How to instruct GCC to stop after 5 errors?
Is it possible to instruct GNU c++ compiler to stop after 5 errors found? Can't find this in documentation.
The command-line option -fmax-errors=N directs the compiler to give up after N errors. This option is present in GCC 4.6 and later. The command-line option -Wfatal-errors directs the compiler to give up after one error. This option is present in GCC 4.0 and later. In both cases, warnings do not count toward the limit...
3,223,854
3,223,940
GetObject - GetObjectA linker error
In my project I have a function named GetObject that is wrapped in one of my classes in my static library. When I call the function in another project that is using my library, I got this error: Error 1 error LNK2019: unresolved external symbol "public: class hamur::HamurObject * __thiscall hamur::HamurWorld::GetOb...
This is a perfect example of why using macros without any sort of library qualification (GetObject instead of WINDOWS_GetObject) is really stupid and a recipe for disaster. So, thanks for the example. This should not be a problem on other platforms (finding this kind of macro nonsense is quite rare on implementations o...
3,223,917
3,223,927
C++ get array key in constructor of array of a custom class/struct?
If I have a simple class like this: class MyClass { MyClass(){} ~MyClass(){} public: int myArrayKeyValue; }; And later, I create an array of these classes: MyClass testing[10]; How, in the constructor, would I access the array key so I can set the myArrayKeyValue appropriately for each element of the a...
Is it possible to accomplish this in the constructor? No. Or do I have to just loop through the array and assign the values manually? Yes. Although you might be able to redesign so that you don't need the knowledge of the index inside and outside of these instances. Possible alternatives would include: an associat...
3,223,942
3,223,954
std::vector is very slow?
Here is what I'm doing. I have a class which I instance and it has a std::vector. when I first instance the class this std::vector is empty. The way I use it is I exponentially add to it and clear. Ex: Add a number, clear the vector: Add 2 numbers, clear the vector: Add 3 numbers, clear the vector, Add 4 numbers, clea...
Your algorithm appears to be quadratic. If you really need 100,000 elements, you're adding an element 1 + 2 + 3 + ... + 100,000 times. That's about 5,000,000,000 operations. That many operations, no matter how trivial they are, will take a while on a standard pc, regardless of whether you're using std::vector or hand-c...
3,224,063
3,224,065
Is there anything wrong with using C++ vectors in structures?
Ok, I'm coming from vb.net to c++. Im trying to use vectors in a structure, but the compiler yells at at me for it. What is wrong with the current statement? #include <vector> struct FactorSet { vector<long long> UpperFactor(0); vector<long long> LowerFactor(0); }; Output error (Visual Studio 2008): Error 1 error...
You want: #include <vector> struct FactorSet { std::vector<long long> UpperFactor; std::vector<long long> LowerFactor; }; though you might also have problems with long long, as this is not currently part of C++. If you actually want to give a size to the vectors, you need to do that via the structs constructor: st...
3,224,291
3,224,301
Compiler warning when returning a reference to a local object
How should i return a reference to object without getting a warning for example: std::string& GetString() { std::string str = "Abcdefghijklmnopqrstuvwxyz"; return str; } int main() { std::string str = GetString(); } This results a warning on compliation.
In your example, you are returning a reference to the local variable str. As soon as GetString() returns, str is destroyed and the reference is invalid (it refers to an object that has been destroyed). If you return a reference to an object, it must be an object that will still be valid after the function returns (e.g...
3,224,405
3,224,423
Std::vector fill time goes from 0ms to 16ms after a certain threshold?
Here is what I'm doing. My application takes points from the user while dragging and in real time displays a filled polygon. It basically adds the mouse position on MouseMove. This point is a USERPOINT and has bezier handles because eventually I will do bezier and this is why I must transfer them into a vector. So basi...
0ms is no time...nothing executes in no time. This should be your first indicator that you might want to check your timing methods over timing results. Namely, timers typically don't have good resolution. Your pre-16ms results are probably just actually 1ms - 15ms being incorrectly reported at 0ms. In any case, if we c...
3,224,467
3,224,475
What's the best way to make a bitwise function work for any type of integer input c++?
So I need to read flags in bits and set flags in bits. These bits are in various sizes of integer: int16, int32, int64, etc. I would like to have a function that does something like this: static integertype function(integertype data, char startbit, char endbit); I don't want to code what will be the same code to isola...
Generally, if you need generic functionality you use templates: template <typename T> T function(T data, char startbit, char endbit); But keep in mind we have std::bitset.
3,224,482
3,224,496
What's a portable and lightweight C/C++ regular expression library?
Possible Duplicate: Lightweight and portable regex library for C/C++? I'm looking for a C++ (C is acceptable, too) library for matching regular expressions. The library should satisfy these requirements: Can be built on Windows (MSVC 7 and newer) Can be built on Linux (g++ 3.4 and newer). Has no external dependenci...
A quick Google for "pcre windows" seems to say that it does, in fact, support Windows. The .so file on my system is < 200 KiB, so it doesn't seem to take up that much disk space either...
3,224,485
3,229,265
Any tutorial for embedding Clang as script interpreter into C++ Code?
I have no experience with llvm or clang, yet. From what I read clang is said to be easily embeddable Wikipedia-Clang, however, I did not find any tutorials about how to achieve this. So is it possible to provide the user of a c++ application with scripting-powers by JIT compiling and executing user-defined code at runt...
I don't know of any tutorial, but there is an example C interpreter in the Clang source that might be helpful. You can find it here: http://llvm.org/viewvc/llvm-project/cfe/trunk/examples/clang-interpreter/ You probably won't have much of a choice of syntax for your scripting language if you go this route. Clang only p...
3,224,522
3,224,539
How to start 64-bit programming with visual studio 2010?
What do I need to do to start making 64bit programs in VS? I tried using 64bit solution platform setting and used "copy settings from x86" option. The process shows up as 64bit. Is there anything else? Am I missing some interesting options?
Nope. All you need to do is set to build an x64 target, which you already did.
3,224,729
3,224,807
dll export/import problem in visual studio 2010
I am wrote a visual c++ win32 console app, and i wrote it and tested it in win32 console project . then i switch to win32 project and imported all the source files and created a dll for it. by mark the class i want to export as #define DllExport __declspec( dllexport ) class DllExport theClass { } it works ...
The Add Reference dialog can only work for DLLs that contain metadata (managed code) or a type library (a COM server). Your DLL doesn't fit that bill, you can only use the [DllImport] attribute in C# code to use the P/Invoke marshaller to call an unmanaged DLL entrypoint. That can not be a native C++ class, like you a...
3,224,771
3,227,258
USB controllable display
I'm looking to be able to display status information using a small LED or a small LCD screen connected through USB. All I need to display is very simple status (standby, error, running). Is there anything already made, decent looking and programmable through C++?
Are you looking for something like this ? Since it's USB HID class, it should be fairly trivial to control from C++ on both Windows and Linux. (And I assume Mac OSX wouldn't be that hard either)
3,224,853
3,225,046
super minimalist plugin for MS Project: where to get started?
I was wondering if you could point me in the right direction as far as developing a super simple plugin for MS Project (both 2007, which uses the old style ribbon, and 2010 which uses the new ribbon). What I need to implement: create an executable that installs a new button, with a specific icon, in some per-determin...
You could try here: http://www.add-in-express.com/support/addin-c-sharp.php#project This was also answered here: http://social.msdn.microsoft.com/Forums/en-US/vsto/thread/280e11ec-9bbc-4d13-bda1-3e053c8d55c7
3,225,032
3,225,084
Which of these is faster?
I was wondering if it was faster to have a std::vector<std::vector<double>>where the nested vector always has 2 elements, or is it faster to have a std::vector<MyPoint>where MyPoint is defined like: struct MyPoint { double Point[2]; }; Thanks
The vector<MyPoint> is preferable, because MyPoint is likely: to be smaller than vector<double> (you can check this with sizeof), and/or to make fewer allocations. A vector object itself is small, but generally points to data on the heap. It's possible for small vectors to be optimised to avoid the extra allocation by...
3,225,172
3,384,452
Asynchronous I/O with Named Pipes WinAPI
Ok, I have asked a few questions about different facets of trying to accomplish what I want to do. This time I'm having big issues just reading from a named pipe. I think I have harvested enough information to possibly complete the project I am working on if I can set this up properly. I will include all relevant code ...
You should have two OVERLAPPED structures, one for reading and one for writing. Also you need one event handle per pipe for when you want to close the pipe, and one more event when you want to abort all (and close application). You can have one WaitForMultipleObjects for every operation that all pipes are currently inv...
3,225,211
3,225,246
Force the order of functions in the virtual method table?
How can I control the order of virtual functions in the virtual table? Are they laid out in the same order that they are declared in? When inheriting a class with a virtual table, is the virtual table of the inherited class an extension of the base class, or is an entirely new virtual table created with only the inher...
(a) As far as the standard is concerned, you can't, (in fact you can't even assume that vtables exist). (b) Probably, but what are the circumstances in which you need to control the order, but you can't check for yourself? The way to check is to look at the disassembly of a virtual call (and find the offset(s) added t...
3,225,223
3,225,350
Do I need to protect this variable with a lock?
so I have a boolean type in C++ on a multiprocessor machine. The variable starts out life as true, and then there are a few threads, any one or more of which might write it to be false. At the same time, these threads may also read this variable to check its state. I don't care if reading this variable is synchronized ...
If only you're checking the state of the variable and setting it to false in one direction ever, there's not much to worry about except that some of the threads may be a little late to see the variable is already set to false. (this may be overcome to some degree by the use of 'volatile' keyword.) Then two threads may ...
3,225,291
3,225,299
on C part of C++ project (VS10)
I have a C++ VS2010 project. I want it to be pure C, so I will have a pure C library and a C++ file that will call that library. Is it possible? Will I have be able to pass data from the C part to C++?
Yes. See how to mix c and c++. Of course, you could (probably) just compile the c code with a c++ compiler and save yourself a headache. If you want to link object files compiled by a c compiler, you'll need to use extern "C" { } to declare the functions, so that they aren't name mangled by the C++ compiler. It really...
3,225,386
3,225,396
If I do a `typedef` in C or C++, when should I add `_t` at the end of typedef'ed type?
I am confused when should I add the trailing _t to typedef'ed types? For example, should I do this: typedef struct image image_t; or this: typedef struct image image; What are the general rules? Another example, should I do this: typdef enum { ARRAY_CLOSED, ARRAY_OPEN, ARRAY_HALFOPEN } array_type_t; or this: typdef ...
In POSIX, names ending with _t are reserved, so if you are targeting a POSIX system (e.g., Linux), you should not end your types with _t.
3,225,568
3,225,579
Unsigned char std::vector to unsigned char[]?
Simple question, how does one create a function which takes an unsigned char std::vector and spits out an unsigned char[] with a length. Thanks! Ah, well it seems my problem was my knowledge of std::vector. I always believed that std::vector did not hold its values in linear fashion. That solves a lot of my problems. T...
Just use: &v.front(). If you need a copy use std::copy.
3,225,652
3,225,658
Algorithm to generate outline of an alpha picture?
I'm trying to figure out an algorithm which can look at raw rgba pixels and return points that make up the polygon of the object inside example: http://img706.imageshack.us/i/polii.png// It doesn't have to return bezier curves or anything smooth or fancy, nor a connected outline as I showed, but basically the points to...
If you just want an image of the line (and not the vectors), then the field of algorithms your looking for is "edge detection", see http://en.wikipedia.org/wiki/Edge_detection. If you are always looking for circles like that you could try the generalized Hough transform (http://en.wikipedia.org/wiki/Hough_transform) w...
3,225,670
3,226,612
Erroneous private base class inaccessible?
Compiling this code using g++ 4.2.1: struct S { }; template<typename T> struct ST { }; template<typename BaseType> class ref_count : private BaseType { }; template<typename RefCountType> class rep_base : public RefCountType { }; class wrap_rep : public rep_base<ref_count<S> > { typedef rep_base<ref_count<S> > base...
Both of those codes are invalid (only the last one is valid), but your compiler (which is not conforming) only diagnoses one. As another answer says, this uses the injected class name. A class S is considered to have a member name S denoting that same class. For example (notice the "class" keyword before S::S in the fi...
3,225,733
3,226,752
Size of a class containing only compile-time constants
If I have a class that contains only compile-time constants, for example, class A { static const int x = 1; static const int y = 2; static const int z = 3; }; I believe it's the case that, so long as the address of the constants is not taken, they can (will?) be replaced at compile time where they are used...
Space used No, the static const int member will will not have any space allocated for them, as they are evaluated as compile time constants. As for size of the class object (i.e. sizeof(A)), this is not relevant unless you are creating instances of the class A - which you explicitly said you are not. Use namespace inst...
3,225,851
3,252,349
Generating a cubic bezier curve from rough points
I'm looking for a way to make my application produce smoother results in freehand mode. Right now it simply adds each mousemove points and makes a polygon out of this. I noticed modern vector applications produce bezier curves to make it look much smoother and im wondering how this is done? So how can I get the 4 point...
If you want to solve the general problem, you can use levenberg-marquardt (LM) optimization. You want to define a bezier curve with some small number of points. You use LM to optimize the parameters of the curve (the point locations) by minimizing the squared distance to the curve for all of your points. This is your...
3,226,029
3,226,649
Calling a C++ class from within a view controller crashes
I have a C++ object that I'm getting the reference to in my view controller like this: m_applicationEngine = (ApplicationEngine *)[(GLView *)[self.parentViewController view] m_applicationEngine]; In my location delegate I call a methid in the class like this: - (void)locationManager:(CLLocationManager *)manager didUpd...
Best guess on the information you have given us is that m_applicationEngine is actually not a C++ object. Where do you create it? in init? in the accessor m_applcationEngine? If you want a better answer than that, show us the code of GotoLoc() and how you init the C++ object. Edit (following new posted code): I thin...
3,226,211
3,227,495
Why is it illegal to have multi-line constexpr functions?
According to Generalized Constant Expressions—Revision 5 the following is illegal: constexpr int g(int n) // error: body not just ‘‘return expr’’ { int r = n; while (--n > 1) r *= n; return r; } This is because all 'constexpr' functions are required to be of the form { return expression; }. I can't see any...
The reason is that the compiler has plenty to do already, without also being a full-fledged interpreter, able to evaluate arbitrary C++ code. If they stick with single expressions, they limit the number of cases to consider dramatically. Loosely speaking, it simplifies things a lot that there are no semicolons in parti...
3,226,329
3,226,340
Function clrscr in C and C++
Does today's C or C++ compilers use the clrscr system function?
clrscr() is a nonstandard function (neither mentioned in ISO C99 nor in ISO C++-98) defined in <conio.h> (which is not standard compliant itself). However some compilers (like Turbo C/C++) support it as an extension.
3,226,626
3,227,141
How to download files from HTTP in Symbian C++?
I need to download file from HTTP in Symbian C++. Can somebody tell me, how I can do this, couse I cannot find it in Google?
See HTTP Client Example on Forum Nokia.
3,226,769
3,227,154
How to open a file which has name with unicode symbols
I created an .exe file and associated .myFile extension to that .exe file. I want to double click on any .myFile file and get that file opened by the .exe. For that I have done the following: int main(int argc, char *argv[]) { QString fileName(QObject::tr(argv[1])); if ( fileName != "" ) { mainWin.l...
The previous answers that focus on int main(int argc, char** argv) are needlessly complex. Qt has a better alternative. From the Qt documentation: On Windows, the QApplication::arguments() are not built from the contents of argv/argc, as the content does not support Unicode. Instead, the arguments() are constructed fro...
3,226,808
3,226,887
Is factory method appropriate here?
I am generating a sequence of Step objects that differ by "Type" and data contained within. e.g: The Step objects should basically be structs that look like this { GRAB, CASCADE_ONE, FACEUP, SOMEOTHERDATA }, { DROP, DECK, FACEDOWN, MOREDATA, ANDSOMEMORE }, { MOVE, 34, 89 }, where GRAB, MOVE and DROP indicate StepType...
You don't need the factory pattern for this. But creating an abstract Step class is a good start: class Step { private: // The presence of a pure virtual makes this class abstract. virtual void DoAction() = 0; public: virtual ~Step() {} // Needed if you are going to delete via a Step* pointer void Actio...
3,227,255
3,227,297
question about location of variable in memory
we know meaning of pointers for example to get location of variable int t=9; we use following notation int *p=&t; how can i obtain address of variable in memory by bitwise operatos and bits manipulation? can i do it in general or what is equivalent of pointer in bit world?i am using c++
Using bit wise operators like and and or, you can't get the address of an arbitrary variable, no. At some point, you have to use &. If you're talking about manipulating bits within one of the more basic types, there are (at least) two approaches you can take: Specify bit-field structures such as struct { int bit:3 } w...
3,227,270
3,227,908
How to convert wchar_t** to char**?
I get argv as wchar_t** (see below), because I need to work with unicode, but I need to convert it to char **. How can I do that? int wmain(int argc, wchar_t** argv) {
There is more than one way to do this. Depending on your environment and available compiler/standard library/other libraries, you have at least three choices: Use std::locale and std::codecvt<> facet; use C locale functions like std::mbstowcs(); use 3rd party functions like iconv() on *nix or WideCharToMultiByte() on ...