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
2,928,834
2,929,183
PhysX: Joint friction/"stiff" joints
I'm working with physx (trying to add ik to ragdoll) at the moment. For some reason, all ragdoll joints are frictionless, and as a result, ragdoll tend to "wobble", especially when it is hung in the air and is connected to several moving kinematic actors. I would like to add friction to the joints and make them "stiff". Imagine a door (with extremely rusty hinge) that needs to be kicked several times to be open - i.e. it rotates around the hinge, but not much, quickly stops, and large force is required to make it rotate. Or think about art manikins (see google images for pictures) - their limbs move around, but they do not swing around freely. Unfortunately, I can't find anything related to joint friction in physx. I've checked documentation, google, and headers, and couldn't find anything useful. So, how do I implement stiff joints/joint friction with physx? (I think) I've seen physx games without that problem, so apparently there should be some way to do that. P.S. I'm not talking about joint/solver instability here. Ragdoll is stable (more or less), and joints honor degrees of freedom(joint limits), but joints have no friction, and I would like to add friction to them.
I've asked a question on the nvidia forums recently which might be related to this: link Unfortunately I didn't get a real answer to my questions but managed to do what I want to do, using a spring in the joint might help you here if you only add a damping constant without a spring constant. This works in my case but I can't explain why so while I'm happy to use it I'm not totally sure whether to recommend it. I don't know whether you could also add angular damping to all of the individual parts of the ragdoll, that would make them slow down quicker after they've started moving but it might not look right. Probably one of those things you will have to experiment with.
2,928,863
2,928,948
Difference between static const char* and const char*
Could someone please explain the difference in how the 2 snippets of code are handled below? They definitely compile to different assembly code, but I'm trying to understand how the code might act differently. I understand that string literals are thrown into read only memory and are effectively static, but how does that differ from the explicit static below? struct Obj1 { void Foo() { const char* str( "hello" ); } }; and struct Obj2 { void Foo() { static const char* str( "hello" ); } };
With your static version there will be only one variable which will be stored somewhere and whenever the function is executed the exact same variable will be used. Even for recursive calls. The non-static version will be stored on the stack for every function call, and destroyed after each. Now your example is a bit complicated in regards to what the compiler actually does so let's look at a simpler case first: void foo() { static long i = 4; --i; printf("%l\n", i); } And then a main something like this: int main() { foo(); foo(); return 0; } will print 3 2 whereas with void foo() { long i = 4; --i; printf("%l\n", i); } it will print 3 3 Now with your example you have a const, so the value can't be changed so the compiler might play some tricks, while it often has no effect on the code generated, but helps the compiler to detect mistakes. And then you have a pointer, and mind that the static has effects on the pointer itself, not on the value it points to. So the string "hello" from your example will most likely be placed in the .data segment of your binary, and just once and live as long as the program lives,independent from the static thing .
2,929,267
2,929,458
Virtual functions and templates in C++ - can they be replaced with other (existing in C++) operations?
For example concept of Templates in C++ are for comfort as compiler generates some additional code, for your class or for your function, isn't it? So we could live without template by doing some additional (manual work). What about virtual functions??? Are there any situations where both of them are irreplaceable?
Yes, we can live without templates by doing more manual work (write the code that the compiler writes, or use void* to remove type specifics). Yes, we can live without polymorphism by doing more manual work (using switch statements, or storing your own vtable struct). Are there instances where they're irreplaceable? The template and polymorphism approaches give you type safety and compiler enforced behavior (e.g. pure virtual) that can't be replaced with some of the manual methods. For example, std::sort is safer to use than qsort which operates on void*. These manual methods can result in lots of code that has to be bug free and maintained. So it depends on your definition of "irreplaceable". With or without these features, these languages are still Turing complete. Theoretically, you can compute anything in a Turing complete language, so we could theoretically replace all languages with BrainF*ck... We just choose not to ;)
2,929,301
3,015,899
Objective-C++ pre-compiled headers
I'm using a C++ library (it happens to be in an iPad application, but I'm not sure that should make any difference) and would really like to have the headers pre-compiled to speed up the builds, but xCode seems to run the pre-compiled header file through the C compiler rather than the C++ one. Is there a way to get it to use the right compiler? I've already changed all of my source files from .m to .mm.
According to the Xcode docs, a compiled header is generated for each language variant. So if you bracket your #include with guard macros, it should work i.e. #if defined __cplusplus #include "mycplusplusheader.h" #endif
2,929,446
2,929,652
Boost shared_ptr use_count function
My application problem is the following - I have a large structure foo. Because these are large and for memory management reasons, we do not wish to delete them when processing on the data is complete. We are storing them in std::vector<boost::shared_ptr<foo>>. My question is related to knowing when all processing is complete. First decision is that we do not want any of the other application code to mark a complete flag in the structure because there are multiple execution paths in the program and we cannot predict which one is the last. So in our implementation, once processing is complete, we delete all copies of boost::shared_ptr<foo>> except for the one in the vector. This will drop the reference counter in the shared_ptr to 1. Is it practical to use shared_ptr.use_count() to see if it is equal to 1 to know when all other parts of my app are done with the data. One additional reason I'm asking the question is that the boost documentation on the shared pointer shared_ptr recommends not using "use_count" for production code. Edit - What I did not say is that when we need a new foo, we will scan the vector of foo pointers looking for a foo that is not currently in use and use that foo for the next round of processing. This is why I was thinking that having the reference counter of 1 would be a safe way to ensure that this particular foo object is no longer in use.
My immediate reaction (and I'll admit, it's no more than that) is that it sounds like you're trying to get the effect of a pool allocator of some sort. You might be better off overloading operator new and operator delete to get the effect you want a bit more directly. With something like that, you can probably just use a shared_ptr like normal, and the other work you want delayed, will be handled in operator delete for that class. That leaves a more basic question: what are you really trying to accomplish with this? From a memory management viewpoint, one common wish is to allocate memory for a large number of objects at once, and after the entire block is empty, release the whole block at once. If you're trying to do something on that order, it's almost certainly easier to accomplish by overloading new and delete than by playing games with shared_ptr's use_count. Edit: based on your comment, overloading new and delete for class sounds like the right thing to do. If anything, integration into your existing code will probably be easier; in fact, you can often do it completely transparently. The general idea for the allocator is pretty much the same as you've outlined in your edited question: have a structure (bitmaps and linked lists are both common) to keep track of your free objects. When new needs to allocate an object, it can scan the bit vector or look at the head of the linked list of free objects, and return its address. This is one case that linked lists can work out quite well -- you (usually) don't have to worry about memory usage, because you store your links right in the free object, and you (virtually) never have to walk the list, because when you need to allocate an object, you just grab the first item on the list. This sort of thing is particularly common with small objects, so you might want to look at the Modern C++ Design chapter on its small object allocator (and an article or two since then by Andrei Alexandrescu about his newer ideas of how to do that sort of thing). There's also the Boost::pool allocator, which is generally at least somewhat similar.
2,929,543
2,936,457
Instance where embedded C++ compilers don't support multiple inheritance?
I read a bit about a previous attempt to make a C++ standard for embedded platforms where they specifically said multiple inheritance was bad and thus not supported. From what I understand, this was never implemented as a mainstream thing and most embedded C++ compilers support most standard C++ constructs. Are there cases where a compiler on a current embedded platform (i.e. something not more than a few years old) absolutely does not support multiple inheritance? I don't really want to do multiple inheritance in a sense where I have a child with two full implementations of a class. What I am most interested in is inheriting from a single implementation of a class and then also inheriting one or more pure virtual classes as interfaces only. This is roughly equivalent to Java/.Net where I can extend only one class but implement as many interfaces as I need. In C++ this is all done through multiple inheritance rather than being able to specifically define an interface and declare a class implements it. Update: I'm not interested in if it is or isn't technically C++, how it was an attempt to dumb down C++ for C programmers to cope, generate smaller binaries, or whatever religious topic people are using to wage flame wars. My point is: I want to know if there are current embedded platforms that, for development purposes, supply their own C++ compiler (i.e. I can't use GCC or MSVC) that does NOT support multiple inheritance. My purpose in mentioning the embedded C++ standard was to give background on the question only.
Many of the restrictions imposed in the EC++ subset were made to allow wide compiler support for small 16 and 32 bit targets at a time when not all C++ compilers supported all emerging features (for example GCC did not support namespaces until version 3.x, and EC++ omits namespace support). This was before ISO C++ standardisation, and standardisation of any kind is important to many embedded projects. So its aim was to promote adoption of C++ in embedded systems before the necessary standardisation was in place. However its time has passed, and it is largely irrelevant. It has a few things to say about 'expensive' and 'non-deterministic' elements of C++ which are still relevant, but much of it was aimed at compatibility. Note that EC++ is a true subset of C++, and that any EC++ program is also a valid C++ program. In fact it is defined solely in terms of what it omits rather than a complete language definition. Green Hills, IAR, and Keil all produce compilers with switches to enforce the EC++ subset, but since it is largely a matter of portability, it is entirely pointless since all these compilers also support ISO C++. For the most part those parts of the EC++ specification you might want to adhere to you can do so simply by not using those features on a fully featured compiler. There are C++ compilers for very restricted systems that are neither fully ISO C++ nor EC++.
2,929,586
2,929,930
Design for fastest page download
I have a file with millions of URLs/IPs and have to write a program to download the pages really fast. The connection rate should be at least 6000/s and file download speed at least 2000 with avg. 15kb file size. The network bandwidth is 1 Gbps. My approach so far has been: Creating 600 socket threads with each having 60 sockets and using WSAEventSelect to wait for data to read. As soon as a file download is complete, add that memory address(of the downloaded file) to a pipeline( a simple vector ) and fire another request. When the total download is more than 50Mb among all socket threads, write all the files downloaded to the disk and free the memory. So far, this approach has been not very successful with the rate at which I could hit not shooting beyond 2900 connections/s and downloaded data rate even less. Can somebody suggest an alternative approach which could give me better stats. Also I am working windows server 2008 machine with 8 Gig of memory. Also, do we need to hack the kernel so as we could use more threads and memory. Currently I can create a max. of 1500 threads and memory usage not going beyond 2 gigs [ which technically should be much more as this is a 64-bit machine ]. And IOCP is out of question as I have no experience in that so far and have to fix this application today. Thanks Guys!
First and foremost you need to figure out what is limiting your application. Are you CPU-bound, IO-bound, memory-bound, network-bound, ...? Is there locking contention between your threads? etc... Its impossible to say from your description. You will need to run your app in a profiler to get an idea where the bottlenecks are.
2,929,598
2,929,691
OpenGL GL_LINE_STRIP gives error 1281 (Invalid value) after glEnd
I have no idea what is wrong with the simple code. The function is for use with python and ctypes. extern "C" void add_lines(bool antialias,GLdouble coordinates[][2],int array_size,GLdouble w,GLdouble r,GLdouble g, GLdouble b,GLdouble a){ glDisable(GL_TEXTURE_2D); if (antialias){ glEnable(GL_LINE_SMOOTH); //Enable line smoothing. } glColor4d(r,g,b,a); glLineWidth(w); glBegin(GL_LINE_STRIP); for (int x = 0; x < array_size; x++) { glVertex2d(coordinates[x][0],coordinates[x][1]); } glEnd(); std::cout << glGetError(); if (antialias){ glDisable(GL_LINE_SMOOTH); //Disable line smoothing. } glEnable(GL_TEXTURE_2D); } std::cout << glGetError(); gives out 1281 each time. Thankyou.
glGetError() is sticky: once the error gets set by some function, it will stay at that error value until you call glGetError(). So, the error is likely being caused elsewhere. Check the value of glGetError() on function entry, and then after each function call to find out where it's being set.
2,929,840
2,929,896
Simple inheritance in C++
I was going over some sample questions for an upcoming test, and this question is totally confusing me. Consider the following code: class GraduateStudent : public Student { ... }; If the word "public" is omitted, GraduateStudent uses private inheritance, which means which of the following? GraduateStudent objects may not use methods of Student. GraduateStudent does not have access to private objects of Student. No method of GraduateStudent may call a method of Student. Only const methods of GraduateStudent can call methods of Student.
Although this is a bare homework-ish question, I'm going to answer it because it is a terrible question. I would almost consider it a trick question, and it doesn't really make for a good test of knowledge. The answer is 2. GraduateStudent does not have access to private objects of Student., except that this has nothing at all to do with private inheritance. Point 2 would be true whether or not the public keyword were present, since derived classes never have access to the private members of their base classes, no matter how they inherit. Private inheritance means essentially two things (as opposed to public inheritance): All public methods of Student become private methods in GraduateStudent. That means that if, for example, Student has a public method foo(), then GraduateStudent has a private method foo(). The base class is "inaccessible", which means that polymorphism does not work. In layman's terms, this means that if GraduateStudent inherits privately from Student, then you cannot treat a GraduateStudent* as if it were a Student* (or a GraduateStudent& as if it were a Student&). It's possible that the author of the question also meant for point 1 to be a correct answer, but it is ambiguously worded. What does it mean that "GraduateStudent objects may not use methods of Student"? It's possible that the intent is for this to mean that you cannot call methods inherited from Student on objects of type GraduateStudent, like I wrote in the first point above, but the GraduateStudent object itself, within its methods, can use methods of Student. For example: class Student { public: void foo() {}; }; class GraduateStudent : Student { public: void bar() { foo(); // Legal } }; int main() { GraduateStudent g; g.bar(); // Legal g.foo(); // Illegal return 0; };
2,929,868
2,929,887
Good C++11 information, other than Wikipedia?
Does anyone know a good website where I can find information on C++11, other than Wikipedia?
The best I know is ISO/IEC JTC1/SC22/WG21 - The C++ Standards Committee where the n3092.pdf document is available.
2,929,925
2,929,964
Fast comparison of char arrays?
I'm currently working in a codebase where IPv4 addresses are represented as pointers to u_int8. The equality operator is implemented like this: bool Ipv4Address::operator==(const u_int8 * inAddress) const { return (*(u_int32*) this->myBytes == *(u_int32*) inAddress); } This is probably the fasted solution, but it causes the GCC compiler warning: ipv4address.cpp:65: warning: dereferencing type-punned pointer will break strict-aliasing rules How can I rewrite the comparison correctly without breaking strict-aliasing rules and without losing performance points? I have considered using either memcmp or this macro: #define IS_EQUAL(a, b) \ (a[0] == b[0] && a[1] == b[1] && a[2] == b[2] && a[3] == b[3]) I'm thinking that the macro is the fastest solution. What do you recommend? Update I just read the article Squeezing performance out of memcmp usage which explains how the compiler (Visual Studio, but perhaps also GCC) can optimize !memcmp(..) calls.
I would go for memcmp() It is more portable I usually try not to be smarter than my compiler/language. You are trying to compare memory contents and (depending on compiler options too) the implementation of memcmp() should be the most efficient way to do that. Also think that if your compiler does not inline memcmp() you will suffer the function context switch Are you sure you need to optimize that hard? Have you already checked that your program spend most of its time doing that type of operations?
2,929,970
2,930,168
How to debug ctypes call of c++ dll?
in my python project I call a c++ dll using ctypes library. That c++ dll consists on a wrapper dll that calls methods of a c# com interop dll. Sometimes I have a COM exception. I like to see what it corresponds exactlly but I don't know how to do it? How can I attach the c++ debugger to this situation? Thanks in advance
I don't know about your direct question, but maybe you could get around it by using comtypes to go straight from COM to Python instead sticking C++ in between. Then all you have to do is: >>> from comtypes import client, COMError >>> myclassinst = client.CreateObject('MyCOMClass.MyCOMClass') >>> try: ... myclassinst.DoInvalidOperation() ... except COMError as e: ... print e.args ... print e.hresult ... print e.text ... (-2147205118, None, (u'MyCOMClass: An Error Message', u'MyCOMClass.MyCOMClass.1', None, 0, None)) -2147205118 None
2,930,111
2,930,568
Wireshark Plugin: Is There a non-ntoh Version of tvb_get_ntoh64?
I am writing a Wireshark dissector plugin for a protocol that does not hton it's data, and I need to extract a 64-bit data value without doing any endian conversions. Is there a version of tvb_get_ntoh64 included in the Wireshark libraries that does not do the ntoh?
I found the answer to my own question. The wireshark document \wireshark\doc\README.developer addresses this: Don't fetch a little-endian value using "tvb_get_ntohs() or "tvb_get_ntohl()" and then using "g_ntohs()", "g_htons()", "g_ntohl()", or "g_htonl()" on the resulting value - the g_ routines in question convert between network byte order (big-endian) and host byte order, not little-endian byte order; not all machines on which Wireshark runs are little-endian, even though PCs are. Fetch those values using "tvb_get_letohs()" and "tvb_get_letohl()". In looking in tvbuff.h, I see there are other flavors as well: extern guint16 tvb_get_letohs(tvbuff_t*, const gint offset); extern guint32 tvb_get_letoh24(tvbuff_t*, const gint offset); extern guint32 tvb_get_letohl(tvbuff_t*, const gint offset); extern guint64 tvb_get_letoh64(tvbuff_t*, const gint offset); Posting so that people asking this question in the future will be able to find the answer.
2,930,444
2,930,518
What to name an array of flags?
I have a project where lots of the objects hold state by maintaining simple boolean flags. There are lots of these, so I maintain them within a uint32_t and use bit masking. There are now so many flags to keep track of, I've created an abstraction for them (just a class wrapping the uint32_t) with set(), clear(), etc. My question: What's a nice accurate, concise name for this class? What name could I give this class so that you'd have a reasonable idea what it was [for] knowing the name only? Some ideas I had: FlagBank FlagArray etc Any ideas? Thanks in advance! Cheers, -Chris
FlagBank would be fairly descriptive. But I have one suggestion. Instead of using uint32_t and bit masking, it might be less C-like to use an STL vector instead. It uses a template specialization for the boolean case where only one bit per element is used for the storage. Very efficient and MUCH more object oriented.
2,930,613
2,930,649
c++ STL vector is not acccepting the copy constructor
I wrote a code ( c++,visual studio 2010) which is having a vector, even I though copy const is declared, but is still showing that copy const is not declared Here the code #include<iostream> #include<vector> using namespace std; class A { public: A() { cout << "Default A is acting" << endl ; } A(A &a) { cout << "Copy Constructor of A is acting" << endl ; } }; int main() { A a; A b=a; vector<A> nothing; nothing.push_back(a); int n; cin >> n; } The error I got is Error 1 error C2558: class 'A' : no copy constructor available or copy constructor is declared 'explicit' c:\program files\microsoft visual studio 10.0\vc\include\xmemory 48 1 delete Anybody please help me
Copy constructor should take the object as a const reference, so it should be: A(const A &a){ cout << "Copy Constructor of A is acting" << endl; }
2,931,288
2,931,887
Edit characters in a String in C#
What's the cleanest way of editing the characters in a string in C#? What's the C# equivalent of this in C++: std::string myString = "boom"; myString[0] = "d";
Decided to time what I felt where the two most canonical approaches, plus one I threw in as unrepresented; here's what I found (Release build): ReplaceAtChars: 86ms ReplaceAtSubstring: 258ms ReplaceAtStringBuilder: 161ms Clearly the Char array approach is by far best optimized by the runtime. Which actually suggests that the current leading answer (StringBuilder) is likely not the best answer. And here was the test I used: class Program { static void Main(string[] args) { Console.WriteLine("ReplaceAtChars: " + new Stopwatch().Time(() => "test".ReplaceAtChars(1, 'E').ReplaceAtChars(3, 'T'), 1000000) + "ms"); Console.WriteLine("ReplaceAtSubstring: " + new Stopwatch().Time(() => "test".ReplaceAtSubstring(1, 'E').ReplaceAtSubstring(3, 'T'), 1000000) + "ms"); Console.WriteLine("ReplaceAtStringBuilder: " + new Stopwatch().Time(() => "test".ReplaceAtStringBuilder(1, 'E').ReplaceAtStringBuilder(3, 'T'), 1000000) + "ms"); } } public static class ReplaceAtExtensions { public static string ReplaceAtChars(this string source, int index, char replacement) { var temp = source.ToCharArray(); temp[index] = replacement; return new String(temp); } public static string ReplaceAtStringBuilder(this string source, int index, char replacement) { var sb = new StringBuilder(source); sb[index] = replacement; return sb.ToString(); } public static string ReplaceAtSubstring(this string source, int index, char replacement) { return source.Substring(0, index) + replacement + source.Substring(index + 1); } } public static class StopwatchExtensions { public static long Time(this Stopwatch sw, Action action, int iterations) { sw.Reset(); sw.Start(); for (int i = 0; i < iterations; i++) { action(); } sw.Stop(); return sw.ElapsedMilliseconds; } }
2,931,345
2,931,359
Trouble with dependent types in templates
I'm having trouble with templates and dependent types: namespace Utils { void PrintLine(const string& line, int tabLevel = 0); string getTabs(int tabLevel); template<class result_t, class Predicate> set<result_t> findAll_if(typename set<result_t>::iterator begin, set<result_t>::iterator end, Predicate pred) // warning C4346 { set<result_t> result; return findAll_if_rec(begin, end, pred, result); } } namespace detail { template<class result_t, class Predicate> set<result_t> findAll_if_rec(set<result_t>::iterator begin, set<result_t>::iterator end, Predicate pred, set<result_t> result) { typename set<result_t>::iterator nextResultElem = find_if(begin, end, pred); if (nextResultElem == end) { return result; } result.add(*nextResultElem); return findAll_if_rec(++nextResultElem, end, pred, result); } } Compiler complaints, from the location noted above: warning C4346: 'std::set<result_t>::iterator' : dependent name is not a type. prefix with 'typename' to indicate a type error C2061: syntax error : identifier 'iterator' What am I doing wrong?
Well, the warning says: dependent name is not a type. prefix with 'typename' to indicate a type The dependent name (that is, the iterator in std::set<result_t>::iterator) is not a type. You need to prefix it with typename to indicate a type: typename std::set<result_t>::iterator So, your declaration should be: template<class result_t, class Predicate> set<result_t> findAll_if(typename set<result_t>::iterator begin, typename set<result_t>::iterator end, Predicate pred) note added typename ^ (and the definition should match the declaration)
2,931,423
2,931,438
Problem overridding virtual function
Okay, I'm writing a game that has a vector of a pairent class (enemy) that s going to be filled with children classes (goomba, koopa, boss1) and I need to make it so when I call update it calls the childclasses respective update. I have managed to create a example of my problem. #include <stdio.h> class A{ public: virtual void print(){printf("Hello from A");} }; class B : public A{ public: void print(){printf("Hello from B");} }; int main(){ A ab = B(); ab.print(); while(true){} } Output wanted: "Hello from B" Output got: "Hello from A" How do I get it to call B's print function?
Polymorphism only works on pointers and references. If you assign a B to an A, it becomes an A and you lose all B-specific information, including method overrides. This is called "slicing"; the B parts are "sliced" off the object when it is assigned to an object of a parent class. On the other hand, if you assign a B* to an A*, it looks like an A*, but is still really pointing to a B, and so the B-specific information remains, and B's virtual overrides will be used. Try: int main(){ A* ab = new B(); ab->print(); delete ab; while(true){} } The same also applies to assigning a B to an A& (reference-to-A), e.g. int main(){ B b; A& ab = b; ab.print(); while(true){} }
2,931,477
2,931,545
C++ ambiguous template instantiation
the following gives me ambiguous template instantiation with nvcc (combination of EDG front-end and g++). Is it really ambiguous, or is compiler wrong? I also post workaround à la boost::enable_if template<typename T> struct disable_if_serial { typedef void type; }; template<> struct disable_if_serial<serial_tag> { }; template<int M, int N, typename T> __device__ //static typename disable_if_serial<T>::type void add_evaluate_polynomial1(double *R, const double (&C)[M][N], double x, const T &thread) { // ... } template<size_t M, size_t N> __device__ static void add_evaluate_polynomial1(double *R, const double (&C)[M][N], double x, const serial_tag&) { for (size_t i = 0; i < M; ++i) add_evaluate_polynomial1(R, C, x, i); } // ambiguous template instantiation here. add_evaluate_polynomial1(R, C, x, serial_tag());
AFAIK, the problem is that you have the nontype arguments inconsistently typed (that is, M and N are int here, but size_t there). This means not all template variable assignments from one can be used in the other, which means there is no partial ordering, hence the error message. Unite the template nontype argument types and it should work.
2,931,551
2,936,281
How to give properties to c++ classes (interfaces)
I have built several classes (A, B, C...) which perform operations on the same BaseClass. Example: struct BaseClass { int method1(); int method2(); int method3(); } struct A { int methodA(BaseClass& bc) { return bc.method1(); } } struct B { int methodB(BaseClass& bc) { return bc.method2()+bc.method1(); } } struct C { int methodC(BaseClass& bc) { return bc.method3()+bc.method2(); } } But as you can see, each class A, B, C... only uses a subset of the available methods of the BaseClass and I'd like to split the BaseClass into several chunks such that it is clear what it used and what is not. For example a solution could be to use multiple inheritance: // A uses only method1() struct InterfaceA { virtual int method1() = 0; } struct A { int methodA(InterfaceA&); } // B uses method1() and method2() struct InterfaceB { virtual int method1() = 0; virtual int method2() = 0; } struct B { int methodB(InterfaceB&); } // C uses method2() and method3() struct InterfaceC { virtual int method2() = 0; virtual int method3() = 0; } struct C { int methodC(InterfaceC&); } The problem is that each time I add a new type of operation, I need to change the implementation of BaseClass. For example: // D uses method1() and method3() struct InterfaceD { virtual int method1() = 0; virtual int method3() = 0; } struct D { int methodD(InterfaceD&); } struct BaseClass : public InterfaceA, public InterfaceB, public InterfaceC // here I need to modify the existing code to add class D { ... } Do you know a clean way I can do this? Thanks for your help edit: I forgot to mention that it can also be done with templates. But I don't like this solution either because the required interface does not appear explicitly in the code. You have to try to compile the code to verify that all required methods are implemented correctly. Plus, it would require to instantiate different versions of the classes (one for each BaseClass type template parameter) and this is not always possible nor desired.
use pattern Adapter struct InterfaceA { virtual int method1() = 0; } struct A { int methodA(InterfaceA& bc) { return bc.method1(); } } struct BaseClassAdapterForA: public InterfaceA { BaseClassAdapterForA(BaseClass& _bc) : bc(_bc) {} virtual int method1() { //note that the name of BaseClass method //can be anything else return bc.method1(); // or return bc.whatever(); } private: BaseClass& bc; }; //usage BaseClass bc; A a; BaseClassAdapterForA bca(bc); a.methodA(bca);
2,931,566
2,931,762
C++: Trouble with templates (C2064)
I'm having compiler errors, and I'm not sure why. What am I doing wrong here: Hangman.cpp: set<char> Hangman::incorrectGuesses() { // Hangman line 103 return Utils::findAll_if<char>(guesses.begin(), guesses.end(), &Hangman::isIncorrectGuess); } bool Hangman::isIncorrectGuess(char c) { return correctAnswer.find(c) == string::npos; } Utils.h: namespace Utils { void PrintLine(const string& line, int tabLevel = 0); string getTabs(int tabLevel); template<class result_t, class Predicate> std::set<result_t> findAll_if(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred) { std::set<result_t> result; // utils line 16 return detail::findAll_if_rec<result_t>(begin, end, pred, result); } } namespace detail { template<class result_t, class Predicate> std::set<result_t> findAll_if_rec(typename std::set<result_t>::iterator begin, typename std::set<result_t>::iterator end, Predicate pred, std::set<result_t> result) { // utils line 25 typename std::set<result_t>::iterator nextResultElem = find_if(begin, end, pred); if (nextResultElem == end) { return result; } result.insert(*nextResultElem); return findAll_if_rec(++nextResultElem, end, pred, result); } } This produces the following compiler errors: algorithm(83): error C2064: term does not evaluate to a function taking 1 arguments algorithm(95) : see reference to function template instantiation '_InIt std::_Find_if<std::_Tree_unchecked_const_iterator<_Mytree>,_Pr>(_InIt,_InIt,_Pr)' being compiled 1> with 1> [ 1> _InIt=std::_Tree_unchecked_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>, 1> _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>, 1> _Pr=bool (__thiscall Hangman::* )(char) 1> ] utils.h(25) : see reference to function template instantiation '_InIt std::find_if<std::_Tree_const_iterator<_Mytree>,Predicate>(_InIt,_InIt,_Pr)' being compiled 1> with 1> [ 1> _InIt=std::_Tree_const_iterator<std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>>, 1> _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>, 1> Predicate=bool (__thiscall Hangman::* )(char), 1> _Pr=bool (__thiscall Hangman::* )(char) 1> ] utils.h(16) : see reference to function template instantiation 'std::set<_Kty> detail::findAll_if_rec<result_t,Predicate>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate,std::set<_Kty>)' being compiled 1> with 1> [ 1> _Kty=char, 1> result_t=char, 1> Predicate=bool (__thiscall Hangman::* )(char), 1> _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>> 1> ] hangman.cpp(103) : see reference to function template instantiation 'std::set<_Kty> Utils::findAll_if<char,bool(__thiscall Hangman::* )(char)>(std::_Tree_const_iterator<_Mytree>,std::_Tree_const_iterator<_Mytree>,Predicate)' being compiled 1> with 1> [ 1> _Kty=char, 1> _Mytree=std::_Tree_val<std::_Tset_traits<char,std::less<char>,std::allocator<char>,false>>, 1> Predicate=bool (__thiscall Hangman::* )(char) 1> ]
Use the following to use a bound member function as a predicate: return Utils::findAll_if<char>( guesses.begin(), guesses.end(), std::bind1st(std::mem_fun(&Hangman::isIncorrectGuess), this))); Member functions expect an implicit this parameter and can't be used directly with STL algorithms. Thus the above generates an adapter for the member function by using std::mem_fun and binds it to the current instance using std::bind1st. You might want to look into Boost.Bind, which makes these things easier: return Utils::findAll_if<char>( guesses.begin(), guesses.end(), boost::bind(&Hangman::isIncorrectGuess, this, _1)); The problem comes from the fact that the STL algorithms call the predicates etc. similar to this: predicate(someParameter); ... which doesn't work for member functions. Member function pointers would have to be invoked using a special syntax and an instance or a pointer to one - e.g.: (pointerToInstance->*predicate)(someParameter); See e.g. this article for more on member pointers. Using std::mem_fun/std::bind1st or boost::bind you can generate adapters that do this and implement operator() which allows them to be called similar to common functions.
2,931,613
2,931,641
after XOR operation find C (and XOR reversability)
Assume: unsigned char A = 10; unsigned char B = 11; unsigned char C = 12; unsigned char Diff1 = A ^ B; unsigned char Diff2 = B ^ C; //find any of A or B or C using Diff1 and Diff2 Question is: There were 3 values initially for which we found 2 differences. Is there any way we can find any of A or B or C using 2 differences Diff1 and Diff2? I know XOR is not reversible unless you know the key, but keeping in view that unsigned __int8 is 0...255 maximum 256 different values. stay well.
You don't have enough information to find any of A, B or C from just knowing the values of Diff1 and Diff2. There are 256 ** 3 different possible inputs and only 256 ** 2 possible outputs so for each output there are 256 different possible inputs that could have given that output - where A, B and C could be any value. But once you know any one of them you can calculate the other two. Effectively you are using XOR encryption twice on a plaintext (B) with two separate unknown keys (A and C). An XOR encryption is provibly impossible to reverse - there is no useful information at all in the output (assuming the key is chosen uniformly at random and never reused). You can find A XOR C though: Diff1 ^ Diff2
2,931,704
2,931,750
How to compare string with const char*?
#include <stdlib.h> #include <stdio.h> #include <iostream> #include <string.h> using namespace std; int main() { string cmd; while(strcmp(cmd.c_str(),"exit")==0 && strcmp(cmd.c_str(),"\exit")==0) { cin>>cmd; cout<<cmd; } return 0; } I am stuck.
After fixing a couple of small bugs, this works on my machine: #include <cstdlib> #include <cstdio> #include <iostream> #include <cstring> #include <string> int main() { std::string cmd; while( std::strcmp(cmd.c_str(),"exit")!=0 && std::strcmp(cmd.c_str(),"\\exit")!=0) { std::cin>>cmd; std::cout<<cmd << '\n'; } return 0; } However, I wonder why you want to use std::strcmp() at all. As you have just found out, it's not as easy to use as the std::string class. This while(cmd!="exit" && cmd!="\\exit") works just as well, is easier to understand, and thus easier to get right.
2,931,854
2,931,961
Can I use a static library compiled with gcc 3.4.2 with gcc 4.2.2
I have a static library that is compiled with gcc 3.4.2. I am building a shared library that relies on this static lib. I will be building this shared library (.so) with gcc 4.2.2. I was wondering what are the potential pitfalls of using the 3.4.2 static library in a gcc 4.2.2 shared library?
If your static library is c++ based then I thought due to ABI changes it probably would not be compatible but according to this other stackoverflow question, gcc is forward compatible starting with gcc 3.4.0. So you could be ok. I had to rebuild all of my libraries going from gcc 3.0/3.2 to gcc 3.4.6 but I have not done the conversion to post-4.0 yet. GCC ABI Compatibility
2,931,925
2,932,366
gluNewQuadric() before opengl's initialization
I'm working on a c++ code that uses SDL/opengl. Is this possible to create a pointer to a quadric with gluNewQuadric() before having initialized opengl with SDL_SetVideoMode? The idea is to create a class with a (pointer to a) quadric class member that has to be instantiate before the SDL_SetVideoMode call. This pointer is initialized in the class' constructor with a gluNewQuadric() call.
I'm not seeing anything in the source code that would require an active GL context.
2,932,189
3,052,780
OpenGL code to render ribbon diagrams for protein
I am looking to render ribbon diagrams of proteins using OpenGL and C++. Does anyone know if any open source code for this already exists, or if there are good guides to do this? If not, I'd prefer to figure it out myself ;) but I didn't want to reinvent the wheel, especially if the wheel was free. EDIT: thanks for the responses. Does anyone know if any of these programs have good documentation about the reasoning behind why they store certain vertices or triangle meshes for rendering based on the structure of the atoms in the protein?
Take a look at http://molvis.sdsc.edu/visres/molvisfw/titles.jsp for an amazing number of projects devoted to molecular visualization, most of them open source.
2,932,204
2,959,902
Timing related crash when unloading a DLL?
I know I'm reaching for straws here, but this one is a mystery... any pointers or help would be most welcome, so I'm appealing to those more intelligent than I: We have a crash exhibited in our release binaries only. The crash takes place as the binary is bringing itself down and terminating sub-libraries upon which it depends. Its ability to be reproduced is dependent on the machine- some are 100% reliable in reproducing the crash, some don't exhibit the issue at all, and some are in between. The crash is deep within one of the sublibraries, and there is a good likelihood the stack is corrupt by the time the rubble can be brought into a debugger (MSVC 2008 SP1) to be examined. Running the binary under the debugger prevents the bug from happening, as does remote debugging, as does (of all things) connecting to the machine via VNC. We have tried to install the Microsoft Driver Development Kit, and doing so also squelches the bug. What would be the next best place to look? What tools would be best in this circumstance? Does it sound like a race condition, or something else?
The problem was a conflicting setting of the pernicious _SECURE_SCL flag under Visual Studio, causing silent ABI incompatibilities between the DLL and one of its dependencies.
2,932,300
2,932,348
conflicting declaration when filling a static std::map class member variable
I have a class with a static std::map member variable that maps chars to a custom type Terrain. I'm attempting to fill this map in the class's implementation file, but I get several errors. Here's my header file: #ifndef LEVEL_HPP #define LEVEL_HPP #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "libtcod.hpp" namespace yarl { namespace level { class Terrain { // Member Variables private: std::bitset<5> flags; // Member Functions public: explicit Terrain(const std::string& flg) : flags(flg) {} (...) }; class Level { private: static std::map<char, Terrain> terrainTypes; (...) }; } } #endif and here's my implementation file: #include <bitset> #include <list> #include <map> #include <string> #include <vector> #include "Level.hpp" #include "libtcod.hpp" using namespace std; namespace yarl { namespace level { /* fill Level::terrainTypes */ map<char,Terrain> Level::terrainTypes['.'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[','] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['\''] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes['`'] = Terrain("00001"); // clear map<char,Terrain> Level::terrainTypes[178] = Terrain("11111"); // wall (...) } } I'm using g++, and the errors I get are src/Level.cpp:15: error: conflicting declaration ‘std::map, std::allocator > > yarl::level::Level::terrainTypes [46]’ src/Level.hpp:104: error: ‘yarl::level::Level::terrainTypes’ has a previous declaration as ‘std::map, std::allocator > > yarl::level::Level::terrainTypes’ src/Level.cpp:15: error: declaration of ‘std::map, std::allocator > > yarl::level::Level::terrainTypes’ outside of class is not definition src/Level.cpp:15: error: conversion from ‘yarl::level::Terrain’ to non-scalar type ‘std::map, std::allocator > >’ requested src/Level.cpp:15: error: ‘yarl::level::Level::terrainTypes’ cannot be initialized by a non-constant expression when being declared I get a set of these for each map assignment line in the implementation file. Anyone see what I'm doing wrong? Thanks for your help.
You can initialize static members outside of functions, but you can't perform arbitrary operations. You could use a function to initialize the members: namespace { std::map<char, Terrain> initTerrainTypes() { std::map<char, Terrain> m; m['.'] = Terrain("00001"); // ... return m; } } map<char,Terrain> Level::terrainTypes = initTerrainTypes(); Or you could use initialization utilities like Boost.Assign: map<char,Terrain> Level::terrainTypes = boost::assign::map_list_of ('.', Terrain("00001")) // ... (178, Terrain("11111"));
2,932,423
2,932,490
Changing type of object in a conditional
I'm having a bit of trouble with dynamic_casting. I need to determine at runtime the type of an object. Here is a demo: #include <iostream> #include <string> class PersonClass { public: std::string Name; virtual void test(){}; //it is annoying that this has to be here... }; class LawyerClass : public PersonClass { public: void GoToCourt(){}; }; class DoctorClass : public PersonClass { public: void GoToSurgery(){}; }; int main(int argc, char *argv[]) { PersonClass* person = new PersonClass; if(true) { person = dynamic_cast<LawyerClass*>(person); } else { person = dynamic_cast<DoctorClass*>(person); } person->GoToCourt(); return 0; } I would like to do the above. The only legal way I found to do it is to define all of the objects before hand: PersonClass* person = new PersonClass; LawyerClass* lawyer; DoctorClass* doctor; if(true) { lawyer = dynamic_cast<LawyerClass*>(person); } else { doctor = dynamic_cast<DoctorClass*>(person); } if(true) { lawyer->GoToCourt(); } The main problem with this (besides having to define a bunch of objects that won't be use) is that I have to change the name of the 'person' variable. Is there a better way? (I am not allowed to change any of the classes (Person, Lawyer, or Doctor) because they are part of a library that people who will use my code have and won't want to change). Thanks, Dave
Dynamic casting to a subclass and then assigning the result to a pointer to superclass is of no use - you practically are back where you started. You do need a pointer to a subclass to store the result of the dynamic cast. Also, if the concrete type of your object is PersonClass, you can't downcast it to a subclass. Dynamic casting can only work for you if you have a pointer to a superclass but you know that the object pointed to is actually an instance of a subclass. As others have pointed out too, the best option would be to redesign the class hierarchy to make your methods really polymorphic, thus eliminate the need for downcasting. Since you can't touch those classes, you need the downcast. The typical way to use this would be something like PersonClass* person = // get a Person reference somehow if(/* person is instance of LawyerClass */) { LawyerClass* lawyer = dynamic_cast<LawyerClass*>(person); lawyer->GoToCourt(); } else { DoctorClass* doctor = dynamic_cast<DoctorClass*>(person); doctor->GoToSurgery(); } Update: if you want to use the subclass instances later, you can do it this way: PersonClass* person = // get a Person reference somehow ... LawyerClass* lawyer = NULL; DoctorClass* doctor = NULL; if(/* person is instance of LawyerClass */) { lawyer = dynamic_cast<LawyerClass*>(person); } else if(/* person is instance of DoctorClass */) { doctor = dynamic_cast<DoctorClass*>(person); } ... if(lawyer) { lawyer->GoToCourt(); } else if (doctor) { doctor->GoToSurgery(); } Note that this code is more complicated and more error-prone than the previous version. I would definitely try to refactor such code to make it look more like the previous version. YMMV.
2,932,644
2,932,662
CoGetClassObject gives many First-chance exceptions in ATL project. Should I worry?
I have written a COM object that in turn uses a thrid party ActiveX control. In my FinalConstruct() for my COM object, I instantiate the ActiveX control with the follow code: HRESULT hRes; LPCLASSFACTORY2 pClassFactory; hRes = CoInitializeEx(NULL,COINIT_APARTMENTTHREADED); bool bTest = SUCCEEDED(hRes); if (!bTest) return E_FAIL; if (SUCCEEDED(CoGetClassObject(__uuidof(SerialPortSniffer), CLSCTX_INPROC_SERVER, NULL, IID_IClassFactory2, (LPVOID *)(&pClassFactory)))) { ... more set up code When I step over the line if (SUCCEEDED(CoGetClassObject(__uuidof(SerialPortSniffer), ..., I get 20+ lines in the Output window stating: First-chance exception at 0x0523f82e in SillyComDriver.exe: 0xC0000005: Access violation writing location 0x00000000. I also get the lines: First-chance exception at 0x051e3f3d in SillyComDriver.exe: 0xC0000096: Privileged instruction. First-chance exception at 0x100ab9e6 in SillyComDriver.exe: 0xC000001D: Illegal Instruction. Notice these are first-chance exceptions. The program runs as expected I can access the third party methods/properties. Still, I'm left wondering why they are occurring. Perhaps my way of instantiating the ActiveX control (for which I want use of it's methods/properties and not it's GUI stuff) is incorrect? Besides the code I'm showing, I also put the line #import "spsax.dll" no_namespace in the stdafx.h That's all the code necessary for my simple demo project. I noticed this problem because I had (inadvertently) set the "break on exceptions" options in my "real" project and it was breaking on this line. Once I removed it, it also works. If you're read this far thank you, and perhaps I can ask one other minor question. In my demo project, if I right click on SerialPortSniffer and "go to definition", it takes me to the file C:....\AppData\Local\Temp\spsax.tlh. Can someone explain that? Finally, in my "real" project, right clicking on SerialPortSniffer and going to difinition leads to "The symbol 'SerialPortSniffer' is not defined". It doesn't seem to affect the program though. Is there some setting I've messed up? By the way, all my code is written w/ VS2008. Thanks, Dave
It's usually nothing to worry about. When an exception is thrown, the debugger is notified and depending on the debugger configuration, it may stop the application or let the application resume normally. This is a "first-chance" exception. If the application resumes, then it may catch the exception, and do whatever is necessary in the exceptional case. If the application does not handle the exception, it becomes a "second-chance" exception and the debugger is notified again. The debugger is usually configured to stop the application at this point to let you see what went wrong. So if you get a first-chance exception and not receive a second-chance exception later, it's usually means that nothing is wrong, and the application is handling exceptions in a "graceful" matter. (Also see Link)
2,932,753
2,932,800
Multidimensional Array Initialization: Any benefit from Threading?
say I have the following code: char[5][5] array; for(int i =0; i < 5; ++i) { for(int j = 0; j < 5; ++i) { array[i][j] = //random char; } } Would there be a benefit for initializing each row in this array in a separate thread? Imagine instead of a 5 by 5 array, we have a 10 by 10? n x n? Also, this is done once, during application startup.
You're joking, right? If not: The answer is certainly no!!! You'd incur a lot of overhead for putting together enough synchronization to dispatch the work via a message queue, plus knowing all the threads had finished their rows and the arrays were ready. That would far outstrip the time it takes one CPU core to fill 25 bytes with a known value. So for almost any simple initialization like this you do not want to use threads. Also bear in mind that threads provide concurrency but not speedup on a single core machine. If you have an operation which has to be completed synchronously--like an array initialization--then you'll only get value by adding a # of threads up to the # of CPU cores available. In theory. So if you're on a multi-core system and if what you were putting in each cell took a long time to calculate... then sure, it may be worth exploiting some kind of parallelism. So I like genpfault's suggestion: write it multithreaded for a multi-core system and time it as an educational exercise just to get a feel for when the crossover of benefit happens...
2,932,822
2,932,853
Is it safe to catch an access violation in this scenario?
I've read a lot, including here on SO that suggests this is a very bad idea in general and that the only thing you can do safely is exit the program. I'm not sure that this is true. This is for a pooling memory allocator that hands off large allocations to malloc. During pool_free() a pointer needs to be checked it it belongs to a pool or was allocated with malloc. By rounding the address down to the nearest 1MB boundary, I get a pointer to the beginning of a block of memory in the pool, or undefined if malloc was used. In the first case I can easily verify that the block of memory belongs to the pool, but, if it does not I will either fail this verification, OR I will get an access violation (note that this is a read-only process). Could I not catch this with SEH (Windows) or handle the signal (POSIX) and simply treat it as a failed verification? (i.e. this is only possible if malloc was used, so pass the ptr to free()) Edit: People seem to be missing the OR above. I do not expect to get an access violation if the pointer was allocated with malloc, but it is one possible outcome. The procedure using the pointer to the beginning of the block (at the 1MB boundary) is to verify a magic number, then follow a pointer to the memory pool, and check that it actually contains aforementioned pointer to the block. If any of these read-only steps produces an access violation, it fails validation as surely as if any individual step failed.
There is no need to implement a reactive mechanism. You can get in front of the problem by aligning heap allocations to a 1 MB boundary: Windows: _aligned_malloc(size, 1<<20) Unix: memalign(1<<20, size) Using this approach, rounding down to 1 MB is guaranteed to point into an allocated block of memory, and you simply have to discern whether that address is in the pool or outside it (in which case it was obviously malloced). You need to be cautious that you only use aligned heap allocation for genuinely large objects. If you use it for, say, size > 100 kB, the allocator will leave huge gaps between objects. Ideally, only use it for objects that don't fit in a 1 MB pool block.
2,932,909
2,932,963
Overriding vs Virtual
What is the purpose of using the reserved word virtual in front of functions? If I want a child class to override a parent function, I just declare the same function such as void draw(){}. class Parent { public: void say() { std::cout << "1"; } }; class Child : public Parent { public: void say() { std::cout << "2"; } }; int main() { Child* a = new Child(); a->say(); return 0; } The output is 2. So again, why would the reserved word virtual be necessary in the header of say() ? Thanks a bunch.
This is the classic question of how polymorphism works I think. The main idea is that you want to abstract the specific type for each object. In other words: You want to be able to call the Child instances without knowing it's a child! Here is an example: Assuming you have class "Child" and class "Child2" and "Child3" you want to be able to refer to them through their base class (Parent). Parent* parents[3]; parents[0] = new Child(); parents[1] = new Child2(); parents[2] = new Child3(); for (int i=0; i<3; ++i) parents[i]->say(); As you can imagine, this is very powerful. It lets you extend the Parent as many times as you want and functions that take a Parent pointer will still work. For this to work as others mention you need to declare the method as virtual.
2,932,954
2,932,959
c++: at what point should I start using "new char[N]" vs a static buffer "char[Nmax]"
My question is with regard to C++ Suppose I write a function to return a list of items to the caller. Each item has 2 logical fields: 1) an int ID, and 2) some data whose size may vary, let's say from 4 bytes up to 16Kbytes. So my question is whether to use a data structure like: struct item { int field1; char field2[MAX_LEN]; OR, rather, to allocate field2 from the heap, and require the caller to destroy when he's done: struct item{ int field1; char *field2; // new char[N] -- destroy[] when done! Since the max size of field #2 is large, is makes sense that this would be allocated from the heap, right? So once I know the size N, I call field2 = new char[N], and populate it. Now, is this horribly inefficient? Is it worse in cases where N is always small, i.e. suppose I have 10000 items that have N=4?
You should instead use one of the standard library containers, like std::string or std::vector<char>; then you don't have to worry about managing the memory yourself.
2,933,124
2,933,139
Buffer size: N*sizeof(type) or sizeof(var)? C++
I am just starting with cpp and I've been following different examples to learn from them, and I see that buffer size is set in different ways, for example: char buffer[255]; StringCchPrintf(buffer, sizeof(buffer), TEXT("%s"), X); VS char buffer[255]; StringCchPrintf(buffer, 255*sizeof(char), TEXT("%s"), X); Which one is the correct way to use it? I've seen this in other functions like InternetReadFile, ZeroMemory and MultiByteToWideChar.
Neither is correct. You are using StringCchPrintf(), which operates on the count of characters, not bytes. sizeof(buffer) returns the size of buffer in bytes, as does 255*sizeof(char). 255*sizeof(char) also has the disadvantage that you are duplicating the size of the array in two places - if you change the size of buffer but forget in the call to StringCchPrintf, you have a bug. This happens to work since sizeof(char) is always 1. You are also specifying buffer as char, but use TEXT() around the string - compiling with UNICODE will cause a break. Any of the following would be correct: char buffer[255]; StringCchPrintf(buffer, ARRAYSIZE(buffer), "%s", X); TCHAR buffer[255]; StringCchPrintf(buffer, ARRAYSIZE(buffer), TEXT("%s"), X); char buffer[255]; StringCbPrintf(buffer, sizeof(buffer), "%s", X); TCHAR buffer[255]; StringCbPrintf(buffer, sizeof(buffer), TEXT("%s"), X);
2,933,295
2,933,357
Embed Text File in a Resource in a native Windows Application
I have a C++ Windows program. I have a text file that has some data. Currently, the text file is a separate file, and it is loaded at runtime and parsed. How is it possible to embed this into the binary as a resource?
Since you're working on a native Windows application, what you want to do is to create a user-defined resource to embed the contents of the text file into the compiled resource. The format of a user-defined resource is documented on MSDN, as are the functions for loading it. You embed your text file in a resource file like this: nameID typeID filename where nameID is some unique 16-bit unsigned integer that identifies the resource and typeID is some unique 16-bit unsigned integer greater than 255 that identifies the resource type (you may define those integers in the resource.h file). filename is the path to the file that you want to embed its binary contents into the compiled resource. So you might have it like this: In resource.h: // Other defines... #define TEXTFILE 256 #define IDR_MYTEXTFILE 101 In your resource file: #include "resource.h" // Other resource statements... IDR_MYTEXTFILE TEXTFILE "mytextfile.txt" Then you load it like this (error-checking code omitted for clarity): #include <windows.h> #include <cstdio> #include "resource.h" void LoadFileInResource(int name, int type, DWORD& size, const char*& data) { HMODULE handle = ::GetModuleHandle(NULL); HRSRC rc = ::FindResource(handle, MAKEINTRESOURCE(name), MAKEINTRESOURCE(type)); HGLOBAL rcData = ::LoadResource(handle, rc); size = ::SizeofResource(handle, rc); data = static_cast<const char*>(::LockResource(rcData)); } // Usage example int main() { DWORD size = 0; const char* data = NULL; LoadFileInResource(IDR_MYTEXTFILE, TEXTFILE, size, data); /* Access bytes in data - here's a simple example involving text output*/ // The text stored in the resource might not be NULL terminated. char* buffer = new char[size+1]; ::memcpy(buffer, data, size); buffer[size] = 0; // NULL terminator ::printf("Contents of text file: %s\n", buffer); // Print as ASCII text delete[] buffer; return 0; } Note that you don't actually have to free the resource since the resource resides in the binary of the executable and the system will delete them automatically when the program exits (the function FreeResource() does nothing on 32-bit and 64-bit Windows systems). Because the data resides in the executable binary, you can't modify it via the retrieved pointer directly (that's why the LoadFileInResource() function implementation stores the pointer in a const char*). You need to use the BeginUpdateResource(), UpdateResource(), and EndUpdateResource() functions to do that.
2,933,504
2,933,525
Where in the standard is forwarding to a base class required in these situations?
Maybe even better is: Why does the standard require forwarding to a base class in these situations? (yeah yeah yeah - Why? - Because.) class B1 { public: virtual void f()=0; }; class B2 { public: virtual void f(){} }; class D : public B1,public B2{ }; class D2 : public B1,public B2{ public: using B2::f; }; class D3 : public B1,public B2{ public: void f(){ B2::f(); } }; D d; D2 d2; D3 d3; MS gives: sourceFile.cpp sourceFile.cpp(24) : error C2259: 'D' : cannot instantiate abstract class due to following members: 'void B1::f(void)' : is abstract sourceFile.cpp(6) : see declaration of 'B1::f' sourceFile.cpp(25) : error C2259: 'D2' : cannot instantiate abstract class due to following members: 'void B1::f(void)' : is abstract sourceFile.cpp(6) : see declaration of 'B and similarly for the MS compiler. I might buy the first case,D. But in D2 - f is unambiguously defined by the using declaration, why is that not enough for the compiler to be required to fill out the vtable? Where in the standard is this situation defined? added in reponse to answer Regarding the answer below that I have accepted: Why does this not seem an error in the spec? - If one has an inheritance hierarchy with a series of non virtual f()'s, the use of which in derived classes being determined by using statements, and one changes the decl of f in a base class to virtual then that can change which f is called in derived classes with using statements to pick their f. It is a c++ "gotcha"of which I was unaware. It may be part of the language but such "action at a distance" makes me uneasy and to me seems a violation of some sort of correctness / maintenance principle (that I can't quite formulate right now). But I can give an example: #include <iostream> using std::cout; namespace NonVirtual_f{ class C0 { public: void f(){cout<<"C0::f()"<<'\n';} }; class C1 : public C0{ public: void f(){cout<<"C1::f()"<<'\n';} }; class C2 : public virtual C1{ public: void f(){cout<<"C2::f()"<<'\n';} }; class D3 : public virtual C1, public C2{ public: using C1::f; }; }//namespace NonVirtual_f namespace Virtual_f{ class C0 { public: virtual void f(){cout<<"C0::f()"<<'\n';} }; class C1 : public C0{ public: void f(){cout<<"C1::f()"<<'\n';} }; class C2 : public virtual C1{ public: void f(){cout<<"C2::f()"<<'\n';} }; class D3 : public virtual C1, public C2{ public: using C1::f; }; }//namespace Virtual_f int main(int argc,const char* const*argv){ NonVirtual_f::D3 nv3; nv3.f(); Virtual_f::D3 v3; v3.f(); return 0; } Whence the output: C1::f() C2::f() All that is changed is the virtualness of f in C0. In particular once the non-virtualness of f in a base class is chosen, it cannot be changed without maintenance issues if some derived class (that in general one can't know about) has "overridden" as in the example immediately above. If you counter with "Well, do not override that way in the NonVirtual case", I agree it is bad practice but this seems more than just that. To me the language should: not allow the using in NonVirtual::D3 (not possible currently as there may be other overloaded f's to bring in [unless using allowed a signature in the function case]) or disallow using statements of functions completely and force forwarding or have using actually override in all cases or allow some syntactical declarative for functions (essentially a function using) like: void f(*signature*) = C2::f; What, exactly, am I missing here? Can someone come up with a scenario that clarifies the "why" of this choice in the standard?
The C++ standard says in §10.3/2: The rules for member lookup (10.2) are used to determine the final overrider for a virtual function in the scope of a derived class but ignoring names introduced by using-declarations. So, even though you use using B2::f; to bring B2::f() into the derived class, it is not considered to override B1::f(). Thus, D2 is abstract because of §10.4/4: A class is abstract if it contains or inherits at least one pure virtual function for which the final overrider is pure virtual.
2,933,554
2,933,571
How can I change the value or a static char* from a function? C++
I am trying to change the value of a "static char *" I define at startup, I do it from inside a function, and when this function returns the var I am trying to re-set the value doesn't retain it. Example: static char *X = "test_1"; void testFunc() { char buf[256]; // fill buf with stuff... X = buf; } How can I achieve this without using static for buf? Should I use another datatype? if so, which one?
As James said, use std::string... except be aware that global construction and destruction order is undefined between translation units. So, if you still want to use char*, use strcpy (see man strcpy) and make sure buf gets NUL-terminated. strcpy will copy the buf into the destination X. char buf[256]; // ... strcpy(X, buf); I should add that there are more reasons to use std::string. When using strcpy, you need to make sure that the destination buffer (X) has enough memory to receive the source buffer. In this case, 256 is much larger than strlen("test_1"), so you'll have problems. There are ways around this reallocate X (like this X = new char[number_of_characters_needed]). Or initialize X to a char array of 256 instead of a char*. IIRC, strcpy to a static defined string literal (like char *X = "test_1") is undefined behavior... the moral of the story is... It's C++! Use std::string! :) (You said you were new to c++, so you may not have heard "undefined behavior" means the computer can punch you in the face... it usually means your program will crash)
2,933,758
2,935,995
priority queue with limited space: looking for a good algorithm
This is not a homework. I'm using a small "priority queue" (implemented as array at the moment) for storing last N items with smallest value. This is a bit slow - O(N) item insertion time. Current implementation keeps track of largest item in array and discards any items that wouldn't fit into array, but I still would like to reduce number of operations further. looking for a priority queue algorithm that matches following requirements: queue can be implemented as array, which has fixed size and _cannot_ grow. Dynamic memory allocation during any queue operation is strictly forbidden. Anything that doesn't fit into array is discarded, but queue keeps all smallest elements ever encountered. O(log(N)) insertion time (i.e. adding element into queue should take up to O(log(N))). (optional) O(1) access for *largest* item in queue (queue stores *smallest* items, so the largest item will be discarded first and I'll need them to reduce number of operations) Easy to implement/understand. Ideally - something similar to binary search - once you understand it, you remember it forever. Elements need not to be sorted in any way. I just need to keep N smallest value ever encountered. When I'll need them, I'll access all of them at once. So technically it doesn't have to be a queue, I just need N last smallest values to be stored. I initially thought about using binary heaps (they can be easily implemented via arrays), but apparently they don't behave well when array can't grow anymore. Linked lists and arrays will require extra time for moving things around. stl priority queue grows and uses dynamic allocation (I may be wrong about it, though). So, any other ideas? --EDIT-- I'm not interested in STL implementation. STL implementation (suggested by a few people) works a bit slower than currently used linear array due to high number of function calls. I'm interested in priority queue algorithms, not implemnetations.
Array based heaps seem ideal for your purpose. I am not sure why you rejected them. You use a max-heap. Say you have an N element heap (implemented as an array) which contains the N smallest elements seen so far. When an element comes in you check against the max (O(1) time), and reject if it is greater. If the value coming in is lower, you modify the root to be the new value and sift-down this changed value - worst case O(log N) time. The sift-down process is simple: Starting at root, at each step you exchange this value with it's larger child until the max-heap property is restored. So, you will not have to do any deletes which you probably will have to, if you use std::priority_queue. Depending on the implementation of std::priority_queue, this could cause memory allocation/deallocation. So you can have the code as follows: Allocated Array of size N. Fill it up with the first N elements you see. heapify (you should find this in standard text books, it uses sift-down). This is O(N). Now any new element you get, you either reject it in O(1) time or insert by sifting-down in worst case O(logN) time. On an average, though, you probably will not have to sift-down the new value all the way down and might get better than O(logn) average insert time (though I haven't tried proving it). You only allocate size N array once and any insertion is done by exchanging elements of the array, so there is no dynamic memory allocation after that. Check out the wiki page which has pseudo code for heapify and sift-down: http://en.wikipedia.org/wiki/Heapsort
2,933,774
2,933,800
C++ Windows function call that get local hostname and IP address
Is there built-in windows C++ function call that can get hostname and IP address? Thanks.
To get the hostname you can use: gethostname or the async method WSAAsyncGetHostByName To get the address info, you can use: getaddrinfo or the unicode version GetAddrInfoW You can get more information about the computer name like the domain by using the Win32 API: GetComputerNameEx.
2,934,021
2,934,046
STL map containing references does not compile
The following: std::map<int, ClassA &> test; gives: error C2101: '&' on constant While the following std::map<ClassA &, int> test; gives error C2528: '_First' : pointer to reference is illegal The latter seems like map cannot contain a reference for the key value, since it needs to instantiate the class sometimes and a reference cannot be instantiated without an object. But why does the first case not work?
It is illegal to store references in an stl container, because types must be copy constructible and assignable. References can not be assigned. Exactly what operation causes the first error is implementation dependent, but I image that it is related to creating a reference and not assigning it immediately. The second error message looks like its actually related to building the map index. If your type is small, you can copy it into the map, or if it is large consider using pointers instead, but remember that the container will not deallocate the objects for you, you'll have to do that explicitly yourself. This SO question might be of interest to you.
2,934,042
2,934,922
Partial template specialization: matching on properties of specialized template parameter
template <typename X, typename Y> class A { // Use Y::Q, a useful property, not used for specialization. }; enum Property {P1,P2}; template <Property P> class B {}; class C {}; Is there any way to define a partial specialization of A such that A<C, B<P1> > would be A's normal template, but A<C, B<P2> > would be the specialization? Edit in response to Marcelo: More specifically, the specialization should be chosen not just with B, but with any type that exhibits a certain property, for example that it's a template whose first argument is P2. The goal is to use Y to present a nice interface for A, allowing to write something like A<C, Y<P2,Q> >. Replacing the Y template parameter by a template template parameter would be nice, but is there a way to partially specialize it based on P then? The intention would be to write something like: template <typename X, template <Property P> typename Y> class A {}; template <typename X> class A<X,template<> Y<P2> > {}; // <-- not valid Edit in response to In silico: I said it would be nice to make Y a template template parameter, but actually that defeats the purpose of what I wanted to do, which is to use Y to group logically linked properties together, but still specialize A based on one of those sub-properties. Is there a way by adding traits to a specialization template <> class B<P2> and then using SFINAE in A? The intention would be to write something like: template <> class B<P2> { typedef int IAmP2; }; // The following is not valid because it's a simple redefinition. template <typename X, typename Y> class A { // Substitution using this template would fail for Y<P1>, and only the // general template would be left for selection. typename Y::IAmP2 skipIfNotP2; };
I've no idea what you mean. Template template parameters seem the solution, although you somehow say they won't work. Why not do this? template <typename X, typename Y> class A { }; template <typename X, template<typename> class Y, typename P> class A< X, Y<P> > { /* property is P */ }; For your SFINAE question, yes that is possible too template <typename X, typename Y, typename Sfinae = void> class A { }; template <typename X, typename Y> class A< X, Y, typename Y::IAmP2 > { /* Y is the class having a property */ }; class Sample { typedef void IAmP2; }; Still i'm not sure what you mean at all.
2,934,216
2,934,671
Did I implement clock drift properly?
I couldn't find any clock drift RNG code for Windows anywhere so I attempted to implement it myself. I haven't run the numbers through ent or DIEHARD yet, and I'm just wondering if this is even remotely correct... void QueryRDTSC(__int64* tick) { __asm { xor eax, eax cpuid rdtsc mov edi, dword ptr tick mov dword ptr [edi], eax mov dword ptr [edi+4], edx } } __int64 clockDriftRNG() { __int64 CPU_start, CPU_end, OS_start, OS_end; // get CPU ticks -- uses RDTSC on the Processor QueryRDTSC(&CPU_start); Sleep(1); QueryRDTSC(&CPU_end); // get OS ticks -- uses the Motherboard clock QueryPerformanceCounter((LARGE_INTEGER*)&OS_start); Sleep(1); QueryPerformanceCounter((LARGE_INTEGER*)&OS_end); // CPU clock is ~1000x faster than mobo clock // return raw return ((CPU_end - CPU_start)/(OS_end - OS_start)); // or // return a random number from 0 to 9 // return ((CPU_end - CPU_start)/(OS_end - OS_start)%10); } If you're wondering why I Sleep(1), it's because if I don't, OS_end - OS_start returns 0 consistently (because of the bad timer resolution, I presume). Basically, (CPU_end - CPU_start)/(OS_end - OS_start) always returns around 1000 with a slight variation based on the entropy of CPU load, maybe temperature, quartz crystal vibration imperfections, etc. Anyway, the numbers have a pretty decent distribution, but this could be totally wrong. I have no idea. Edit: According to Stephen Nutt, Sleep(1) may not be doing what I'm expecting, so instead of Sleep(1), I'm trying to use: void loop() { __asm { mov ecx, 1000 cylcles: nop loop cylcles } }
The Sleep function is limited by the resolution of the system clock, so Sleep (1) may not be doing what you want.
2,934,240
2,934,260
Calling a method at a specific interval rate in C++
This is really annoying me as I have done it before, about a year ago and I cannot for the life of me remember what library it was. Basically, the problem is that I want to be able to call a method a certain number of times or for a certain period of time at a specified interval. One example would be I would like to call a method "x" starting from now, 10 times, once every 0.5 seconds. Alternatively, call method "x" starting from now, 10 times, until 5 seconds have passed. Now I thought I used a boost library for this functionality but I can't seem to find it now and feeling a bit annoyed. Unfortunately I can't look at the code again as I'm not in possession of it any more. Alternatively, I could have dreamt this all up and it could have been proprietary code. Assuming there is nothing out there that does what I would like, what is currently the best way of producing this behaviour? It would need to be high-resolution, up to a millisecond. It doesn't matter if it blocks the thread that it is executed from or not. Thanks!
A combination of boost::this_thread::sleep and time duration found in boost::datetime?
2,934,314
2,934,329
How to escape a semicolon in C++ string
std:string str("text1\; text2\;"); How come VS2005 says ; unrecognized character escape sequence. Please advise, thanks.
Because this is wrong: std:string str("text1\; text2\;"); This is correct: std::string str("text1; text2;"); TWO colons after std.
2,934,648
2,934,660
C++: Platform independent game lib?
I want to write a serious 2D game, and it would be nice if I have a version for Linux and one for Windows (and eventually OSX). Java is fantastic because it is platform independent. But Java is too slow to write a serious game. So, I thought to write it in C++. But C++ isn't very cross-platform friendly. I can find game libraries for Windows and libraries for Linux, but I'm searching one that I can use for both, by recompiling the source on a Windows platform and on a Linux platform. Are there engines for this or is this idea irrelevant? Isn't it that easy (recompiling)? Any advice and information about C++ libraries would be very very very appreciated!
Try SDL (in association with c/c++), it's great for 2D games (and supports 3D through opengGL), and it works on windows, os x and linux.
2,934,672
2,934,725
link .a and .o files in GCC
I have two precompiled library: X.a and Y.a and a test.cpp (without main function) source code use these two libraries. I compiled the C++ using: g++ -c test.cpp and I got 'test.o'. Now how can I link these three together to generate a .a file because test.cpp use some function in X.a and Y.a and other GCC libraries? BTW, I am doing these under Windows using MinGW. Can I rename this .a file to .lib and use this .lib in VC? Thanks!
Now how can I link these three together to generate a .a file because test.cpp use some function in X.a and Y.a and other GCC libraries? .a is nothing more then ar archive containg all object files (.o files) Can I rename this .a file to .lib and use this .lib in VC? Yes, but it requires little trick to work. See: http://opensees.berkeley.edu/community/viewtopic.php?t=2267
2,934,692
2,934,710
how to see contents of a.out file?
The executable file of c++ will contain linkers, modules and others, i would like to look into its contents, i'm using linux, how can i view contents of a.out? which command should use to browse a.out, text editors wont show the contents......
You can use nm to see the internal symbols and objdump to get the disassemble. By example: objdump -D a.out | less Note however that during the final linking of the object files into the executable a lot of symbols and internal data get eliminated, therefore you won't be able to understand the structure as you would be with object files. If you want to edit and modify the executable, I suggest you to use the hte editor, which can act as disassembler for x86 executables. If you are a debian/ubuntu user the package name is "ht" (not "hte"). Also I wrote a little elf disassembly library which is still incomplete but pretty funny. You can find other (more complete and probably better) implementations however!
2,934,746
4,645,606
How to remove one folder from C:\Windows\winsxs?
I've installed: Microsoft Visual C++ 2008 SP1 Redistributable Package (x86) and got the following folders: x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91 x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.30729.4926_none_508ed732bcbc0e5a I allready uninstalled the redistribute package but they continue overthere. I want to remove them because I want to test my program without installing nothing (I've included those dll's when building it in another computer). So, how can I remove those folders from C:\Windows\winsxs? Thanks in advance :D
Modifying the registry or filesystem directly is a bit dangerous, since there's a lot of extra configuration data associated with installed assemblies. The fact that those files are still present doesn't do great harm (WinSxS is a cache), what's important is whether the system treats them as installed or not. I've blogged about how to accomplish this here: http://blogs.msdn.com/b/talagrand/archive/2010/03/02/9973115.aspx
2,934,764
2,934,775
Receiving integers, but also want to test for char
Say I am looking to receive a series of numeric values and read them into an int, but I also want to test if the user hit key 'x'. I am sure I am missing something obvious, and have tried a few things but seem to be stuck. This is what I have so far... cout << endl << "Enter key (or 'x' to exit): "; cin >> key; if (key == 'x') { cout << "exiting";} // continue on...
You need to read into a string and then convert that to an integer. In outline: #include <string> #include <sstream> #include <iostream> using namespace std; int main() { string s; cout << endl << "Enter key (or 'x' to exit): "; getline( cin, s ); if ( s == "x" ) { // do exit stuff } else { istringstream is( s ); int n; if ( ! is >> n ) { // report not an integer } else { // do something with n } } }
2,934,904
2,934,909
Order of evaluation in C++ function parameters
If we have three functions (foo, bar, and baz) that are composed like so... foo(bar(), baz()) Is there any guarantee by the C++ standard that bar will be evaluated before baz?
No, there's no such guarantee. It's unspecified according to the C++ standard. Bjarne Stroustrup also says it explicitly in "The C++ Programming Language" 3rd edition section 6.2.2, with some reasoning: Better code can be generated in the absence of restrictions on expression evaluation order Although technically this refers to an earlier part of the same section which says that the order of evaluation of parts of an expression is also unspecified, i.e. int x = f(2) + g(3); // unspecified whether f() or g() is called first
2,935,017
2,935,050
Input system reference trouble
I'm using SFML for input system in my application. size_t WindowHandle; WindowHandle = ...; // Here I get the handler sf::Window InputWindow(WindowHandle); const sf::Input *InputHandle = &InputWindow.GetInput(); // [x] Error At the last lines I have to get reference for the input system. Here is declaration of GetInput from documentation: const Input & sf::Window::GetInput () const The problem is: >invalid conversion from ‘const sf::Input*’ to ‘sf::Input*’ What's wrong?
Is there a special reason why you want to have a pointer rather than a reference? If not, you could try this: const sf::Input & InputHandle = InputWindow.GetInput(); This will return you a reference to your Input handle. Btw, this worked for me: const int& test(int& i) { return i; } int main() { int i = 4; const int* j = &test(i); cout << *j << endl; return 0; } Output : 4 Don't know why your compiler doesn't want you to point the reference.
2,935,038
2,935,044
Why can't I add pointers?
I have code very similiar to this: LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator+(const Iterator& right)const { return (this + &right);//IN THIS PLACE I'M GETTING AN ERROR } LINT_rep::Iterator::difference_type LINT_rep::Iterator::operator-(const Iterator& right)const {//substracts one iterator from another return (this - &right);//HERE EVERYTHING IS FINE } err msg: Error 1 error C2110: '+' : cannot add two pointers Why I'm getting an error only in one place and not in both?
Pointer addition is forbidden in C++, you can only subtract two pointers. The reason for this is that subtracting two pointers gives a logically explainable result - the offset in memory between two pointers. Similarly, you can subtract or add an integral number to/from a pointer, which means "move the pointer up or down". Adding a pointer to a pointer is something which is hard to explain. What would the resulting pointner represent? If by any chance you explicitly need a pointer to a place in memory whose address is the sum of some other two addresses, you can cast the two pointers to int, add ints, and cast back to a pointer. Remember though, that this solution needs huge care about the pointer arithmetic and is something you really should never do.
2,935,109
2,935,146
Window Wrapper Class C++ (G++)
I am attempting to learn about creating windows in c++, I have looked at an article about creating a wrapper class but I don't really understand it. So far I know that you can't have a class method WndProc (I dont know why) but honestly, that is all. Can somebody give an explanation, also explaining the reinterpret_cast? Here is the article. LRESULT CALLBACK Window::MsgRouter(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { Window *wnd = 0; if(message == WM_NCCREATE) { // retrieve Window instance from window creation data and associate wnd = reinterpret_cast<Window *>((LPCREATESTRUCT)lparam)->lpCreateParams; ::SetWindowLong(hwnd, GWL_USERDATA, reinterpret_cast<long>(wnd)); // save window handle wnd->SetHWND(hwnd); } else // retrieve associated Window instance wnd = reinterpret_cast<Window *>(::GetWindowLong(hwnd, GWL_USERDATA)); // call the windows message handler wnd->WndProc(message, wparam, lparam); } Thanks in advance, ell.
The MsgRouter() procedure acts as a proxy between the Windows message handling system to the Window instance associated with a HWND. It routes Windows messages to C++ objects. A pointer to the Window instance is passed to the MsgRouter() procedure via the last parameter of the CreateWindow() function. When you first create a HWND via CreateWindow() (or CreateWindowEx()), some messages are sent - one of them being WM_NCCREATE. When the procedure receives a WM_NCCREATE message, the LPARAM parameter contains a pointer to a CREATESTRUCT which contains the arguments that was passed into the CreateWindow() function. The procedure retrieves the Window instance pointer from the CREATESTRUCT and saves it in the HWND by setting it as an attribute of the HWND (GWL_USERDATA via SetWindowLong()). Now that the pointer has been saved, the window procedure can from now on retrieve a pointer to the original Window instance from a HWND via GetWindowLong() when it receives a message. Finally, the window procedure calls WndProc() on the retrieved Window pointer, passing in the exact message and parameters, so the Window instance can handle the message.
2,935,166
2,935,262
What good programming practices will change with C++11?
For example, "Don't return objects by value if they are expensive to copy" (RVO can't always be used). This advice might change because of rvalue references. The same might be said about storing collections of pointers to objects, because copying them by value into the collection was too expensive; this reason might no longer be valid. Or the use of enums might be discouraged in favour of "enum class". What other practices or tips will change?
I expect that C++ written in a functional-like style will become more prevalent because: Lambda expressions make using the standard library algorithms much easier Move semantics make returning standard library or other RAII container objects significantly cheaper
2,935,173
2,935,191
Init var without copy constructor
I have some class(Window) without copy constructor (it's private). I can't understand how to init var of this class in my own class: class MyClass { Window obj; // Hasn't copy constructor public: void init() { obj = Window(/* constructor params */); // [error] obj(/* constructor params */); // [error] } } Error 1: initializing argument 1 of ‘Window::Window(WindowHandle, const sf::WindowSettings&)’ Error 2: ‘NonCopyable& NonCopyable::operator=(const NonCopyable&)’ is private But it works in this way: Window obj(/* constructor params */);
Your MyClass needs a constructor to initialize the obj member. class MyClass { private: Window obj; public: MyClass() : obj(/* constructor params */) // This is an initializer list {} }; If you need the init() function, and the Window object provides its own init() function of some sort, you can do this: class MyClass { private: Window obj; public: void init() { obj.init(/* init params */); // Window's own init() function } }; If the Window class does not have anything like an init() function, you can use the heap (not recommended unless you absolutely have to): class MyClass { private: // Alternatively, we can use a smart pointer here and avoid // managing memory ourselves. Window* obj; public: MyClass() : obj(0) {} ~MyClass() { uninit(); } void init() { uninit(); obj = new Window(/* constructor params */); } void uninit() { if(obj != 0) { delete obj; obj = 0; } } }; If the Window class declares a private copy constructor and/or copy assignment operator, then you cannot assign a new Window instance to obj.
2,935,201
2,935,230
Will C++0x support __stdcall or extern "C" capture-nothing lambdas?
Yesterday I was thinking about whether it would be possible to use the convenience of C++0x lambda functions to write callbacks for Windows API functions. For example, what if I wanted to use a lambda as an EnumChildProc with EnumChildWindows? Something like: EnumChildWindows(hTrayWnd, CALLBACK [](HWND hWnd, LPARAM lParam) { // ... return static_cast<BOOL>(TRUE); // continue enumerating }, reinterpret_cast<LPARAM>(&myData)); Another use would be to write extern "C" callbacks for C routines. E.g.: my_class *pRes = static_cast<my_class*>(bsearch(&key, myClassObjectsArr, myClassObjectsArr_size, sizeof(my_class), extern "C" [](const void *pV1, const void *pV2) { const my_class& o1 = *static_cast<const my_class*>(pV1); const my_class& o2 = *static_cast<const my_class*>(pV2); int res; // ... return res; })); Is this possible? I can understand that lambdas that capture variables will never be compatible with C, but it at least seems possible to me that capture-nothing lambdas can be compatible.
Lambdas without a capture are implicitly convertible to a pointer to function (by a non-explicit conversion function defined by the closure type). The FCD does not seem to specify what language linkage the function type of that function pointer type has, so if you need to pass this function pointer to C functions, the calling convention of C++ functions and C functions need to be the same. I believe that on Windows, that is the case though. So you should be able to pass the lambda to Windows API functions typedef void(*callbackType)(void *userData); extern "C" void someCFunction(callbackType callback); int main() { someCFunction([](void *userData) { /* ... */ }); } FCD wording at 5.1.2/6: The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type’s function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type’s function call operator. I think the final Standard should have a note that says that there is a conversion function to both C linkage function pointers and C++ linkage function pointers, as convertibility to C function pointers is one of the goal of this functionality.
2,935,239
2,935,274
C++ Inheritance and Constructors
trying to work out how to use constructors with an inherited class. I know this is very much wrong, I've been writing C++ for about three days now, but here's my code anyway: clientData.h, two classes, ClientData extends Entity : #pragma once class Entity { public: int x, y, width, height, leftX, rightX, topY, bottomY; Entity(int x, int y, int width, int height); ~Entity(); }; class ClientData : public Entity { public: ClientData(); ~ClientData(); }; and clientData.cpp, which contains the functions: #include <iostream> #include "clientData.h" using namespace std; Entity::Entity(int x, int y, int width, int height) { this->x = x; this->y = y; this->width = width; this->height = height; this->leftX = x - (width/2); this->rightX = x + (width/2); this->topY = y - (height/2); this->bottomY = y + (height/2); } Entity::~Entity() { cout << "Destructing.\n"; } ClientData::ClientData() { cout << "Client constructed."; } ClientData::~ClientData() { cout << "Destructing.\n"; } and finally, I'm creating a new ClientData with: ClientData * Data = new ClientData(32,32,32,16); Now, I'm not surprised my compiler shouts errors at me, so how do I pass the arguments to the right classes? The first error (from MVC2008) is error C2661: 'ClientData::ClientData' : no overloaded function takes 4 arguments and the second, which pops up whatever changes I seem to make is error C2512: 'Entity' : no appropriate default constructor available Thanks.
Currently the constructor for the Client data class wont work. You will need to make a constructor for Client data like: ClientData(int x, int y, int width, int height): Entity(x, y, width, height) if you want to call new ClientData(32,32,32,16);
2,935,366
2,935,379
In C++, what happens when you return a variable?
What happens, step by step, when a variable is returned. I know that if it's a built-in and fits, it's thrown into rax/eax/ax. What happens when it doesn't fit, and/or isn't built-in? More importantly, is there a guaranteed copy constructor call? edit: What about the destructor? Is that called "sometimes", "always", or "never"?
Where the return value is stored depends entirely on the calling convention and is very architecture- and system-specific. The compiler is permitted to elide the call to the copy constructor (i.e., it does not have to call the copy constructor). Note that returning a value from a function might also invoke an assignment operator, depending on what is being done with the return value of a function.
2,935,513
2,935,564
Draw OpenGL on the windows desktop without a window
I've seen things like this and I was wondering if this was possible, say I run my application and it will show the render on whatever is below it. So basically, rendering on the screen without a window. Possible or a lie? Note: Want to do this on windows and in c++.
It is possible to use your application to draw on other application's windows. Once you have found the window you want, you have it's HWND, you can then use it just like it was your own window for the purposes of drawing. But since that window doesn't know you have done this, it will probably mess up whatever you have drawn on it when it tries to redraw itself. There are some very complicated ways of getting around this, some of them involve using windows "hooks" to intercept drawing messages to that window so you know when it has redrawn so that you can do your redrawing as well. Another option is to use clipping regions on a window. This can allow you to give your window an unusual shape, and have everything behind it still look correct. There are also ways to take over drawing of the desktop background window, and you can actually run an application that draws animations and stuff on the desktop background (while the desktop is still usable). At least, this was possible up through XP, not sure if it has changed in Vista/Win7. Unfortunately, all of these options are too very complex to go in depth without more information on what you are trying to do.
2,935,532
2,935,580
Portable way to hide console window in GLUT application?
Hey, I'm creating a little GLUT application and need help with hiding/removing the console window. I am developing on windows and I already know of the various methods to hide the console window on a windows system, however is there no portable method of hiding it? Thanks...
You don't really want to "hide" the console window. What you want is to configure your compiler to generate a "Windows application" instead of a "Console application". That will tell windows to never create a console for your application. You'll need to consult your compiler's documentation to figure out how to do that. For Visual Studio, it is a step on one of the wizards. There isn't really a good way to control the console inside of a console application. The console is designed so that the application knows nothing about it. While it is possible, as you said, it's not very portable or clean. The correct approach if you need fine-grained control over the "console" is to implement your own window which provides a text output area where you can print things. Then you can do pretty much anything with your "console" because it isn't really a console, it's just another window owned and operated by your application.
2,935,587
2,939,249
Handle complex options with Boost's program_options
I have a program that generates graphs using different multi-level models. Each multi-level model consists of a generation of a smaller seed graph (say, 50 nodes) which can be created from several models (for example - for each possible edge, choose to include it with probability p). After the seed graph generation, the graph is expanded into a larger one (say 1000 nodes), using one of another set of models. In each of the two stages, each model require a different number of parameters. I would like to be have program_options parse the different possible parameters, according to the names of the models. For example, say I have two seed graphs models: SA, which has 1 parameters, and SB, which has two. Also for the expansion part, I have two models: A and B, again with 1 and 2 parameters, respectively. I would like to be able do something like: ./graph_generator --seed=SA 0.1 --expansion=A 0.2 ./graph_generator --seed=SB 0.1 3 --expansion=A 0.2 ./graph_generator --seed=SA 0.1 --expansion=B 10 20 ./graph_generator --seed=SB 0.1 3 --expansion=B 10 20 and have the parameters parsed correctly. Is that even possible?
By using a custom validator and boost::program_options::value::multitoken, you can achieve the desired result: #include <iostream> #include <boost/lexical_cast.hpp> #include <boost/optional.hpp> #include <boost/program_options.hpp> // Holds parameters for seed/expansion model struct Model { std::string type; boost::optional<float> param1; boost::optional<float> param2; }; // Called by program_options to parse a set of Model arguments void validate(boost::any& v, const std::vector<std::string>& values, Model*, int) { Model model; // Extract tokens from values string vector and populate Model struct. if (values.size() == 0) { throw boost::program_options::validation_error( "Invalid model specification"); } model.type = values.at(0); // Should validate for A/B if (values.size() >= 2) model.param1 = boost::lexical_cast<float>(values.at(1)); if (values.size() >= 3) model.param2 = boost::lexical_cast<float>(values.at(2)); v = model; } int main(int argc, char* argv[]) { Model seedModel, expansionModel; namespace po = boost::program_options; po::options_description options("Generic options"); options.add_options() ("seed", po::value<Model>(&seedModel)->multitoken(), "seed graph model") ("expansion", po::value<Model>(&expansionModel)->multitoken(), "expansion model") ; po::variables_map vm; po::store(po::parse_command_line(argc, argv, options), vm); po::notify(vm); std::cout << "Seed type: " << seedModel.type << "\n"; if (seedModel.param1) std::cout << "Seed param1: " << *(seedModel.param1) << "\n"; if (seedModel.param2) std::cout << "Seed param2: " << *(seedModel.param2) << "\n"; std::cout << "Expansion type: " << expansionModel.type << "\n"; if (expansionModel.param1) std::cout << "Expansion param1: " << *(expansionModel.param1) << "\n"; if (expansionModel.param2) std::cout << "Expansion param2: " << *(expansionModel.param2) << "\n"; return 0; } The validate function probably needs more rigor, but you get the idea. This compiles and works for me.
2,935,604
2,935,614
Qt cross thread call
I have a Qt/C++ application, with the usual GUI thread, and a network thread. The network thread is using an external library, which has its own select() based event loop... so the network thread isn't using Qt's event system. At the moment, the network thread just emit()s signals when various events occur, such as a successful connection. I think this works okay, as the signals/slots mechanism posts the signals correctly for the GUI thread. Now, I need for the network thread to be able to call the GUI thread to ask questions. For example, the network thread may require the GUI thread to request put up a dialog, to request a password. Does anyone know a suitable mechanism for doing this? My current best idea is to have the network thread wait using a QWaitCondition, after emitting an object (emit passwordRequestedEvent(passwordRequest);. The passwordRequest object would have a handle on the particular QWaitCondition, and so can signal it when a decision has been made.. Is this sort of thing sensible? or is there another option?
Using signals to send messages between threads is fine, if you don't like using the Condition Variable, then you can send signals in both directions in a more-or-less asynchronous manner: this might be a better option if you want to continue processing network stuff while you wait for a reply from the GUI.
2,935,760
2,935,786
Getline and 16h (26d) character
in VC++ environment Im using (string) getline function to read separate lines in opened file. Problem is that getline takes character 1Ah as end of file and if it is present on the line, whole reading ends prematurely. Is there any solution for this? Code snippet: fstream LogFile (Source,fstream::in); string Line while (getline(LogFile,Line)) { .... } File contents: line1text1asdf line2text2asd //EOF for getline here line3asdas // this line will never be read by getline Thank you for any info. Kra
Replace getline with a hand-rolled function that reads in character by character until end of line or eof, as defined by you.
2,935,984
2,936,092
C++ meta-splat function
Is there an existing function (in boost mpl or fusion) to splat meta-vector to variadic template arguments? For example: splat<vector<T1, T2, ...>, function>::type // that would be the same as function<T1, T2, ...> My search have not found one, and I do not want to reinvent one if it already exists. Alternatively, is there a solution for: apply(f, t); // that would be the same as f(t[0], t[1], ...); Given f is some template function and t is a fusion sequence. edit: after some searching I found it in http://www.boost.org/doc/libs/1_43_0/libs/fusion/doc/html/fusion/functional/invocation/functions.html
You need unpack_args and quoteN, where N is the number of template arguments your template takes. Alternatively if you implement function as a metafunction class, you don't need to quoteN. Example of a metafunction class yielding the first of two given types: struct function1st { template<typename T1, typename T2> struct apply { typedef T1 type; }; }; /* create a metafunction class that takes a sequence and apply it to function1st */ typedef unpack_args<function1st> unpacker; Then you can use unpacker as a metafunction class that takes a sequence BOOST_MPL_ASSERT(( is_same< apply<unpacker, vector<int, char> >::type, int> )); Or if you have it as a template, you need to quote it first template<typename T1, typename T2> struct function1st { typedef T1 type; }; /* create a metafunction class that takes a sequence and apply it to function1st */ typedef unpack_args< quote2<function1st> > unpacker; Hope it helps.
2,935,997
2,936,057
How to use environment variable in #import c++ command?
nowadays I have this piece of code: #import "C:\Users\Public\SoundLog\DLLs\ForPython\SoundLogDLL.tlb" named_guids but I want to substitute the C:\Users\Public part by the %PUBLIC% environment variable. How can I do this ?
It would be wise to store your projects in a common folder so that you can use relative paths. The #import directive also searches files in the same folders where it looks for #include files. In the IDE, you can add them with Project + Properties, C/C++, General, Additional Include Directories.
2,936,001
2,936,017
Doing extra initialisations on a MFC Dialog in Visual Studio C++ 2008 Pro
How do I make extra initializations on a modal dialog before calling DoModal(); ? The whole application is created using VS wizards. I have a main Dialog (the one that is created automatically when I select new MFC Application in Visual Studio 2008 Professional). When I click a button on this dialog I want to open another dialog and set a CString value into a CEdit control. my code: ... void MainDlg::OnClickedButtonX(){ SecondDialogClass Dlg2; Dlg2.asocVar2Cedit.SetWindowTextW(L"my text"); Dlg2.DoModal(); } //asocVar2Cedit is the associeted control variable to the //CEdit control on the second Dialog (Right Click > Add Variable.. in VSC++) ... this code generates at runtime a "Debug Assertion" error in winocc... Any ideas ? Thank you in advance.
Add an OnInitDialog (WM_INITDIALOG) handler to your CDialog-derived class and have it initialise itself.
2,936,044
2,936,082
Loop invariants (Specifically Ch.3 of "Accelerated C++")
I'm currently working my way through "Accelerated C++" and just came across this in chapter 3: // invariant: // we have read count grades so far, and // sum is the sum of the first count grades while (cin >> x) { ++count; sum += x; } The authors follow this by explaining that the invariant needs special attention paid to it because when the input is read into x, we will have read count + 1 grades and thus the invariant will be untrue. Similarly, when we have incremented the counter, sum will no longer be the sum of the last count grades (in case you hadn't guessed, it's the traditional program for calculating student marks). What I don't understand is why this matters. Surely for just about any other loop, a similar statement would be true? For example, here is the book's first while loop (the output is filled in later): // invariant: we have written r rows so far while (r != rows) { // write a row of output std::cout << std::endl; ++r; } Once we have written the appropriate row of output, surely the invariant is false until we have incremented r, just as in the other example? What makes these two conditions different? EDIT: Thanks for all your replies. I think I've got it but I'm going to leave it going a little longer before I choose an "Accepted answer" just to be sure. So far, all the replies basically agree so it hardly seems fair, but worth doing I guess. The original paragraph, as requested below: "Understanding the invariant for this loop requires special care, because the condition in the while has side effects. Those side effects affect the truth of the invariant: Successfully executing cin >> x makes the first part of the invariant-the part that says that we have read count grades-false. Accordingly, we must change our analysis to account for the effect that the condition itself might have on the invariant. We know that the invariant was true before evaluating the condition, so we know that we have already read count grades. If cin >> x succeeds, then we have now read count + 1 grades. We can make this part of the invariant true again by incrementing count. However, doing so falsifies the second part of the invariant-the part that says that sum is the sum of the first count grades-because after we have incremented count, sum is now the sum of the first count - 1 grades, not the first count grades. Fortunately, we can make the second part of the invariant true by executing sum += x; so that the entire invariant will be true on subsequent trips through the while. If the condition is false, it means that our attempt at input failed, so we didn't get any more data, and so the invariant is still true. As a result, we do not have to account for the condition's side effects after the while finishes."
From your description it sounds like the author is talking nonsense. Yes, the invariant becomes untrue temporarily between instructions, but that is going to happen whenever you have non-atomic operations like this. As long as there aren't any clear break points that could lead to the invariant being incorrect and the program in an inconsistent state, you are fine. In this case, the only way that could happen is if std::cout throws an exception while an invariant is untrue, then you catch that exception somewhere but continue execution in a bad state. It seems to me the author is being overly pedantic. So again, as long as you don't have any break/continue statements in the wrong place or exceptions being thrown you are OK. I doubt many people would bother focusing on your example code because it's just so simple.
2,936,052
2,936,064
Clang doesn't support the Lock Prefix. How shall I workaround?
Assume this code: static inline void inc(int64_t* atomic) { __asm__ __volatile__ ( "lock incq %0\n" : "=m" (*atomic) : "m" (*atomic) ); } The Clang compiler doesn't support the lock prefix (yet?). What shall I do now?
Why not use the built-ins...? static inlint void inc(int64_t* atomic) { __sync_add_and_fetch_8(atomic, 1); }
2,936,078
2,936,081
How do I reset my pointer to a specific array location?
I am a brand new programming student, so please forgive my ignorance. My assignment states: Write a program that declares an array of 10 integers. Write a loop that accepts 10 values from the keyboard and write another loop that displays the 10 values. Do not use any subscripts within the two loops; use pointers only. Here is my code: #include "stdafx.h" #include <iostream> using namespace std; int main() { const int NUM = 10; int values[NUM]; int *p = &values[0]; int x; for(x = 0; x < NUM; ++x, ++p) { cout << "Enter a value: "; cin >> *p; } for(x = 0; x < NUM; ++x, ++p) { cout << *p << " "; } return 0; } I think I know where my problem is. After my first loop, my pointer is at values[10], but I need to get it back to values[0] to display them. How can I do that?
You can do exactly as you did first when you assigned p: p = &values[0]; Besides, arrays are very much like pointers (that you can't change) to statically allocated memory. Therefore, the expression &values[0] evaluates to the same thing that just values does. Consequently, p = &values[0]; is the same as p = values;
2,936,111
19,524,080
Emacs hide/show support for C++ triple-slash Doxygen markup?
I use Doxygen's triple-slash syntax to markup my C++ code. There are two important cases which arise: 1) block markup comments which are the sole element on the line and may or may not begin flush left; e.g. class foo /// A one sentence brief description of foo. The elaboration can /// continue on for many lines. { ... }; void foo::bar /// A one sentence brief description of bar. The elaboration can /// continue on for many lines. () const { ... } 2) trailing markup comments which always follow some number of C++ tokens earlier on the first line but may still spill over onto subsequent lines; e.g. class foo { int _var1; ///< A brief description of _var1. int _var2; ///< A brief description of _var2 ///< requiring additional lines. } void foo::bar ( int arg1 ///< A brief description of arg1. , int arg2 ///< A brief description of arg2 ///< requiring additional lines. ) const { ... } I wonder what hide/show support exists to deal with these conventions. The most important cases are the block markup comments. Ideally I would like to be able to eliminate these altogether, meaning that I would prefer not to waste a line simply to indicate presence of a folded block markup comment, preferring a fringe marker, a la hideshowvis.el.
Maybe, as a partial answer the following snippet of code would do the trick. Press M-s M-s in C++-mode and it hides all comments of the kind you described. Again pressing M-s M-s reveals the comments again. I know that the short code has its limitations: It would be nice if one could hide/show each special comment separately. Since all special comments are hidden you would need M-s M-s quite often. Therefore, hs1-mode should be more effective on large C++-files (maybe, it should be implmented via jit-font-lock). Consecutive lines of special comments should be joined to one hidden block. (defvar hs1-regexp "\\(\n[[:blank:]]*///\\|///<\\).*$" "List of regular expressions of blocks to be hidden.") (define-minor-mode hs1-mode "Hide/show predefined blocks." :lighter " hs1" (if hs1-mode (let (ol) (save-excursion (goto-char (point-min)) (while (search-forward-regexp hs1-regexp nil 'noErr) (when (eq (syntax-ppss-context (syntax-ppss (match-end 1))) 'comment) (setq ol (make-overlay (match-beginning 0) (match-end 0))) (overlay-put ol 'hs1 t) (overlay-put ol 'invisible t) )))) (remove-overlays (point-min) (point-max) 'hs1 t) )) (add-hook 'c++-mode-hook '(lambda () (local-set-key (kbd "M-s M-s") 'hs1-mode)))
2,936,165
2,936,183
C++ - 3 possible values in Variable?
I need to store a 30 letter combination, but each letter can only be "0", "1" or "2". When I use sizeof(myString), it returns 32. I want to use this 30 letter combination to access a row of an array, so I'm wondering if it is possible to use a 3 value bool of some sort to store 1 of 3 values in.
3^30 = 205891132094649 (~2E14), which is less than the maximum value of a 64-bit integer (~2E19), so you could map the strings to 64-bit ints in a 1:1 fashion. An obvious way to do this would be to treat your string as a base-3 number, which would be quite slow to convert. Much faster would be to treat it as base 4, then conversion can be done entirely with bit shifts (no modulus division / multiplication), this is possible since 4^30 is still less than 2^64.
2,936,279
2,937,871
Disable script debugging in IWebBrowser2 OLE control? C++
I have a IWebBrowser2 I use to visit some webpages with .Navigate() When the page has a js error I got a warning box for "Syntax error", so I used .put_Silent(TRUE). And now I get a warning for "VS Just-In-Time Debugger: Unhandled exception" instead How can I disable all the script error warnings (including JIT debugger) from my code (i mean without modifying the real IE settings)?
You can disable script debugging by overriding the registry settings that control it. The correct way to do this is to implement the IDocHostUIHandler interface, and specifically the IDocHostUIHandler::GetOptionKeyPath or IDocHostUIHandler::GetOverrideKeyPath methods. Use GetOptionKeyPath to ignore all the user's IE settings (e.g., font size) and use IE defaults, or GetOverrideKeyPath to use most of the user's IE settings but override a few specific ones. The MSDN articles linked above contain good documentation on how to use this interface, as well as sample implementations of the IDocHostUIHandler interface and its methods. Say that your GetOptionKeyPath method returns "SOFTWARE\MyCompany\MyApp\IE" as the new registry path. To ensure that script debugging is disabled, you would need to create the HKEY_CURRENT_USER\Software\MyCompany\MyApp\IE\Main registry key, then create a string value named Disable Script Debugger having the value yes.
2,936,472
2,936,705
SetMatrix() does not copy all values to HLSL
I want to use the contents of a vector of D3DXMatrices to my shader. m_pLightMatrices->SetMatrixArray(&currentLightMatrices[0].m[0][0],0,numLights); As we know the internals of a vector this poses no problems (as it is just a dynamic array). Now when I access this matrix in hlsl to fill up a struct I get this strange behavior: struct LightTest { float3 LightPos; float LightRange; float4 LightDiffuse; float3 LightAtt; }; float4x4 currentLight = gLights[0]; LightTest lt; lt.LightPos = currentLight._m00_m01_m02; //{0,0,0} lt.LightDiffuse = currentLight[1].rgba; //{0,0,0,0} lt.LightRange = currentLight._m03; //this gives me a value lt.LightAtt = currentLight[2].xyz; //{0,0,0} While debugging I see that my matrix is nicely filled with the variables I want. When I try to hardcode check what is in the struct I get all zero's, except the LightRange. As you can see I tried different methods of accessing the float4x4 but without any other results. Why oh why is hlsl not copying all my variables ?
I managed to fix the issue. I do need some clarification on why it works now. I just put the SetMatrixArray() function before the Input layout is set and suddenly it works perfectly. Previously it was inside an update function together with all other variables (like world matrices, etc ..) and those work fine.
2,936,481
2,936,486
Visual C++ 2010 atomic types support?
Does VC++ 2010 have support for C++11's portable atomic type template?
No; none of the C++11 atomic operations or thread support features are supported by Visual C++ 2010. Both of these sets of features are supported by Visual C++ 2012.
2,936,757
2,936,759
What C++11 features does Visual Studio 2010 support?
There is a list for GCC; is there a similar list for Visual Studio 2010?
There is also a list for Visual C++ 2010 (that article describes the core language features that have been implemented; the PDF linked from the article describes the library features that have been implemented). Edit: I've just come across an awesome list: the Apache C++ Standard Library wiki has a table listing the C++11 core language features and which C++ compilers support each of them.
2,936,805
2,937,119
How do C++ compilers actually pass reference parameters?
This question came about as a result of some mixed-language programming. I had a Fortran routine I wanted to call from C++ code. Fortran passes all its parameters by reference (unless you tell it otherwise). So I thought I'd be clever (bad start right there) in my C++ code and define the Fortran routine something like this: extern "C" void FORTRAN_ROUTINE (unsigned & flag); This code worked for a while but (of course right when I needed to leave) suddenly started blowing up on a return call. Clear indication of a munged call stack. Another engineer came behind me and fixed the problem, declaring that the routine had to be defined in C++ as extern "C" void FORTRAN_ROUTINE (unsigned * flag); I'd accept that except for two things. One is that it seems rather counter-intuitive for the compiler to not pass reference parameters by reference, and I can find no documentation anywhere that says that. The other is that he changed a whole raft of other code in there at the same time, so it theoretically could have been another change that fixed whatever the issue was. So the question is, how does C++ actually pass reference parameters? Is it perhaps free to do copy-in, copy-out for small values or something? In other words, are reference parameters utterly useless in mixed-language programming? I'd like to know so I don't make this same code-killing mistake ever again.
Just to chime in, I believe you are right. I use references for passing parameters to Fortran functions all the time. In my experience, using references or pointers at the Fortran-C++ interface is equivalent. I have tried this using GCC/Gfortran, and Visual Studio/Intel Visual Fortran. It may be compiler dependent, but I think basically all compilers implement references by pointer passing.
2,936,844
2,936,850
C++: Create abstract class with abstract method and override the method in a subclass
How to create in C++ an abstract class with some abstract methods that I want to override in a subclass? How should the .h file look? Is there a .cpp, if so how should it look? In Java it would look like this: abstract class GameObject { public abstract void update(); public abstract void paint(Graphics g); } class Player extends GameObject { @Override public void update() { // ... } @Override public void paint(Graphics g) { // ... } } // In my game loop: List<GameObject> objects = new ArrayList<GameObject>(); for (int i = 0; i < objects.size(); i++) { objects.get(i).update(); } for (int i = 0; i < objects.size(); i++) { objects.get(i).paint(g); } Translating this code to C++ is enough for me. Edit: I created the code but when I try to iterate over the objects I get following error: Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’ GameObject.h:13: note: because the following virtual functions are pure within ‘GameObject’: GameObject.h:18: note: virtual void GameObject::Update() GameObject.h:19: note: virtual void GameObject::Render(SDL_Surface*) Game.cpp:17: error: cannot allocate an object of abstract type ‘GameObject’ GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions Game.cpp:17: error: cannot declare variable ‘go’ to be of abstract type ‘GameObject’ GameObject.h:13: note: since type ‘GameObject’ has pure virtual functions With this code: vector<GameObject> gameObjects; for (int i = 0; i < gameObjects.size(); i++) { GameObject go = (GameObject) gameObjects.at(i); go.Update(); }
In Java, all methods are virtual by default, unless you declare them final. In C++ it's the other way around: you need to explicitly declare your methods virtual. And to make them pure virtual, you need to "initialize" them to 0 :-) If you have a pure virtual method in your class, it automatically becomes abstract - there is no explicit keyword for it. In C++ you should (almost) always define the destructor for your base classes virtual, to avoid tricky resource leaks. So I added that to the example below: // GameObject.h class GameObject { public: virtual void update() = 0; virtual void paint(Graphics g) = 0; virtual ~GameObject() {} } // Player.h #include "GameObject.h" class Player: public GameObject { public: void update(); void paint(Graphics g); } // Player.cpp #include "Player.h" void Player::update() { // ... } void Player::paint(Graphics g) { // ... }
2,936,910
2,936,917
Static variable inside a constructor, are there any drawbacks or side effects?
What I want to do: run some prerequisite code whenever instance of the class is going to be used inside a program. This code will check for requiremts etc. and should be run only once. I found that this can be achieved using another object as static variable inside a constructor. Here's an example for a better picture: class Prerequisites { public: Prerequisites() { std::cout << "checking requirements of C, "; std::cout << "registering C in dictionary, etc." << std::endl; } }; class C { public: C() { static Prerequisites prerequisites; std::cout << "normal initialization of C object" << std::endl; } }; What bothers me is that I haven't seen similar use of static variables so far. Are there any drawbacks or side-effects or am I missing something? Or maybe there is a better solution? Any suggestions are welcome.
This isn't thread-safe, since if two threads try to construct C for the first time at the same time, Prerequisites will probably be initialized twice. If you're okay with that, you can probably do this, though gaming the scoped constructor system has zero discoverability (i.e. once you forget the 'trick' or others try to read your code, they'll be baffled as to what's going on).
2,936,993
2,937,030
What is the rationale for difference between -> and . in c/c++?
Possible Duplicates: C++: ptr->hello(); /* VERSUS */ (*ptr).hello(); Why does C have a distinction between -> and . ? I know the difference between the member operator (.) and the member by pointer operator (->). Why did the C designers create a different operator for this access? Why can't the compiler figure it out on its own? If you always used a . does any case exist where it is ambiguous whether you mean a member or a member by pointer? edit: I'm not looking for the "(*a).b" syntax. I asking why didn't the designers allow you to use "a.b" instead of "a->b"?
When you have a language that is, at its core, intended to be a "portable assembler" you don't try to hide implementation details from the user. Of course the compiler can figure out that in the expression a.b the a in question is a pointer. Can you? Reliably? All the time? In hairy, complicated code? And can you not envision a circumstance where not being able to quickly note that a is a pointer could be a problem? Stop thinking in terms of "hard to write" and start thinking in terms of "easy to read". (Yeah, I know. This goes against the whole C programmer mythos!) You'll be reading code a couple of orders of magnitude more often than you'll be writing it.
2,937,273
2,937,401
questions about name mangling in C++
I am trying to learn and understand name mangling in C++. Here are some questions: (1) From devx When a global function is overloaded, the generated mangled name for each overloaded version is unique. Name mangling is also applied to variables. Thus, a local variable and a global variable with the same user-given name still get distinct mangled names. Are there other examples that are using name mangling, besides overloading functions and same-name global and local variables ? (2) From Wiki The need arises where the language allows different entities to be named with the same identifier as long as they occupy a different namespace (where a namespace is typically defined by a module, class, or explicit namespace directive). I don't quite understand why name mangling is only applied to the cases when the identifiers belong to different namespaces, since overloading functions can be in the same namespace and same-name global and local variables can also be in the same space. How to understand this? Do variables with same name but in different scopes also use name mangling? (3) Does C have name mangling? If it does not, how can it deal with the case when some global and local variables have the same name? C does not have overloading functions, right? Thanks and regards!
C does not do name mangling, though it does pre-pend an underscore to function names, so the printf(3) is actually _printf in the libc object. In C++ the story is different. The history of it is that originally Stroustrup created "C with classes" or cfront, a compiler that would translate early C++ to C. Then rest of the tools - C compiler and linker would we used to produce object code. This implied that C++ names had to be translated to C names somehow. This is exactly what name mangling does. It provides a unique name for each class member and global/namespace function and variable, so namespace and class names (for resolution) and argument types (for overloading) are somehow included in the final linker names. This is very easy to see with tools like nm(1) - compile your C++ source and look at the generated symbols. The following is on OSX with GCC: namespace zoom { void boom( const std::string& s ) { throw std::runtime_error( s ); } } ~$ nm a.out | grep boom 0000000100001873 T __ZN4zoom4boomERKSs In both C and C++ local (automatic) variables produce no symbols, but live in registers or on stack. Edit: Local variables do not have names in resulting object file for mere reason that linker does not need to know about them. So no name, no mangling. Everything else (that linker has to look at) is name-mangled in C++.
2,937,331
2,937,424
win32 console - form example!
I'm trying to build a simple form in a c++ win32 console application. instead of using cin and keep prompting the user to enter the details, i would like to display the form labels then using the tab key, allow the user to tab through. What is the simplest way of doing this, without having to use ncurses? all I need is cout the below all at once: Name: Username: Email: set the cursor position next to name Field, then each time you hit tab, i gotoxy, and set the cursor at the next position, then set the the cin to the next variable eg. at startup gotoxy(nameX, nameY); cin >> name; Hit Tab/enter gotoxy(usernameX, usernameY); cin >> username; Hit Tab/enter gotoxy(emailX, emailY); cin >> email; is this even doable? I tried while loops with, GetAsyncKeyState, and keyboard events, but the cin is not working properly in that loop. is there any good example for a super simple form, or reference for doing that? I know how to SetConsoleCursorPosition, but how to implement the tabbing while still being able to capture cin? thanks
What is the simplest way of doing this, without having to use ncurses? Using ncurses (or an equivalent library) is the simple way to do this, by far. You seem to forget that tab is just another character when reading by lines (as in cin>>name;). To emulate ncurses, your program would need to handle multiple classes of key strokes (backspace, tab, arrows, characters, digits, even function keys, etc.), do whatever is appropriate, properly maintain the state of the screen, and the position of the cursor -- all to read three text fields from the user. Consider spending a few hours perusing the source code, even if you don't use it you might learn quite a lot (that's a serious suggestion, BTW).
2,937,351
2,937,447
How to use autoconf with C++0x features
What are the best practices for using autoconf in conjunction with shared_ptr and other TR1/BOOST C++0x templates so as to maximize portability and maintainability? With autoconf I can determine whether shared_ptr is available as std::tr1::shared_ptr and/or boost::shared_ptr. Given that the same feature has two different names, I have the following questions: In the code, how should shared_ptr be referenced? Should std::tr1::shared_ptr be preferred over boost::shared_ptr? For the first, the code is currently using preprocessor conditionals allowing non-qualified references to shared_ptr, a la #if HAVE_STD_TR1_SHARED_PTR using std::tr1::shared_ptr; #elif HAVE_BOOST_SHARED_PTR using boost::shared_ptr; #else #error "No definition for shared_ptr found" #endif Second, the code uses std::tr1:: over boost:: to minimize dependencies on external libraries (even if the the libraries are widely used). Are these two solutions common? Are there better ones?
One improvement to your example code, and an answer to your first question, is to use the "template typedef" idiom: #if HAVE_STD_TR1_SHARED_PTR template <class T> struct SharedPtr { typedef std::tr1::shared_ptr<T> Type; }; #elif HAVE_BOOST_SHARED_PTR template <class T> struct SharedPtr { typedef boost::shared_ptr<T> Type; }; #else # error "No definition for shared_ptr found" #endif // Declare a shared_ptr using our wrapper classes, saving us from having to care // where shared_ptr comes from: SharedPtr<int>::Type my_shared_int(new int(42)); The main problem with this is the need to use the ::Type notation. It is purely because C++ currently has no way to have a typedef for a template. You can have a typedef for a template type instance, but it's important here that we retain genericity. As for whether you should prefer TR1 to Boost, I'd say yes. Now that compilers are shipping with partial C++0x support, I'd say you should also test for std::shared_ptr and prefer that to either of the others. You might need a fourth typedef if there are compilers that have a shared_ptr that's somewhere else. I don't know of such a compiler, but some C++ code I maintain does something similar to what you're asking about with the common slist extension to the Standard C++ Library, for singly-linked lists. Old g++ versions put it at global namespace, modern g++ puts it in the compiler-specific __gnu_cxx namespace, and we even found one that erroneously put it in std!
2,937,425
2,937,522
boost::enable_if class template method
I got class with template methods that looks at this: struct undefined {}; template<typename T> struct is_undefined : mpl::false_ {}; template<> struct is_undefined<undefined> : mpl::true_ {}; template<class C> struct foo { template<class F, class V> typename boost::disable_if<is_undefined<C> >::type apply(const F &f, const V &variables) { } template<class F, class V> typename boost::enable_if<is_undefined<C> >::type apply(const F &f, const V &variables) { } }; apparently, both templates are instantiated, resulting in compile time error. is instantiation of template methods different from instantiation of free functions? I have fixed this differently, but I would like to know what is up. the only thing I can think of that might cause this behavior, enabling condition does not depend immediate template arguments, but rather class template arguments Thank you
Your C does not participate in deduction for apply. See this answer for a deeper explanation of why your code fails. You can resolve it like this: template<class C> struct foo { template<class F, class V> void apply(const F &f, const V &variables) { apply<F, V, C>(f, variables); } private: template<class F, class V, class C1> typename boost::disable_if<is_undefined<C1> >::type apply(const F &f, const V &variables) { } template<class F, class V, class C1> typename boost::enable_if<is_undefined<C1> >::type apply(const F &f, const V &variables) { } };
2,937,511
2,937,521
C++ struct containing unsigned char and int bug
Ok i have a struct in my C++ program that is like this: struct thestruct { unsigned char var1; unsigned char var2; unsigned char var3[2]; unsigned char var4; unsigned char var5[8]; int var6; unsigned char var7[4]; }; When i use this struct, 3 random bytes get added before the "var6", if i delete "var5" it's still before "var6" so i know it's always before the "var6". But if i remove the "var6" then the 3 extra bytes are gone. If i only use a struct with a int in it, there is no extra bytes. So there seem to be a conflict between the unsigned char and the int, how can i fix that?
The compiler is probably using its default alignment option, where members of size x are aligned on a memory boundary evenly divisible by x. Depending on your compiler, you can affect this behaviour using a #pragma directive, for example: #pragma pack(1) will turn off the default alignment in Visual C++: Specifies the value, in bytes, to be used for packing. The default value for n is 8. Valid values are 1, 2, 4, 8, and 16. The alignment of a member will be on a boundary that is either a multiple of n or a multiple of the size of the member, whichever is smaller. Note that for low-level CPU performance reasons, it is usually best to try to align your data members so that they fall on an aligned boundary. Some CPU architectures require alignment, while others (such as Intel x86) tolerate misalignment with a decrease in performance (sometimes quite significantly).
2,937,822
2,938,475
Is it possible to use Boehm garbage collector only for the part of the program?
I've read article in LinuxJournal about Boehm-Demers-Weiser garbage collector library. I'm interesting to use it in my library instead of my own reference counting implementation. I have only one question: is it possible to use gc only for my shared library and still use malloc/free in the main application? I'm not quite understand how gc checks the heap so I'm worrying about performance of gc in that case and possible side effects.
The example in the manual states: It is usually best not to mix garbage-collected allocation with the system malloc-free. If you do, you need to be careful not to store pointers to the garbage-collected heap in memory allocated with the system malloc. And more specifically for C++: In the case of C++, you need to be especially careful not to store pointers to the garbage-collected heap in areas that are not traced by the collector. The collector includes some alternate interfaces to make that easier. Looking at the source code in the manual you will see the garbage-collected memory is handled through specific calls, hence, the management is handled separately (either by the collector or manually). So as long your library handles its internals properly and doesn't expose collected memory, you should be fine. You don't know how other libraries manage their memory and you can use them as well, don't you? :)
2,937,971
2,937,977
How are open source projects in C/C++ carried out exactly without .sln/.project files?
Seems most open source projects in C/C++ only provide the source code,i.e. nginx Is this a convention that anyone interested in joining the developing team should figure out the .sln/.project files himself to qualify??
most open source projects are coming from the linux side of computing. thus, they are mainly using unix style build tools, as well as open source compilers. the main build tool is make, which uses a makefile to know how to build a project. on Windows, the main open source compiler is MinGW which is a win32 port of gcc. the use of those tools allows to keep a maximum of common things between unix and windows. note that .sln files are specific to microsoft compilers which are not free to use (and are rather costly), they are not portable and so are not suitable for multi-platform programming.
2,938,160
2,940,486
SWIG interface file questions
I am writing a C/C++ extension module for other languages and I am using SWIG to generate the bindings. I have two questions Can I include more than 1 header file in the declaration part of the interface file e.g.: /* Declarations exposed to wrapper: */ > %{ > #define SWIG_FILE_WITH_INIT > #include "a.h" > #include "b.h" > #include "c.h" %} In all of the examples I have seen so far, after the header include declaration (as shown above), the functions declared in the header are then declared again in the interface file. Is this really necessary, as it means there are two copies of the function declarations that need to be maintained. Note: I can appreciate that some functions/methods declaration may need to be 'decorated' with the 'newobject' declaration so these obviously need to be in the interface file, to avoid memory leaks - however, I would have though that it would be sufficient to include the headers and then ONLY the declarations of the functions/methods that need to be declared with 'newobject' - is this recommended way of doing things?
Yes ( see http://www.swig.org/Doc1.1/HTML/Library.html ) No ( see http://www.swig.org/tutorial.html ; look for SWIG for the truly lazy )
2,938,313
2,938,367
C++/Win32 : XP Visual Styles - no controls are showing up?
Okay, so i'm pretty new to C++ & the Windows API and i'm just writing a small application. I wanted my application to make use of visual styles in both XP, Vista and Windows 7 so I added this line to the top of my code: #pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"") It seemed to work perfectly on my Windows 7 machine and also Vista machine. But when I tried the application on XP the application wouldn't load any controls (e.g. buttons, labels etc.) - not even messageboxes would display. This image shows a small test application which i've just put together to demonstrate what i'm trying to explain: http://img704.imageshack.us/img704/2250/myapp.png In this test application i'm not using any particularly fancy or complicated code. I've effectively just taken the most basic sample code from the MSDN Library (http://msdn.microsoft.com/en-us/library/ff381409.aspx) and added a section to the WM_CREATE message to create a button: MyBtn = CreateWindow(L"Button", L"My Button", BS_PUSHBUTTON | WS_CHILD | WS_VISIBLE, 25, 25, 100, 30, hWnd, NULL, hInst, 0); But I just can't figure out what's going on and why its not working. Any ideas guys? Thank you in advanced. (By the way the application works in XP if i remove the manifest section from the top - obviously without visual styles though. I should also probably mention that the app was built using Visual C++ 2010 Express on a Windows 7 machine - if that makes a difference?)
Do you call InitCommonControlsEx? Details are here.
2,938,389
2,938,397
A cross between std::multimap and std::vector?
I'm looking for a STL container that works like std::multimap, but has constant access time to random n-th element. I need this because I have such structure in memory that is std::multimap for many reasons, but items stored in it have to be presented to the user in a listbox. Since amount of data is huge, I'm using list box with virtual items (i.e. list control polls for value at line X). As a workaround I'm currently using additional std::vector to store "indexes" into std::map, and I fill it like this: std::vector<MMap::data_type&> vec; for (MMap::iterator it = mmap.begin(); it != mmap.end(); ++it) vec.push_back((*it).second); But this is not very elegant solution. Is there some such containter?
What you need is: Boost Multi-Index
2,938,414
2,938,429
How to cast correctly a struct in C++
Consider a code excerpt below: typedef struct tagTHREADNAME_INFO { DWORD dwType; LPCTSTR szName; DWORD dwThreadID; DWORD dwFlags; } THREADNAME_INFO; const THREADNAME_INFO info = { 0x1000, threadName, CurrentId(), 0}; ::RaiseException(kVCThreadNameException, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR*)&info); How to cast correctly into ULONG_PTR* using C++ style cast? p.s. it's platform dependent code.
I guess it would be const_cast<ULONG_PTR*>(reinterpret_cast<const ULONG_PTR*>(&info)). From Effective C++, 3rd. Ed., Item 27: const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this. reinterpret_cast is intended for low-level casts that yield implementation-dependent (i.e., unportable) results, e.g., casting a pointer to an int. Such casts should be rare outside low-level code. And for the sake of completeness, the remaining two C++ casts are: dynamic_cast is primarily used to perform "safe downcasting," i.e., to determine whether an object is of a particular type in an inheritance hierarchy. It is the only cast that cannot be performed using the old-style syntax. It is also the only cast that may have a significant runtime cost. static_cast can be used to force implicit conversions (e.g., non-const object to const object (as in Item 3), int to double, etc.). It can also be used to perform the reverse of many such conversions (e.g., void* pointers to typed pointers, pointer-to-base to pointer-to-derived), though it cannot cast from const to non-const objects. (Only const_cast can do that.)
2,938,435
2,938,448
COM(C++) programming tutorials?
Are there any good sites for learning C++/COM from the ground up? I'm looking for something like a crash course with perhaps two weeks' worth of content. The course can assume knowledge in standard C/C++, or at least not a complete dummy.
Since you're asking for websites, you can try this introduction to COM on The Code Project, and how to handle COM in plain C and in C++ on the same site. And of course, you have MSDN.
2,938,467
2,938,472
Instantiating a class within a class
I'm trying to instantiate a class within a class, so that the outer class contains the inner class. This is my code: #include <iostream> #include <string> class Inner { private: std::string message; public: Inner(std::string m); void print() const; }; Inner::Inner(std::string m) { message = m; } void Inner::print() const { std::cout << message << std::endl; std::cout << message << std::endl; } class Outer { private: std::string message; Inner in; public: Outer(std::string m); void print() const; }; Outer::Outer(std::string m) { message = m; } void Outer::print() const { std::cout << message << std::endl; } int main() { Outer out("Hello world."); out.print(); return 0; } "Inner in", is my attempt at containing the inner within the outer, however, when I compile, i get an error that there is no matching function for call to Inner::Inner(). What have I done wrong? Thanks.
You need to use initialization lists to initialize class members: Inner::Inner(const std::string& m) : message(m) { } Outer::Outer(const std::string& m) : in(m) { } (Note that I passed the strings per const reference, which is better than passing them by value. See this answer for how to pass function arguments.) This way you can specify exactly which constructors should be called for class members. If you don't specify a constructor, the default one will be called implicitly. Assigning to the object later will then invoke the assignment operator and override whatever the default constructor initialized the object to. That's wasting performance at best. Since our Inner doesn't have a default constructor (declaring any constructor prevents the compiler from defining a default constructor by itself), it cannot be called, so you need to specify the constructor taking a string explicitly. Edit: Note that, if you have more than one class member, they are all initialized that way, separated by commas: Outer::Outer(const std::string& m) : in1(m), in2(m), in3() {} Note that the order of initialization of class members is determined by their declaration order within the class definition, not by the order they appear in the initialization list. It's best to not to rely on initialization order, since changing that in the class definition would then create a very subtle bug in the constructor's definition. If you can't avoid that, put a comment besides the class members declaration: class outer { public: outer(const inner& in) : in_(in), rin_(in_) // depends on proper declaration order of in_ and rin_ {} private: inner in_; // declaration order matters here!1 inner& rin_; // (see constructor for details) }; Base class constructors are specified the same way, and they are initialized before class members, also in order of declaration in the base class list. Virtual base classes, however, are initialized before all non-virtual base classes. Destructors, BTW, are always called in the reverse order of constructors. You can rely on that.
2,938,545
2,938,630
Why can operator-> be overloaded manually?
Wouldn't it make sense if p->m was just syntactic sugar for (*p).m? Essentially, every operator-> that I have ever written could have been implemented as follows: Foo::Foo* operator->() { return &**this; } Is there any case where I would want p->m to mean something else than (*p).m?
operator->() has the bizarre distinction of implicitly being invoked repeatedly while the return type allows it. The clearest way to show this is with code: struct X { int foo; }; struct Y { X x; X* operator->() { return &x; } }; struct Z { Y y; Y& operator->() { return y; } }; Z z; z->foo = 42; // Works! Calls both! I recall an occasion when this behaviour was necessary to enable an object to behave as a proxy for another object in a smart-pointer-like context, though I can't remember the details. What I do remember is that I could only get the behaviour to work as I intended using the a->b syntax, by using this strange special case; I could not find a way to get (*a).b to work similarly. Not sure that this answers your question; really I'm saying, "Good question, but it's even weirder than that!"
2,938,571
2,938,589
How to declare a function that accepts a lambda?
I read on the internet many tutorials that explained how to use lambdas with the standard library (such as std::find), and they all were very interesting, but I couldn't find any that explained how I can use a lambda for my own functions. For example: int main() { int test = 5; LambdaTest([&](int a) { test += a; }); return EXIT_SUCCESS; } How should I declare LambdaTest? What's the type of its first argument? And then, how can I call the anonymous function passing to it - for example - "10" as its argument?
Given that you probably also want to accept function pointers and function objects in addition to lambdas, you'll probably want to use templates to accept any argument with an operator(). This is what the std-functions like find do. It would look like this: template<typename Func> void LambdaTest(Func f) { f(10); } Note that this definition doesn't use any c++0x features, so it's completely backwards-compatible. It's only the call to the function using lambda expressions that's c++0x-specific.
2,938,592
2,938,696
C++ Primer Plus: 2D Arrays
I've just started working through C++ Primer Plus and I have hit a little stump. const int MONTHS = 12; const int YEARS = 3; int sales[YEARS][MONTHS] = {0}; const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for (int year = 0; year < YEARS; year++) { for (int month = 0; month < MONTHS; month++) { cout << "Please enter year " << year + 1 << " book sales for the month of " << months[month] << ": \t"; cin >> sales[year][month]; } } int yearlyTotal[YEARS][3] = {0}; int absoluteTotal = 0; cout << "Yearly sales:" << endl; for (int year = 0; year < YEARS; year++) { cout << "Year " << year + 1 << ":"; for (int month = 0; month < MONTHS; month++) { absoluteTotal = (yearlyTotal[year][year] += sales[year][month]); } cout << yearlyTotal[year][year] << endl; } cout << "The total number of books sold over a period of " << YEARS << " years is: " << absoluteTotal << endl; I wish to display the total of all three years. The rest of the code works fine: input is fine, individual yearly output is fine but I just can't get three years added together for one final total. Sample data would be entering 1 for every option, to give me three totals of 12: year 1: 12 year 2: 12 year 3: 12 The total number of books sold over a period of 3 years is: 12 The final 12 should obviously be 36. I did have the total working at one point but I didn't have the individual totals working. I messed with it and reversed the situation.
#include <iostream> #include <string> using namespace std; int main (void) { const int MONTHS = 12; const int YEARS = 3; int sales[YEARS][MONTHS] = {0}; const string months[MONTHS] = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for (int year = 0; year < YEARS; year++) { for (int month = 0; month < MONTHS; month++) { cout << "Please enter year " << year + 1 << " book sales for the month of " << months[month] << ": \t"; cin >> sales[year][month]; } } int yearlyTotal[YEARS] = {0}; int absoluteTotal = 0; cout << "Yearly sales:" << endl; for (int year = 0; year < YEARS; year++) { cout << "Year " << year + 1 << ":"; for (int month = 0; month < MONTHS; month++) { yearlyTotal[year] += sales[year][month]; } absoluteTotal += yearlyTotal[year]; cout << yearlyTotal[year] << endl; } cout << "The total number of books sold over a period of " << YEARS << " years is: " << absoluteTotal << endl; return 0; } You only need to increment the absoluteTotal outside of the per month count You only need a one dimensional array for the yearly count. When it comes to things like this it helps to write them out on paper first.
2,938,689
2,939,310
Azure and native code
It looks like you can host native code on Azure: http://msdn.microsoft.com/en-us/library/dd573362.aspx. Is it possible to run a socket server (listening tcp/udp) here? And even hosting a CLR on top?
It's easy to run a socket server on a worker role, but only tcp, not udp. You can start your own process from the worker role's OnStart() method You can do it from the Run() method too but once you hit the run state, your role is seen by the load balancer and outside world, so you might get tcp traffic before your socket server is running. You'll need to create a tcp endpoint in your worker role's configuration (right-click the worker role and view Properties): That port number you specify is for the outside world. The load balancer will give each of your role's instances a unique port that your code will bind to. For example, imagine your MyApp.exe that takes a --tcpport parameter on startup: var rootDirectory = Path.Combine(Environment.GetEnvironmentVariable("RoleRoot") + "\\", "approot\\MyApp"); int port = RoleEnvironment.CurrentRoleInstance.InstanceEndpoints["MyExternalEndpoint"].IPEndpoint.Port; var cmdline = String.Format("--tcpport {0}",port); MyProcess = new Process() { StartInfo = new ProcessStartInfo(Path.Combine(rootDirectory, "myapp.exe"), cmdline) { UseShellExecute = false, WorkingDirectory = rootDirectory } }; MyProcess.Start(); Then in your Run() method, simply wait forever, knowing you should never exit: MyProcess.WaitForExit(); throw new Exception("MyApp quit on me!");
2,938,744
2,938,910
can't increment Glib::ustring::iterator (getting "invalid lvalue in increment" compiler error)
in the following code: int utf8len(char* s, int len) { Glib::ustring::iterator p( string::iterator(s) ); Glib::ustring::iterator e ( string::iterator(s+len) ); int i=0; for (; p != e; p++) // ERROR HERE! i++; return i; } I get the compiler error on the for line, which is sometimes "invalid lvalue in increment", and sometimes "ISO C++ forbids incrementing a pointer of type etc... ". Yet, the follwing code: int utf8len(char* s) { Glib::ustring us(s); int i=0; for (Glib::ustring::iterator p = us.begin(); p != us.end(); p++) i++; return i; } compiles and works fine. according the Glib::ustring documentation and the include file, ustring iterator can be constructed from std::string iterator, and has operator++() defined. Weird? ---EDIT--- It gets "Curiouser and curiouser"! this code int utf8len(string::iterator s, string::iterator e) { Glib::ustring::iterator p(s); Glib::ustring::iterator end(e); int i=0; for (; p != end; p++) i++; return i; } compiles and works fine. ---EDIT--- BONUS QUESTION :) Is there a difference in C++ between the 2 ways of defining a variable: classname ob1( initval ); classname ob1 = initval; I believed that they are synonymous; yet, if I change Glib::ustring::iterator p( string::iterator(s) ); to Glib::ustring::iterator p = string::iterator(s); I get a compiler error (gcc 4.1.2) conversion from ‘__gnu_cxx::__normal_iterator, std::allocator > >’ to non-scalar type ‘Glib::ustring_Iterator<__gnu_cxx::__normal_iterator, std::allocator > > >’ requesed thanks a lot!
Your declaration declares this function: Glib::ustring::iterator p(string::iterator s); The parentheses in your code around s are ignored. They are like the parentheses around n in the following example int(n); n = 0; /* n is actually an int variable! */ They are for grouping modifiers like pointer (*) or references (&) (think about void(*fptr)()). In your case the parentheses are just semantically redundant. Try this one instead: Glib::ustring::iterator p( (string::iterator(s)) ); The parentheses introduced make the compiler regognize that it should instead construct an object p initialized from an expression (because a function parameter declaration can't have parentheses around it, it's not parsed as a parameter declaration, but instead as an initializer).
2,938,755
2,938,759
A public struct inside a class
I am new to C++, and let's say I have two classes: Creature and Human: /* creature.h */ class Creature { private: public: struct emotion { /* All emotions are percentages */ char joy; char trust; char fear; char surprise; char sadness; char disgust; char anger; char anticipation; char love; }; }; /* human.h */ class Human : Creature { }; And I have this in my main function in main.cpp: Human foo; My question is: how can I set foo's emotions? I tried this: foo->emotion.fear = 5; But GCC gives me this compile error: error: base operand of '->' has non-pointer type 'Human' This: foo.emotion.fear = 5; Gives: error: 'struct Creature::emotion' is inaccessible error: within this context error: invalid use of 'struct Creature::emotion' Can anyone help me? Thanks P.S. No I did not forget the #includes
There is no variable of the type emotion. If you add a emotion emo; in your class definition you will be able to access foo.emo.fear as you want to.
2,938,939
2,938,996
Generic transparent Qt widget that can catch clicks?
I've figured out how to use QPainter to draw rectangles. Now I want to have a drawing area where if the user clicks, a 1x1 rectangle is drawn where the mouse pointer is. To accomplish this, I assume I need a transparent Qt widget that supports the clicked() signal. How do I make such a transparent widget? Or is there something else I can use? Perhaps I can only use the window's clicked() signal?
You don't really need a transparent widget? All you have to do is implement protected: void mousePressEvent(QMouseEvent *event); for your widget and draw your rectangle. Take a look at scribble example that comes with Qt.