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,614,253
3,614,265
Prevent default click event (WinAPI)
I'm making a color dropper tool and while this tool is active, when the user clicks or taps I only want it to run my mouse event, not anything else,so while this tool is running,if the user clicks the start orb, it should not open the start menu (or if the user clicks anything else). How could I do this? Thanks
You could implement a system-wide mouse event hook. Hooks are described here. Depending on your hook's return value, the application underneath the cursor will or will not receive the mouse event. You may need to implement a low level mouse hook in order to catch mouse clicks. The hook function should also be provided ...
3,614,334
3,614,358
Makefile with different rules for .o generation
If I have a rule like this in my make file: CC = g++ CFLAGS = -Wall COMPILE = $(CC) $(CFLAGS) -c src = A.cpp \ main.cpp test_src = Test.cpp test = testAll OBJFILES := $(patsubst %.cpp,%.o,$(src)) TEST_OBJS := $(patsubst %.cpp,%.o,$(test_src)) %.o: %.cpp $(COMPILE) -I UnitTest++/src -LUnitTest++/ -l UnitT...
Specify which files your rule applies to: $(TEST_OBJS): %.o: %.cpp $(COMPILE) -I UnitTest++/src -LUnitTest++/ -l UnitTest++ -o $@ $<
3,614,518
3,614,583
How to enable depth testing for the GL_SELECT buffer?
I am using the GL selection buffer to implement mouse picking. Unfortunately, OpenGL is returning hits in the selection buffer even for objects that are entirely occluded. For example, if there is a man hidden behind a wall, the selection buffer will include a hit record for the man even though he is not visible. Selec...
The selection buffer will give you all the objects that match your mouse position regardless of depth from the camera. It's up to you to determine whether you want the closest, furthest or all objects. Remember the mouse only works in a 2D world and is trying to do selection for a 3D space. Imagine a ray shooting ou...
3,614,533
3,614,733
should always return a pointer to class in interface design?
I wish I could return an object of virtual base class so that I won't need to deal with the memory management(the idea of function programming also stimulate this pursuit). That means I am looking for some things like below: class Car { public: virtual int price() = 0 ; virtual string brand() = 0 ; } class...
In Java, "returning and object" is actually semantically equivalent to returning a pointer to the object in C++, you are trying to return an object by value, which makes a copy of it. You can't make a copy of an abstract object. So, while C++ may be more verbose, it supports different semantics for passing parameters a...
3,614,557
3,614,578
Array based stack - error in destructor
This is my first pathetic attempt at C++. I did an array based stack in C++ and the destructor is throwing out some memory dump. I can't figure out what went wrong. #include <stdio.h> #include <iostream> #include <exception> using namespace std; class FullStackException : public exception { virtual const char* ...
The problem line is t = -1; Should be t = 0; because when you add first element, the following code is excecuted } else { S[t] = data; // t == -1 t++; }
3,614,719
3,614,728
What does "loop" mean in "loop device"?
This maybe a linguistic question. I have checked the loop device on Wikipedia. It is just for mounting files as block device. But what does "loop" mean here? Its usage here is totally bizarre to me. I am not a native English speaker. So could someone explain this jargon to me in plain English? :) Thanks.
It's short for "loopback".
3,614,789
3,614,902
How should the C++ standard be used
I have this classic question of how should the C++ Standard (I mean the actual official document of the finalized ones) e.g. C++98, C++03 be used to learn and teach C++. My idea is only from the point of view of an average C++ user and not from the point of view of the language lawyers or someone who wishes to be in t...
The C++ language standard would be an absolutely terrible place to start learning the language. It is dense, obtuse, and really long. Often the information you are looking for is spread across seven different clauses or hidden in a half of a sentence in a clause completely unrelated to where you think it should be (o...
3,615,421
3,615,528
boost::weak_ptr interaction with custom deleter
I have a boost::shared_ptr with a custom deleter attached. When converting this to weak_ptr is the deleter information lost? If yes, how do I reattach the same deleter to shared_ptr-s acquired from weak_ptr::lock() method? The feature I am implementing is a container of weak_ptr-s pointing to the alive instances of so...
No, the custom deleter is never lost. When you lock() your weak_ptr you regain a shared_ptr with the same custom deleter (and other attributes) that the one you use to create the weak_ptr from in the first place. However, If no shared_ptr references your weak_ptr any longer, the lock() will fail and return a null share...
3,615,422
3,615,944
MySQL server has gone away
Here my code snippet: query.next(); qDebug()<<query.lastError(); qlonglong res=query.value(0).toLongLong(); qDebug()<<query.lastError(); and the corresponding log I have: Debug: QSqlError(2006, "QMYSQL: Unable to execute query", "MySQL server has gone away") Warning: QSqlQuery::value: not positioned on a valid record...
From the MySQL Manual: The most common reason for the MySQL server has gone away error is that the server timed out and closed the connection. ... By default, the server closes the connection after eight hours if nothing has happened. You can change the time limit by setting the wait_timeout variable when you start my...
3,615,439
3,615,492
template parameters, #define and code duplication
I have a lot of code like this: #define WITH_FEATURE_X struct A { #ifdef WITH_FEATURE_X // ... declare some variables Y #endif void f (); }; void A::f () { // ... do something #ifdef WITH_FEATURE_X // ... do something and use Y #else // ... do something else #endif // ... do something } and I'd like to r...
I believe what you want is an equivalent to the "static if" command that exists in D language. I am afraid such a feature does not exist in C++. Note that if parts of your code vary depending on the feature your request, these parts don't belong in the main function because they are not part of the bare algorithm. So ...
3,615,724
3,615,898
How to trace a NaN in C++
I am going to do some math calculations using C++ . The input floating point number is a valid number, but after the calculations, the resulting value is NaN. I would like to trace the point where NaN value appears (possibly using GDB), instead of inserting a lot of isNan() into the code. But I found that even code l...
In Visual Studio you can use the _controlfp function to set the behavior of floating-point calculations (see http://msdn.microsoft.com/en-us/library/e9b52ceh(VS.80).aspx). Maybe there is a similar variant for your platform.
3,615,729
3,617,483
Is it possible to have source code that 'times out' (becomes invalid after a certain moment)?
We are currently busy migrating from Visual Studio 2005 to Visual Studio 2010 (using unmanaged C/C++). This means that about half of our developers are already using Visual Studio 2010, while the other half is still using Visual Studio 2005. Recently, I came into a situation where a certain construction can be writte...
Personally, I would choose to disbelieve that everyone will actually migrate by the expected date. Even if I'm confident that it's going to happen, I don't want to create extra work for anyone, or stop them working, in the event that I'm wrong. If nothing else, builds should be reproducible. What if, in December, you r...
3,615,789
3,617,360
What to do about a 11000 lines C++ source file?
So we have this huge (is 11000 lines huge?) mainmodule.cpp source file in our project and every time I have to touch it I cringe. As this file is so central and large, it keeps accumulating more and more code and I can't think of a good way to make it actually start to shrink. The file is used and actively changed in s...
Find some code in the file which is relatively stable (not changing fast, and doesn't vary much between branches) and could stand as an independent unit. Move this into its own file, and for that matter into its own class, in all branches. Because it's stable, this won't cause (many) "awkward" merges that have to be a...
3,615,865
3,615,909
how to return an null tr1::shared_ptr and test if it is null
I have a function getA() with the following signature: class A { public: typedef std::tr1::shared_ptr <A> Ptr; //other member functions.... }; class B { public: A::Ptr getA(); }; And, I want to return an empty pointer in getA() in same case; Also, as a user of Class B , I need to test if the return value of get...
Note that A::Ptr is private in your sample. You should fix it. To return an empty pointer: A::Ptr B::getA() { // ... if ( something ) return A::Ptr(); // return empty shared_ptr else return something_else; } To check it: int test() { B b; A::Ptr p = b.getA(); // getA is private too, but suppose it will no...
3,615,867
3,616,059
Accessing public inherited Template data members
I require some clarification on the question why do we need the scope resolution operator or this pointer to access publicly inherited members from a template base class. As I understand it is for adding clarity but then how does this add any further clarity than just point that it is a member of the class. To make my ...
Refer to Name lookup - Using the GNU Compiler Collection (GCC) By adding explicit prefix mypair<T, A>, or this->, you make printA template argument dependent. Then the definitions will be resolved during template instantiation stage.
3,615,941
3,616,039
i want to show the output of my programe written in c++ to a xml file
int countNodes( TreeNode *root ) { // Count the nodes in the binary tree to which // root points, and return the answer. if ( root == NULL ) return 0; // The tree is empty. It contains no nodes. else { int count = 1; // Start by counting the root. ...
Your question is unclear, so I guess you want to "output data into an XML file" Outputing data into a file stream in an XML format could be something like: #include <iotream> #include <fstream> int main(int argc, char * argv[]) { TreeNode * root = doWhataverGizmoYouWantToCreateThat() ; int count = countNodes(roo...
3,616,000
3,616,492
Accessing an object from a different class - Design
I have three classes, TImageProcessingEngine, TImage and TProcessing TImageProcessingEngine is the one which i am using to expose all my methods to the world. TImage is the one i plan to use generic image read and image write functions. TProcessing contains methods that will perform imaging operations. class TImagePro...
I would certainly recommend a different implementation, but let's check the design first. I don't really understand the added value of TImageProcessingEngine, it doesn't bring any functionality. My advice would be quite simple in fact: Image class, to hold the values Processing class (interface), to apply operations E...
3,616,007
3,616,240
How Callback functions are useful while building and DLL
Are callback functions equivelent to events in C#(.NET). What I understand about callback function is, it is a function that is called by a reference to that Function. Example Code will be: void cbfunc() { printf("called"); } int main () { void (*callback)(void); callback=(void *)cbfunc; ca...
Callbacks and interface classes are great ways to manage your code boundaries. They help create formal boundaries and/or layers in your code instead of lumping everything together. This becomes necessary when working on large software solutions. Below is an example of how to use callbacks and interface classes. In ...
3,616,175
3,616,317
creating datatypes at runtime
I have a scenario where I am given data records at runtime. The datatype of the cells of the record are variable and only known at runtime. How wil I store these records? For e.g., At runtime, I get record_Info = "char[]","int16","int32" Then I get records = "abc" "2" "30", "def" "3" "40" how can I store these when I c...
Assuming you want to store them in a file. Store the type information at the beginning of the file(say like a header). There are only a predefined set of types. With the type info available you can have converter functions to convert the data into the respective types and store them as binary data in the file. If you h...
3,616,595
3,616,621
Why mkdir fails to work with tilde (~)?
When I write mkdir("~/folder1" , 0777); in linux, it failed to create a directory. If I replace the ~ with the expanded home directory, it works fine. What is the problem with using ~ ? Thanks
~ is known only to the shell and not to the mkdir system call. But if you try: system("mkdir ~/foo"); this works as the "mkdir ~/foo" is passed to a shell and shell expands ~ to $HOME If you want to make use of the $HOME with mkdir, you can make use of the getenv function as: char path[MAX]; char *home = getenv ("HOM...
3,616,706
3,616,764
C2065 identifier undeclared
In my Service.h I have: #include "Configuration.h" and in my class: private: ConfigurationInterface* configuration_; Then, in my Service.cpp: Service::Service(Foundation::Framework* framework) : framework_(framework) { configuration_ = new Configuration(); } and later... const Info GetInfo() { ...
Change const Info GetInfo() to const Info Service::GetInfo()
3,616,804
3,616,861
Question about references
I think the following is really basic but I don't really get what would be the "advantages" of one of these code. Having this: int main() { int a = 10; f(a); return 0; } What would be the difference between void f(int& a) { int& b = a; } and void f(int& a) { int b = a; } In particular, in the cas...
First: void f(int& a) { int& b = a; } The caller passes in an a, which we get as a reference to the caller's a. Then we create a new referece b which refers to a, which is still the caller's a. As a result, any changes the caller makes will be visible to f and its containing class, and any changes made in f to eit...
3,616,991
3,617,105
What's the point of boost::multi_index_container::index<Tag>::type?
If you have a boost::multi_index_container< > with multiple indices, there are obviously multiple ways to iterate over it - each index defines a way. For instance, if you have an index with tag T, you can iterate from container.get<T>().begin() to container.get<T>().end(). If you try to do so in a for-loop (and do not...
Personally, I think it was just an oversight. Especially with such a non-trivial library such as boost::multi_index_container<T>. I often find code I've written that aren't bugs per se, but felt that I could've been done better in retrospect.
3,617,080
3,617,141
C++ from a Java-view: I must have missed a few things
Before anything, let me first clarify that the below thoughts are purely my personal opinions and due to my limited knowledge. I have no intention whatsoever to say that C++ is not cool. I've been programming C++ for like a year and I think it really has some cool features. Nevertheless, I feel a bit empty and disappo...
You're totally wrong, in short. The fact is that C++ offers a HUGE quantity of freedom compared to Java. For example, you can allocate classes on the stack. Java doesn't offer that. You can compute certain values at compile-time. Templates offer far more power than generics. You have the power to make something a refer...
3,617,317
3,617,930
Encapsulating boost::random for ease of usage to replace rand()
for my program I need pseudo random integers with different ranges. Until now I used the rand() function but it has it's limitations. I found the boost::random library to be a much better replacement but I didn't want to create random generators all over the place. ( I need random integers in many classes, because it's...
Joe Gauterin demonstrated the issue, however it didn't offered any solution :) The problem with shared state is the absence of reentrance: ie, executing twice the same method does not provide the same result. This is particularly critical in multithreaded situations because the global state may not always change at the...
3,617,465
3,617,607
How are constructors and destructors implemented in C++?
I have 2 classes Base and Derived (derived publically from Base). When I write - Derived * d1 = new Derived; delete d1; Compiler sees that d1 is a Derived type object. So it calls the derived class constructor (which calls the base class constructor). I have 2 questions here - 1) Why do we follow this order? 2) How d...
(1) The base class does not depend on the derived class, but the other way around is possible. I.e. a Base class cannot know which fields any Derived class has, so Base::Base won't and can't touch them. The other way around is possible, Derived::Derived can access Base::member. Therefore, Base::member is initialized by...
3,617,716
3,617,791
Deal with a lot of if-else , switch
What is the best way to deal with something like this : if(key==Space) { switch(weapon) { case GUN: p->shotGun(); break; case BOW: p->shotBow(); break; } } else if(key==Enter) { //... } else if(key==Up) { //... }
I tend to use a map type expression: unordered_map<KEY_PRESS,ICommand> myCommands; unordered_map<KEY_PRESS,ICommand>::const_iterator currentCommand = myCommands.find( key ); if( currendCommand != myCommands.end() ){ currentCommand->performAction( weapon ); } Then again, if you made weapons into objects instead of ...
3,617,773
3,617,861
OpenGL: Selecting all dots from the current view area
Im using gluUnProject() to get the screen 2d coordinate in 3d world coordinate. I take 4 positions from each corner of the screen to get the area of visible objects. How to check which points are inside that "rectangle" ?, i have no idea about the terms or anything. The image below shows what that "rectangle" looks lik...
Are you trying to find which 3D point are visible by a camera? If so, you might find some interesting informations on this website: http://www.lighthouse3d.com/opengl/viewfrustum/. In the following image, we can see the view frustum and your selection frustum (in red). Applying frustum visibility checks to your select...
3,617,862
3,618,918
Custom made win32 drag-drop, can't get change invalid (slashed circle ) cursor
I've a quite difficult problem to explain but I will try my best. I've made a custom drag-drop implementation to a win32 GUI based application. Due to limitations of the program I can't use the proper OLE drag-drop mechanism. Its okey, I made my own with mouse key tracking and it works so so. The only problem I can't s...
You're on the wrong track with this. The cursor shape is not controlled by WM_SETCURSOR anymore when a D+D is in progress. COM takes over and alters the shape when a window give the 'okay to drop' feedback. Which is probably what's missing from your code. You cannot bypass 'OLE' or the MFC wrappers that make it easy...
3,617,866
3,618,000
3.4.1 Unqualified name lookup
According to C++ standard :- The name lookup rules apply uniformly to all names (including typedef-names (7.1.3), namespace-names (7.3), concept-names (14.9), concept-map-names (14.9.2), and class-names (9.1)) wherever the grammar allows such names in the context discussed by a particular rule. Name lookup rules appl...
If I am working in namespace N. I just wrote a function called func() then I write some code to call this new function. It would seem counter intuitive for it to choose a function from another namespace before it used the function I just wrote. Now consider the situation is reversed. (ie. It uses overload resolution) I...
3,618,011
3,618,025
C++: What is the default length of an int?
I've been searching for a while but couldn't find a definite answer to this apparently simple question: what is the default length of an int? I know that by default, an int is signed. But is it short or long? According to the "Fundamental data types"table found in the following page, an int is a long int by default...
It depends on the compiler implementor. An int is supposed to be the best "native" length for the platform. Best native here typically refers to whichever size is most handy/efficient/fast for the targeted processor to work with. Often you can expect int to have the same size as the processor's (integer) registers. As ...
3,618,066
3,618,086
Error while trying to use class in another class
I'm writing something in C++. I have 2 classes which I want to contain one into the other as in the folowing (these are just the header files): //Timing.h #ifndef _Timing_h #define _Timing_h #include "Agent.h" class Timing{ private: typedef struct Message{ Agent* _agent; //i get here a compilat...
Try not to include "Agent.h" in Timing.h but include a forward reference instead: #ifndef _Timing_h #define _Timing_h class Agent; class Timing{ private: typedef struct Message{ Agent* _agent; //I get here a compilation problem double _id; }Message; typedef struct M...
3,618,130
3,618,387
How to skip assembly code when debugging?
Sometimes when I use the debugger to step through my code, it goes into some assembly code (I guess I've stepped into some system library code). The question is, how can I skip over it and jump to the nearest c++ code of my project?
Use the "Step-out" button or Shift+F11, this will step back up the call stack. Alternatively display the call stack (Alt+7), then double click on the function level you want to return to; this will indicate in the source window where the call was made. Then in the source window right-click the statement following the...
3,618,133
3,618,233
How to get unique pairs of values from a stl set
I have a stl set of integers and I would like to iterate through all unique pairs of integer values, where by uniqueness I consider val1,val2 and val2,val1 to be the same and I should only see that combination once. I have written this in python where I use the index of a list (clusters): for i in range(len(clusters) -...
How about something along the following lines: for(set<int>::const_iterator iter1 = myset.begin(); iter1 != myset.end(); ++iter1) { for(set<int>::const_iterator iter2 = iter1; ++iter2 != myset.end();) { { std::cout << *iter1 << " " << *iter2 << "\n"; } } This yields all N*(N-1)/2 unique pairs, wh...
3,618,499
15,987,925
C/C++ API to decode cron-style timings
Does anyone know of a library which will assist in decoding cron style timings, i.e. 30 7 * * 1-5 Which is 7:30am every Monday, Tuesday, Wednesday, Thursday, Friday. M.
For those that wish to achieve the same goal as @ScaryAardvark Dependency: http://cron.sourcearchive.com/downloads/3.0pl1/cron_3.0pl1.orig.tar.gz Build: gcc -o main main.c cron-3.0pl1.orig/entry.c cron-3.0pl1.orig/env.c cron-3.0pl1.orig/misc.c -I cron-3.0pl1.orig Source: #include <pwd.h> #include <stdio.h> #include <...
3,618,540
3,618,564
Generating a set of methods for checking messages' content
in my unit test framework, for some of the messages ( which are simply POD structures ) I need a method to compare two such messages ( structs ) for equality of all fields. That is if for example I have a message: struct SExampleMessage { int someField; int someField2; char someField3[10]; }; I have a meth...
If the structures are plain POD (no pointer internals) then you don't need to have a function and doing var A == var B of the same type is fine. In C++0x they even relaxed the POD rules to allow classes with constructors and other things to remove this burden of boilerplate http://www2.research.att.com/~bs/C++0xFAQ.htm...
3,618,560
3,618,632
Convert C++ array of struct w/o tons of new calls?
C++ typedef struct someStruct { int val1, val2; double val3; } someStruct; someStruct a [1000] = { {0, 0, 0.0}, {1, 1, 1.0}, ... }; The only way to initialize such a table in C# I know of is to write something like class SomeStruct { int val1, val2; double val3; public SomeStruct (int val1, int val2,...
You can use the struct keyword in C#. C# structs are value types- an array of structs is contiguously stored structs, identical to a C++ standard array.
3,618,572
3,618,877
How to end up with a pointer to 0xCCCCCCCC
The program I'm working on crashes sometimes trying to read data at the address 0xCCCCCCCC. Google (and StackOverflow) being my friends I saw that it's the MSVC debug code for uninitialized stack variable. To understand where the problem can come from, I tried to reproduce this behavior: problem is I haven't been able ...
Compile your code with the /GZ compiler switch or /RTCs switch. Make sure that /Od switch is also used to disable any optimizations. s Enables stack frame run-time error checking, as follows: Initialization of local variables to a nonzero value. This helps identify bugs that do not appear when running in debug mode. ...
3,618,581
3,619,229
Our code sucks and I'm powerless to fix it. Help!
Our code sucks. Actually, let me clarify that. Our old code sucks. It's difficult to debug and is full of abstractions that few people understand or even remember. Just yesterday I spent an hour debugging in an area that I've worked for over a year and found myself thinking, "Wow, this is really painful." It's not...
Your management may be focused on getting working features into the product, and keeping them working. In this case, you will need to make a business case for refactoring the old stuff, in that by X investment of time and effort you can reduce necessary maintenance time by Y over period Z. Or your management may be f...
3,618,656
3,618,677
Should I protect operations on primitive types with mutexes for being thread-safe in C++?
What is the best approach to achieve thread-safety for rather simple operations? Consider a pair of functions: void setVal(int val) { this->_val = val; } int getVal() { return this->_val; } Since even assignments of primitive types aren't guaranteed to be atomic, should I modify every getter and setter in t...
Are you using _val in multiple threads? If not, then no, you don't need to synchronize access to it. If it is used from multiple threads, then yes, you need to synchronize access, either using a mutex or by using an atomic type (like std::atomic<T> in C++0x, though other threading libraries have nonstandard atomic typ...
3,618,760
3,618,828
c++, protected abstract virtual base pure virtual private destructor
So, I found this quote today, can anyone explain? "If you think C++ is not overly complicated, just what is a protected abstract virtual base pure virtual private destructor and when was the last time you needed one? — Tom Cargill"
I believe it is a private pure virtual destructor (I think that part is self-explanatory) that is part of an abstract base class, which you've used through protected virtual inheritance. . class Base { private: virtual ~Base() = 0; /* A */ }; class Derived : protected virtual Base { private: ...
3,618,954
3,618,994
is there a loop controlled by time in c++?
I am wondering if I can loop x times in one minute interval between each loop. for (int x = 10; x > 0; x--) { cout << "BOOM" << endl; } Is there any way I can print boom every one minute? Or there is a better way to do this? Thank you
Standard C++ has no such function. The closest thing you could do is have an infinite loop constantly asking if a minute has gone by. The draft C++0x standard has sleep_until() and sleep_for() under the header <thread>, but your implementation may not support these features yet (they aren't standard yet anyway), and i...
3,618,993
3,619,091
Can a C++ compiler optimize away code when dealing with pointers?
With these two questions as background (first and second), I got curious about how much optimization a C++ compiler can perform when dealing with pointers? More specifically, I'm interested in how smart a compiler is when it optimizes away code which it may detect will never be run. (Some may point out that this is a d...
In the first case (while ( !escape );) the compiler will treat that as label: goto label; and omit everything after it (and probably give you a warning). In the second case (while ( *escape );), the compiler has no way of knowing if *escape will be true or false when run, so it has to do the comaprision and loop or not...
3,619,020
3,619,083
Qt - widget - update
I am having a widget with a push button. I want, for every click on the push button one label should be added in the widget. I am giving the code below, but is not working. I don't know why. Somebody help me? class EditThingsWindow:public QWidget { Q_OBJECT QPushButton * add; public: EditThingsWindow(); ...
A new QLabel is indeed added to the EditThingsWindow every time you click on the button. However, since the labels are not placed in a layout, and they are all moved at the same position with the same text (hence the same size), they all appear on top of each other, and you can only see the top one, which is probably w...
3,619,226
3,619,306
how to store larger binary numbers in bitset (C++)
i m trying to make a program to convert a number into it's binary. Code: #include<iostream> #include<algorithm> #include<bitset> using namespace std; int main() { int a; string k; bitset<CHAR_BIT> n; cin>>a; n=bitset<CHAR_BIT>(a); cout<<n<<" "; ...
A bitset has a fixed number of bits. You specify bitset<CHAR_BIT> -- on most systems, CHAR_BIT is 8 so you will have an 8-bit bitset. When you try to stuff a bigger number into the bitset, the most significant bits are discarded. If you know in advance the largest numbers you will have to deal with, you can specify eg ...
3,619,323
3,619,370
"x = ++x" is it really undefined?
I am using Coverity Prevent on a project to find errors. It reports an error for this expression (The variable names are of course changed): x= (a>= b) ? ++x: 0; The message is: EVALUATION_ORDER defect: In "x=(a>= b) ? ++x: 0;", "x" is written in "x" (the assignment LHS) and written in "(a>= b) ? ++x: 0;" but t...
Conditional operator ?: has a sequence point between evaluation of the condition (first operand) and evaluation of second or third operand, but it has no dedicated sequence point after the evaluation of second or third operand. Which means that two modifications of x in this example are potentially conflicting (not sep...
3,619,340
3,619,692
Maximum number of fields for a C++ object
This answer states that in Java the maximum number of fields an object may have is 65536. Is there any such limit imposed on an object in C++?
C++03 standard, Annex B (implementation quantities): Because computers are finite, C++ implementations are inevitably limited in the size of the programs they can successfully process. Every implementation shall document those limitations where known. This documentation may cite fixed limits where they ex...
3,619,566
3,619,596
What is the preferred way of allocating C++ class member data?
Let's say I have a class that allocates some arbitrary member data. There are two common ways that I have seen used (I know that there are others): class A { public: A(); ~A(); //Accessors... private: B *mB; } A::A() { mB = new B(); } A::~A() { delete B; } Versus... c...
The second is the preferred route. Do not use new / delete unless you specifically need a variable to be on the heap or have a lifetime longer than it's container. C++ value types are easier to manage and have less error cases to worry about IMHO
3,619,872
3,619,901
Append integer to end of const char* c++
I have const char* FilePathName which looks like this: C:\ImportantFile.hex And an int id = 12345; I need to define a new const char* FilePathName_ID that would append the id with an underscore to the original FilePathName to look like this: C:\ImportantFile_12345.hex I have looked at this but its different as I am u...
You need to create a new std::string object or a null-terminated byte string. One easy way is this: std::string append_number(std::string const& x, unsigned int num, char sep = '_') { std::stringstream s; s << strip_extension(x) << sep << num; return s.str(); } You can pass a string literal to the above fu...
3,619,883
3,620,037
C++: Binding class functions in DLLs
I'm relatively new to DLL importing and function binding. Let's say I have a C++ project which is a GUI library written fully in OOP aiming to be used in games. My game project however is written in Delphi. I now want to bind Delphi functions to the ones in the DLL. I would know how to do this with simple functions, wi...
I'm still coming to grips with many aspects of C++, but hopefully the following makes some kind of sense. There are some aspects of C++ that I don't think will translate well via a purely DLL import based mechanism. For example I don't think that you'll be able to support polymorphism or method overloading. However, th...
3,619,949
3,620,153
Singleton in my C++ program
I wrote 2 classes, Agent and Timing. The third class will contain the main() function and manage it all. The goal is to create n instances of Agent and a SINGLE instance of Timing. It's important to mention that Agent uses Timing fields and Timing uses Agent functions. How can I turn Timing to singleton? //Agent.h #ifn...
The most conventional way to create a singleton has following requirements: 1) The constructor should be private and a static interface shall be provided which in turn creates a static object of the singleton class (which is a member of the class itself) and return it. Basically provide a global point of access. 2) You...
3,620,096
3,623,880
Minimizing Sum of Distances: Optimization Problem
The actual question goes like this: McDonald's is planning to open a number of joints (say n) along a straight highway. These joints require warehouses to store their food. A warehouse can store food for any number of joints, but has to be located at one of the joints only. McD has a limited number of warehouses (say k...
The straight highway makes this an exercise in dynamic programming, working from left to right along the highway. A partial solution can be described by the location of the rightmost warehouse and the number of warehouses placed. The cost of the partial solution will be the total distance to the nearest warehouse (for ...
3,620,305
3,620,366
How do I get started writing a daemon process in a Unix-like operating system, like Linux?
I am doing a tool in PHP for my personal use. But PHP is very slow and the task I need to do is takes much time, so I'll make a daemon in c++ and keep it in the background (It will run in a VPS). PHP would connect to the daemon througt a simple tcp socket (I'll try to design/use a simple IPC protocol) in order to subm...
http://www.enderunix.org/docs/eng/daemon.php provides a fairly thorough but short introduction with sample code that seems to cover all the important bits. There's a much more in-depth description in "Advanced Programming in the UNIX Environment (2nd edition)" if you're willing to spend some money on paper (worth it, I...
3,620,436
3,620,475
When can optimizations done by the compiler destroy my C++ code?
When can optimizations done by the compiler cause my C++ code to exhibit wrong behaviour which would not be present had those optimizations not been performed? For example, not using volatile in certain circumstances can cause the program to behave incorrectly (e.g. not re-reading the value of a variable from memory an...
Compiler optimizations should not affect the observable behavior of your program, so in theory, you don't need to worry. In practice, if your program strays in to undefined behavior, anything could already happen, so if your program breaks when you enable optimizations, you've merely exposed existing bugs - it wasn't ...
3,620,484
3,620,784
Is there any library that gives access to PC (windows) microphone in a way Open CV gives access to camera?
So in Open CV we have such easy way of getting to some camera device and its data: #include "cv.h" #include "highgui.h" #include <stdio.h> // A Simple Camera Capture Framework int main() { CvCapture* capture = cvCaptureFromCAM( CV_CAP_ANY ); if( !capture ) { fprintf( stderr, "ERROR: capture is NULL \n" ); ...
Just use the same API that OpenCV uses. You need the waveInXxxx() functions for recording audio. A good example is available here.
3,620,515
3,620,656
Combining vectors of string's
I have a number of vectors of strings each containing dates. As a simple example vector A of size 2 might contain: A[0] = "01-Jul-2010"; A[1] = "03-Jul-2010"; while a second vector B of size 3 might contain: B[0] = "02-Jul-2010"; B[1] = "03-Jul-2010"; B[2] = "04-Jul-2010"; I'd like to form a vector C which cont...
If set is not applicable std::unique is also possible: std::vector<std::string> A; std::vector<std::string> B; std::vector<std::string> C; A.resize (2u); B.resize (3u); A[0] = "01-Jul-2010"; A[1] = "03-Jul-2010"; B[0] = "02-Jul-2010"; B[1] = "03-Jul-2010"; B[2] = "04-Jul-2010"; ...
3,620,742
3,620,957
question on function returning a reference in C++
Is it OK to return a reference to a local variable from a function? By local I mean that the variable would be created(on the stack i.e. without using new) within the function and its scope is within that function only. I got contradictory answers when I searched about this. 1) says that kind of usage is correct but 2)...
As everybody else is saying, don't do that. Returning a reference or pointer to a local variable is always wrong, because the act of returning gets rid of the local variable and hence the reference or pointer is automatically invalid. Copying may not be an issue. C++ compilers are allowed to skip copy constructors wh...
3,621,083
3,621,953
Deadlocked when allocating an std::string
I have an application with several threads running. I have 2 threads that seem deadlocked when trying to allocate an std::string. Inspecting the backtrace of both threads suggest that at some point one has tried to allocate an std::string, and got a bad_alloc exception. In its catch block, another string is created in ...
Trying to create a dynamically allocated string from within your new operator is probably a very bad idea (particularly after you were unable to allocate memory). I guess what's happening is that std::__default_alloc_template is not safe to be used recursively - most likely because it has locked some data structure in ...
3,621,181
3,621,947
Short options only in boost::program_options
How would one go about specifying short options without their long counterparts in boost? (",w", po::value<int>(), "Perfrom write with N frames") generates this -w [ -- ] arg : Perfrom write with N frames Any way to specify short options only?
If you are using command line parser, there is a way to set different styles. So the solution would be to use only long options and enable allow_long_disguise style which allows long options to be specified with one dash (i.e. "-long_option"). Here is an example: #include <iostream> #include <boost/program_options.hpp>...
3,621,197
3,621,243
What's a good 2D graphics drawing API for Windows/C++?
I've been working on a small little application, and I've been using DirectX/3D to draw textures to the screen (all 2-dimensional elements). The API, I find, is pretty easy to use and to incorporate using OOP principles, but I can't help but feel that using DirectX on something this small is insanely over-kill. I can't...
If you need alpha blending you have to use the graphics hardware; the only good way to do that is to use a 3D API similar to how you're doing it now (DirectX or OpenGL). Any alternative (GDI/+ or say, DirectDraw) will not use the full graphics hardware for accelerating blending and will have to perform it on the CPU, g...
3,621,481
3,621,513
T is not a class but it is
Why this doesn't work? (For hell's sake!) template<class T> class A { typedef typename T::value_type value_type; public: A(); }; I'm getting following error: Error 1 error C2825: 'T': must be a class or namespace when followed by ':: But T is a class, I've just specified that didn't I? So what's the probl...
T could be a primitive type, depending on how you instantiate the template...
3,621,488
3,621,740
enable_if on overloaded operator with different return type
I am trying to basically do 3 things at once here: overload the assignment operator using a template, restrict the types (using boost::enable_if), and having a specific return type. Take this as an example: template <class T> std::string operator =(T t) { return "some string"; } Now, according to boost enable_if (sec...
#include <iostream> #include <boost/utility/enable_if.hpp> #include <boost/mpl/vector.hpp> #include <boost/mpl/contains.hpp> class FooBar { public: FooBar () {} ~FooBar () {} template <typename T> typename boost::enable_if < typename boost::mpl::contains < boost::mpl::vector<std::s...
3,621,540
3,632,138
Convert REG_BINARY data to REG_TZI_FORMAT
I'm trying to pull time zone information out of the registry so I can perform a time conversion. The registry data type is REG_BINARY which holds information about a REG_TZI_FORMAT structure. The key is stored at: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows \CurrentVersion\Time Zones\(time_zone_name) How do I get th...
You can do this with the following code: #include <Windows.h> #include <stdio.h> #include <tchar.h> // see http://msdn.microsoft.com/en-us/library/ms724253.aspx for description typedef struct _REG_TZI_FORMAT { LONG Bias; LONG StandardBias; LONG DaylightBias; SYSTEMTIME StandardDate; SYSTEMTIME Dayl...
3,621,550
3,623,230
Promote to custom widget in a namespace
I have MyCustomWidget in a namespace MyNameSpace namespace MyNameSpace{ class MyCustomWidget : public QWidget{ }; } How do I promote a QWidget to MyCustomWidget in my UI form? It doesn't seem to accept a custom namespace.
Type the name of the class with the namespace included: My::PushButton. It works. Note that: Qt Designer will try and guess the header name: my_pushbutton.h. Change it if it is wrong. You should check the include paths in your project to determine if a global include for the promoted widget will work
3,621,551
3,621,665
C++ advice on writing code
I am having difficulty writing my code in the way it should be written. This is my default constructor: Address::Address() : m_city(NULL), m_street(NULL), m_buildingNumber(0), m_apartmentNumber(0) {} ...and this is my other constructor: Address::Address(const char* city, const char* street, const int buildingNumber,co...
You can combine the two ctors: Address::Address(const char* city=NULL, const char* street=NULL, int buildingNumber=0, int apartmentNumber=0) : m_city(city), m_street(street), m_buildingNumber(buildingNumber), m_apartmentNumber(apartmentNumber) {} [The top...
3,621,741
3,621,778
Weird behaviour with std::getline and std::vector<std::string>
I have the following code: std::vector<std::string> final_output; std::string input; int tries = 0; std::cin >> tries; int counter = 0; while(counter < tries) { std::getline(std::cin, input); final_output.push_back(input); ++counter; } Given the input: 3 Here Goes Here Goes 2 The output is: <blank li...
When you enter the number for tries, you hit the return key. After you read tries, the carriage return from hitting the return key is still sitting in the input buffer. That carriage return will normally be translated to a new-line character. Your next call to getline reads everything in the input buffer up to the next...
3,621,790
3,627,654
How to disable GTK Drag'n Drop?
How to complete disable Drag'n Drop from a GtkEntry ?
I'd discovered that if you set the property gtk-dnd-drag-threshold to a value larger than the screen size, it will block the DnD for the whole application.
3,621,792
3,621,827
Pass by Reference v. Pass by Pointer -- Merits?
Possible Duplicates: When pass-by-pointer is preferred to pass-by-reference in C++? Are there benefits of passing by pointer over passing by reference in C++? How to pass objects to functions in C++? Hi all, I'm working to develop a large object oriented c++ application framework as part of my chemical engineering g...
The main difference is that a reference cannot be NULL (at least not without some malicious programming). For syntactical sugar and when an argument is required, I'd pass by reference. If I had a situation where the argument were optional, I'd pass by pointer. There are always exceptions. If it conforms to the current ...
3,621,875
3,622,293
Adding some comments to the C/C++ header file automatically or manually
I add the following preprocessor code in header files all the time. #ifdef _HELLO_H_ #define _HELLO_H_ #endif Is there a way to do this automatically (I mean, when I load the header file for the first time, the emacs just adds the code), or manually (I mean, I have some M-x SOMETHING)? If none exists, how can I prog...
I use YaSnippet and it works just great. It comes default with a lot of snippets for different languages and modes, not only for C++. Plus, you can write your own templates (snippets) and even use Lisp inside them (i.e. generate file header with copyright information including current year). There is also a good docume...
3,621,956
3,621,975
How do I code a simple integer circular buffer in C/C++?
I see a lot of templates and complicated data structures for implementing a circular buffer. How do I code a simple integer circular buffer for 5 numbers? I'm thinking in C is the most straightforward? Thanks.
Have an array, buffer, of 5 integers. Have an index ind to the next element. When you add, do buffer[ind] = value; ind = (ind + 1) % 5;
3,621,958
3,622,123
Implementation of hash_multimap in C++
I am trying to implement hash_multimap in C++. Here is the code: #include <hash_map> #include<iostream> #include <string> #include <hashtable.h> #include <hash_set> #include <stdlib.h> #include <stdio.h> struct eqstr{ bool operator()(const char *s1,const char* s2)const{ return strcmp(s1,s2)==0; } }; t...
The problems seem pretty straightforward. warning: #warning This file includes at least one deprecated or antiquated header which may be removed without further notice at a future date. Please use a non-deprecated interface with equivalent functionality instead. For a listing of replacement headers and interfaces, con...
3,622,030
3,622,058
Checking for file existence in C++
Currently I use something like: #include <sys/stat.h> #include "My_Class.h" void My_Class::my_function(void) { std::ofstream my_file; struct stat file_info; if ( filename_str.compare("")!=0 && stat(filename_str.c_str(),&file_info) == 0 ) { my_file.open(filename_str.data(),std::ios::trunc); ...
Generally I think it is best to just try opening it and catch an error. IMO, checking permissions is unwise because what if it's a Linux box and you check its attributes, decide you can't write to it, but the filesystem supports ACL's and they do grant you permission? (As a sysadmin I can't stand when apps do this. I...
3,622,134
3,622,852
Streaming data for state machine playback
I have a state machine design that needs to support playback. We have states that perform actions and sometimes need to generate random numbers. In case the program shuts down while in the middle of the FSM's execution, the program needs to playback the whole FSM using the same random numbers as before. For a basic exa...
Why have the states interact directly with the filestream? Single Responsibility says we should have a class who's job it is to provide the proper number based on some logic. struct INumberSource { virtual int GenNextNumber() = 0; } // My job is to provide numbers from an RNG struct RNGNumberSource : public INumbe...
3,622,355
3,622,484
How to compile a C++ program in Xcode 3.2.3?
I want to know how I can compile a C++ program with Xcode 3.2.3? In the previous version of Xcode, there was a C++ tool available for command line utility. However, after I upgraded to the latest version of Xcode 3.2.3, these options are gone.
They're still there - on the left side pick "Mac OS X Application", then in the pane that comes up, pick "Command Line Tool". There is a pop-up button for Type, where you can pick "C++ stdc++".
3,622,357
3,622,926
Multi-Dimensional Arrays--> Null Object Pointers
I am trying to develop a C++ application. Part of the Application is meant to create and initiate some properties of an Object and then store the object in a multi-dimensional array. Problem is after Object creation and storing the objects in the array, retrieving the Object values gives me pointers to NULL. Please see...
There are several issues in your code. As already stated in comments, you have a memory leak issue. if (currentArrayCell==NULL){ // This line throws an error ->No match for ‘operator==’ in ‘currentArrayCell == 0’. Why? currentArrayCell as declared in your code is a Cell object. Not a pointer to one. So you aren't c...
3,622,561
3,622,623
visual studio 2010 express STL list compiler error
I am porting some code from linux to windows and am coming up with some strange error. I have the following class: (header) RegionRectangle.h #ifndef __RECTANGLE_H__ #define __RECTANGLE_H__ #include <iostream> using namespace std; class Rectangle { public: Rectangle(int x = 0,int y = 0,int width = 0,int height = ...
The key is: C:\Program Files\Microsoft SDKs\Windows\v7.0A\include\wingdi.h(3989) : see declaration of 'Rectangle' The compiler thinks you're referring to the Win32 SDK Rectangle function in wingdi.h, not the one you just defined. I suggest renaming your rectangle (or putting in a namespace) and seeing what happens....
3,622,589
3,622,669
Does GCC support querying the current range of the stack?
I'm wondering if it's possible to determine if a given address is on the stack or in the heap. I'd like this because a reference counting system we use has a flaw that if a smart pointer is somehow pointed at an object on the stack, bad things can happen. If I had this functionality, I could use it to detect this error...
Any solution would have to be platform specific. In Windows, you can use HeapWalk to enumerate all chunks of memory in the heap. In Unix, you can try to use pthread_attr_getstack().
3,622,601
3,622,620
What happens in C++ if you pass an anonymous object into a function that takes a reference?
IE what happens if you have this following piece of code? int mean(const vector<int> & data) { int res = 0; for(size_t i = 0; i< data.size(); i++) { res += data[i]; } return res/data.size(); } vector<int> makeRandomData() { vector<int> stuff; int numInts = rand()%100; for(int i = 0; i< numInts; i++) ...
My psychic powers tell me that you're compiling this on Visual C++, which is why it even works. In standard C++, you cannot pass an rvalue (which is what the return value of makeRandomData is) to a reference-to-non-const, so the question is moot. However, the question is still valid if you change the signature of mean ...
3,623,001
22,211,220
Function overloading where parameters only differ by ellipses
I've got this logging system for which I'm looking to shortcut some of the string manipulation. The logging system is used via functional macros which then forward to a single function call. E.g. #define Warning(...) LogMessage(eWarning, __VA_ARGS__);. LogMessage then does a snprintf into a new buffer and then present...
I was inspired by the original answer to this question, but have come up with a slight improvement. static void LogMessage(LogLevel level, const char* message); template <typename T> static void LogMessage(LogLevel level, const char* format, T t, ...) { LogMessageVA(level, format, (va_list)&t); } static void LogM...
3,623,207
3,623,232
Can I make a public member variable private in a derived class?
I want to do make a public member in a base class private in a derived class, like this: class A { public: int x; int y; }; class B : public A { // x is still public private: // y is now private using y; }; But apparently "using" can't be used that way. Is there any way to do this in C++? (I c...
Short answer: no. Liskov substitution and the nature of public inheritance demands that everything that you can do with an A (i.e. its public members) can also be done by B. That means you can't hide a public method. If you're trying to hide public fields, there isn't much you can do. To "hide" public methods, you coul...
3,623,242
5,088,205
Serialize stdext::hash_map using boost serialization library
I want to serialize a hash map to a file and de-serialize it later on. #include <boost/serialization/hash_map.hpp> #include <boost/filesystem/fstream.hpp> #include <hash_map> class A: virtual public B { public: friend class boost::serialization::access; stdext::hash_map<std::string, myClass> myClassHashTabl...
First at all , insert #define BOOST_HAS_HASH in top of your code . This change your compilation error to : “error C2039: 'resize' : is not a member of 'stdext::hash_map<_Kty,_Ty>'”. :D Next, if you comment your restoring function, you'll see your code WORK fine and output ! < Good > But the problem is about an incompa...
3,623,255
3,623,309
How do I modify a MFC dialog member after it is created?
I used the Wizard to create a baisc input box with a OK and Cancel I made the input box type "int" with min value 0 and max 99. Now I want to edit the input box so that it is type string. I have the MFC ClassWizard open and can see the ControlID, Type, and Member ID of the input box. However, there is no option to ...
The easiest way is probably to delete the variable that's currently associated with the control (using the ClassWizard, and deleting the function implementation by hand) and then creating a new variable to associate with it of type CString. Note that, for better or worse, you will not be able to limit the string to a n...
3,623,263
3,626,468
Reverse iteration with an unsigned loop variable
I've been discussing the use of size_t with colleagues. One issue that has come up is loops that decrement the loop variable until it reaches zero. Consider the following code: for (size_t i = n-1; i >= 0; --i) { ... } This causes an infinite loop due to unsigned integer wrap-around. What do you do in this case? It...
Personally I have come to like: for (size_t i = n; i --> 0 ;) It has a) no funny -1, b) the condition check is mnemonic, c) it ends with a suitable smiley.
3,623,375
3,623,388
shared object can't find symbols in main binary, C++
I'm experimenting with making a kind of plugin architecture for a program I wrote, and at my first attempt I'm having a problem. Is it possible to access symbols from the main executable from within the shared object? I thought the following would be fine: testlib.cpp: void foo(); void bar() __attribute__((constructor)...
Try: g++ -fPIC -rdynamic -o testexe testexe.cpp -ldl Without the -rdynamic (or something equivalent, like -Wl,--export-dynamic), symbols from the application itself will not be available for dynamic linking.
3,623,471
4,036,697
How do you get info for an arbitrary time zone in Windows?
Ideally, what I'd like to be able to do is take the name of a time zone and ask Windows for its corresponding time zone info (offset from UTC, DST offset, dates for DST switch, etc.). It looks like Windows uses a TIME_ZONE_INFORMATION struct to hold this sort of info. So, presumably, I want a function which takes a str...
The time zone information is contained as binary data in the registry under HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones\(zone name)\TZI. The structure of the data is given in the TIME_ZONE_INFORMATION documentation: struct STimeZoneFromRegistry { long Bias; long StandardBias; long ...
3,623,631
3,623,643
Where should non-member operator overloads be placed?
I want to overload operator<< for my class. Should I add this overloaded definition to the std namespace? (since the ostream operator<< is part of the std namespace) Or should I just leave it in the global namespace? In short: class MyClass { }; namespace std { ostream& operator<< ( ostream& Ostr, const MyClass& ...
You should put the operator overload in the same namespace as your class. This will allow the operator to be found during overload resolution using argument-dependent lookup (well, actually, since ostream is in namespace std, the overload overload would also be found if you put it in namespace std, but there is no re...
3,623,671
3,639,355
Are C++ initializers called in Objective-C synthesized properties?
Are C++ initializers called in Objective-C synthesized properties? Meaning if I write a custom initializer for creation from another object of the same type (C++) does the synthesized property setter call that initializer?
I assume by initializer you actually mean a C++ constructor. In a synthesized setter the copy constructor for the C++ object is called.
3,623,824
3,623,847
Using x64 dll in x86 application
I have a DLL that needs to operate large ammounts of memory and must be x64 to do that, but the application, which calls it is x86 and can not be converted to x64. COM is already used for interaction between application and the dll. Is it possible to use surrogate process for that purpose? I know that it is possible t...
Yea, you can, and there should be no differences as COM handles everything for you. On 64-bit Windows, an out-of-process 32-bit COM server can communicate with a 64-bit client, and an out-of-process 64-bit COM server can communicate with a 32-bit client. http://msdn.microsoft.com/en-us/library/aa384231(VS.85)...
3,624,187
3,624,219
How to create .txt file in Temporary Internet folder?
I want to create a .txt file inside Temporary Internet folder.For that I am reading registry.I am reading HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cache. But this give me path **%USERPROFILE%\Local Settings\Temporary Internet Files**. Here I need a absolute path like C:\Do...
ExpandEnvironmentString
3,624,306
3,625,710
MSVC 10 + Luabind + std::vector == refuse to compile
So, I have a code, that compiled on MSVC 9 and some previous (dunno how far back it goes...), GCC, MingW, GCC on Mac... But one line, does not compile on MSVC: class_< vector<unsigned int> >("LayerList") .def(constructor<>()) .def("GetCount", &vector<unsigned int>::size) .def("Get", &NumberGet) .def("Add", &vector<uns...
If you have overloaded functions you must specify which you want to use by casting "&vector::push_back" to the correct function. You must check luabind documentation for the syntax. Maybe now there is several methods named "push_back" and you must specify which one to use?
3,624,417
3,624,438
What is the meaning of char (& test(...))[2]
What is the meaning of the following declaration: char (& test(...))[2]; I pasted it inside a function body as is and it compiles all right. I don't know what I can do with it but it passes the compilation. I've encountered something similar in this answer.
It's the declaration of a function taking a variable argument list and returning a reference to an array of 2 char. Note that if define a function like this the parameters are inaccessible (via standard means) as the <cstdarg> macros require a variable argument list to follow a named parameter. If you like, you can def...
3,624,651
3,624,766
c++ Url Parser using boost regex match
how can i parse an url in c++ with boost regex like i have an url http://www.google.co.in/search?h=test&q=examaple i need to split the base url www.google.com and then query path search?h=test&q=examaple
Are you sure you need regex for that? #include <iostream> #include <algorithm> int main() { using namespace std; string x = "http://www.google.co.in/search/search/?h=test&q=examaple"; size_t sp = x.find_first_of( '/', 7 /* skip http:// part */ ); if ( sp != string::npos ) { string base_url( x.begin()+...
3,624,733
3,625,390
How to make a QGraphicsTextItem clickable?
In the "About box" of my software, I used a QGraphicsTextItem to show the about-text. This text contains hypertext links (in the form of: <a href="http://some.random.site">link</a>). The item shows up properly (hypertext links are blue and underlined). However, when I click on them, nothing happens. Here is how I crea...
I found what I did wrong: My containing QGraphicsView had setInteractive() set to false. I removed it and since now, it works fine.
3,625,356
3,625,408
Any negative outcome from writing a function body on a separate line?
I'm reviewing our Visual C++ code base and see lots of helper functions with really short bodies. Like for example this: inline int max( int a, int b ) { return a > b ? a : b; } the problem is when code is debugged in Visual Studio debugger it's impossible to immediately see what a and b are upon entering the function...
The only reasons i can imagine are, that this is such a simple method and that the file would be bigger if you don't write the method in one line. There is nothing negative about formatting it the second way. It's only positive :)
3,625,387
3,625,696
How to start a new thread for a procedure for a member object
I am trying to start a method from my main() as a new thread with pthread: int main(int argc, char** argv) { pthread_t shipGeneratorThread; Port portMelbourne; pthread_create(&shipGeneratorThread, NULL, portMelbourne.generateShips(), NULL); return (EXIT_SUCCESS); } The Port class has a function that ...
you should use static method in this case and yes, look into man pthread_create. Signature of functiona is significant. Also if you create thread way your code show it will be terminated as soon as main() exits. You need to wait for thread to accomplish. I put example below. It is not ideal but seems good enough for de...
3,625,410
3,628,383
C++ static_cast from float** to void**
Just ran into this: #include <iostream> using namespace std; int main(int argc, char** argv) { float *a = new float[10]; void **b; b = static_cast<void**>(&a); delete(a); return 0; } macbook:C nils$ g++ -Wall -g -o static_cast static_cast.cpp static_cast.cpp: In function ‘int main(int, char**)’...
$5.2.9/2 - "An expression e can be explicitly converted to a type T using a static_cast of the form static_cast(e) if the declaration “T t(e);” is well-formed, for some invented temporary variable t (8.5). The effect of such an explicit conversion is the same as performing the declaration and initiali...
3,625,545
3,625,560
How to define 'final' member functions for a class
Is it possible to make my member functions final as in Java, so that the derived classes can not override them?
It is so much possible that it is in fact the default behaviour. I.e. if you don't declare your class instance methods explicitly as virtual, they can't be overridden in subclasses (only hidden, which is a different - and almost always erroneous - case). Effective C++ Third Edition, Item 36 deals with this in detail. C...
3,625,598
3,626,144
Qt: QPushButton never shows up
I'm trying to learn Qt, with a fairly simple application: #include <QtGui/QApplication> #include <QPushButton> #include <QDebug> /* -- header begin {{{ */ class BareBase { public: BareBase(); }; class BareBones: public QApplication { private: BareBase* base; public: BareBones(int...
Your QPushButton is creating and display correctly but go out of scope when leaving BareBase constructor. Using a member variable or a pointer will solve your problem. If you use a pointer, you should add your button to its parent. By this way the button will be automatically deleted when the parent will be deleted.
3,625,718
3,625,779
About delete, delete[], operator delete(), etc
Possible Duplicates: How does delete[] “know” the size of the operand array? ( POD )freeing memory : is delete[] equal to delete ? As I understand, the following class A {}; A* a = new A; // delete A; will result first in a call to operator new() (the global one, or a specialized one provided by A) to allocate the ...
It all depends on the implementation. Most run-times will indeed store the memory size just before the returned memory ((BYTE *)p-sizeof(size_t)) but there are other alternatives. In my own memory manager (yes, I write this kind of stuff), I have a more complex data structure (using pointers to linked lists, checksums...
3,625,836
3,625,906
how to link shared library against other shared library in linux?
My application dynamically loads liba.so (with dlopen). liba.so uses libb.so so I want to link liba.so against libb.so. How to do this in Linux? Thanks in advance.
If you build liba.so yourself, you need to link it with -l option gcc -o liba.so liba.o -L/libb/path -lb If you don't have liba sources, perhaps you could create libawrapper.so linked against liba and libb and to load dynamically this library gcc -o libawrap.so -L/liba/ -L/libb/ -la -lb