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,960,317
3,960,495
Optimum Update frequency for a client server based multiplayer game
I am making a multiplayer game in c++ : The clients simply take commands from the users, calculate their player's new position and communicate it to the server. The server accepts such position updates from all clients and broadcasts the same about each to every. In such a scenario, what parameters should determine the...
This answer is going to depend on what kind of a multiplayer game you are talking about. It sounds like you are talking about an mmo-type game. If this is the case then it will make sense to use an 'ephemeral channel', which basically means the client can generate multiple movement packets per second, but only the most...
3,960,548
3,960,566
What is this second new?
What is the second line? (Seen while answering another question.) int * x = new int [1] ; int * y = new (x) int; After the second line x and y have the same value (point to a same place). What's the difference between y = x and the second line? Is it like a constructor or something?
It's placement new. It constructs a new int in the memory pointed to by x. If you try: int * x = new int [1]; *x = 5; std::cout << *x << std::endl; int * y = new (x) int; *y = 7; std::cout << *x << std::endl; the output will be: 5 7
3,960,650
3,966,781
Conditional wait overhead
When using boost::conditional_variable, ACE_Conditional or directly pthread_cond_wait, is there any overhead for the waiting itself? These are more specific issues that trouble be: After the waiting thread is unscheduled, will it be scheduled back before the wait expires and then unscheduled again or it will stay unsc...
Here's what is written in the pthread_cond man page: pthread_cond_wait atomically unlocks the mutex and waits for the condition variable cond to be signaled. The thread execution is suspended and does not consume any CPU time until the condition variable is signaled. So from here I'd answer to the questions as foll...
3,960,812
3,960,859
does exists a stl data structures that "holds" a current element index/pointer?
i would like to improve my c++ code style so i decided that i definitively have to deep into stl...at first, as i need it in a real case, i woudl like to know if it is available some kind of container that hold a current index inside... for example i mean some container class i can navigate with next()/prev() but i c...
It sounds like you want an iterator. An iterator is used with a container. It acts as a pointer to a position in the container, and you can increment (next) and decrement (prev) it.
3,960,845
3,961,051
c++ pointer management with local variables
I've got a method that creates some Foo and adds it to a vector of Foos. Foos are in charge of deleting their Bars during destruction. The Foo constructor takes a pointer of Bars and a size of them. When the function returns, the local Foo gets deleted and destroys its Bars, however I get a valid Foo object back. How s...
Similar to Bars, you can create Foo objects also on the heap to avoid destruction in doIt functon. If Foo object is dynamically allocated, it will not be destroyed upon the return of doIt() function. You can clean up all Foo and Bar objects at the end like below(Working code) #include <vector> using namespace std; clas...
3,960,849
3,960,925
C++ template constructor
I wish to have a non-template class with a template constructor with no arguments. As far as I understand, it's impossible to have it (because it would conflict with the default constructor - am I right?), and the workaround is the following: class A{ template <typename U> A(U* dummy) { // Do something } }; M...
There is no way to explicitly specify the template arguments when calling a constructor template, so they have to be deduced through argument deduction. This is because if you say: Foo<int> f = Foo<int>(); The <int> is the template argument list for the type Foo, not for its constructor. There's nowhere for the cons...
3,960,948
3,964,014
Fast and flexible iterator for abstract class
In order to traverse grids with data in a fast and flexible way I set up an abstract, templated GridDataStructure class. The data should be accessed by STL iterators. When someone uses the class, he should not worry about which kind of STL iterator is appropriate for a specific subclass. A solution to this problem see...
In the solution, begin and end don't need to be virtual, because they just call BaseIteratorImpl::begin and BaseIteratorImpl::end which are virtual. In your specific case, you could just make begin and end virtual and not do any forwarding and it would be able to do what you want. The solution you pointed to is if you...
3,960,954
3,961,219
Multicharacter literal in C and C++
I didn't know that C and C++ allow multicharacter literal: not 'c' (of type int in C and char in C++), but 'tralivali' (of type int!) enum { ActionLeft = 'left', ActionRight = 'right', ActionForward = 'forward', ActionBackward = 'backward' }; Standard says: C99 6.4.4.4p10: "The value of an integer c...
I don't know how extensively this is used, but "implementation-defined" is a big red-flag to me. As far as I know, this could mean that the implementation could choose to ignore your character designations and just assign normal incrementing values if it wanted. It may do something "nicer", but you can't rely on that b...
3,961,103
3,961,120
Error: '...' does not name a type
I had a working project. After rearranging some code, I tried to recompile my project and then weird things started happening. Have a look at this excerpt from the compiler's output. I'm compiling from Eclipse on Windows using MinGW G++. **** Build of configuration Debug for project Pract2 **** **** Internal Builder i...
Most likely by "rearranging your code" you created a circular inclusion between board.h and piece.h. Your header files contain include guards that prevent infinite inclusion in such cases, but that will not help the declarations to compile. Check for circular inclusion and rethink you inclusion strategy accordingly. If...
3,961,467
4,054,215
Why isn't "0f" treated as a floating point literal in C++?
Why isn't 0f treated as a floating point literal in C++? #include <iostream> using namespace std; int main(){ cout << 0f << endl; return 0; } Compiling the above gives me C2509 (syntax error: 'bad suffix on number') using VS2008.
If there was an explicitly stated reason for this design decision, it would be in the C99 "Rationale" document (C++ copied all this stuff verbatim from C without reconsidering it). But there isn't. This is everything that's said about the 'f' suffix: §6.4.4.2 Floating constants Consistent with existing practice, a f...
3,961,558
3,961,610
Access to data, BSS segments will be through using a pointer or by instructions directly addressing?
I know when it's a matter of accessing memory of a stack frame it'll be through using stack frame pointer but I wonder about how the access to data, BSS segments containing global/static data will be, through using a pointer like stack frame pointer indicating starting point of those segments or instructions address pi...
Virtual memory means that these segments always appear in the same location in virtual-address space, so their addresses can be hardcoded into the executable code. (Note, this is not true for ASLR).
3,961,752
3,961,822
How do I know what shared variables I need to protect with a lock in c++ using boost?
For example, multithreading would never work if mutexes were not resilient to multithreaded access (e.g., two simultaneous calls to mutex.lock() can't screw things up). Does this extend to condition variables too? Specifically, I want to release a lock and then call cond.notify_one(). Theoretically, another thread coul...
You need to synchronize access to any object where the object is used by more than one thread and at least one of those threads may modify the object. There are various ways to do that synchronization: locks (mutexes) and atomics are probably the two most commonly used, though there are lock-free implementations of ...
3,962,140
3,962,202
Enable / Disable Aero in C#/VB.NET or C++ Win32
How to disable aero effects in C# .NET or C++ Win32 ??? This is my test code in C/C++, but only works if my app is runnig #include <dwmapi.h> int main() { DwmEnableComposition(DWM_EC_DISABLECOMPOSITION); while(true); //... return 0; } //LINK dwmapi.lib Thanks Edit: i figured it out #include <Window...
This should work: [DllImport("dwmapi.dll", PreserveSig = false)] public static extern int DwmEnableComposition(bool fEnable); static void Main(string[] args) { DwmEnableComposition(false); // Your application here. }
3,962,186
3,969,132
A solution for integrating ads in (Qt) applications
I'm working on a software that I would like to offer for free in charge with advertisement banners inside the application. Something like the banners in Spotify or the banner in the MS Live Messenger Contact List. Something like the iAd system that integrates in iOS-applications. Are there any solution for this? I'm pr...
As you all have pointed on; it's very difficult to imagine a system that will run even without a network connection. As I mentioned in the question, the best solution would be to have a WebView and depend on the network. And I think so too, but I was interested IF there was something geneous solution out there that I c...
3,962,227
3,962,253
Placement New and directions
I have been trying to understand the Placement new concept. I searched on the internet for some examples. And with all that info I created one example myself, here´s the code: #include <iostream> #include <cstdlib> #include <new> using namespace std; class MyClass { private: size_t num; public: ~My...
You're printing the address of the variable memAlloc, not the pointer's value. Replace cout<<"memAlloc : "<<&memAlloc with cout<<"memAlloc : "<< (void*)memAlloc.
3,962,708
3,962,760
How much do forward declarations affect compile time?
I am very interested in some studies or empirical data that shows a comparison of compilation times between two c++ projects that are the same except one uses forward declarations where possible and the other uses none. How drastically can forward declarations change compilation time as compared to full includes? #incl...
Forward declarations can make for neater more understandable code which HAS to be the goal of any decision surely. Couple that with the fact that when it comes to classes its quite possible for 2 classes to rely upon each other which makes it a bit hard to NOT use forward declaration without causing a nightmare. Equall...
3,962,902
3,962,967
detect currently installed anti-virus
Possible Duplicates: Detect Antivirus on Windows using C# How to detect if a virusscanner and/or firewall is installed? (And a few other security-related Q's.) is there a way to detect currently instaled av without searching for known processes?
Yes there is. You can use WMI, I assume you are asking about Windows, to check installed instances of an anti-virus program. It is quite simple from C# and this link gives a good explanation of how to do it. It is also possible to access WMI from C++ and that is explained here. Also for anything WMI related I highl...
3,962,991
3,963,583
&&= and ||= operators
Possible Duplicates: Why doesn't Java have compound assignment versions of the conditional-and and conditional-or operators? (&&=, ||=) Why does a “&&=” Operator not exist? Today at work I wrote the following LOC (the real identities of b and b1 are confidential :) b &&= b1; // meaning b = b && b1; I stared at it...
I don't know why both the question and some of the answers mention short-circuiting behavior of the corresponding logical operators as a potential issue. There's absolutely no short-circuit-related problems with defining &&= and ||= operators. They should be defined uniformly with += and other similar operators, meani...
3,963,352
3,963,446
Prevent last element in char * vector from changing
I am reading strings in C++ using fread where I am reading and storing shortSiteText in siteNames_. siteNames_ is declared as std::vector<char*> siteNames_; I use siteNames_ in other functions but because shortSiteText is a pointer, when I call the delete command on it, the last entry in siteNames_ is changed. How do ...
Let's zoom on this: shortSiteText = new char[shortSiteTextLength]; siteNames_.push_back(shortSiteText); delete [] shortSiteText; Explanation: The second line just pushes a pointer to the array, not the array itself. The first line then desallocate the array, on which the last element of siteNames still points to; this...
3,963,409
3,963,887
Dealing with M occurrences among N
Question I've been given at the job interview. I was close to the solution but did not solve it unfortunately. Assume we have a sequence that contains N numbers of type long. And we know for sure that among this sequence each number does occur exactly n times except for the one number that occurs exactly m times (0 < m...
You do 64 sums, one for each bit, for each of the sums you calculate sum mod n, this calculation return m for each bit that should to be set in the result, and 0 for each bit that should not be set. Example: n = 3, m = 2. list = [5 11 5 2 11 5 2 11] 5 11 5 2 11 5 2 11 sum of bit 0: 1 + 1 + 1 + ...
3,963,492
3,963,554
C++ - type traits question
I wish to know if it's possible in C++ to somehow handle the following situations: Situation 1) (Easily handled) class BasicFacility { } template <typename U1, typename U2> class Facility : public BasicFacility { } Suppose now that we want to have some compilation-time assertion and we want to check if the arbitrary ...
IIUC, you want to make sure a certain template parameter is an instance of the Facility template. That's simple: template< typename Policy > struct some_template; // note: only declared template< typename U1, typename U1 > struct some_template< Facility<U1,U2> > { // implementation }; Of course, you could also gen...
3,963,717
3,963,760
QT ListWidget itemclicked into a String
I am trying to just click on an item in a list of items in a listwidget. I right clicked in my UI and went to the slot: void main::listWidget_itemClicked(QListWidgetItem* item) In there I can run commands ect... But I want the selected item that I click on to be set to a String... I tried using the CONNECT/SIGNAL rou...
If I get you right, you just want to set the clicked item to a new String, right? item->setText(someQString) Edit: I'm not sure what you mean with "set it to a string", but you can retrieve the text (a QString) of the item with item->text()
3,963,771
3,963,864
Example of using scoped try_shared_lock and upgrade lock in boost
I have a thread pool that is using shared mutexes from the boost library. While the answers to my other question were helpful, Example of how to use boost upgradeable mutexes What I have realised that what I actually need is not to block if a shared lock or upgrade lock could not be obtained. Unfortunately, the boost ...
The answer seems to be that you can provide boost:try_to_lock as a parameter to several of these scoped locks. e.g. boost::shared_mutex mutex; // The reader version boost::shared_lock<boost::shared_mutex> lock(mutex, boost::try_to_lock); if (lock){ // We have obtained a shared lock } // Writer version boost::upgrad...
3,963,902
6,233,704
Why doesn't this Avahi client code work to add a CNAME alias to my Linux machine?
I'm trying to write a little program that will add mDNS CNAME aliases to my Linux device, so that it can be accessed via more than one "something.local." domain name. This program's intended function is the same as the avahi-aliases Python script, but in order to avoid a Python dependency, I'm trying to implement it in...
I finally figured this one out... the problem was that the (AvahiPublishFlags) argument to avahi_entry_group_add_record needed to include the AVAHI_PUBLISH_USE_MULTICAST bit, not just be zero. Oddly enough, the Python script I used as an example didn't include that bit. In any case, a working version of the source co...
3,963,944
3,964,090
GetPrivateProfileString - c++ class - return string - memory pre calculation
In GetPrivateProfileString, lpReturnedString returns the string value present in the key of a particular section of an ini file. My question is that how will i know exactly, how much memory has to be allocated, rather than just allocation a large chunk prior to calling this function. DWORD WINAPI GetPrivateProfileStrin...
Standard case The return value from GetPrivateProfileString is the number of characters copied to the buffer, not including the null terminator. Therefore, you could start with (say) a buffer of 100 _TCHARs and check the return value. If it’s 99, then either you exactly guessed the size of the string or (more likely) y...
3,964,017
3,964,150
Checking if integer falls in range using only < operator
I need to come up with some code that checks if a given integer falls within the bounds of a range. (The range is represented by a pair of integers.) So, given a range r defined as an std::pair<int, int>, and a test integer n, I want to say: if (n >= r.first && n <= r.second) The catch is, I need to use a std::less<in...
Polling others is not the best way to verify correctness. :) Instead, consider your problem. Everything you are dealing with is an int, so all values involved can be represented as an int. No addition or subtraction is involved, so you needn't worry about leaving the representable range. So, we can fall back to standar...
3,964,300
5,986,679
Problems with CamShift on the OpenCV C++ interface
I'm somewhat new to OpenCV and for some reason, I'm not managing to get CamShift to work in C++. First of all, if anyone has a working CamShift example using the C++ interface I would really appreciate it. Second, I'm trying to adapt the C example to C++, just to get it to work. Nothing fancy, yet. Basically, what I'm ...
It is a moderately easy-to-replicate bug. There are situations that arise (moving too fast, especially bumping the camera) that cause the logic of cv::RotatedRect( ... ) to explode and create a box that either collapses to a point or is bigger than the frame. This error is then caught. When doing exactly this I just m...
3,964,357
3,964,422
How to tell if class contains a certain member function in compile time
Possible Duplicate: Is it possible to write a C++ template to check for a function's existence? say there are 2 classes: struct A{ int GetInt(){ return 10; } }; struct B{ int m; }; I want to use object of type A or B in following function tempate< typename T > int GetInt( const T & t ) { //if it's A, I'll call: ...
Stealing from here, and assuming you fix your code so GetInt is const, we get: HAS_MEM_FUNC(GetInt, has_GetInt); template <bool B> struct bool_type { static const bool value = B; }; typedef bool_type<true> true_type; typedef bool_type<false> false_type; namespace detail { template <typename T> int get_in...
3,964,790
3,964,894
C++ method-invoking template-function not able to call overloaded methods
If you have this generic function: template<class type, class ret, class atype1, class atype2, class atype3> ret call3(type *pClass, ret(type::* funcptr)(atype1, atype2, atype3), atype1 arg, atype2 arg2, atype3 arg3) { //do some stuff here return (pClass->*funcptr)(arg, arg2, arg3); } and you do this: class My...
You can explicitly specify which template to use. call3<MyClass, void, int, int, int>( a, &MyClass::test, 1, 2, 3 ); If you rearange the order of your template parameters, you can get the MyClass and void deduced from the argument, so the call when needing an overload will look like this: call3<int,int,int>( a, &MyCla...
3,964,982
3,965,019
C++'s default inheritance access specifier?
I have some legacy code that I have to wrap, and I have come across this declaration: class Foo : Bar { // ... }; This seems to compile under GCC. I know it's bad, but I can't change it. My question is, if no inheritance access specifier is present, how does the C++ compiler handle it?
BTW, it is not called access modifier. It is called access specifier $11.2/2 - "In the absence of an access-specifier for a base class, public is assumed when the derived class is defined with the class-key struct and private is assumed when the class is defined with the class-key class." In your context,...
3,965,039
3,968,102
Recursively create a sine wave given a single sine wave value and the period
I am trying to write a .oct function for Octave that, given a single sine wave value, between -1 and 1, and sine wave period, returns a sine wave vector of period length with the last value in the vector being the given sine wave value. My code so far is: #include <octave/oct.h> #include <octave/dColVector.h> #include ...
Lets start with some trigonometric identities: sin(x)^2 + cos(x)^2 == 1 sin(x+y) == sin(x)*cos(y) + sin(y)*cos(x) cos(x+y) == cos(x)*cos(y) - sin(x)*sin(y) Given the sine and cosine at a point x, we can exactly calculate the values after a step of size d, after precalculating sd = sin(d) and cd = cos(d): sin(x+d) = si...
3,965,161
3,965,210
Convert Between Floating Point Standards
I am trying to convert an IEEE based floating point number to a MIL-STD 1750A floating point number. I have attached the specification for both: I understand how to decompose the floating point 12.375 in IEEE format as per the example on wikipedia. However, I'm not sure if my interpretation of the MIL-STD is correct....
The diagram above is a bit misleading, I think. In IEEE format, to switch from positive to negative, you simply flip the first bit. The remaining three bits can be treated as an unsigned number. In the MIL-STD format, the mantissa is a two's complement number, so while the first bit does indicate the sign, the remai...
3,965,212
3,965,224
How to read a input file with both argv and redirection from a input file
My program needs to accept three kinds of input commands below: ./Myprogram input.txt ./Myprogram < input.txt ./Myprogram I'm thinking about using argc to check the number of arguments to resolve the first two situations (since redirection doesn't count as an argument). But then I stuck on the last case, which simply ...
Redirection will never be seen by your program as an argument. So in: ./Myprogram input.txt ./Myprogram < input.txt ./Myprogram the second and third forms are identical. As for your second set of possibilities: ./Myprogram input1.txt input2.txt input3.txt ./Myprogram input1.txt < input2.txt input3.txt ./Myprogram the...
3,965,403
3,972,186
Algorithm to generate security token for MMO Login Service
I'm building a Login Service for an open source MMO game. I do not know much on the side of security/encryption and I am looking for a solution that will provide good protection against hackers and must not be too costly to generate. Our old system used a very simple system of authentication by storing the password as ...
Don't reinvent the wheel. The biggest problem with modern cryptography is when people want to roll their own, use SSL/TLS or HTTPS. This can be done safely without buying a certificate if you hard-code a self-singed certificate. Although each server should have its own certificate, or you run this risk Of MITM. ...
3,965,851
3,966,120
How would you implement attribute lists?
When speaking about attribute lists I mean a generic list which stores additional information for a class. The simplest case: A class has a std::map<std::string, std::string>. The first string names the attribute (like "Color"), the second string describes the value (like "Yellow"). In this example another class which ...
I did something similar. If the attributes are common for all instances of your class, make a separate Meta description of your class in which you describe the attributes. Then, per instance provide a simple vector of type boost::any (I don't use boost::any but something similar that we wrote ourselves). If the attrib...
3,965,895
3,966,079
How to draw a triangle by using QGraphicsView's QGraphicsItem class
I want to draw a triangular object in QGraphicsView by using QGraphicsItem. But I don't know how to implement bounding rect according to triangler.
You could use a QGraphicsPolygonItem. You just have to describe a triangle polygon with QPolygonF and then add it to your scene with QGraphicsScene::addPolygon(). // Describe a closed triangle QPolygonF Triangle; Triangle.append(QPointF(-10.,0)); Triangle.append(QPointF(0.,-10)); Triangle.append(QPointF(10.,0)); Triang...
3,966,039
3,966,080
Why does my C++ object loses its VPTr
While debugging one of the program's core dump I came across the scenario where its contained object which is polymorphic loses its VPTr and I can see its pointing to NULL. What could be the scenario when an object loses its VPTr. Thanks in advance, Brijesh
The memory has been trashed, i.e. something overwrote the memory. You destroyed it by calling delete or by invoking the destructor directly. This typically does not NULL out the vptr, it will just end up having it point to the vtable of the base class, but that depends on your implementation. Most likely, case 1. If ...
3,966,227
3,967,229
Read python dictionary using c++
I have a python dictionary stored in a file which I need to access from a c++ program. What is the best way of doing this? Thanks
How to do this depends on the python types you've serialised. Basically, python prints something like... {1: 'one', 2: 'two'} ...so you need code to parse this. The simplest case is a flat map from one simple type to another, say int to int: int key, value; char c; if (s >> c && c == '{') while (s >> key) {...
3,966,352
3,966,390
Can I create a map with a dynamic constructed comparer?
I want to create std::map in STL, but the comparer depends some dynamic value which is available only at runtime.. How can I make this? For example, I want something looks like std::map<int, int, Comp(value1, value2)>. value1 and value2 are not the compared number here, they are some kind of configuration numbers.
Use a functor class: #include <map> class Comp { public: Comp(int x, int y) : x(x), y(y) {} bool operator() (int a, int b) const { /* Comparison logic goes here */ } private: const int x, y; }; int main() { std::map<int,float,Comp> m(Comp(value1,value2)); } This is like a function, but in the form of...
3,966,406
3,966,849
Sending messages to a thread?
I need to imlement in cocoa, a design that relies on multiple threads. I started at the CoreFoundation level - I created a CFMessagePort and attached it to the CFRunLoop, but it was very inconvenient as (unlike on other platforms) it needs to have a (systemwide) unique name, and CFMessagePortSendRequest does not proces...
use -performSelectorOnThread:withObject:waitUntilDone:. The object you pass would be something that has a property or other "slot" that you can put the return value in. e.g. SomeObject* retObject = [[SomeObject alloc] init]; [anotherObject performSelectorOnThread: whateverThread withObject: retObject waitUntilDone: YE...
3,966,967
3,967,049
lower_bound in set (C++)
I've got a set and I want to find the largest number not greater than x in it. (something like lower_bound(x) ) how should i do it? Is there any predefined functions? set<int> myset; myset.insert(blahblahblah); int y; //I want y to be greatest number in myset not greater than x
You can use upper_bound like this: upper_bound(x)--. Upper bound gives you the first element greater than x, so the element you seek is the one before that. You need a special case if upper_bound returns begin().
3,967,177
3,968,697
When to use const and const reference in function args?
When writing a C++ function which has args that are being passed to it, from my understanding const should always be used if you can guarantuee that the object will not be changed or a const pointer if the pointer won't be changed. When else is this practice advised? When would you use a const reference and what are th...
Asking whether to add const is the wrong question, unfortunately. Compare non-const ref to passing a non-const pointer void modifies(T &param); void modifies(T *param); This case is mostly about style: do you want the call to look like call(obj) or call(&obj)? However, there are two points where the difference matter...
3,967,415
3,968,298
COM Interoperability with .Net - missing methods/properties
I have a .Net asm with several interfaces and classes exposed to COM using the [ComVisible(true)] attribute. I generate a tlb, then reference this in my StdAdx file within a C++ COM component. What's odd is that for some reason, even though the very basic intellisense (VS6 for C++) is able to see my properties and me...
You didn't show the calls generating the error message. I suppose you used the property name directly. You need to use the method get_Comment instead of simply Comment property. The generated tlh refers to that method. Did you used raw_interfaces_only attribute of the #import directive? Later edit about BSTR: BSTR is...
3,967,564
3,967,657
How to fetch memory in realtime after CreateProcess?
I have executed a process using CreateProcess, but I want to fetch or dump the memory area allocated to the process, preferably in real time. Unfortunately I do not know how to recieve the pointer to the memory are after creating the process. I've been searching around, but I have not found any useful answers so far. I...
Try VirtualQueryEx() to see what memory pages are used, and ReadProcessMemory() to read them.
3,967,620
3,968,108
Member-function pointers and phantom classes
I've been messing about with member-function pointers in relation to a previous question. In the code below I call methods on a class (B) that change a variable (count) in it, but I never make an instance of this class. Why does this work? #include <iostream> #include <string> #include <map> class A; typedef int (A::*...
The result is just undefined behavior. For example, I get that b = 2083899728 and d = -552766888. The persistent thing you are manipulating is most likely an int's worth of bytes in the map instance of A (because if the object were indeed a B, then that's the offset where the count member would be located. In my stdlib...
3,967,661
3,968,022
error while loading shared libraries: libstdc++.so.6: wrong ELF class: ELFCLASS64
I am trying to install Qt in my CentOS system. While building the library, I'm getting this error: /root/capture/qt-everywhere-opensource-src-4.7.0/bin/qmake: error while loading shared libraries: libstdc++.so.6: wrong ELF class: ELFCLASS64 /root/capture/qt-everywhere-opensource-src-4.7.0/bin/qmake: error while loading...
It seems the softlink of the libstdc++.so.6 has been changed and is pointing to libstdc++.so.6.0.13 (64-bit?). I just changed the softlink by issuing the following command (in /usr/lib folder): rm -f libstdc++.so.6 ln -s ./libstdc++.so.6.0.8 ./libstdc++.so.6
3,967,808
3,967,856
QT and Visual Studio 2010
Can any one provide me with a step by step how-to for getting QT to work in VS 2010? I have: Visual Studio 2010 Ultimate Windows 7 Enterprise. qt-sdk-win-opensource-2010.05 qt-vs-addin-1.1.7 I tried executing this from Visual Studio command prompt: configure.exe -platform win32-msvc2008 -no-webkit -no-phonon -no-pho...
Download the version of Qt already compiled for Visual Studio 2008 (latest version from here). It should work with Visual Studio 2010.
3,967,832
3,968,180
static allocated data structures
I'm working on a existing embedded system (memory is limited, Flash is limited, ...) with an RT OS. All data structures have a fixed size and are allocated at "compile time" and are therefore suited for RT. There is no dynamic memory allocation. The programming language is C++, but there is no STL available. I like to ...
Have you considered passing your own allocator (allocating from a static pool) to STL containers? Other than that, I don't think anything like this exists. You might want to look at this related question to get started with a static vector class. If you do this, consider to make it Open Source.
3,967,932
3,967,947
Why does Process.waitFor() never return?
I am launching a windows process (wrote in C++ but I don't have sources) from Java code in the following way: Process p1 = Runtime.getRuntime().exec(cmdAndParams); p1.waitFor(); My problem is that the waitFor() method never ends. Thus I tried to launch the process in a simple shell and it ends correctly with many pr...
This is an OS thing. The child process is writing to stdout, and that's being buffered waiting for your Java process to read it. When you don't read it, the buffer eventually fills up and the child process blocks writing to stdout waiting for buffer space. You would have to processes the child process' stdout (and stde...
3,967,996
3,968,040
How to retrieve value type from iterator in C++?
My question is sure a simple one for anybody familiar with C++ syntax. I'm learning C++ and this is some sort of homework. template<typename Iter> void quickSort(Iter begin, Iter end) { //.. auto pivot = * ( begin + (end - begin)/2 ); //.. } pivot is supposed to contain the value from the center of...
typename std::iterator_traits<Iter>::value_type This will work if your template is instantiated with Iter as a pointer type. By the way, typename isn't part of the type itself. It tells the compiler that value_type really is a type. If it were the name of a function or a static data member, then that affects the syntax...
3,968,175
3,968,216
simple C++ project samples
Im trying to learn OOP but I need to see some real case scenarios of using C++. For me, as a beginner in programming internet is too big and the book is too few examples. All I find on the source repositories are large projects or too few details. Can you give me a link to some c++ projects which are good for beginners...
I'd recommend starting at the C++ Language Tutorial. There are lots of good examples there, including a section on OOP.
3,968,223
3,968,382
Put breakpoint on named function
Is there a way to put a breakpoint on any function in Visual Studio, sort of like bm kernel32!LoadLib* in WinDbg? I know one way is to break at application start, find the required DLL load address, then add offset to required function you can get via Depends, and create a breakpoint on address. But that's really slow,...
Go to "Debug / New breakpoint / Break at function..." and paste the function name. For APIs, this can be tricky, as the name of the function as seen by the debugger is different from its real name. Examples: {,,kernel32.dll}_CreateProcessW@40 {,,user32.dll}_NtUserLockWindowUpdate@4 See this blog post to find the righ...
3,968,404
4,036,413
Should I declare these methods const?
I'm working on some C++ code where I have several manager objects with private methods such as void NotifyFooUpdated(); which call the OnFooUpdated() method on the listeners of this object. Note that they don't modify the state of this object, so they could technically be made const methods, even though they typically...
Loosely speaking you have a container class: A manager full of observers. In C and C++ you can have const containers with non-const values. Consider if you removed one layer of wrapping: list<Observer> someManager; void NotifyFooUpdated(const list<Observer>& manager) { ... } You would see nothing strange about a g...
3,968,439
3,968,776
Interface-based programming in C++ in combination with iterators. How too keep this simple?
In my developments I am slowly moving from an object-oriented approach to interface-based-programming approach. More precisely: in the past I was already satisfied if I could group logic in a class now I tend to put more logic behind an interface and let a factory create the implementation A simple example clarifies...
You are mixing metaphors here. If a library is a container then it needs its own iterator it can't re-use an iterator of a member. Thus you would wrap the member iterator in an implementation of ILibraryIterator. But strictly speaking a Library is not a container it is a library. Thus the methods on a library are actio...
3,968,536
3,969,284
objective-c++ how to add method into c++ class
i'd like to have a function in api style. But implementation must be on Objective-C lang. So i've read some information and decided to do following - to mix objective-C with C++. And have problem to call an objC method in C++ class. Thats my example: //MYClass.h : class CClass { private: id fileName; BOOL rez; publi...
The line where you want to create your instance of the Objective-C class is wrong, there is a '*' and a ';' missing, it should look like this: ObjCClass *c = [[ObjCClass alloc] init]; You also need to add a forward declaration for your Objective-C class in front of the C++ class: @class ObjCClass; Those changes shoul...
3,968,634
3,968,735
Turing machine: But why use template metaprogramming?
I am a final year engineering student. Me and my friends have decided that our final year project would be "Simulation of Turing Machine using Template Metaprogramming". I understand what "Turing Machine" and "Template Metaprogramming" are but my question is why the simulation would be tedious if we design the Turing M...
The primary reason why one would implement Turing machines using template metaprogramming is not because it's easier than in "ordinary" C++ (it isn't), but to demonstrate that C++ templates are Turing complete.
3,968,731
3,969,157
Fast Updating of QPixmap from byte array
I'm working on a vision application and I need to have a "Live View" from the camera displayed on the screen using a QPixmap object. We will be updating the screen at 30frames/second on a continuous basis. My problem is that this application has to run on some 3-5 year old computers that, by todays standards, are slow...
First of all, the most important piece of information regarding the "picture" classes in Qt: QImage is designed and optimized for I/O, and for direct pixel access and manipulation, while QPixmap is designed and optimized for showing images on screen. What this means is that QPixmap is a generic representation of your...
3,968,784
3,968,915
C++ beginner question
I am in the process of learning C++ in order to understand some open source code I have been given. I came across a line as follows: cmd << '\n' I assumed that "cmd" must be some kind of special receptor for a stream, perhaps a string - but on further investigation I found that "cmd" was an entire class with assorted ...
See operators as functions: For instance, 3 + 4 calls a binary function taking two numbers and returning the sum of them. Here, the author has created such a function to define the << operator, so that it can work with a cmd class instance as the left parameter, and a string as the right parameter. This is called "oper...
3,968,972
3,968,994
Should C++ keep variables intact on input failure?
Doesn't C++ offer any guarantee about keeping variables intact on input failure? With older versions of gcc, a program like this one keeps the -1 value of i on failure (for instance if a letter is typed instead of a number on input). With Ubuntu 10.10 (gcc 4.4.5), i is reset to zero in case of input failure. #include <...
Don't rely on the variable. Rely on the state of the stream: if (std::cin >> i) // "if (!std::cin.fail())" would also work { // ok } else { // error } As for why the behavior has changed, that's because the C++ standard has evolved: From C++03: If an error occurs, val is unchanged; otherwise it is set t...
3,969,047
3,969,146
Is there a standard way of representing an SHA1 hash as a C string, and how do I convert to it?
This question is about how to create an SHA-1 hash from an array of data in C using the OpenSSL library. It returns an array of 20 bytes, containing the hash. Is there some standard way of representing that data in string form, not binary? If so, is there a function in OpenSSL itself to convert to said string format? I...
Usually hashes are represented as a sequence of hexadecimal digits (naturally, two per byte). You can write the code to write such thing easily using an ostringstream with the right modifiers: #include <string> #include <sstream> #include <iomanip> std::string GetHexRepresentation(const unsigned char *Bytes, size_t Le...
3,969,063
3,970,654
array of objects,c++
i have two classes namely Flight and Runway. Now i am trying to pass an array of these objects as parameter to a function. void fun(Flight ptr1[],Runway ptr2[]) { ... ... } ptr1 should point to an array of Flight objects and ptr2 should point to an array of Runway objects. Now inside this function fun() how do i acce...
void fun(Flight ptr1[],Runway ptr2[]) is interpreted as void fun(Flight *ptr1, Runway *ptr2) This is called "decomposition," and I think it's rotten. It's mainly a feature for backward compatibility with C. If you want pointers, specify pointers, not arrays, because pointers and arrays are different things. You can a...
3,969,113
3,969,135
Derived class stored in ptr_vector not being destructed
Was trying to find the best way to use ptr_vector to store, access and release objects, especially when the stored object is inherited from other (ptr_vector should not have any issues with object slicing). But when running the below program, surprisingly the derived class isn't being destructed. Anyone know why? #incl...
The destructor of the base class is not virtual: ~A() {cout<<"* Destructed A"<<id<<endl;} Should be: virtual ~A() {cout<<"* Destructed A"<<id<<endl;} Why ? See When should your destructor be virtual?
3,969,190
4,871,945
Is rebasing DLLs (or providing an appropriate default load address) worth the trouble?
Rebasing a DLL means to fix up the DLL such, that it's preferred load adress is the load address that the Loader is actually able to load the DLL at. This can either be achieved by a tool such as Rebase.exe or by specifying default load addresses for all your (own) dlls so that they "fit" in your executable process. Th...
I'd like to provide one answer myself, although the answers of Hans Passant and others are describing the tradeoffs already pretty well. After recently fiddling with DLL base addresses in our application, I will here give my conclusion: I think that, unless you can prove otherwise, providing DLLs with a non-default Bas...
3,969,196
3,989,437
Inherit class with template function
I would like to create a base class that will be inherited by other objects so that they can be stored in the same container. This base class will contain a templated method that defines the function as a setter or getter used for accessing a buffer in a multithreaded system. I want to do something like this guy did ...
I ended making two helper classes, a consumer class and producer class that inherit the base class. The base class contains a enum define define whether the derived classes are what functionality. This enum value is set during the base class constructor call. The helper classes contain the appropriate version of the...
3,969,297
3,971,557
GetKeyState doesn't work in Windows 2000 (C++)
I have just tested my DirectX game on a Windows 2000 SP4 system but it won't receive any mouse clicks! This is how I check for mouse clicks : unsigned int mButtons = 0; if (GetKeyState(VK_LBUTTON) < 0) mButtons |= HIDBoss::MOUSE_LEFT; if (GetKeyState(VK_RBUTTON) < 0) mButtons |= HIDBoss::MOUSE_RIGHT; if...
I'm not sure why it doesn't work but I'd recommend using GetAsyncKeyState instead. Edit: In answer to your comment. It is merely a suggestion but its, equally, pretty easy to find out if the buttons are swapped by calling: GetSystemMetrics(SM_SWAPBUTTON) Your big problem arises from the fact that GetKeyState is not s...
3,969,610
3,970,289
How to combine templates with enums in C++?
There are a huge feature collection in C++ programming language that supply a strict control over datatypes. Frequently one would mold his code with template system to achieve the most adequate functionality while guaranteeing within it correct type preservation and flexibility in its manipulation. Less frequently enum...
The type traits idiom as @UncleBens illustrates is the usual way of solving this problem. You can attach information to classes using static const members of integer or enumeration type, as well. #include <iostream> enum color { red, green, blue }; struct x { static const color c = red; }; template< color c > st...
3,969,621
3,969,671
Copy Constructor with reference variable
I have a class as given below, I want to write a copy constructor for the same. I need to create a deep copy constructor for this. following code is printing x and c properly but value of y here is garbage. #include "stdafx.h" #include <string.h> class MyClass { public: MyClass(int a) : y(a) { } MyClass(const MyCl...
In your code, y is reference.. You're creating MyClass m1(0), so m1.y points to a temporary variable - 0. You just must not do this.. I don't know why you y member is reference.. ?? Anyway, if you want this to be that way, do that: //.. int a = 10; MyClass m1(a); //.. Anyway, this is ugly.. And dangerous, if you don't...
3,970,021
3,971,079
How to read Lua table return value from C++
I have a Lua function that returns table (contains set of strings) the function run fine using this code: lua_pushstring (lua, "funcname"); lua_gettable (lua, LUA_GLOBALSINDEX); lua_pushstring(lua, "someparam"); lua_pcall (lua, 1, 1, 0); the function returns a table. How do I read it's contents from my C++ code?
If you are asking how to traverse the resulting table, you need lua_next (the link also contains an example). As egarcia said, if lua_pcall returns 0, the table the function returned can be found on top of the stack.
3,970,066
3,971,732
Creating a transparent window in C++ Win32
I'm creating what should be a very simple Win32 C++ app whose sole purpose it to ONLY display a semi-transparent PNG. The window shouldn't have any chrome, and all the opacity should be controlled in the PNG itself. My problem is that the window doesn't repaint when the content under the window changes, so the transpar...
I was able to do exactly what I wanted by using the code from Part 1 and Part 2 of this series: Displaying a Splash Screen with C++ Part 1: Creating a HBITMAP archive Part 2: Displaying the window archive Those blog posts are talking about displaying a splash screen in Win32 C++, but it was almost identical to wha...
3,970,241
3,970,640
Displaying log data in latest-first format
I like having log data in a last-first form (the same way most blogs and news sites organize their posts). The languages I'm most comfortable in are C++ and Python: is there a way to output log data either to the screen (stdout) or a file with the most recent entry always being on top? Or is there perhaps a way of modi...
using the tac command you can also do : watch "tac file.log" add the -n option if you want to control the refresh time like this watch -n 0.3 "tac file.log"
3,970,279
3,978,552
What is the point of a private pure virtual function?
I came across the following code in a header file: class Engine { public: void SetState( int var, bool val ); { SetStateBool( int var, bool val ); } void SetState( int var, int val ); { SetStateInt( int var, int val ); } private: virtual void SetStateBool(int var, bool val ) = 0; virtua...
The question in the topic suggest a pretty common confusion. The confusion is common enough, that C++ FAQ advocated against using private virtuals, for a long time, because confusion seemed to be a bad thing. So to get rid of the confusion first: Yes, private virtual functions can be overridden in the derived classes. ...
3,970,435
3,970,459
Fedora Equivalent of prstat /truss
Is there any command in Fedora core (10) which displays the system call being executed ? Scouring the internet only reveals top and likes...
Have you tried strace ?
3,970,734
3,970,790
What is object index of QTextFormat?
The function int QTextFormat::objectIndex () const returnes an object index. What is it? And what if I do the following: QTextBlockFormat bfmt; bfmt.setObjectIndex(0); What this code does? ADDED: Here there is a function void TextEdit::textStyle(int styleIndex). This function is for adding a list into QTextEdi...
QTextOjbects are used to group parts of a QTextDocument. Some text objects would be QTextList, QTextFrame, QTextTable etc. Each of these text objects have an index. The ojbectIndex of a QTextFormat associates the format object with a text object. Your code above would associate bfmt with the text object with index 0.
3,970,818
3,970,921
What’s the best way to delete boost::thread object right after its work is complete?
I create boost::thread object with a new operator and continue without waiting this thread to finish its work: void do_work() { // perform some i/o work } boost::thread *thread = new boost::thread(&do_work); I guess, it’s necessary to delete thread when the work is done. What’s the best way to this without explic...
The boost::thread object's lifetime and the native thread's lifetime are unrelated. The boost::thread object can go out of scope at any time. From the boost::thread class documentation Just as the lifetime of a file may be different from the lifetime of an iostream object which represents the file, the lifetime of a t...
3,970,962
3,971,045
STL Set: insert two million ordered numbers in the most efficient manner
For the following mass-insert, because the inputs are ordered, are there any (slight) optimizations? set<int> primes; for ( int i = 2; i <= 2000000; i++ ) { primes.insert(i); } // then follows Sieve of Eratosthenes algorithm New improvement, twice as fast: set<int> primes; for ( int i = 2; i <= 2000000; i++ ) { ...
There is a overloaded version of insert method available which takes an iterator as the first parameter. This iterator is used as the hint i.e. the comparison will start from this iterator. So if you pass the proper iterator as the hint, then you should have a very efficient insert operation on the set. See here for de...
3,971,049
3,971,051
What's the C++ version of Java's ArrayList
Just getting back into using C++ and trying to convert a simple Java program I wrote recently. What's the preferred equivalent to the Java ArrayList in C++?
Use the std::vector class from the standard library.
3,971,085
3,971,263
How does a bit field work with character types?
struct stats { char top : 1; char bottom : 1; char side : 2; } MyStat; I have seen this format with integers but how does the above char bit field work and what does it represent? Thank You.
Char bit fields work in the same way as int, just the base type is 8-bit wide, not 32-bit. So you'd get a struct stats, which has the size of 1 byte, and 3 member variables, occupying a total of 4 bits.
3,971,124
3,971,145
How to call an operator as function in C++
I want to call a specific operator of specific base class of some class. For simple functions it's easy: I just write SpecificBaseClass::function( args );. How should I implement the same for operators without casting trickery? Isolated problem: class A { public: A operator+( const A &other ) const {...} }; ...
The operator is a nonstatic member function, so you could use a.A::operator+( b ) However, for another class that defines operator+ as a static member function, what you tried would be correct. And a third class might make it a free function (arguably the best way), so B::operator+(a,b) and a.operator+(b) would both b...
3,971,140
3,971,445
Weird behaviour with sockets on localhost
I have two .net applications communicating with sockets on port 5672 and everthing works fine. On server side, i open the connection with this simple code lines: IPAddress localAddr = Dns.GetHostEntry("localhost").AddressList[0]; TcpListener socket = new TcpListener(localAddr, 5672); socket.Start(); If i try ...
When I run the following code: IPAddress localAddr = Dns.GetHostEntry("localhost").AddressList[0]; IPAddress localAddr2 = Dns.GetHostEntry("localhost").AddressList[1]; I get the IPV6 address you showed in localAddr, and "127.0.0.1" in localAddr2 (and there are no more entries in AddressList). If you wa...
3,971,612
3,971,627
Debug and Release configurations
As we all know, in Visual Studio there are two predefined configurations - Debug and Release. I have been using them since I started programming and soon learnt their differences. However recently I had to create my own configurations and now I have a question: Are those two configurations defined/determined solely by ...
Are those two configurations defined/determined solely by their parameters/options from "project options" page? Yes. if I create a new configuration and copy all settings from Debug or Release, will my new configuration be equivalent to the predefined Debug/Release ? Yes it will. For instance, the deb...
3,971,703
4,027,790
How to use C++ Boost library with pkg-config?
I successfully compiled and installed the latest version of the Boost library onto my linux machine. Now, I would like to be able to use pkg-config to ease the process of providing linking paremeters with GCC. Since I am too lazy for hand-coding my own .pc file, is there a script/tool which would automatically generate...
What you're looking for seems to be a bit complicated, and a long-requested feature, as indicated in this 3 year old post https://svn.boost.org/trac/boost/ticket/1094 on Boost's trac. Reading through it shows that the feature was repeatedly postponed and never implemented (as of 1.4.3). The cause of the inability to g...
3,971,730
3,971,755
learning about function prototypes and function overloading
can anyone give me an example of function overloading in c++ with 4 function prototypes ? i still don't get them quite good .. sorry newbie question, thanks for looking in. Adam Ramadhan
The following are C++ function declarations and would typically be in the header (.h or .hpp) file. These particular declarations have no code. The code is in the definition shown further below. int sum(int a, int b); int sum(int a, int b, int c); int sum(int a, int b, int c, int d); int sum(int a, int b, int c, int ...
3,971,818
3,971,846
C++ std::auto_ptr copy constructor
std::auto_ptr lacks const copy constructor, therefore I cannot use it directly in collections. is there some way to have for example vector of std::auto_ptr without using boost pointer collection template?
If you have a C++0x compiler you can use shared_ptr or unique_ptr as appropriate. There is a good example of correct unique_ptr usage here courtesy of @James McNellis. For a shared_ptr walkthrough look here, courtesy of @D.Shawley. [Upvotes would still be appreciated on those threads, I am sure.] vector of auto_ptr i...
3,971,902
3,971,934
how would I sort a list and get the top K elements? (STL)
I have a vector of doubles. I want to sort it from highest to lowest, and get the indices of the top K elements. std::sort just sorts in place, and does not return the indices I believe. What would be a quick way to get the top K indices of largest elements?
The first thing that comes to mind is somewhat hackish, but you could define a struct that stored both the double and its original index, then overload the < operator to sort based on the double: struct s { double d; int index; bool operator < (const struct &s) const { return d < s.d; } }; Then...
3,971,966
3,972,093
How to write my own download manager using c++?
i want to write my own download manager using c++(qt4) but i have no idea about that so please suggest me from where should i start if you know any good tutorial or link the please post it. i also want to implement the pause/resume and multiple download features also. i already know that there is a long list of downl...
If you are trying to make production grade I would recommend URDL or Boost.Asio in general. But if you are tinkering around for fun then consider Byte Ranges and multi-threading for async processing. Still asio would be the best bet for that too.
3,972,042
3,972,079
C++ event processing
I am using the excellent asio for an asynchronous network client. When handling read (async_read) I am concerned that the method/function handling the data might hang or take too long (the function is supplied by the user of the class). What is the best way of calling the supplied function and ensuring it won't take ...
You could write a wrapper function which launches the given handler in a separate thread and does a timed_join on it. If the timeout reaches, you could throw an exception or do whatever else you want.
3,972,109
3,972,179
will compiler reserve memory for this object?
I have following two classes: template <size_t size> class Cont{ public: char charArray[size]; }; template <size_t size> class ArrayToUse{ public: Cont<size> container; inline ArrayToUse(const Cont<size+1> & input):container(reinterpret_cast<const Cont<size> &>(input)){} }; I have three following lines of code at...
Any variable defined at global scope has memory reserved for it at compile time. That does not mean it's guaranteed to be properly initialized, but it's there all the same. At link-time, Visual C++ offers the option to strip unused data and functions via /OPT - see here.
3,972,517
3,972,558
2D Polygon Collision Detection
Does anyone know a simple way to check if two polygons, especially rectangles, are colliding? I found a simple way to see if two are touching by just checking if any lines on the two rectangles are colliding, but this will not work if one polygon is in another. Does anyone know a more efficient way to do this or just...
Look up the Separating Axis Theorem. There's a tutorial here. It's quick, elegant, robust, not too hard, and has lots of resources.
3,972,548
3,972,780
Virtual dispatch implementation details
First of all, I want to make myself clear that I do understand that there is no notion of vtables and vptrs in the C++ standard. However I think that virtually all implementations implement the virtual dispatch mechanism in pretty much the same way (correct me if I am wrong, but this isn't the main question). Also, I b...
1. Do I have any errors in the above description? All good. :-) 2. How does the compiler know f's position in vtable Each vendor will have their own way of doing this, but I always think of the vtable as map of the member function signature to memory offset. So the compiler just maintains this list. 3. Does this mean ...
3,972,946
3,973,181
MSVCR80.DLL is missing. What shall I install or what shall I trick in c++ project configuration
I have a legacy msvs2005 c++ project library (dll). I opened project on WindowsXP workstation with msvs2008 installed and code compiled fine. But when I try to use it with executable module i observe "my-library.dll or one of it's dependencies were not found". Dependency Walker tells me that MSVCP80.DLL, MSVCR80.DLL, ...
installed 2008 Visual C++ redistributable package but the problem remains. Where did you get the redist from? There are a variety of versions of the redist, the one that comes with MSVC is most likely to be the appropriate one. There are however a bunch of things that happened such as ATL security updates and such...
3,973,057
3,973,082
Overriding = operator in C++
I am trying to override the = operator so that I can change my Point class into a Vector3 class. Point tp = p2 - p1; Vec3 v; v = tp; The problem I am facing is that, "v" will have its x,y,z members equal to zero all the time. Vec3.h: Vec3 operator =(Point a) const; Vec3.cpp: Vec3 Vec3::operator =(Point a) const {...
It's been a while, but I think you want Vec3& Vec3::operator=(const Point &a) { x = a.x; y = a.y; z = a.z; return *this; // Return a reference to myself. } Assignment modifies 'this', so it can't be const. It doesn't return a new Vec3, it modifies an existing one. You will also probably want a copy construc...
3,973,173
3,973,528
string manipulating in C?
I want to print an array of characters, these characters are underscores first. Then the user can write characters on these underscores.I used gotoxy() but it doesn't work properly. That is what i wrote: int main(void) { char arr[20]; int i; char ch; clrscr(); for(i=0;i<=20;i++) { texta...
The first thing is this: You probably don't want to have all those calls to gotoxy, textattr and cprintf in your main function, since that is not what the main function is supposed to do. It is much more likely that the main function's purpose is "to read some text from the user, presented nicely in an input field". So...
3,973,176
3,974,323
Cross-Platform C++ Dynamic Library Plugin Loader
I was just wondering what my options were for cross-platform implementations for the dynamic loading of plugins using shared libraries. So far the only one that I have found is: http://library.gnome.org/devel/glib/stable/glib-Dynamic-Loading-of-Modules.html And I was just wondering if I had other options? Essentially...
You could look into Boost Extension, though it has not yet been accepted into Boost. The Boost.Extension library has been developed to ease the development of plugins and similar extensions to software using shared libraries. Classes, functions and data can be made available from shared libraries and loade...
3,973,218
3,973,236
Header-only libraries and multiple definition errors
I want to write a library that to use, you only need to include one header file. However, if you have multiple source files and include the header in both, you'll get multiple definition errors, because the library is both declared and defined in the header. I have seen header-only libraries, in Boost I think. How did ...
Declare your functions inline, and put them in a namespace so you don't collide: namespace fancy_schmancy { inline void my_fn() { // magic happens } };
3,973,293
4,163,045
Passing a C# string to an unmanaged C DLL in Windows Mobile
I've got an unmanaged c++ DLL that I need to call from a Windows Mobile C# app. I've got the C# wrapper and it works nicely in desktop. I can call the DLL functions from a C# desktop program and pass strings around with no problem. However, when I compile the lib and the wrapper for the mobile platform, I get an error ...
No, there isn't. Microsoft documentation specifies that: [...] the .NET Compact Framework only supports Unicode, and consequently only includes the CharSet.Unicode (and CharSet.Auto which equals Unicode) value, and does not support any of the clauses of the Declare statement. This means that the ExactSpell...
3,973,398
3,973,490
How does the string class in c++ std work?
I'm afraid I don't know templates (or C++, really), but I know algorithms and data structures (even some OOP! :). Anyway, to make the question a bit more precise, consider what I would like to be part of the answer (among others I don't know in advance). Why is it coded as a template? How does the template work? How d...
std::string is actually a typedef to a std::basic_string<char>, and therein lies the answer to your #1 above. Its a template in order to make basic_string work with pretty much anything. char, unsigned char, wchar_t, pizza, whatever... string itself is just a programmer convenience that uses char as the datatype, s...
3,973,470
3,973,775
Is there any free portable (meaning <100mb ) IDE for C++ windows developers with compiler capable of codehinting and tested working with Win32 API?
What I need is a small sized IDE+compiler for creating C++ applications that will interact with win32APIs... And It'd be grat for it to be capable of analizing headers I give it for code completion and connecting DLL's (not .Net DLLs but If it'd be capable ofcompiling C++ .NET projects I would just be super-duper glad)...
Code::Blocks is another one to consider. The binaries for the IDE + the Mingw compiler are only 73 MB compressed. Code::Blocks should be able to do all or most of what you want, though I'm pretty sure it can't do any C++/CLI stuff.
3,973,659
3,973,692
c++ unordered_map compiling issue with g++
I am using g++ in Ubuntu g++ (Ubuntu 4.4.3-4ubuntu5) 4.4.3 I have this code #include<unordered_map> using namespace std; bool ifunique(char *s){ unordered_map<char,bool> h; if(s== NULL){ return true; } while(*s){ if(h.find(*s) != h.end()){ return false; } h.insert(*s,true); s++; ...
In GCC 4.4.x, you should only have to #include <unordered_map>, and compile with this line: g++ -std=c++0x source.cxx More information about C++0x support in GCC. edit regarding your problem You have to do std::make_pair<char, bool>(*s, true) when inserting. Also, your code would only insert a single character (the der...
3,973,665
3,973,698
How do I use rand_r and how do I use it in a thread safe way?
I am trying to learn how to use rand_r, and after reading this question I am still a little confused, can someone please take a look and point out what I'm missing? To my understanding, rand_r takes a pointer to some value (or a piece of memory with some initial value) and use it to generate new numbers every time it i...
That's correct. What you're doing in the first case is bypassing the thread-safety nature of rand_r. With many non-thread-safe functions, persistent state is stored between calls to that function (such as the random seed here). With the thread-safe variant, you actually provide a thread-specific piece of data (seed1 an...
3,973,674
3,973,743
address in push instruction changing after modifying exe in hex
running on windows 7, 32bit home pro I created a very simple few line app in visual studio 2008 , compiled and linked with standard libraries in release mode into executable test.exe. The code in c is as follows: char* test = "h"; int main() { _asm { push 0xFEEDBACC; } MessageBoxA(0,test,test,0...
The image base was changed too between the last two screens. I think that it just got relocated (there used to be an address): the dword at 0x15: A4 20 26 00 points to IAT, so after relocation its high word (bytes 0x17 0x18) will be modified by adding 0x00F7 - 0x0040 = 0x00B7 to it. Try disabling image-base randomiza...