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
1,778,278
1,778,287
If you had the time and inclination to create a programming language, what characteristics would it have?
Just curious. If you had the time and inclination to create a programming language, what characteristics would it have? One language I would like to see would borrow as much from the syntax of Python as possible but compile to machine code that runs as fast as C or C++.
A mix of COBOL and XML, for the lulz <program> <data> <const> <name>myStr</name> <value><[CDATA[Hello, World!]]></value> </const> </data> <sub> <name>main</name> <params /> <return /> <code> <call> <name>writeline</name> <params> <var>myStr</var> </params> <giving /> </call> </code> </sub> <meta> <entrypoint>main</entrypoint> </meta> </program>
1,778,279
1,778,310
Q_Object with no type
The error I am receiving: g++ -c -g -I/usr/lib/qt-3.3/include TCPEchoServer.cpp Product.h:22: error: ISO C++ forbids declaration of âQ_Objectâ with no type Product.h:24: error: expected â;â before âvoidâ make: *** [TCPEchoServer.o] Error 1 I'm using QT 3.3. What am I missing...? T___T #include <string> #include <qtimer.h> #include "HandleTCPClient.h" #ifndef PRODUCT_H #define PRODUCT_H #include <qobject.h> #include <qgl.h> class Handler; //Define ourselves a product class class Product { Q_Object void startTimer(); public: Product(); string seller, itemName, description, highestBidder; double price, min, buyingPrice, currentBid; int time; bool isSold; Handler *handler; void setHandler(Handler *h); public slots: void setProductToSold(); }; #endif
You are missing the correct case for the macro, it should be Q_OBJECT.
1,778,487
1,779,076
Python subclass with C++ baseclass
I have some C++ I have exposed to Python through SWIG. In there is a base class with a single pure virtual function. In Python, I import my module and define a class that uses the abstract class as base. import mymodule class Foo(mymodule.mybase): ... In that module is also a manager class, I want to add my new defined class to the manager. m = mymodule.mymanager() m.add(Foo()) Definition of add: void add(mybase* b) { ... } Didn't work as I would expect: TypeError: in method 'mymanager_add', argument 2 of type 'mymodule::mybase *' What did I miss? It seems it's not sure that my Foo class is a "mybase". I tried adding a call to the base class constructor in Python but that didn't work, said the class was abstract. def __init__(self): mymodule.mybase.__init__(self)
My guess is that Foo is not derived from mybase in the eyes of the C++ environment. I'm not sure if SWIG can pull this off since it requires a bidirectional understanding of inheritance - Python class uses C++ class as base and C++ code recognizes the inheritance relationship. I would take a serious look into Boost.python since it seems to support the functionality that you are after. Here's an entry on wiki.python.org about it.
1,778,491
1,778,558
How does one return a local CComSafeArray to a LPSAFEARRAY output parameter?
I have a COM function that should return a SafeArray via a LPSAFEARRAY* out parameter. The function creates the SafeArray using ATL's CComSafeArray template class. My naive implementation uses CComSafeArray<T>::Detach() in order to move ownership from the local variable to the output parameter: void foo(LPSAFEARRAY* psa) { CComSafeArray<VARIANT> ret; ret.Add(CComVariant(42)); *psa = ret.Detach(); } int main() { CComSafeArray<VARIANT> sa; foo(sa.GetSafeArrayPtr()); std::cout << sa[0].lVal << std::endl; } The problem is that CComSafeArray::Detach() performs an Unlock operation so that when the new owner of the SafeArray (main's sa in this case) is destroyed the lock isn't zero and Destroy fails to unlock the SafeArray with E_UNEXPECTED (this leads to a memory leak since the SafeArray isn't deallocated). What is the correct way to transfer ownership between to CComSafeArrays through a COM method boundary? Edit: From the single answer so far it seems that the error is on the client side (main) and not from the server side (foo), but I find it hard to believe that CComSafeArray wasn't designed for this trivial use-case, there must be an elegant way to get a SafeArray out of a COM method into a CComSafeArray.
The problem is that you set the receiving CComSafeArray's internal pointer directly. Use the Attach() method to attach an existing SAFEARRAY to a CComSafeArray: LPSAFEARRAY ar; foo(&ar); CComSafeArray<VARIANT> sa; sa.Attach(ar);
1,778,503
1,779,361
VC++ 'Generating Code', what does it mean?
WHen compiling in visual studio the compiler outputs this at what seems to be its own discretion: 1>Generating Code... what is it doing here exactly?
It is doing what it says: it is generating the machine code. Many compilers translate C/C++ sources into some intermediate internal representation that is later used as the source to generate the actual machine code. Visual C++ compiler (as many other compilers) does this in batches: first it translates a bunch of source files into that intermediate representation and then converts them all to machine code (and then starts working on the next batch). This is what happens when you see the "Generating code" messages. I don't know what logic exactly it is using to split the source files into batches. Maybe it works simply by size: once the total size of all intermediate representations generated so far gets to some limit, it switches to "generating code" mode. Maybe there's some other logic at work there as well. In any case note that the unqualified term "code" in this case does not refer to source code, meaning that it has nothing to do with templates and/or preprocessor or anything like that. Moreover, referring to C sources with unqualified "code" (as opposed to the qualified "source code") is a very niche thing, more at home with marketing department than with actual programmers. At the programmers' level nobody refers to C sources as just "code" :)
1,778,619
1,778,624
encoding conversion from JIS X 208 to UNICODE
How can I convert a JIS X 208 encoded string into UNICODE in C++? A VC++ specific answer would be helpful. The bigger problem that I am finding difficulty in understanding is that there are too many encodings for Japanese characters. JIS itself has many versions, then there is Shift-JIS. It would be great if some one could point towards a good explanation of these in English. I looked through code page identifiers in MSDN. This does list Japanese (JIS 0208-1990 and 0121-1990) but I am wondering whats the difference between JIS 0208 and JIS X 0208.
The ICU project contains many functions for converting from and to Unicode. It'll work on most OS's, including Windows. It'll handle conversions to/from pretty much all the codepages out there. From what I can see, JIS X 0208 and JIS 0208 appear to be 2 variations in the name for the same thing, i.e. the actual codepage is the same. Here's the wikipedia article on JIS 0208, hopefully it'll answer some of your questions as it goes into more depth into the history of JIS and it's different versions
1,779,149
1,779,188
Will there be any performance issue using C++ inside C#?
I have a C++ program which does text processing on 40k records. We developed this program in C++ because we thought it would be faster. Then I used/executed this C++ part inside my C# program using the process-execute but the problem is we feel like we lost control of the execution flow: not able to debug the C++ part. I want to integrate the C++ much more in my C# program. I googled and found that I have to generate a DLL for my C++ and then i can use it inside my C# program. Question: Will this slow down the execution of the C++ part? Is there any other better alternative to integrate the C++ part inside my c# program?
You have a few options here: Write the processing in .NET and measure the performance. If it is unacceptable try to optimize it. If it is still too slow you revert to unmanaged code. But thinking that unmanaged code will be faster and for this reason writing unmanaged code without measuring IMHO is wrong approach. As you already wrote unmanaged code you can expose it as a dynamic link library by exporting a function that will do the processing: extern "C" __declspec(dllexport) int DoProcessing(int); Next you import the function in managed code: class Program { [DllImport("mylibrary.dll")] static extern int DoProcessing(int input); static void Main() { int result = DoProcessing(123); } } This works if the input and output of your processing is not very complex and can be easily marshaled. It will have very little overhead. Compile the unmanaged code using C++ CLI as managed assembly and reference it directly.
1,779,313
1,779,320
Returning a pointer vs. passing a reference to an object to store the answer in C++
I have general question regarding the use of pointers vs. references in this particular scenario. Let's say that I have a function that is going to do some computation and store the value inside an object for later use by the caller. I can implement this by using either pointers or references. Although, I would prefer using references because I trying avoiding pointers as much as possible, are there any pros/cons of one approach over the other. The code using Pointers would be as follows: Node*& computeNode() { // Do some computation before creating a node object. Node* newNode = new Node; newNode->member1 = xyz; newNode->member2 = abc; // and so on ... return newNode; } The code using references could do something like this: void computeNode(Node& newNode) { // Do some computation before assigning values to the node object. newNode.member1 = xyz; newNode.member2 = abc; // and so on. } The differences that I can see are as follows: When using the pointer method, the newNode object is allocated on the Heap. So, unless I call delete on it, it is not going to get deleted. However, in the reference method, whether newNode is allocated on the Heap/Stack depends on what the caller did to create the newNode object. Whenever we use references, the number of arguments needed to pass to the function increases by at least 1. This is fine, only I find it a bit counter-intuitive to pass the return object also to a function call unless I name the function in such a way that it becomes obvious to the API user. By using references, I can simulate the return of multiple objects. In the pointer method, I think I will have to wrap all the objects in another structure (like a pair class) and then return it. That increases the overhead. However, I do not know if usually one is preferred over the other. And if there are any function naming conventions in C++ that let the developer know that he is supposed to pass the return object also as an argument.
The second approach is probably preferable because there is no possibility of a memory leak, in the event you forget to delete the returned pointer. It's usually good practice to code in such a way that each function or object which allocates heap memory also deallocates that memory. Your first example violates that practice, making it the function caller's responsibility to deallocate the memory. This makes memory leaks more likely, because now every time the function is called there is another opportunity to forget to delete the returned pointer. You may also want to consider returning the object by value (which will return a copy of the object) in cases where the size of the object is not that large. Even though this will require a copy to be created, if the object is not so large it won't impact performance. (This method will become a lot more attractive in the future with C++0x move semantics.)
1,779,362
1,779,411
How could I apply a genetic algorithm to a simple game that follows rollercoaster tracks?
I have free-rein over what I do on a final assignment for school, with respect to modifying a simple direct-x game that currently just has the camera follow some rollercoaster rails. I've developed an interest in genetic algorithms and would like to take this opportunity to apply one and learn something about them. However, I can't think of any way I could possibly apply one in this case. What are some options available to me?
From your query, it seems like that you want to use Genetic Algorithms to get optimized roller coaster rail tracks. For any optimization problem: you will first need to break down your desired solution into its components or design variables. Once you have the "variables" you need to look at formulating a objective function with them. Usually you would code it in such a way that your desired solution minimizes it. Then you need to decide on a coding scheme to use in your Genetic Algorithm. Real Coded Genetic Algorithm is more useful in cases where you have a continuous search space. These are the first things. Once you have them, you need to decide on a Crossover and Mutation strategy. Then finally you have to decide, whether you want to use a existing GA code in your problem, use some library or code it yourself. A more descriptive question will help me to add more to this. What language are you looking to work in? EDIT: I haven't used it myself, PARDISEO is a C++ template based library for among many other things, Genetic Algorithms, as well. Also, you can take a look at the C version of a Real Coded GA at http://www.iitk.ac.in/kangal/codes.shtml From your(OP) comment: Literally, all it does is load an xml file with some track coordinates, build the rails, and have teh camera follow these tracks like you were on a rollercoaster. All that in about 100 thousand lines of code I think you would like to look at the track coordinates as possible design variables and see what combination of them give you a optimized (in terms of cost, better view, comfort, etc..) and then see what mathematical relation you can obtain among the best set. Then you are all set to apply GA to it. :)
1,779,438
1,779,472
Error with `QObject` subclass and copy constructor: `QObject::QObject(const QObject&) is private`
The following compile errors is what I have: /usr/lib/qt-3.3/include/qobject.h: In copy constructor Product::Product(const Product&): /usr/lib/qt-3.3/include/qobject.h:211: error: QObject::QObject(const QObject&) is private Product.h:20: error: within this context HandleTCPClient.cpp: In member function int Handler::HandleTCPClient(int, std::string, std::string): HandleTCPClient.cpp:574: note: synthesized method Product::Product(const Product&) first required here HandleTCPClient.cpp:574: error: initializing argument 1 of std::string productDetails(Product) /usr/lib/qt-3.3/include/qobject.h: In member function Product& Product::operator=(const Product&): Product.h:20: instantiated from void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>] /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/stl_vector.h:610: instantiated from âvoid std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>]â HandleTCPClient.cpp:173: instantiated from here /usr/lib/qt-3.3/include/qobject.h:212: error: QObject& QObject::operator=(const QObject&) is private Product.h:20: error: within this context /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc: In member function void std::vector<_Tp, _Alloc>::_M_insert_aux(__gnu_cxx::__normal_iterator<typename std::_Vector_base<_Tp, _Alloc>::_Tp_alloc_type::pointer, std::vector<_Tp, _Alloc> >, const _Tp&) [with _Tp = Product, _Alloc = std::allocator<Product>]: /usr/lib/gcc/i386-redhat-linux/4.1.2/../../../../include/c++/4.1.2/bits/vector.tcc:260: note: synthesized method âProduct& Product::operator=(const Product&) first required here make: *** [HandleTCPClient.o] Error 1 Part of my HandleTCPClient.cpp Line 574: Product tempProduct;// temporary Product storage variable tempProduct.setHandler(this); ... else if (output[1] == '5') // description { output.erase(0,2); // erase the sequence numbers tempProduct.description = output; LINE 574 output = productDetails(tempProduct); // obtain client given information about selling product } Product.h:: #include <string> #include <qtimer.h> #include "HandleTCPClient.h" #ifndef PRODUCT_H #define PRODUCT_H #include <qobject.h> #include <qgl.h> class Handler; //Define ourselves a product class class Product : public QObject { Q_OBJECT void startTimer(); public: Product(); string seller, itemName, description, highestBidder; double price, min, buyingPrice, currentBid; int time; bool isSold; Handler *handler; void setHandler(Handler *h); public slots: void setProductToSold(); }; #endif Product.cpp:: #include <string> using std::string; #include "Product.h" Product::Product() { seller = ""; itemName = ""; price = 0.00; min = 0.00; buyingPrice = 0.00; time = 0; description = ""; highestBidder = "None"; currentBid = 0.00; } void Product::setHandler(Handler *h) { handler = h; } Thanks for all the help =)
Product is a subclass of QObject, which cannot be copied. Your code is attempting to copy it somewhere (perhaps in productDetails(tempProduct)) and this causes the error. Perhaps you could pass it to your function by const reference instead; or perhaps some redesign of your program is needed. Your compiler is telling you that the copy constructor of QObject is private, so it cannot be called by any function that is not a method of the base class. Qt has designed it to work that way. One reason that Qt disables copying of QObjects is that it manages the memory of the children of a QObject. When a QObject gets deleted, so do all of its children. This would be impractical to do properly if the QObject was copyable.
1,779,494
1,779,558
Dynamic Allocation of an Array of Pointers to Objects
This question is in C++. I am trying to dynamically allocate an array of pointers to objects. I know I can use a vector container but the point of the exercise is not to... Here is the code: void HealthClub::AddHealthClubDevice ( char* HealthClubDeviceName ) { //We added NumberOfDevices as an attribute, so we won't have to use sizeof all the time if (NumberOfDevices==0) // This is for the first device we want to add { HealthClubDevices = new Device*[1]; HealthClubDevices[0]= new Device(HealthClubDeviceName); NumberOfDevices++; } else // Here we did realloc manually... { Device** tempHealthClubDevices; tempHealthClubDevices = new Device*[++NumberOfDevices]; //this is where we see the first sign of a problem, The tempHealthClubDevices is not allocated properly for (int i=0 ; i<(NumberOfDevices-1) ; i++) tempHealthClubDevices[i]=HealthClubDevices[i]; delete[] HealthClubDevices; HealthClubDevices = tempHealthClubDevices; HealthClubDevices[NumberOfDevices-1]= new Device(HealthClubDeviceName); } } The Device** objects are not allocated properly, they never grow in size, they are always one element. Does anyone know why? Thanks!
Can't reproduce your problem. Specifically, here's all of the skeleton code I compiled and ran successfully -- your method plus the minimal scaffolding to make it into a complete program: #include <iostream> struct Device { char* name; Device(char* n) {name = n;} }; struct HealthClub { int NumberOfDevices; Device** HealthClubDevices; HealthClub() { NumberOfDevices = 0;} void AddHealthClubDevice(char *); }; std::ostream& operator<<(std::ostream& o, const HealthClub& h) { o << h.NumberOfDevices << " devices:" << std::endl; for(int i=0; i<h.NumberOfDevices; ++i) { o << " " << h.HealthClubDevices[i]->name << std::endl; } o << "That's all!\n" << std::endl; return o; } void HealthClub::AddHealthClubDevice ( char* HealthClubDeviceName ) { //We added NumberOfDevices as an attribute, so we won't have to use sizeof all the time if (NumberOfDevices==0) // This is for the first device we want to add { HealthClubDevices = new Device*[1]; HealthClubDevices[0]= new Device(HealthClubDeviceName); NumberOfDevices++; } else // Here we did realloc manually... { Device** tempHealthClubDevices; tempHealthClubDevices = new Device*[++NumberOfDevices]; //this is where we see the first sign of a problem, The tempHealthClubDevices is not allocated properly for (int i=0 ; i<(NumberOfDevices-1) ; i++) tempHealthClubDevices[i]=HealthClubDevices[i]; delete[] HealthClubDevices; HealthClubDevices = tempHealthClubDevices; HealthClubDevices[NumberOfDevices-1]= new Device(HealthClubDeviceName); } } int main() { HealthClub h; std::cout << h; h.AddHealthClubDevice("first"); std::cout << h; h.AddHealthClubDevice("second"); std::cout << h; h.AddHealthClubDevice("third"); std::cout << h; return 0; } Compiles fine, even with --pedantic, and when run emits: $ ./a.out 0 devices: That's all! 1 devices: first That's all! 2 devices: first second That's all! 3 devices: first second third That's all! as desired. So, your problem's cause must lie elsewhere. Given your real program which fails (you don't show us exactly how) and this minimal one which succeeds, you can "interpolate by bisection" to build the minimal failing case -- if that still doesn't show you where the problem lies, posting the minimal failing case and the one epsilon smaller than it which still succeeds as a SO question can surely get you the help you need (be sure to also specify compiler, OS, and so on).
1,779,522
1,779,582
Unable to correct error in C++ code
I am unable to detect the error in the following C++ program. The code defines a Graph class. #include <vector> #include <list> using namespace std; class Neighbor { public: int node_id; float edge_cost; float price; Neighbor(int&,float&,float&); }; Neighbor::Neighbor(int& node_id, float& edge_cost,float& price) { this->node_id = node_id; this->edge_cost = edge_cost; this->price = price; } template <class NS> class Graph { private: vector<list<NS> > adjacency_list; vector<list<NS> >::iterator node_iterator; public: void add(int node_id, Neighbor& neighbor); void remove(int node_id, Neighbor& neighbor); Graph(); }; template <class NS> Graph<NS>::Graph() { node_iterator = adjacency_list.begin(); } template <class NS> void Graph<NS>::add(int node_id, Neighbor& neighbor) { if(adjacency_list.size()<node_id){ while(adjacency_list.size()<node_id) adjacency_list.pushback(list<NS>()); } adjacency_list[node_id].push_back(neighbor); } template <class NS> void Graph<NS>::remove(int node_id,Neighbor& neighbor) { if(adjacency_list.size()<node_id) return; adjacency_list[node_id].remove(neighbor); } When I compile it, I get the following error: max_flow.cpp:21: error: type ‘std::vector >, std::allocator > > >’ is not derived from type ‘Graph’ max_flow.cpp:21: error: expected ‘;’ before ‘node_iterator’ max_flow.cpp: In constructor ‘Graph::Graph()’: max_flow.cpp:31: error: ‘node_iterator’ was not declared in this scope vector::iterator works. But why doesn't vector >::iterator ? Thanks!
Try to replace the line of code from vector<list<NS> >::iterator node_iterator; to typename vector<list<NS> >::iterator node_iterator; You also need to implement copy-constructor for Neighbor class if you are going to use it as template argument for Graph. This is because you define Neighbor constructor manually and this disables compiler generated copy constructor. Also you need to define Neighbor::operator== because you use vector::remove method in graph, which requires operator== of its item class. Actually to check all compilation errors you can use explicit instantiation for the templates: template class Graph<Neighbor>; And one more smaaaaaaall error is the following line adjacency_list.pushback(list<NS>()); should be replaced by adjacency_list.push_back(list<NS>());
1,779,545
1,779,586
Stack allocation limit for programs on a Linux 32 bit machine
In C++ how much can the stack segment grow before the compiler gives up and says that it cannot allocate more memory for stack. Using gcc on a linux (fedora) 32 bit machine.
Under UNIX, if you are running bash run $ ulimit -a it will list various limits including stack size. Mine is 8192kb. You can use ulimit to change the limits. Also, you can use ulimit() function to set various limits from within your program. $ man 3 ulimit Under Windows see StackReserveSize and StackCommitSize In practice stack addresses begin at high addresses (on a 32-bit platform, close to the 3GB limit) and decrease while memory allocation begins at low addresses. This allows the stack and memory to grow until whole memory is exhausted.
1,779,608
1,779,626
integer automatically converting to double but not float
I have a function like below: void add(int&,float&,float&); and when I call: add(1,30,30) it does not compile. add(1,30.0,30.0) also does not compile. It seems that in both cases, it gets implicitly converted to double instead of float. So, do you suggest that it is better to re-define add as add(int&,double&,double&)? Is there any other way of passing making add(1,30,30) work other than casting 30 with float or assigning like "float x = 30 ; add(1,x,x)" ? I used to think that the compiler will be able to detect that float is a super-set of integer and so would compile it successfully. Apparently, that is not the case. Thanks!
Your function takes its parameters by reference, not by value, and you can't pass constant integer/floating-point values by non-const reference. You should either change your function to take its parameters by value, or pass actual variables instead of constants, e.g.: int x = 1; float y = 30, z = 30; add(x, y, z); You can implicitly cast an int to a float or double, but you cannot implicitly cast an int& to a float&.
1,779,670
1,779,717
Show colored compilation errors in C++ on Terminal
Is there any way to show compilation errors in colors on the terminal? I mean when we do "g++ filename.cpp", is there a way to show the compiler messages in colors? By default it is always in Black color. But if we have a lot of error messages, then it helps to have them in different colors (just like the code is highlighted in different colors). Thanks!
http://schlueters.de/colorgcc.html http://colorifer.sourceforge.net/
1,779,685
1,779,788
What is ->* operator in C++?
C++ continues to surprise me. Today i found out about the ->* operator. It is overloadable but i have no idea how to invoke it. I manage to overload it in my class but i have no clue how to call it. struct B { int a; }; struct A { typedef int (A::*a_func)(void); B *p; int a,b,c; A() { a=0; } A(int bb) { b=b; c=b; } int operator + (int a) { return 2; } int operator ->* (a_func a) { return 99; } int operator ->* (int a) { return 94; } int operator * (int a) { return 2; } B* operator -> () { return p; } int ff() { return 4; } }; void main() { A a; A*p = &a; a + 2; } edit: Thanks to the answer. To call the overloaded function i write void main() { A a; A*p = &a; a + 2; a->a; A::a_func f = &A::ff; (&a->*f)(); (a->*f); //this }
The overloaded ->* operator is a binary operator (while .* is not overloadable). It is interpreted as an ordinary binary operator, so in you original case in order to call that operator you have to do something like A a; B* p = a->*2; // calls A::operator->*(int) What you read in the Piotr's answer applies to the built-in operators, not to your overloaded one. What you call in your added example is also the built-in operator, not your overloaded one. In order to call the overloaded operator you have to do what I do in my example above.
1,779,722
1,779,754
(c)make - resursive compile
Let's assume I have directories like: dir1 main.cpp dir2 abc.cpp dir3 def.cpp dir4 ghi.cpp jkl.cpp And let's assume that main.cpp includes dir2/abc.cpp and dir3/def.cpp, def.cpp includes dir4/ghi.cpp and dir4/jkl.cpp. My question is, how can I have one Makefile/CMakeLists.txt in dir1/ which goes in each directory recursively and compiles *.cpp, and then "joins" them? Sorry for my english, hope that I explained my question well! Thanks!
For makefile, dir1/Makefile should: declare that main.o dependends on dir2/abc.o and dir3/def.o declare how to create dir2/abc.o and dir3/def.o As for cmake it detects such dependencies "automatically" (binary depended on dir2/abc.o and dir3/def.o), so virually you don't need care about it.
1,779,812
1,779,821
Strange "type class::method() : stuff " syntax C++
While reading some stuff on the pImpl idiom I found something like this: MyClass::MyClass() : pimpl_( new MyClassImp() ) First: What does it mean? Second: What is the syntax? Sorry for being such a noob.
This defines the constructor for MyClass. The syntax is that of a constructor definition with an initialization list (I assume there is a set of braces following this that define the body of the constructor). The member pimpl_ of MyClass is being initialized as a pointer to a new object of type MyClassImp. It's almost the same as the following: MyClass::MyClass() { pimpl_ = new MyClassImp(); } However, it is preferable to use the initialization list for initializing class members wherever possible; see the C++ FAQ Lite entry linked above.
1,779,974
1,780,040
C++ Templates vs. Aggregation
Consider the following piece of code: class B { private: // some data members public: friend bool operator==(const B&,const B&); friend ostream& operator<<(ostream&,const B&); // some other methods }; template <typename T=B> class A { private: // some data members vector<vector<T> > vvlist; public: // some other methods }; My requirement is that the type T that is passed as type parameter must provide definitions for the operator== and the operator<< methods. I do not want to enforce any other restrictions on T. How can I do this? One way that I can think of is to Create an Abstract class say "Z" that declares these two methods. and then write vector<vector<Z> > vvlist; and NOT have class A as a template. Is there a better way to do this?
It happens automatically. If your code calls the operators == and <<, then the code simply won't compile if the class is passed a type that doesn't define these operators. It is essentially duck-typing. If it looks like a duck, and quacks like a duck, then it is a duck. It doesn't matter whether it implements an IDuck interface, as long as it exposes the functionality you try to use.
1,780,024
1,787,312
Visual C++ Team Test problems
I am trying to get some unit tests for native C++ running with Visual Studio Test Suite. I have just a single, simple class named "Shape". I followed a tutorial and did the following steps: Created a "ref class" wrapper called "MShape" for the native class I want to test Changed configuration type to .dll Changed CLR support to /CLR Set Linker "Profile" to /PROFILE Recompiled successfully Added a Visual C++ Test Project Added a new unit test using the Unit Test Wizard In the wizard, selected the methods I want to test Now I have the following problems: Visual Studio reports that most unit test generation failed because "Failed to compare two elements in the array" The C++ compiler crashes when I attempt to compile the test project. This line is the culprit: MShape_Accessor^ shape = gcnew MShape_Accessor(); If I right-click and select Go to definition, VS says the symbol is undefined. Here is the full code for MShapeTest.cpp (generated by Visual Studio): #include "StdAfx.h" #include "StdAfx.h" using namespace Microsoft::VisualStudio::TestTools::UnitTesting; namespace TestProject1 { using namespace System; ref class MShapeTest; /// <summary> ///This is a test class for MShapeTest and is intended ///to contain all MShapeTest Unit Tests ///</summary> [TestClass] public ref class MShapeTest { private: Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public: property Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ TestContext { Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ get() { return testContextInstance; } System::Void set(Microsoft::VisualStudio::TestTools::UnitTesting::TestContext^ value) { testContextInstance = value; } } #pragma region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //public: [ClassInitialize] //static System::Void MyClassInitialize(TestContext^ testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //public: [ClassCleanup] //static System::Void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //public: [TestInitialize] //System::Void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //public: [TestCleanup] //System::Void MyTestCleanup() //{ //} // #pragma endregion public: [TestMethod] [DeploymentItem(L"TP4.dll")] void MShapeConstructorTest() { MShape_Accessor^ shape = gcnew MShape_Accessor(); } }; } namespace TestProject1 { } The same exact problems happen on every install of VSTS I tried.
I've just set up a simple test test using MS VS Test and I could get it to run. Here is the project: http://www.somethingorothersoft.com/TestTest.zip I guess whatever problem you having is to do with the definition of MShape. Alternatively, you could just test your unmanaged code directly inside tests. You will need to change the test project's CLR Support from /CLR:Safe to /CLR and then just run straight C++ in your tests. I tried to include that capability in the demo but I couldn't get both kinds to run in the same project - i.e. both using a managed wrapper and one without from the same target project. If you make undertest project a static library and remote CLR support, you will be able to run unamanged code from it in your test project.
1,780,105
1,781,411
QTimer & Select use. Need to get auction time working
Currently I am having issues with QTimer. I am trying to make each "Product" have a timer and so it will let my "Handler" know that the auction time of the product has ended. The problem that I am having is that from my test, it doesn't seem to print "Timer started". This is part of my socket programming project. I use select because I haven't learned multithreading yet. So if anyone can give me tips. My HandleTCPClient is called from my server when a client sends a message. Thanks in advance. Product.cpp #include <string> using std::string; #include <iostream> using std::cout; #include "Product.h" Product::Product() { seller = ""; itemName = ""; price = 0.00; min = 0.00; buyingPrice = 0.00; time = 0; description = ""; highestBidder = "None"; currentBid = 0.00; timer = new QTimer( this ); connect( timer, SIGNAL(timeout()), this, SLOT(setProductToSold()) ); } void Product::startTimer() { cout << " Timer Started " << endl; <<< When called this isn't printed timer->start( 2000, TRUE ); // 2 seconds single-shot timer } void Product::setHandler(Handler *h) { handler = h; } void Product::setProductToSold() { cout << " Item auction over" << endl; } From my HandleTCPClient: ... vector <Account> account; vector <Product *> product; ... product = checkUser(product,&tempProduct,clntSocket); // check to see if the user is logged in, else can't sell product output = checkUserSell(clntSocket); // generate a string to see if user is logged in or not tempProduct.startTimer(); // Start the Timer!!! Where : // Push product onto products list vector <Product *> checkUser(vector <Product *> products, Product * temp, int clntSocket) // generate a new product: check to see if user is logged in or not (2) sell product { for (int i=0; i<account.size(); i++) { if (account[i].socket == clntSocket) // user is logged in! { temp->seller = account[i].name; products.push_back(temp); break; } } return products; } and ... string checkUserSell(int clntSocket) // generate a string: check to see if user is logged in or not (2) sell product { string output = "2\n<You must first log in if you would like to sell your products>\n<<<TRANSACTION CANCELLED>>>\n"; for (int i=0; i<account.size(); i++) { if (account[i].socket == clntSocket) // user is logged in! { output = "1\n<Your product has been put up for Auction>\n"; break; } } return output; } ========================================================================================
Keep in mind that Qt's event loop is single threaded: If you are blocking in select() inside the main thread, then Qt's event loop can't run until select() returns, and so any pending QTimer timeout events won't be executed. Possible solutions: instead of blocking in select(), use Qt's QSocket class (etc) to implement your networking (so that network event multiplexing is integrated into the Qt event loop) ... or run your select()-based event loop in a separate thread from the Qt event loop thread. The first solution is simpler.
1,780,186
1,780,197
include file error in C++
Problem fixed! Thanks a lot for the constructive suggestions! I am unable to figure out what is the mistake in the following code. Is there something wrong with the way I am doing includes? // This is utils.h #ifndef UTILS_H #define UTILS_H #include <iostream> #include <fstream> #include <stack> #include <queue> #include <vector> #include <list> #include <string> #include <algorithm> typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vii> vvii; typedef stack<int> si; typedef queue<int> qi; #define tr(c,i) for(typeof((c).begin()) i = (c).begin() ; i!=(c).end() ; ++i ) #define all(c) (c).begin(),(c).end() #define cpresent(c,x) (find(all(c),x) != (c).end()) #endif // ============================================================== // Below is main.cpp #include "utils.h" int main() { vi v; } On compiling "g++ main.cpp" I get the following error message: utils.h:13: error: expected initializer before ‘<’ token utils.h:14: error: expected initializer before ‘<’ token utils.h:15: error: expected initializer before ‘<’ token utils.h:16: error: expected initializer before ‘<’ token utils.h:17: error: expected initializer before ‘<’ token utils.h:18: error: expected initializer before ‘<’ token main1.cpp: In function ‘int main()’: main1.cpp:4: error: ‘vi’ was not declared in this scope main1.cpp:4: error: expected `;' before ‘v’ What is wrong with this code? The utils.h used to work fine some time back when I did not have the #ifndefs in it.
Those types (pair, stack, queue, vector, etc.) are in the std namespace. You either need to add using namespace std; at the top of your file (generally after all of the standard library includes) or fully qualify the type names by adding std:: in front of them. Generally, it's better practice to fully qualify the type names than to use using namespace to avoid potential collisions between names and to make your code cleaner. You should never use using namespace std in header files. (Along the lines of clean code, you should consider using better, longer names for your types; ii, vii, and vvii are atrocious type names).
1,780,256
1,780,696
Boost::Random and Enumerated Types
Right now I'm generating a random enumerator using boost's random library. Basically I'm using an implicit conversion to specify the random generator's distribution, getting a random number, and then casting that back to the enumerated type. Ex: (minColor and maxColor are parameters of the enumerated type) boost::mt19937 randGen(std::time(0)); boost::uniform_int<> dist(minColor, maxColor); boost::variate_generator< boost::mt19937&, boost::uniform_int<> > GetRand(randGen, dist); return static_cast<Common::Color> (GetRand()); I'm curious whether boost's library supports anything like creating a distribution for an enumerated type, and thus returns a randomly selected enumerator. Something like... boost::uniform<Common::Color> dist(minColor, maxColor);
Although it would make sense with C++0xs strongly typed enums, what you wan't isn't in general possible. Enumeration terminology distinguishes the enumeration type and its underlying type which holds the enumeration values. The standard mainly requires the underlying type to be big enough to hold all values, to not be larger as int if possible and that the size return by sizeof(someEnum) equals the size of its underlying type (§7.2.5 C++03). Given only that and without restricting the style of how enums are used/declared, we know the size of the enumerations but not their signedness, which makes e.g. defining type-safe constructors taking min and max arguments impossible. Sidenote: I'd also personally find a distribution which is templated with an enumeration type somewhat misleading. Is the distribution only defined for the enumeration values that are in the range? Or is it defined for all values in the underlying type that are in the range?
1,780,351
1,780,586
Linking error in C++
Problem fixed. Thanks a lot! I am having the following error in the code shown below: Error is as follows: $ g++ main.cpp Neighbor.cpp Graph.cpp /tmp/ccclDcUN.o: In function main': main.cpp:(.text+0xc1): undefined reference toGraph::add(int, Neighbor&)' main.cpp:(.text+0xd3): undefined reference to `Graph::add(int, Neighbor&)' collect2: ld returned 1 exit status what could be going wrong? // FILENAME: Graph.cpp #include "Neighbor.h" #include "Graph.h" template <typename NS> void Graph<NS>::add(int id,NS& n){ if(id>=adj_list.size()) while(adj_list.size()<id+1) adj_list.push_back(list<NS>()); adj_list[id].push_back(n); } template <typename NS> void Graph<NS>::remove(int id,NS& n){ if(id<adj_list.size()){ adj_list[id].remove(n); } } // FILENAME: Graph.h #ifndef GRAPH_H #define GRAPH_H #include "utils.h" #include <vector> #include <list> class Neighbor; template <typename NS> class Graph { private: std::vector<std::list<NS> > adj_list; public: void add(int,NS&); void remove(int,NS&); inline typename std::vector<std::list<NS> >::iterator begin() { return adj_list.begin(); } inline typename std::vector<std::list<NS> >::iterator end() { return adj_list.end(); } }; #endif // FILENAME: Neighbor.cpp #include "Neighbor.h" #include <iostream> Neighbor::Neighbor(int id,float e,float p):id(id),edge_cost(e),price(p){} bool operator==(const Neighbor& n1,const Neighbor& n2) { if(&n1==&n2) return true; return false; } ostream& operator<<(ostream& ostr,const Neighbor& n1) { ostr<<"["<<n1.id<<","<<n1.price<<","<<n1.edge_cost<<"]"; return ostr; } // FILENAME: Neighbor.h #ifndef NEIGHBOR_H #define NEIGHBOR_H #include <iosfwd> class Neighbor { private: int id; float edge_cost; float price; public: Neighbor(int,float,float p=0.0); friend bool operator==(const Neighbor&,const Neighbor&); friend std::ostream& operator<<(std::ostream&,const Neighbor&); }; #endif // FILENAME: utils.h #ifndef UTILS_H #define UTILS_H #include <iostream> #include <fstream> #include <stack> #include <queue> #include <vector> #include <list> #include <string> #include <algorithm> namespace utility { typedef std::pair<int,int> ii; typedef std::vector<int> vi; typedef std::vector<ii> vii; typedef std::vector<vii> vvii; typedef std::stack<int> si; typedef std::queue<int> qi; } #define UTILITY_TR(c,i) for(typeof((c).begin()) i = (c).begin() ; i!=(c).end() ; ++i ) #define UTILITY_ALL(c) (c).begin(),(c).end() #define UTILITY_CPRESENT(c,x) (find(all(c),x) != (c).end()) #endif // FILENAME: main.cpp #include "utils.h" #include "Neighbor.h" #include "Graph.h" using namespace std; int main() { Graph<Neighbor> graph; Neighbor n1(1,10); Neighbor n2(0,10); graph.add(0,n1); graph.add(1,n2); cout<<"Printing graph"<<endl; cout<<"--------------"<<endl; UTILITY_TR(graph,it) { UTILITY_TR(*it,n) { cout<<*n<<endl; } } };
You need to have the definition of Graph's functions (add and remove) in the .h file so that the linker can find it. I try to think of templates like envelopes. It's nonsensical to send it (compile) before you put in a letter (defined type). Seeing as cpp files are what is compiled, it makes sense that there shouldn't be cpp files for templated types. HTH!
1,780,536
1,780,604
setting strings in gdb
c++: int main() { string a = "a"; ... ... } when i debug in gdb: (gdb) set var a = "ok" Invalid cast I run the program and pause at a break point after string a has been initialized. I'm trying to set its value, but it complains about invalid cast. What's the proper syntax for this?
You can do this: call a.assign("ok") This way, gdb knows right away that it needs to call a function (rather than what you tried using operator=), it knows what function to call (std::string::assign), and it doesn't need to convert types at all (since there's an overload of assign which matches exactly).
1,780,695
1,780,759
Is is better to do const pass by references over non-const pass by references?
I came across this. http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml?showone=Reference_Arguments#Reference_Arguments According to the style guide, only const references are allowed as parameters. (That's what I understood) Although, I don't seem to like that approach. Comments?
Here are a couple of rules of thumb that can be useful when deciding between your options: If you don't need to modify the object being passed into the function, consider whether the size of the object is less than or equal to the size of a pointer. If so, pass by value; otherwise, pass by const reference. If you do need to modify the object being passed into the function, consider whether the parameter is optional (that is, null is a valid argument). If so, pass by pointer; otherwise, pass by non-const reference.
1,780,851
1,780,864
Is it possible to deallocate a statically defined array?
Can you release the memory of an array defined with static allocation?
No, it is not possible to de-allocate statically allocated memory. Depending on the language (for example C/C++, using pointers) you may be able to use the memory held by this array for other purposes, but doing so will only re-use the memory; memory won't be released per-se. This said, this idea of reusing static memory for / with variables other than the variables originally defined there, is only suggested to help understand the nature of this type of allocation. In practical terms, and in particular as a novice, it makes absolutely no sense to have the need for such a feature: either the variable is expected to have a lifetime as long as the program at which case it should be declared static or the variable is not going to be needed at some time during program execution at which case it should be dynamically allocated (? shortly after/during program initialization) and released whenever appropriate.
1,780,876
1,780,891
How to read unsigned short from file?
I have a bitmap image that I am parsing and I need to be able to open the file and store the first unsigned short. I tried to accomplish this using FILE and fscanf() but fscanf() always fails and returns 0 (number of items successfully read). FILE *pFile = fopen ( fileName->c_str() , "r" ); if ( pFile == NULL ) { cerr << "couldn't open file ; exiting..." << endl; exit(0); } unsigned short seed; fscanf (pFile, "%hu", &seed); Does anyone know of another approach I could take (possibly ifstream?) or maybe could just give me some pointers? Any help would be greatly appreciated. Thank you.
Don't use the formatted functions like *scanf; they expect character representations of the data, the complement of the *printf functions which translate values into character representations. unsigned val; f = fopen (filename, "rb"); if (fread (&val, 1, sizeof (val), f) != sizeof (val)) // error The biggest caveat of this is how the file was written. If the endianness of the writer is different than the computer this runs on, then explicit endian code should be used instead: unsigned val; unsigned char buf[2]; f = fopen (filename, "rb"); if (fread (buf, 1, sizeof (buf), f) != sizeof (buf)) // error else { // val = (buf [0] << 8) | buf [1]; // for big endian written file val = (buf [1] << 8) | buf [0]; // for little endian written file }
1,780,933
1,780,947
Parameters Naming for Constructor
In Java, usually, I can have my constructor's parameters same name as member variables. public A(int x) { this.x = x; } private int x; In C++, I can't. Usually, I have to do it this way. public: A(int x_) : x(x_) { } private: int x; Is there any better way? As the constructor parameters name look ugly, when IDE IntelliSense pop up the constructor parameters windows.
In C++, you can, if you want: struct A { int x; A(int x) : x(x) { foo(this->x); // if you want the member instead of the parameter here } }; Though I also commonly use stylistic names for members (e.g. _x), I do it for non-public members. If x is public as in this example, I would do it like this, and look at renaming the ctor's parameter if I thought it would be more readable. Edit: Since people seem to be getting sidetracked, I'll clarify on _x. The standard reserves some identifier names: any name with two adjacent underscores, in any namespace any name with a leading underscore followed by an uppercase letter, in any namespace any name with a leading underscore at global scope Since members are scoped to the class, they do not fall in the third category. That said, it would be nice to not continue getting sidetracked. :) Feel free to ask a question about reserved identifiers in C++ and post a link to it in the comments if you want.
1,780,969
1,781,130
std::copy problem when reading matrix from file
I dont know why the entire matrix gets stored in the first row itself. The loop does actually get called N times if there are N rows. and this is matrix.dat 5 1 2 3 1 2 0 100 3 4 0 5 6 -1 0 9 10 11 #include <fstream> #include <iterator> #include <vector> #include <iostream> int main() { std::vector<std::vector<int> > matrix; std::ifstream infile("matrix.dat"); int num_rows; infile>>num_rows; //If there are 5 rows in the matrix, this loops DOES run 5 times. for(int i=0;i<num_rows;i++){ matrix.push_back(std::vector<int>()); std::copy( std::istream_iterator<int>(infile), std::istream_iterator<int>(), std::back_inserter(matrix[i]) ); } // Printing the size of matrix. This correctly prints the value of num_rows std::cout<<matrix.size()<<std::endl; // Printing just 1st row, but that contains the entire matrix. // Seems like copy always happens to matrix[0] only. for(int j=0;j<matrix[0].size();j++) std::cout<<matrix[0][j]<<" "; }
#include <vector> #include <fstream> #include <string> #include <sstream> #include <algorithm> int main() { std::vector< std::vector< int > > matrix; std::ifstream infile( "matrix.dat" ); std::string s; while( std::getline( infile, s ) ) { std::string token; std::vector< int > tokenisedLine; std::istringstream line(s); while( std::getline( line, token, ' ' ) ) tokenisedLine.push_back( atoi( token.c_str() ) ); matrix.push_back( tokenisedLine ); } return 0; } This code should do what you are after, however it is a little slow, with the copying and creation of all the temporary objects. but for small files like your example this will be fine. It compiled and worked for me using your test data. as you can see it uses getline twice the first time is splitting lines based on the \n char, then we use it again using the space char. Therefore you need to use spaces to separate elements when using this code. Then once we have the token as a string we use atoi to convert it to an int. HTH.
1,781,137
1,781,206
C++ Preprocessor metaprogramming: obtaining an unique value?
I'm exploiting the behavior of the constructors of C++ global variables to run code at startup in a simple manner. It's a very easy concept but a little difficult to explain so let me just paste the code: struct _LuaVariableRegistration { template<class T> _LuaVariableRegistration(const char* lua_name, const T& c_name) { /* ... This code will be ran at startup; it temporarily saves lua_name and c_name in a std::map and when Lua is loaded it will register all temporarily global variables in Lua. */ } }; However manually instantiating that super ugly class every time one wants to register a Lua global variable is cumbersome; that's why I created the following macro: #define LUA_GLOBAL(lua_name, c_name) static Snow::_LuaVariableRegistration _____LuaGlobal ## c_name (lua_name, c_name); So all you have to do is put that in the global scope of a cpp file and everything works perfectly: LUA_GLOBAL("LuaIsCool", true); There you go! Now in Lua LuaIsCool will be a variable initialized to true! But, here is the problem: LUA_GLOBAL("ACCESS_NONE", Access::None); Which becomes: static Snow::_LuaVariableRegistration _____LuaGlobalAccess::None ("ACCESS_NONE", &Access::None); :(( I need to concatenate c_name in the macro or it will complain about two variables with the same name; I tried replacing it with __LINE__ but it actually becomes _____LuaGlobalAccess__LINE__ (ie it doesn't get replaced). So, is there a way to somehow obtain an unique string, or any other workaround? PS: Yes I know names that begin with _ are reserved; I use them anyway for purposes like this being careful to pick names that the standard library is extremely unlikely to ever use. Additionally they are in a namespace.
You need to add an extra layer of macros to make the preprocessor do the right thing: #define TOKENPASTE(x, y) x ## y #define TOKENPASTE2(x, y) TOKENPASTE(x, y) #define LUA_GLOBAL(lua_name, c_name) ... TOKENPASTE2(_luaGlobal, __LINE__) ... Some compilers also support the __COUNTER__ macro, which expands to a new, unique integer every time it is evaluated, so you can use that in place of __LINE__ to generate unique identifiers. I'm not sure if it's valid ISO C, although gcc accepts its use with the -ansi -pedantic options.
1,781,182
1,781,190
NULL Pointer Problem?
void Insert(AVLnode * & root, string X) { if ( root == NULL) { root = GetNode(X); } else if ( root->info > X ) { Insert(root->left,X); if ( height(root->left) - height(root->right) == 2 ) if ( X < root->left->info ) RotateRR(root); else RotateLR(root); } else if ( root->info < X ) { Insert(root->right,X); if ( height(root->right) - height(root->left) == 2 ) if ( X > root->right->info ) RotateRR(root); else RotateLR(root); } root->height = max( height(root->left), height(root->right) )+1; } AVLnode* find(AVLnode* root,string X) { if (!root) return 0; if ( root->info == X ) return root; else if (root->info < X) find(root->left,X); else if (root->info > X) find(root->right,X); return 0; } int main(int argc,char* argv) { AVLnode* Dic; Insert(Dic,"adf"); return 0; } The first time in Insert, root is NULL but when I debug, it skips root == null. What's going on?
The problem is in the AVLnode* Dic; statement of main(). You are sending an uninitialized pointer to insert() from main(). It contains garbage values. Initialize it to NULL
1,781,312
1,781,360
Question about file transfer for socket programming
Is there a good method on how to transfer a file from say... a client to a server? Probably just images, but my professor was asking for any type of files. I've looked around and am a little confused as to the general idea. So if we have a large file, we can split that file into segments...? Then send each segment off to the server. Should I also use a while loop to receive all the files / segments on the server side? Also, how will my server know if all the segments were received without previously knowing how many segments there are? I was looking on the Cplusplus website and found that there is like a binary transfer of files... Thanks for all the help =)
If you are using TCP: You are right, there is no way to "know" how much data you will be receiving. This gives you a few options: 1) Before transmitting the image data, first send the number of bytes to be expected. So your first 4 bytes might be the 4-byte integer "4096". Then your client can read the first 4 bytes, "know" that it is expecting 4096 bytes, and then malloc(4096) so it can expect the rest. Then, your server can send() 4096 bytes worth of image data. When you do this, be aware that you might have to recv() multiple times - for one reason or another, you might not have received all 4096 bytes. So you will need to check the return value of recv() to make sure you have gotten everything. 2) If you are just sending one file, you could just have your receiver read it. And it can keep recv()ing from the socket until the server closes the connection. This is a bit harder - you will have to keep track of how much you have received, and then if your buffer is full, you will have to reallocate it. I don't recommend this method, but it would technically accomplish the task. If you are using UDP: This means that you don't have reliable transfer. So packets might be dropped. They might also arrive out of order. So if you are going to use UDP, you must fragment your data into little segments. Both the sender and receiver must have agreement on how large a segment is (100 bytes? 1000 bytes?) Not only that, but you must also transmit a sequence number with each packet - that is, label each packet #1, #2, etc. Because your client must be able to tell: if any packets are missing (you receive packets 1, 2 and 4 - and are thus missing #3) and to make sure they are in order (you receive 3, 2, then 1 - but when you save them to the file, you must make sure the packets are saved in the correct order, 1, 2, then 3). So for your assignment, well, it will depend on what protocol you have to/are allowed to use.
1,781,417
1,781,422
Get the number of elements in a pointer to a char array in C++
I realise this is an incredibly noob question, but I've googled for it and can't seem to find an answer (probably because I've worded the question wrong... feel free to fix if I have) So I have this code: int main(int argc, char* argv[]) { puts(argv[1]); return 0; } It works fine if I've passed a parameter to my program, but if I haven't, then obviously it's going to fail since it's trying to index a non-existent element of the array. How would I find how many elements in in my string array?
That's what argc is for. It holds the number of elements in argv. Try to compile and run this: #include <stdio.h> int main(int argc, char* argv[]) { int i; if (argc < 2) { printf ("No arguments.\n"); } else { printf ("Arguments:\n"); for (i = 1; i < argc; i++) { printf (" %d: %s\n", i, argv[i]); } } return 0; } Test runs: pax> ./prog No arguments. pax> ./prog a b c Arguments: 1: a 2: b 3: c The argv array ranges from argv[0] (the name used to invoke the program, or "" if it's not available) to argv[argc-1]. The first parameter is actually in argv[1]. The C++ standard actually mandates that argv[argc] is 0 (a NULL pointer) so you could ignore argc altogether and just step through the argv array until you hit the NULL.
1,781,616
2,308,352
C++/WinInet Change Proxy Settings Windows 7
[Disclaimer: this is a Windows 7 specific issue as far as I can tell] I've got a block of code that changes the proxy settings in the Windows registry, then proceeds to call the WinInet API with the following: InternetSetOption(NULL, INTERNET_OPTION_SETTINGS_CHANGED, NULL, 0); InternetSetOption(NULL, INTERNET_OPTION_REFRESH , NULL, 0); This is completely fine in XP and Vista, however in Windows 7 something has apparently changed, and for some reason the previous registry keys get injected back in causing it to not work as expected. If I comment out those two lines of code, the registry values stick, but obviously IE and other applications relying on that proxy information have no idea that the configuration has changed. Is there a better way to handle notifying the system that the options have changed and need to be reloaded? I have searched for days on this issue, switched compilers, etc., and nothing I do makes it work as I would expect in Windows 7.
FWIW my original problem was not using the entire WinInet API to handle the proxy settings. The answer has been staring me in the face from the beginning... A final solution might look something like: LPWSTR proxyName; if (on) { proxyName = L"http=[IPADDRESS:PORT];https=[IPADDRESS:PORT]"; } else { proxyName = 0; } INTERNET_PER_CONN_OPTION_LIST OptionList; INTERNET_PER_CONN_OPTION Option[3]; unsigned long listSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); Option[0].dwOption = INTERNET_PER_CONN_PROXY_SERVER; Option[1].dwOption = INTERNET_PER_CONN_FLAGS; Option[2].dwOption = INTERNET_PER_CONN_PROXY_BYPASS; OptionList.dwSize = sizeof(INTERNET_PER_CONN_OPTION_LIST); OptionList.pszConnection = NULL; OptionList.dwOptionCount = 3; OptionList.dwOptionError = 0; DWORD proxyType = PROXY_TYPE_DIRECT; // this proxy type disables any proxy server if (proxyName) { if (proxyName[0]) { proxyType = PROXY_TYPE_PROXY; // a name has been passed, so choose the correct proxy type for enabling the proxy server } } Option[0].Value.pszValue = (LPWSTR)proxyName; Option[1].Value.dwValue = proxyType; if (on) { Option[2].Value.pszValue = (LPWSTR)L""; } else { Option[2].Value.pszValue = (LPWSTR)L""; } OptionList.pOptions = Option; if (!InternetSetOption(0, INTERNET_OPTION_PER_CONNECTION_OPTION, &OptionList, listSize)) { // handle error } InternetSetOption(0, INTERNET_OPTION_REFRESH, NULL, NULL);
1,781,722
1,785,687
Can't lua_resume after async_wait?
I have some lua script that have some long running task like getting a web page so I make it yield then the C code handle get page job async, so the thread free to do other job and after a specify time it check back to see is the get page job finished , if so then resume the script. the problem is the thread can't resume the job after async wait. here is my code I riped it from a class so a little messy sorry ////script: function Loginmegaupload_com(hp, user, pass, cookie) setURL(hp, "http://megaupload.com/?c=login") importPost(hp, "login=1&redir=1") addPost(hp, "username", user) addPost(hp, "password", pass) GetPage() if isHeaderContain(hp, "user=") ~= nil then SetFileLink(cookie, GetAllCookie(hp)) return 1 else return 0 end end ////c code int FileSharingService::GetPage(lua_State *ls) { return lua_yield(ls, 0); } void FileSharingService::AsyncWait(Http_RequestEx *Http, lua_State *LS, boost::asio::deadline_timer* Timer) { if( (Http->status_code == Http_RequestEx::ERROR) || (Http->status_code == Http_RequestEx::FISNISHED)) { if(Http->status_code == Http_RequestEx::FISNISHED) { int result = lua_resume(LS, 0); // here I got result == 2 mean error ? if(result == 0)//lua script exit normal, resume success { delete Http; delete Timer; } } else return; } else { Timer->expires_from_now(boost::posix_time::milliseconds(200)); Timer->async_wait(boost::bind(&FileSharingService::AsyncWait, this, Http, LS, Timer)); } } bool FileSharingService::Login(string URL, string User, string Pass, string &Cookie) { Http_RequestEx *http = new Http_RequestEx; http->url = URL; LuaWarper* Lua = Lua_map[boost::this_thread::get_id()]; //one main luaState per ioservice thread lua_State *thread = lua_newthread(Lua->GetState()); boost::asio::deadline_timer *timer = new boost::asio::deadline_timer(*HClient.ioservice); string functioname = "Login" + GetServicename(URL); if( Lua->isFunctionAvaliable(functioname.c_str()) == false ) { throw(FileSharingService::SERVICE_NOT_AVALIABLE); } else { lua_getglobal(thread, functioname.c_str()); lua_pushlightuserdata(thread, http); lua_pushstring(thread, User.c_str()); lua_pushstring(thread, Pass.c_str()); lua_pushlightuserdata(thread, &Cookie); int result = lua_resume(thread, 4); if(result == LUA_YIELD) { HClient.Do(*http, false); AsyncWait(http, thread, timer); } else if(result == 0) { //fisnished at first call } else { //yield error, will handle late } } }
Sorry never mind this question, lua_resume return 2 mean error but script work just fine, asio get page work fine too, and I tracked down the line that respond for fail of lua_resume : httpinfo.header.append(buffer, (HeaderEndIndex-buffer+2) ); if I comment that line lua_resume work as expected it return 0 mean script exit, this line don't do any thing that can affect the lua thread state it just a string assign, I checked there no overflow. so weird.
1,781,763
1,781,776
what exactly is dynamic casting in c++
can anyone tell what exactly is dynamic casting means in c++. where exactly can we use this dynamic casting? this was asked to me in the interview and i went blank for this question:).
Try to use the search first old answer
1,781,777
1,782,002
How to write mp3 frames from PCM data (C/C++)?
How to write mp3 frames (not full mp3 files with ID3 etc) from PCM data? I have something like PCM data (for ex 100mb) I want to create an array of mp3 frames from that data. How to perform such operation? (for ex with lame or any other opensource encoder) What do I need: Open Source Libs for encoding. Tutorials and blog articles on How to do it, about etc.
You should be able to use LAME. It has a -t command line switch that turns off the INFO header in the output (otherwise present in frame 0). If that still leaves too much bookkeeping data, you should be able to write a separate tool to strip that away.
1,781,802
1,781,817
Order of destruction for Array of Objects
class MyClass { }; void foo { MyClass arr[10]; } I want to know the order of destruction of array objects when function returns. I read it More Effective C++ about it and it says that destructor are invoked in reverse order to that of constructor order as follows: for(int i = 9 ; i >= 0 ;i--) { arr[i].MyClass::~MyClass(); } Can anybody tell me the reason for it ?
That's continuation of reverse order of destructor invokation filosophy of C++. When stack-allocated objects are destroyed it is done in reverse order to facilitate RAII. Although that is not really necessary for array elements (they are all constructed with the default constructors and any order of construction/destruction would do) the same is done with them just for consistency.
1,781,818
1,781,971
Set dirty dot in mac window using Qt
screen shot http://img14.imageshack.us/img14/2338/200911231633.png Is there a way to set the dirty dot (as shown in the screenshot) using Qt 4.5/4.6?
Use the QWidget::setModified()
1,781,906
1,782,153
CoCreateInstance returning E_NOINTERFACE even though interface is found
I have a COM class CMyCOMServer implementing IMyInterface in one application, both with correct GUIDs. CMyCOMServer::QueryInterface will return S_OK (and cast itself to the right type) if IUnknown or IMyInterface is requested, otherwise it returns E_NOINTERFACE. In another app on the same PC, I call: HRESULT hr = ::CoCreateInstance(__uuidof(CMyCOMServer), 0, CLSCTX_SERVER, __uuidof(IMyInterface ),(void **)&pInterface); It returns E_NOINTERFACE. So I assumed I was doing something wrong and added a breakpoint on CMyCOMServer::QueryInterface. I found that when CoCreateInstance is called, QueryInterface is triggered several times for different interfaces: First, IUnknown is requested - no problem Then, several interfaces like IMarshall etc are requested... these are not supported so E_NOINTERFACE is returned Finally, IMyInterface is requested. I verify QueryInterface returns S_OK and sets (IMyInterface *)this as the interface pointer, as expected So my confusion is why the calling CoCreateInstance is leaving me a NULL pointer and return code of E_NOINTERFACE, when the COM server app is clearly returning the interface I ask for? EDIT: my client app calls CoInitialize(NULL) at startup, this makes no difference.
If your COM server is running in a different process, or a different apartment in the same process, COM needs to know how to package and transmit parameters when you make calls to your interface. This process is called "marshaling". If you define a custom interface, you need to implement marshaling for it using one of the following approaches. Standard marshaling: have the MIDL compiler to generate a proxy and stub which you must register on the system. This is probably the best option since you have already defined your interface. OLE Automation marshaling: you define an automation compatible custom interface and use the marshaller which is already part of the COM framework Custom marshaling: you implement the methods of IMarshal When you are debugging your COM server, although you see that you are returning your custom interface in the call to QueryInterface, it does not make it across the process boundary because COM cannot figure out how to marshal that interface, hence the client sees E_NOINTERFACE. UPDATE (based on your comment) If this is an existing COM server app then you probably already have a proxy/stub. You need to register this on both the client and server. Could it be that you were testing this on a new machine(s) and you simply forgot to register this? To register you simply do regsvr32 on the proxy/stub dll.
1,782,035
1,782,082
Can I have a compile time constant instance of a class (as a member) in C++?
In C++, say I have a class Thing, I'd like it to include a const member of that type, something like: class Thing { public: Thing(); private: static const Thing THING; }; But I don't think this works as above. How can I do this?
The following little program compiles and links using GCC 3.4.5 (MinGW): class Thing { public: Thing(); private: static const Thing THING; }; Thing::Thing() {} // We must instantiate the static variable somewhere, like inside 'Thing.cpp' const Thing Thing::THING = Thing(); int main(int argc, char* argv[]) { return 0; }
1,782,068
1,789,271
Compile Combination of qtwinmigrate + qtpropertybrowser Under VC++ 2008
I need to display a property browser under a MFC app. I try to combine and compile the solution for the two http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Windows/qtwinmigrate/ http://qt.nokia.com/products/appdev/add-on-products/catalog/4/Widgets/qtpropertybrowser/ I am using VC2009, QT 2009.04 with Visual Studio Add-On 1.1.1 Take note, under my machine, there are no problem for me to compile them successfully separately. I copy, and add all exsiting CPP and HEADER files found in qtpropertybrowser-2.5-opensource\src into qtwinmigrate-2.8-opensource\examples\qtdll Here is how my new project looks like in the screen shoot (qtwinmigrate - windows at right most) (source: googlepages.com) The qtpropertybrowser, is the project which I am able to compile with no problem : 1>------ Rebuild All started: Project: simple, Configuration: Release Win32 ------ 1>Deleting intermediate and output files for project 'simple', configuration 'Release|Win32' 1>Moc'ing qtpropertybrowserutils_p.h... 1>RCC ..\..\src\qtpropertybrowser.qrc 1>MOC ..\..\src\qtvariantproperty.h 1>MOC ..\..\src\qttreepropertybrowser.h 1>MOC ..\..\src\qtpropertymanager.h 1>MOC ..\..\src\qtpropertybrowser.h 1>MOC ..\..\src\qtgroupboxpropertybrowser.h 1>MOC ..\..\src\qteditorfactory.h 1>MOC ..\..\src\qtbuttonpropertybrowser.h 1>Compiling... . . . 1>Compiling... 1>moc_qtpropertybrowserutils_p.cpp 1>Linking... 1>Embedding manifest... However, when come to build modified version of qtwinmigrate (original version of qtwinmigrate was able to compiled with no problem) 1>------ Rebuild All started: Project: qtdialog, Configuration: Release Win32 ------ 1>Deleting intermediate and output files for project 'qtdialog', configuration 'Release|Win32' 1>Moc'ing qtpropertybrowserutils_p.h... 1>Moc'ing qteditorfactory.h... 1>Moc'ing qtvariantproperty.h... 1>Moc'ing qttreepropertybrowser.h... 1>Moc'ing qtpropertymanager.h... 1>Moc'ing qtpropertybrowser.h... 1>Moc'ing qtgroupboxpropertybrowser.h... 1>Moc'ing qtbuttonpropertybrowser.h... 1>Moc'ing qwinwidget.h... 1>Moc'ing qwinhost.h... 1>Compiling... . . . 1>Compiling... 1>moc_qtpropertybrowserutils_p.cpp 1>moc_qteditorfactory.cpp 1>.\Release\moc_qteditorfactory.cpp(74) : error C2027: use of undefined type 'QtSpinBoxFactoryPrivate' 1> c:\documents and settings\yan-cheng.cheok\my documents\downloads\qtwinmigrate-2.8-opensource\qtwinmigrate-2.8-opensource\examples\qtdll\release\../../../lib/qtpropertybrowser-2.5-opensource/src/qteditorfactory.h(97) : see declaration of 'QtSpinBoxFactoryPrivate' 1>.\Release\moc_qteditorfactory.cpp(74) : error C2227: left of '->slotPropertyChanged' must point to class/struct/union/generic type My questions is Why qtpropertybrowser just perform "Moc'ing" in 1 file, but qtwinmigrate perform "Moc'ing" in so many files? Why qtpropertybrowser just compile "moc_qtpropertybrowserutils_p.cpp", but qtwinmigrate try to compile so many "moc_....cpp"?
1) Under Visual Studio 2008, go to Qt -> Open Qt Project File (.pro), open qtpropertybrowser.pro 2) Go to "simple" Properties, under Build Events -> Pre-Build Event, enter the following commands : moc ..\..\src\qttreepropertybrowser.cpp > ..\..\src\qttreepropertybrowser.moc moc ..\..\src\qtpropertymanager.cpp > ..\..\src\qtpropertymanager.moc moc ..\..\src\qteditorfactory.cpp > ..\..\src\qteditorfactory.moc 3) Under C/C++ -> Additional Include Directories, enter the following path : ..\..\lib\qtwinmigrate\src 4) Under General -> Configuration Type, change to Dynamic Library (.dll) 5) Under Linker -> General -> Output File, change to \qtdialog.dll 6) Exclude original main.cpp from simple project. Add in main.cpp from ..\..\lib\qtwinmigrate\examples\qtdll 7) Add in all 3 cpp files and 3 header files from ..\..\lib\qtwinmigrate\src 8) Build all. qtdialog.dll will be generated. 9) Open up \lib\qtwinmigrate\examples\mfc\step1. Build all. 10) Move qtdialog.dll same directory as step1 generated exe. Run the application.
1,782,109
1,782,142
MSN Messenger/Growl Style Alerts in Windows C++
Does anyone know of any C++ Libraries which I can easily integrate in a project to allow me to show MSN Messenger/Outlook/Growl style toast popups? Tried having a look and found lots of Visual Basic controls etc but nothing for C++ so far.
You might wanna a look at Customizable Alert Window by Marius Bancila.
1,782,138
1,782,192
A template question: Can compiler deduce template type in static method
I have the following setup: A templated class SpecialModel: template<typename A, typename B> class SpecialModel<A, B> { }; A templated Worker, working on some kind of Model: template<typename M> class Worker<M> { Worker(M& model); void work(); }; And a specialization of Worker for SpecialModel: template<typename A, typename B> class Worker<SpecialModel<A, B> > { Worker(SpecialModel& model); void work(); }; Finally, there is a class that handels a given worker through a static method, basically this Manager class does lots of administration things to allow Worker focus on the real work: template<typename W> class Manager<W> { Manager() {}; static void getThingsDone(W worker) { ...; worker.work(); ...; }; }; To 'getThingsDone' for a SpecialModel, I need the following in the code: SpecialModel<A1, B1> spmo; Worker< SpecialModel<A1, B1> > w(spmo); Manager<Worker< SpecialModel<A1, B1> > >::getThingsDone(w); The last line is the one I have problems with. Isn't there a way to just say: Manager::getThingsDone(w); Can't the compiler deduce the type of W from w? Why do i want that, anyway? I have an array of Workers, working on different kinds of SpecialModels (different As and Bs). Now i want to loop over this array, calling Manager::getThingsDone(w) on each worker. How should i be able to pass typeinformation on to Manager, when only having the array of workers? (The array of SpecialModles is known at compile time (part of this code is autogenerated and then compiled for this kind of special input), the array will be defined somewhere at the toplevel of the code, yet, the code doing the work should be as general as possible. However, i would be happy to find an answer without regard to this last point).
If Train is a templated class, as it appears to be, the compiler cannot deduce class templates from static method template arguments. If Train::train is a static method, why is your class Train templated? Method train cannot access any member variables anyway. You could probably make train a free function: template<class W> void train(W const& w) { ... } And in your code you could simply do train(w); If class Train must be templated with type Worker, you could write a helper function that can discover the template parameter automatically: template<class W> Train<W> make_trainer(W const& w) { return Train<W>(w); } You can also make train a static function of class Train with its own template parameter: class Train { template<class W> vod train(W const& w) { ... } }; Your code could then call Train::train(w); What's best depends on your exact use case.
1,782,337
2,057,662
Implementing and inheriting from C++ classes in Lua using SWIG
Would it be possible using Lua and SWIG and say an IInterface class, to implement that interface and instantiate it all within Lua? If so how would it be done?
Store the table in a c++ class by holding a pointer to the lua state, and the reference returned for the table as specified using this API: http://www.lua.org/pil/27.3.2.html Then when a method on the wrapper class is called, push the referenced object onto the stack and do the necessary function call
1,782,683
1,782,691
Is there any standard way to load parameters from a file in C++ on Linux?
Imaging that a program needs to know quite a lot of parameters to do its tasks properly, such as 'Port = 2323' this kind of things. now I want to save these parameters in a plain text file, similar to Unix' system variables such as users and groups. Is there any standard way/libraries that can help me to do this? Does anyone ever used them before? thanks
Boost.Program_options library. Is this you are looking for? The program_options library allows program developers to obtain program options, that is (name, value) pairs from the user, via conventional methods such as command line and config file.
1,783,350
1,783,366
C++ copy constructor invocation
As far as i know, a copy constructor is invoked in the following scenarios : 1) Pass by value 2) Return by value 3) When you create and initialize a new object with an existing object Here's the program : #include <iostream> using namespace std; class Example { public: Example() { cout << "Default constructor called.\n"; } Example(const Example &ob1) { cout << "Copy constructor called.\n"; } Example& operator=(const Example &ob1) { cout << "Assignment operator called.\n"; return *this; } ~Example() { cout<<"\nDtor invoked"<<endl; } int aa; }; Example funct() { Example ob2; ob2.aa=100; return ob2; } int main() { Example x; cout << "Calling funct..\n"; x = funct(); return 0; } The output is: Default constructor called. Calling funct.. Default constructor called. Assignment operator called. Dtor invoked Dtor invoked Please correct me, IIRC the following sequence of calls should occur : 1) Constructor of x is called 2) Constructor of ob2 is called 3) The function returns and so copy constructor is invoked (to copy ob2 to unnamed temporary variable i.e funct() ) 4) Destructor of ob2 called 5) Assign the unnamed temporary variable to x 6) Destroy temporary variable i.e invoke its destructor 7) Destroy x i.e invoke x's destructor But then why copy constructor is not invoked and also only 2 calls to dtors are there whereas i expect 3. I know compiler can do optimizations, however, is my understanding correct ? Thanks a lot :) Regards lali
A copy constructor might not be invoked when you return by value. Some compilers use return value optimization feature. Read about "Return Value Optimization"
1,783,465
1,783,509
Why must I put a semicolon at the end of class declaration in C++?
In a C++ class declaration: class Thing { ... }; why must I include the semicolon?
The full syntax is, essentially, class NAME { constituents } instances ; where "constituents" is the sequence of class elements and methods, and "instances" is a comma-separated list of instances of the class (i.e., objects). Example: class FOO { int bar; int baz; } waldo; declares both the class FOO and an object waldo. The instance sequence may be empty, in which case you would have just class FOO { int bar; int baz; }; You have to put the semicolon there so the compiler will know whether you declared any instances or not. This is a C compatibility thing.
1,783,652
1,783,672
What is the best autocomplete/suggest algorithm,datastructure [C++/C]
We see Google, Firefox some AJAX pages show up a list of probable items while user types characters. Can someone give a good algorithm, data structure for implementing autocomplete?
A trie is a data structure that can be used to quickly find words that match a prefix. Edit: Here's an example showing how to use one to implement autocomplete http://rmandvikar.blogspot.com/2008/10/trie-examples.html Here's a comparison of 3 different auto-complete implementations (though it's in Java not C++). * In-Memory Trie * In-Memory Relational Database * Java Set When looking up keys, the trie is marginally faster than the Set implementation. Both the trie and the set are a good bit faster than the relational database solution. The setup cost of the Set is lower than the Trie or DB solution. You'd have to decide whether you'd be constructing new "wordsets" frequently or whether lookup speed is the higher priority. These results are in Java, your mileage may vary with a C++ solution.
1,783,762
1,783,812
typedef _W64 unsigned int UINT_PTR, *PUINT_PTR;
What does exactly this mean? typedef _W64 unsigned int UINT_PTR, *PUINT_PTR; Does this mean that *PUINT_PTR is a pointer (obviously) and UINT_PTR is NOT a pointer? If so, why is it called UINT_PTR ? (which I would read as unsigned int pointer, or pointer to unsigned int) Thanks
Yes, this means that PUINT_PTR is a pointer and UINT_PTR is not a pointer. It's a little confusing, but a UINT_PTR (as well as the more standardized uintptr_t) is defined to be an unsigned integer that is guaranteed to be large enough to hold a pointer value. It's typically used for tricky code where pointers are put into integer values and vice-versa. The _W64 annotation is a note to the Miscrosoft compiler that when compiling for a 64-bit target, the variable should be 64 bits wide instead of the usual 32, since on 64-bit platforms, pointers are 64 bits, but unsigned ints are usually still 32 bits. This ensures that sizeof(UINT_PTR) >= sizeof(void*) for all target platforms. The second declaration just declares PUINT_PTR to be a pointer to a _W64 unsigned int, or more specifically, a pointer to a UINT_PTR.
1,783,822
8,914,410
Technical reasons behind formatting when incrementing by 1 in a 'for' loop?
All over the web, code samples have for loops which look like this: for(int i = 0; i < 5; i++) while I used the following format: for(int i = 0; i != 5; ++i) I do this because I believe it to be more efficient, but does this really matter in most cases?
I have decided to list the most informative answers as this question is getting a little crowded. DenverCoder8's bench marking clearly deserves some recognition as well as the compiled versions of the loops by Lucas. Tim Gee has shown the differences between pre & post increment while User377178 has highlighted some of the pros and cons of < and !=. Tenacious Techhunter has written about loop optimizations in general and is worth a mention. There you have my top 5 answers. DenverCoder8 Lucas Tim Gee User377178 Tenacious Techhunter
1,783,849
1,783,905
What are the advantages and disadvantages of implementing classes in header files?
I love the concept of DRY (don't repeat yourself [oops]), yet C++'s concept of header files goes against this rule of programming. Is there any drawback to defining a class member entirely in the header? If it's right to do for templates, why not for normal classes? I have some ideas for drawbacks and benefits, but what are yours?
Possible advantages of putting everything in header files: Less redundancy (which leads to easier changes, easier refactoring, etc.) May give compiler/linker better opportunities for optimization Often easier to incorporate into an existing project Possible disadvantages of putting everything in header files: Longer compile/link cycles Loss of separation of interface and implementation Could lead to hard-to-resolve circular dependencies Lots of inlining could increase executable size Prevents binary compatibility of shared libraries/DLLs Upsets co-workers who prefer the traditional ways of using C++
1,783,883
1,784,224
Special interaction between derived objects (i.e. mutiple dispatch)
So, I have a list of base class pointers: list<Base*> stuff; Then, at some point one of the objects will look through all other objects. Base * obj = ...; // A pointer from the 'stuff'-list. for (list<Base*>::iterator it = stuff.begin(); it != stuff.end(); it++) { if (obj == *it) continue; // Problem scenario is here obj->interact(it); } What I want to achieve is that depending on what derived typeobj and *it are, they will interact differently with each other, i.e. DerivedA will destroy itself if it's interacting with DerivedB, but only if DerivedB has set the property bool c = true;. So something like: struct Base { virtual void interact(Base * b); // is always called }; struct DerivedA : public Base { virtual void interact(Base * b){} // is never called virtual void interact(DerivedB * b) // is never called { if (b->c) delete this; } }; struct DerivedB : public Base { bool c = false; virtual void interact(Base * b){} // is never called virtual void interact(DerivedA * a) // is never called { c = true; } }; // and many many more Derived classes with many many more specific behaviors. At compile time, they are both Base-pointers and will not be able to call each other and expect the type to magically appear. If this was a one way relation, i.e. I knew what type of one of them, I could use the Visitor pattern. I believe I should use some kind of Mediator pattern but can't really figure out how since the mediator too will hold Base-pointers and thus it won't make a difference. I haven't got a clue on how to continue... anyone? Background: I'm creating a game, this problem originates from the Room class who keeps track of it's contents, i.e. what GameObjects are currently in the room. Sometimes, an object moves (for example, the player). The room will then loop over all objects that are on the soon-to-be-moved-upon floor tile (the loop above) and will check if the objects will interact with eachother. For example, if it's a Troll the Player would want to hurt it. Or he would just like to hurt any Character (both Troll and Player are derived from Character) that originates from any another "team" (which can be accessed from the function getAlignment(), which all Characters implement).
If you can, grab a copy of "More Effective C++", and have a look at item #31 which is about implementing multiple dispatch, which is basically what you're looking for here. Meyers discusses several approaches to the problem and their various trade-offs. (He even uses a game as an example.) Perhaps the best advice he gives, however, is to try and redesign your code to avoid requiring this facility. In the text, a non-member function approach is also explored, which has the added bonus of eliminating the question of to which object each function describing an interaction should belong.
1,784,573
1,784,845
iterator for 2d vector
How to create iterator/s for 2d vector (a vector of vectors)?
Although your question is not very clear, I'm going to assume you mean a 2D vector to mean a vector of vectors: vector< vector<int> > vvi; Then you need to use two iterators to traverse it, the first the iterator of the "rows", the second the iterators of the "columns" in that "row": //assuming you have a "2D" vector vvi (vector of vector of int's) vector< vector<int> >::iterator row; vector<int>::iterator col; for (row = vvi.begin(); row != vvi.end(); row++) { for (col = row->begin(); col != row->end(); col++) { // do stuff ... } }
1,784,767
1,784,778
g++ error: ‘stricmp’ was not declared in this scope (but OK for 'strcmp')
I am trying to compile the following very very simple piece of source code: #include <cstring> // #include <string.h> // using namespace std; class Helper { public: int cStringsAreEqual(const char *s1, const char *s2) { return stricmp(s1, s2); } }; ... but I am getting the following error message: g++ error: ‘stricmp’ was not declared in this scope However when I use strcmp() instead of stricmp() then everything is fine! What can be wrong here? Shouldn't stricmp() be allowed when strcmp() is allowed? Sureley, this all could be written in a much better way without using strcmp/stricmp. But that's not the point here. I am porting a piece of software - which makes much use of calls to stricmp(). And if somehow possible I would like to avoid all of the efforts needed to change every call to stricmp. Any help on this would be very much appreciated! BTW: I am using Ubuntu karmic OS (v9.10) with g++ v4.4.1. BTW: as you can see I also made some trials with '#include string.h' or with 'namespace std' but nothing helped.
Try strcasecmp(). Here's the manual page for it. It is conforming to 4.4BSD and POSIX.1-2001.
1,785,028
1,785,135
Class not registered
I'm working through "Developer's Workshop to COM and ATL 3.0" by Andrew W. Troelsen. I'm trying to implement the lab in Chapter 3. It shows you how to build a COM client to connect to an inprocess COM server that was developed in an earlier lab. When I run the client, I receive the error "Class not registered" when calling 'CoGetClassObject'. Here is a snippet of code: // Get the class factory pointer of CoCar. hr = CoGetClassObject(CLSID_CoCar, CLSCTX_INPROC_SERVER, NULL, IID_IClassFactory, (void**)&pCF); if(SUCCEEDED(hr)) { // Make a CoCar & get ICreateCar hr = pCF->CreateInstance(NULL, IID_ICreateCar, (void**)&pICreateCar); pCF->Release(); } else { char buff[100]; BOOL bRet = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, hr, 0, buff, sizeof(buff), 0); std::cout << buff << std::endl; } I have tried to register the class by merging the following .reg file with the system registry: REGEDIT HKEY_CLASSES_ROOT\CarInProcServer.CoCar\CLSID = {EFC76CF8-71B8-477b-890A-1233BD9177CB} HKEY_CLASSES_ROOT\CLSID\{EFC76CF8-71B8-477b-890A-1233BD9177CB} = CarInProcServer.CoCar HKEY_CLASSES_ROOT\CLSID\{EFC76CF8-71B8-477b-890A-1233BD9177CB} \InprocServer32 = C:\Users\Steven\Documents\Visual Studio 2005\Projects\CarInProcServer\release\CarInProcServer.dll Not sure if this is relevant, but here is my .def file: LIBRARY "CarInProcServer" EXPORTS DllGetClassObject @1 PRIVATE DllCanUnloadNow @2 PRIVATE NB: I'm using Windows 7 Can anyone help? Thanks Got it! I manually added: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID{EFC76CF8-71B8-477b-890A-1233BD9177CB} \InprocServer32 = "C:\Users\Steven\Documents\Visual Studio 2005\Projects\CarInProcServer\release\CarInProcServer.dll" to the registry. It seems merging the .reg file with this entry in it did not work. Thanks to Ken White for his help. (and others who suggested solutions)
Open a command prompt, change to your DLL's folder, and run regsvr32.exe: cd \Users\Steven\Documents\Visual Studio 2005\Projects\CarInProcServer\release regsvr32 CarInProcServer.dll
1,785,100
1,785,120
Why use a pointer to a pointer to the stack when creating a push function?
I am looking at a textbook example of a linked list that implements a stack. I don't understand why using a pointer to a pointer to the stack is necessary for the push operation. See the following example: bool push( Element **stack, void *data) { Element *elem = new Element; if(!elem) return false; elem->data = data; elem->next = *stack; *stack = elem; return true; } If anyone can help clarify why the first parameter of the push method is a pointer to a pointer, I would greatly appreciate it. Thanks. Amazing, thank you for all of the excellent help.
The function needs to modify the value of the Element pointer, so it needs a pointer to that pointer. Put it another way: a function takes a pointer of something when it needs to modify that thing. In this case, that something is a pointer itself. So the function ends up taking a pointer to a pointer.
1,785,416
1,785,427
C++ naming: read_input() vs. readInput()
Which naming convention is more preferable in C++? The underscore method or the camelCase method? I have coded in Java for a while and I am used to the camelCase naming conventions. Which one is more prevalent? Also, while defining a class, is there any preferred ordering of private/public/protected variables/methods? Are friends usually put in the end? What about typedefs, do they come at the top of the class definition?
This is all very subjective, but generally for C++ I do: camelCase for functions and variables. PascalCase for classes. public: protected: private: In classes. Edit: Forgot these 2: Yes, friend at the end, typedef either at the beginning if they are used in the class, or after if they use the class (for obvious reasons).
1,785,426
1,785,435
C# null coalescing operator equivalent for c++
Is there a C++ equivalent for C# null coalescing operator? I am doing too many null checks in my code. So was looking for a way to reduce the amount of null code.
There isn't a way to do this by default in C++, but you could write one: in C# the ?? operator is defined as a ?? b === (a != null ? a : b) So, the C++ method would look like Coalesce(a, b) // put your own types in, or make a template { return a != null ? a : b; }
1,785,572
1,785,622
Why should one bother with preprocessor directives?
This question may seem rather basic, but coming from an engineering (non computer-science) background, I was unsure about what the snippets of '#'s were in some C++ code. A quick search led me to the concise, well-explained cplusplus tutorial page on preprocessor directives. But why bother with the concept of preprocessor directives at all? Is it not possible to write equivalent code that can assign values to constants, define subroutines/function/macros and handle errors? I guess I ultimately want to know when it is good practice to use such preprocessor directives, and when it is not.
You use preprocessor directives when you need to do something outside of the scope of the actual application. For instance, you'll see preprocessing done to include or not include code based on the architecture the executable is being built for. For example: #ifdef _WIN32 // _WIN32 is defined by Windows 32 compilers #include <windows.h> #else #include <unistd.h> #endif Preprocessor directives are also used to guard includes so that classes/functions etc. are not defined more than once. #ifndef MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_ #define MY_CLASS_6C1147A1_BE88_46d8_A713_64973C9A2DB7_H_ class MyClass { .... }; #endif Another use is for embedding versioning inside of code and libraries. In the Makefile you have something along the lines of: -D MY_APP_VERSION=4.5.1 While in the code you have cout << "My application name version: " << MY_APP_VERSION << endl;
1,785,612
1,785,703
How do I pass multiple heap arrays to a new thread?
I'm trying to learn how create new threads and run them. I need to pass a few variables into the function that is run on the new thread but I can't find out how to actually pass anything to that new function/thread. I'm following http://www.devarticles.com/c/a/Cplusplus/Multithreading-in-C/1/ but it only goes through how to pass a single parameter and nothing else. Side question, do threads work the exact same way as functions do except just on a different thread or is it a little more complicated than just that? Thanks, -Faken
The underlying OS allows to pass only one parameter to a thread CreateThread: HANDLE WINAPI CreateThread( __in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes, __in SIZE_T dwStackSize, __in LPTHREAD_START_ROUTINE lpStartAddress, __in_opt LPVOID lpParameter, __in DWORD dwCreationFlags, __out_opt LPDWORD lpThreadId ); Accordingly the CRT thread create function allows also only one parameter, despite the name being arglist: uintptr_t _beginthreadex( void *security, unsigned stack_size, unsigned ( *start_address )( void * ), void *arglist, unsigned initflag, unsigned *thrdaddr ); Given these restrictions the usual convention is to pass a pointer to a structure/class with all the arguments. Usually, with C++, one creates a static function that will be the thread handler and passes an instance as the argument: class Foo { int _someState; int _otherState; char _moreState[256]; unsigned DoWork(); static unsigned ThreadHandler(void*); public: void StartThread(); } void Foo::StartThread() { _beginthreadex(..., Foo::ThreadHandler, this, ...); } unsigned Foo::ThreadHandler(void* arglist) { Foo* pFoo = (Foo*) arglist; return pFoo->DoWork(); } unsigned Foo::DoWork() { // do here all the thread work } This is a fairly common idiom and in effect it allows you to pass as much state (=arguments) as needed to the thread.
1,785,617
1,785,643
Shared Library Path as Executable Directory
I have an application that is broken into several libraries for purposes of code reuse. On Windows all I have to do is put the .dll files in the same path as the executable and it automatically finds them. On Linux (since it hardcodes the paths to things) I have to specify the environmental variable LD_LIBRARY_PATH or preload the libraries before the executable. I've seen some things about embedding the path using the linker option of -Wl,-rpath=<PATH> and I've tried it using . as the path. But that just looks in the current working directory, not the executable's directory. Is there a way to specify in the linker to look in the directory of the executable for the shared libraries by default (like on Windows)? Thanks! Matt
You need $ORIGIN in your RPATH, via an appropriate option to ld or other Darwin tool. See this and this. Remember that the $ has to really end up in the path, so you need to quote or escape it in the link command line. Update: You can see what the linker actually put into your executable with readelf -d /path/to/exe | grep RPATH Here is what the output should look like: 0x0000000f (RPATH) Library rpath: [$ORIGIN]
1,786,066
1,786,108
Questions about vector, union, and pointers in C++
The questions I have are NOT homework questions, but I am considering using these concepts in my assignment. The context, if it helps, is like this: I need to keep track of several union instances and they belong to my own union in one of my own classes as class variables. (Note: the number of union instances is unknown, so I cannot just have a fixed number of union instances. Q1: If I have a union, say MyUnion, and many instances of this union, can I then put them into a vector like vector<union MyUnion> myVector(10); Q2: Is it valid to have a pointer of union? Like union MyUnion *myUnionPtr = new union myUnion; Q3: I am considering using a vector of union pointers in my implementation, is this concept correct? Also, is it a normal approach in C++? Do I need to rethink about my design?
If the union is CopyConstructable and Assignable, then it meets the requirements for std::vector. Yes: MyUnion* ptr = new MyUnion(); A container of pointers works in some situations, but if you want a container of owning pointers, look at Boost's ptr_* containers. However, here it appears you'd either have a container of non-pointers or a container of non-owning pointers, either of which is fine and common for vector. All types are, by default, both CopyConstructable and Assignable. ("Copyable" is used to mean the union of these concepts, however the standard specifies them individually.) This is because copy ctors and op= are added to classes (unions are one class-type) except under certain circumstances. There are a few references online, but I'm not aware of a single one, available freely online, that spells these out. You have to go out of your way to prevent it, such as: make the copy ctor or op= non-public make the copy ctor or op= take a non-const reference give the class type a non-CopyConstructable or non-Assignable member Example: union CopyableUnion { int n; char c; double d; }; union NonCopyableUnion { int n; char c; double d; NonCopyableUnion() {} // required, because any user-defined ctor, // such as the private copy ctor below, prevents the supplied // default ctor private: NonCopyableUnion(NonCopyableUnion const&); NonCopyableUnion& operator=(NonCopyableUnion const&); }; int main() { CopyableUnion a; CopyableUnion b = a; // fine, uses copy ctor b = a; // fine, uses op= NonCopyableUnion c; NonCopyableUnion d = c; // compile error (copy ctor) d = c; // compile error (op=) return 0; } Note: And just because something is Copyable, doesn't mean it does what you want! Example: struct A { int* p; A() : p(new int()) {} // the provided copy ctor does this: //A(A const& other) : p(other.p) {} // which is known as "member-wise" copying ~A() { delete p; } }; int main() { A a; { A b = a; assert(b.p == a.p); // this is a problem! } // because when 'b' is destroyed, it deletes the same pointer // as 'a' holds return 0; // and now you have Undefined Behavior when // ~A tries to delete it again } The same thing holds true for unions, of course. The fix applies equally, though, as well: struct A { int* p; A() : p(new int()) {} A(A const& other) : p(new int(*other.p)) {} ~A() { delete p; } }; (If you spotted it, yes, A has a problem if you ever try to use op=, in just the same way as it originally had with the copy ctor.)
1,786,144
1,786,280
C++ passing const string references in methods?
I'm trying to initialize a private variable of my Class passing a const string &aString to it as parameter. Here's my method: void Image::initWithTextureFile(const std::string &inTextureName) { Texture2D *imTexture = TEXTURE_MANAGER->createTexture(inTextureName); if(imTexture) { texture = imTexture; scale = 1.0f; name = inTextureName; //name is a private string variable inside my class initImplementation(); }else { printf("Could not load texture when creating Image from file %s\n",inTextureName.c_str()); } } My problem is the following, when I call this method I do it like: myInitializer.initWithTextureFile("myFile.bmp"); When I'm inside the scope of initWithTextureFile the name variable takes the value of inTextureName. For this example if I cout << name << endl; inside initWithTextureFile i would get "myFile.bmp" But when I leave the scope of the function, name looses it's value, so when i cout << name << endl; I get nothing printed in the console. Could anyone point me out to what's going on here? Name is declared: private: std::string name;
If you're outside the class scope, and cout << name compiles at all, it means you have another variable named name, and that's what's being picked up. If you want to refer to it outside the class, you'll have to come up with a way that will export it. You might, for example, have a member function like const std::string &GetName() { return name; }.
1,786,661
1,786,691
Semicolon after classes and structs
Possible Duplicate: Why must I put a semicolon at the end of class declaration in C++? Found duplicate, vote to close please. Why do classes and structs have to be concluded with semicolon in C++? Like in the following code: class myClass { }; struct muStruct { }; This syntax isn't necessary in Java or C#. Why does the C++ parser need it?
This is why... int a,b,c,d; int main(void) { struct y { }; a, b, c, d; struct x { } a, b, c, d; } Two different statements, two completely different meanings, both legal C / C++, and the only difference is the ; after the struct declaration.
1,786,809
1,786,968
Map functions of a class
Before I was trying to map my classes and namespaces, by using static calls I succeded and now I need to map the functions of my classes because they will be used dynamically. Firstly I was thinking to hardcode in the constructor so I can assign a std:map with the string of the name of function pointing to the function itself. for example: class A{ int B(){ return 1; } }; int main(){ A *a = new A(); vector<string, int (*)()> vec; vector["A.B"] = a.B; } By that I have mapped the function B on A class, I know that I only mapped the function the instance and thats B is not static to be globally mapped. But thats what I need, at somepoint someone will give me a string and I must call the right function of an instance of a class. My question is if I only can do that by hardcoding at the constructor, since this is a instance scope we are talking or if there is somehow a way to do this in the declaration of the function, like here for namespaces and classes: Somehow register my classes in a list
If I understand you correctly, you want your map to store a pointer that can be used to call a member function on an instance, the value being chosen from the map at run time. I'm going to assume that this is the right thing to do, and that there isn't a simpler way to solve the same problem. Quite often when you end up in strange C++ backwaters it's a sign that you need to look again at the problem you think you have, and see whether this is the only way to solve it. The problem with using an ordinary function pointer is that a non-static member function is not an ordinary function. Suppose you could point to a member function with an ordinary function pointer, what would happen when you dereferenced that pointer and called the function? The member function needs an object to operate on, and the syntax doesn't provide a way to pass this object in. You need a pointer to member, which is a slightly obscure feature with relatively tricky syntax. While an ordinary pointer abstracts an object, a pointer to member abstracts a member on a class; the pointer specifies which class member should be called, but not which object to obtain the member from (that will be specified when the pointer is used). We can use it something like this: class B; class A { B some_function() { /* ... */ } }; B (A::* myval)() = A::some_function; Here myval is a variable that indicates one of the members of class A, in this case the member some_function (though it could point to any other member of A of the same type). We can pass myval round wherever we want (e.g. storing it in an STL container, as in your example) and then when we want to call the function, we specify the instance it should be called on in order to locate the function: A some_a; B newly_created_b = (some_a.*myval)(); This works for a particular case, but it won't solve your general issue, because member pointers contain the class they refer to as part of the definition. That is, the following two variables are of entirely different types: B (Foo::* first_variable)() = Foo::some_function; B (Bar::* second_variable)() = Bar::some_function; Even though both functions can produce a B when called without arguments, the two values operate on different classes and therefore you can't assign a value of one type to a variable of the other type. This of course rules out storing these different types in a single STL container. If you're committed to storing these in a container, you'll have to go with a functor-based solution like Charles Salvia proposes.
1,786,873
1,786,883
Calculate direction vector
HI All, How can I calculate direction vector of a line segment, defined by start point (x1, y1) and end point (x2, y2)? Cheers.
(x2 - x1, y2 - y1) If you want the unit direction vector, divide each component by sqrt((x2 - x1)² + (y2 - y1)²).
1,786,884
1,786,981
iterator dereferencing issue
if I have list<NS*> v; typename list<NS*>::iterator it; for(it = v.begin();it!=v.end();++it){ cout<<**it.ns_member1<<endl; // does not compile NS ns = **it; cout<<ns.ns_member1<<endl; // this compiles. } Why so?
Dereference (the '*') has a lower precedence than the '.' operator, so this line: cout<<**it.ns_member1<<endl; Works out like this: cout << (**(it.ns_member1)) <<endl; // ERROR I would suggest doing it like this: cout << (*it)->ns_member1 << endl; There is really no need to use the dereference operator twice, once followed by the '->' operator will do the same thing and should read clearer to most people. HTH.
1,786,887
1,786,954
From Visual Studio to Vim or Emacs?
I'm starting a new job next month. I've practically lived inside Visual Studio professionally for 10 years give or take, but for this job I'll be working full time on the linux platform for the first time in my life. During one of the interview meatings I was seated in the middle of the developer room to socialize with the crowd. We had some light conversation for ten minutes and then one of the guys said: "ok, now for the truly important question - Vim or Emacs?". I informed them that I'm not very experienced working on Linux, so I had no real opinion. But the question has rendered a dilemma for me since I would like to get comfortable with my potential working environment before I start. I'm guessing I won't be able to unravel the full potential of both these editors before I start, so in order to pick the one which is likely to work best for me, the question goes - which of Vim and Emacs will make me most comfortable and efficient (working with C++) if I'm all about Visual Studio at the moment?
If you're ambivalent, the only correct answer is: Use what the people around you use.
1,786,986
1,786,994
Why is my insert into std::map failing?
In my header file, I'm declaring a map like so: std::map<LPD3DXSPRITE, LPDIRECT3DTEXTURE9> sprites; In my C++ file, I am trying to insert like so: sprites.insert(sprite, texture); The types I am passing to sprites.insert are correct. Why can I not insert this way? What is the proper way to insert? When I do this, the error I get is like this (snipped): error C2664: 'std::_Tree<_Traits>::iterator std::_Tree<_Traits>::insert(std::_Tree<_Traits>::iterator,const std::pair<_Ty1,_Ty2> &)' : cannot convert parameter 1 from 'LPD3DXSPRITE' to 'std::_Tree<_Traits>::iterator'
You need to wrap your key and value in an std::pair object: sprites.insert(std::make_pair(sprite, texture)); This is because std::map is a Pair Associative Container. The value_type of std::map<K,V> is std::pair<const K,V>.
1,787,174
1,787,195
How does C++ handle multiple source files?
I'm studying C++ right now, coming from a background in Python, and I'm having some trouble understanding how C++ handles multiple source files. In Python, the import statement first checks the current working directory for the module you're trying to import and then it checks the directories in sys.path. In C++, where would I place a custom made .h file? Where would the compiler even look? For example, I've got a program, foo.exe compiled from a single source file, foo.cpp, both in the same directory. I decide that I want to organize things a little better, so I create a new .h file, bar.h and dump stuff in there. Would I just need to #include to get to the stuff I put there? What if I want to use bar.h with another program (in a completely different directory)?
There are two include variants: #include "path-spec" #include <path-spec> Quote notation: This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file. The bracket notation looks for header files in certain defined locations. With gcc you can get some information about these pathes via: $ echo | gcc -v -x c++ -E - Compilers accept -I or /I options to add additional pathes.
1,787,246
1,787,460
How to best save XML files
I have a bunch of classes that each read in their values from an XML file using TinyXML. I've done this so everything is in memory, and my user is using the app and making changes. If the user presses Save, I need to iterate through my objects and call the Save() function which writes out the XML file. Should I rebuild the XML file programmatically from scratch and write it out? Or should I use the same TiXmlHandle that I used to read the file, modify that and then write it back out? That way, the original order is kept. If I recreate the XML, then the order of the original would be changed. I want the user to be able to modify the XML by hand, so I think it would be wierd for them to change it manually, only to have it reshuffled when saving. Am I understanding my options correctly? Never used TinyXML before, or XML for that matter.
I would dispose of the reading handles once you have read the XML input. To write them back out you would typically have a writeXML() method in the parent or main document type object an then have that call a writeXML() method in each object in your design. ps. It's not unusual to have different XML reading and writing libs. pps. if you are concerned about the order in an XMl document that you can't enforce from your object hierarchy - you have some fundemantal design wrong.
1,787,293
1,787,318
Get a reverse iterator from a forward iterator without knowing the value type
I'm trying to implement some STL-style sorting algorithms. The prototype for std::sort looks something like this (from cplusplus.com): template <class RandomAccessIterator> void sort ( RandomAccessIterator first, RandomAccessIterator last ); The function is generally called like this (although the container type can vary): std::vector<int> myVec; // Populate myVec std::sort(myVec.begin(), myVec.end()); I duplicated the prototype of std::sort for my own sorting function. To iterate through the container to be sorted, I do the following: template <class RandomAccessIterator> void mySort(RandomAccessIterator first, RandomAccessIterator last) { RandomAccessIterator iter; for (iter = first; iter != last; ++iter) { // Do stuff } } Easy enough. But what if I want to use a reverse iterator? This would be convenient in algorithms that sort a container from both ends, e.g. cocktail sort. Is there any way to get a reverse iterator from the iterators that are passed in as parameters? If I knew the container type in advance, I could do something like this: template <class RandomAccessIterator> void mySort(RandomAccessIterator first, RandomAccessIterator last) { std::vector<int>::reverse_iterator riter(last); std::vector<int>::reverse_iterator rend(first); for ( ; riter != rend; ++riter) { // Do stuff } } Unfortunately, I don't know the container type. What I really need to do is something like this: template <class RandomAccessIterator> void mySort(RandomAccessIterator first, RandomAccessIterator last) { RandomAccessIterator riter = reverse_iterator(last); RandomAccessIterator rend = reverse_iterator(begin); for ( ; riter != rend; ++riter) { // Do stuff } } Is there some way to do this without having to pass in reverse iterators as additional parameters (which would solve the problem, but make the function prototype less intuitive)? Note that I need both forward and reverse iterators in my implementation, so calling the function this way std::vector<int> myVec; // Populate myVec mySort(myVec.rbegin(), myVec.rend()); will not work.
The STL has std::reverse_iterator<Iterator>: template <class RandomAccessIterator> void mySort(RandomAccessIterator first, RandomAccessIterator last) { typedef std::reverse_iterator<RandomAccessIterator> RIter; RIter riter(last); RIter rend(first); for ( ; riter != rend; ++riter) { // Do stuff } } An important note: Notice however that when an iterator is reversed, the reversed version does not point to the same element in the range, but to the one preceding it. This is so, in order to arrange for the past-the-end element of a range: An iterator pointing to a past-the-end element in a range, when reversed, is changed to point to the last element (not past it) of the range (this would be the first element of the range if reversed). And if an iterator to the first element in a range is reversed, the reversed iterator points to the element before the first element (this would be the past-the-end element of the range if reversed).
1,787,548
1,787,566
How many threads to create?
I am just learning how to write mutithreaded programs right now and I have a hypothetical question about how many threads are optimal for a program. Let me describe 2 scenarios. The first scenario is that i have a program that is easily multi threaded but each thread is going to be doing a lot of work (execution times for each thread is on the order of seconds). The second scenario is that i have a program that is also easily multi thread but each thread has a very short execution time, on the order of milliseconds. In either one of these scenarios, what is the most efficient way of mutithreading the programs? Is it either creating as many threads as my system memory will allow, or wait for threads to finish before creating new ones so that I only ever have a maxim of 4 worker threads running at any one time. On one hand, many threads may have overhead problems with cores switching in between threads (from my understanding, its not such a severe overhead). On the other hand, if I limit the number of threads running, that means that I'll be running extra checking conditions and locking and unlocking a counter variable to keep track of the number of threads running, and creating new threads when old ones finish. I can see that if there are many small threads, it would be best to simply overload my system with as many threads as possable as since there wont be too much thread switching before a thread finishes running. That would save me the overhead of constantly keeping track of the number of threads. Also, if there are only a few large threads (by few, i mean a couple hundred or so large ones) it would make sense to keep track of the threads so that we keep the threads at optimal numbers such that there isent very much thread switching (as since the overhead would be greater as we would likely switch many times before a single thread finishes). So would these assumptions be correct for each case or is there a universal way of doing things that would be correct in all situations? Note: this is assuming a muti core system (for now, lets ignore hyperthreading) and lets ignore any of the typical problems associated with mutithreading (assume that all threads have private write locations and can only read from public ones, locking and unlocking only happens when incrementing or decrementing the counter for number of active threads). Thanks, -Faken
Scenario #1: Make n threads, where 'n' is the number of CPU cores Scenario #2: The same, but instead of creating and killing the threads all the time, use a Workitem / Thread Pool based approach, like the .NET Parallel Framework does. Edit: This is a good article that covers #2 - http://msdn.microsoft.com/en-us/magazine/cc163340.aspx ; let PFx figure out how many threads to run, you just describe how tasks are related to each other.
1,787,599
1,787,623
Int32 not declared in this scope
I have the following code: //Comp454 program 2 #include <iostream> #include <string> #include <fstream> // file I/O support #include <cstdlib> // support for exit() const int SIZE = 60; int main() { using namespace std; string states; int numStates = 0, i = 0, stateVar = 0; string line; char filename[SIZE]; ifstream inFSM, inString; //Open FSM definition cout << "Enter name of FSM definition: "; cin.getline(filename, SIZE); inFSM.open(filename); //Associate inFile with a file if (!inFSM.is_open()) // failed to open file { cout << "Could not open the file " << filename << endl; cout << "Program terminating.\n"; exit(EXIT_FAILURE); } //Process FSM definition line by line until EOF getline(inFSM, states); numStates = Int32.TryParse(states); //Check for num of states if(numStates > 10) { cout << "There can be no more than 10 states in the FSM definition, exiting now." << endl; return 0; } while (!inFSM.eof()) // while input good and not at EOF { getline(inFSM, line); cout << line << endl; } return 0; } I'm trying to convert a string to an integer using Int32.TryParse(), but when I compile I get the error that Int32 was not declared in this scope. Not sure why this is coming up, am I missing a namespace declaration?? Any help is appreciated, thank you UPDATE: Thanks for all the responses, as in the comment I posted, I'm not trying to use C++/CLI, how to I convert a string, declared from the string class, to an integer?
Try using atoi() instead. States is a std::string so you will need to say: numStates = atoi( states.c_str() );
1,787,601
1,787,615
HTTP server, after a connection is accepted I get -1 returned from recv()
I have to implement an HTTP server for a class in C++, but after a connection is accepted, recv() just returns -1. How can I fix this? I posted my code below. int main( int argc, char* argv[] ) { // Interpret the command line arguments unsigned short port = 8080; char* base_directory = NULL; base_directory = getcwd(base_directory, 100); if ( (argc != 1) && (argc != 3) && (argc != 5) ) { cerr << "Usage: " << argv[0]; cerr << " -p <port number> -d <base directory>" << endl; return 1; } else { for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-p") == 0) port = (unsigned short) atoi(argv[++i]); else if (strcmp(argv[i], "-d") == 0) base_directory = argv[++i]; } } // Create TCP socket int tcp_sock = socket(AF_INET, SOCK_STREAM, 0); if (tcp_sock < 0) { cerr << "Unable to create TCP socket." << endl; return 2; } // Create server socket sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons( port ); server.sin_addr.s_addr = INADDR_ANY; // Bind the socket if (bind(tcp_sock, (sockaddr*)&server, sizeof(server)) < 0) { cerr << "Unable to bind TCP socket." << endl; return 3; } // Listen for a connection request on TCP port listen(tcp_sock, 5); // Create HTTP_Request object and start a while loop of accepting connections char recv_buffer[3000]; int bytes_recv = 0; int recv_len = 0; while (true) { int acc_tcp_sock = accept(tcp_sock, NULL, NULL); if (acc_tcp_sock == -1) { cerr << "Unable to open TCP connection with client." << endl; return 4; } do { recv_len = recv( tcp_sock, recv_buffer + bytes_recv, 3000 - bytes_recv, 0 ); bytes_recv += recv_len; cout << bytes_recv << endl; break; } while (recv_len); bytes_recv = 0; HTTP_Request* request = HTTP_Request::Parse(recv_buffer, 3000); cout << recv_buffer << endl; } return 0; }
you are recv'ing on the wrong socket. You are using tcp_sock(which is your listening socket), not the socket returned by the accept call. Change it to acc_tcp_sock and you should be good to go: recv_len = recv( acc_tcp_sock, recv_buffer + bytes_recv, 3000 - bytes_recv, 0 );
1,787,604
1,787,609
printf((char *) i); runtime error? (i as integer)
In a for loop, I am trying to use printf to print the current i value. This line: printf((char *) i); is giving me runtime errors. Why is this?! Below is a quick fizzbuzz solution that is doing this: void FizzBuzz() { for (int i = 0; i < 20; i++) { printf((char *)i); if ((i % 3 == 0) && (i % 5 == 0)) { printf("FizzBuzz \n"); } else if (i % 3 == 0) { printf("Fizz \n"); } else if (i % 5 == 0) { printf("Buzz \n"); } else { printf("%d\n", i); } } }
Because that's not how printf works. You want this instead: printf("%d\n", i); Or even better, std::cout << i;
1,787,643
1,787,671
Is this a standard C++ code?
The following simple piece of code, compiles with VC2008 but g++ rejects the code: #include <iostream> class myclass { protected: void print() { std::cout << "myclass::print();"; } }; struct access : private myclass { static void access_print(myclass& object) { // g++ and Comeau reject this line but not VC++ void (myclass::*function) () = &myclass::print; (object.*function)(); } }; int main() { myclass object; access::access_print(object); } (/W4) is turned on in VC, but it doesn't give any warning. g++ 4.4.1 gives me an error: correct.cpp: In static member function ‘static void access::access_print(myclass&)’: correct.cpp:6: error: ‘void myclass::print()’ is protected If g++ is correct, how do I access a protected member of a class? is there another way? @Suroot Do you mean that I shouldn't pass an object of type myclass? It doesn't matter actually, g++ gives the same error but VC compiles the code without any warning. #include <iostream> class myclass { protected: void print() { std::cout << "myclass::print();"; } }; struct access : private myclass { static void access_print() { myclass object; void (myclass::*function) () = &myclass::print; (object.*function)(); } }; int main() { access::access_print(); }
I believe g++ and comeau are correct. The specifier for a protected member must be of type "access" or derived, so I believe the code: void (myclass::*function) () = &access::print; would compile. I believe this is because of 11.5.1: ... If the access [ed. to a protected member ] is to form a pointer to member, the nested-name-specifier shall name the derived class (or any class derived from that class).
1,787,752
1,787,870
Is there a g++ equivalent to Visual Studio's __declspec(novtable)?
Is there a g++ equivalent to Visual Studio's __declspec(novtable) argument? Basically, in a pure virtual base class the __declspec(novtable) argument can be used to suppress the creation of a vtable for the base class as well as vtable initialization/deinitialization code in the contstructor/destructor respectively. E.g., class __declspec(novtable) PureVirtualBaseClass { public: PureVirtualBaseClass(){} virtual ~PureVirtualBaseClass() = 0; }; See Paul DiLascia's article for more info. Also see my related question.
I don't think there is one -- if there was, it would be listed under the type attributes page of the GCC manual. GCC uses type attributes to add extra annotations to types (such as alignment and padding), but there is no type attribute equivalent to __declspc(novtable) listed there. I also don't see any compiler flag in the command line options relating to this optimization.
1,787,822
1,787,830
Why aren't include guards or pragma once working?
I'm compiling some code that relies on include guards to prevent multiple definitions of objects and functions, but Visual Studio 2008 is giving me link errors that there are multiple definitions. I don't understand why because I've used code very similar to this before and it hasn't caused problems. I must be doing something dumb but I have no idea what it is. I also tried to take out the include guards and use #pragma once, but I get the same link errors. What should I check for?
If they are linker errors, the most likely cause is probably non-inline functions defined in the header. If you have a non-inline function in a header that is included in more than one source file, it will be defined in each of those source files ("translation units"), thus the function will be defined more than once, hence the multiple definitions error.
1,787,856
1,787,922
What is the element value in an uninitialized vector?
If I create a vector like vector<myClass> v(10); what is the default value of each element? Also, what if it is a vector<myUnion> v(10) ?
The constructor of std::vector<> that you are using when you declare your vector as vector<myClass> v(10); actually has more than one parameter. It has three parameters: initial size (that you specified as 10), the initial value for new elements and the allocator value. explicit vector(size_type n, const T& value = T(), const Allocator& = Allocator()); The second and the third parameters have default arguments, which is why you were are able to omit them in your declaration. The default argument value for the new element is the default-contructed one, which in your case is MyClass(). This value will be copied to all 10 new elements by means of their copy-constructors. What exactly MyClass() means depends on your class. Only you know that. P.S. Standard library implementations are allowed to use function overloading instead of default arguments when implementing the above interface. If some implementation decides to use function overloading, it might declare a constructor with just a single parameter (size) in std::vector. This does not affect the end result though: all vector elements should begin their lives as if they were value-initialized.
1,787,875
1,787,927
Use of "extern" storage class specifier in C
How does the following example usage of extern specifer behave. We have a global variable int x both in files one.c and two.c We want to use these in three.c so have declared this variable in three.c as extern int x; What would happen when we compile and link these files? My answer is: compilation of all these files should succeed, however the linker should flag an error at linking, due to multiple declarations of x. Would there be any difference in behavior in C++ ? Is these any way to refer to int x (in three.c) simultaneously from both files, in C and C++. In C++, I guess we can use namespaces to acheive this. Right?
By default, global variables have external linkage, which means that they can be used by other source files (or "translation units"). If you instead declare your global variables with the static keyword, they will have internal linkage, meaning they will not be usable by other source files. For variables with external linkage, you can't have multiple variables with the same name, or the linker will complain. You can have two variables with the same name, though, as long as at least one has internal linkage, and of course you can't reference both of them in the same source file. An extern declaration is just saying to the compiler "here is the name of some variable with external linkage defined in another translation unit," allowing you to refer to that variable. C++ is exactly the same, except for the addition of namespaces. If global variables are put inside a namespace, then they can have the same name without linker errors, provided they are in different namespaces. Of course, all references to those variables then have to either refer to the full name namespace::var_name, or use a using declaration to establish a local namespace context. C++ also has anonymous namespaces, which are entirely equivalent to using the static keyword for global variables in C: all variables and functions declared inside an anonymous namespace have internal linkage. So, to answer your original question, you are right -- compilation would succeed, but linking would fail, due to multiple definitions of the variable x with external linkage (specifically, from the translation units one.c and two.c). From three.c, there is no way to refer simultaneously to both variables x. You'll need to rename x in one or both modules, or switch to C++ and put at least one x inside a namespace.
1,787,909
1,787,943
Pthreads C++ compilation error
I'm getting error "undefined reference to `pthread_attr_init'", even though that should be in pthread.h. This is in a UNIX environment that should be set up for Pthreads. Also, is a void* a good way to point to the current matrix? Here's my code, any ideas? #include <cstdlib> #include <iostream> #include <sstream> #include <string> #include <vector> #include <time.h> #include <limits.h> #include <pthread.h> #include <semaphore.h> #define MAX_MATRIX_SIZE 256 #define MAX_THREADS 64 using namespace std; void *StripProcessor(void *); void Barrier(); void InitMatrix(int rows, int cols); int main(int argc, char *argv[]) { /* Get command line params */ if (argc != 3) { cout << "Error: need 2 command line params." << endl; getchar(); return 1; } int numThreads = atoi(argv[1]); double epsilon = atof(argv[2]); /* Locals hang here */ pthread_mutex_t barrier; pthread_cond_t leave; int numWaiting = 0; int rows; int cols; int stripSize; int lastStripSize; int iterations; double matrix1[MAX_MATRIX_SIZE][MAX_MATRIX_SIZE]; double matrix2[MAX_MATRIX_SIZE][MAX_MATRIX_SIZE]; void *currentMatrix = matrix1; //???????????????? double stripMaxDiff[MAX_THREADS]; clock_t start; clock_t finish; /* Get rows and cols from standard in */ string buffer; getline(cin, buffer); istringstream myStream(buffer); myStream >> rows; myStream >> cols; cout << rows << " " << cols << endl; getchar(); /* Set locals */ if (rows % numThreads == 0) { stripSize = rows / numThreads; lastStripSize = 0; } else { stripSize = rows / numThreads + 1; if (rows % stripSize == 0) { numThreads = rows / stripSize; lastStripSize = 0; } else { numThreads = rows / stripSize + 1; lastStripSize = rows - (stripSize * (numThreads - 1)); } } /* Set up threads */ vector<pthread_t> threadID; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); /* Init mutex, CV, and matrix */ pthread_mutex_init(&barrier, NULL); pthread_cond_init(&leave, NULL); //InitMatrix(rows, cols); /* Create threads and wait for completion */ start = clock(); /*for (unsigned int i = 0; i < threadID.size; i++) pthread_create(&threadID[i], &attr, StripProcessor, (void *) i); for (unsigned int i = 0; i < threadID.size; i++) pthread_join(threadID[i], NULL);*/ finish = clock(); /* Print results */ }
It will depend on your platform, but I would try adding -lpthread to your link command as that's what is required in Linux and a few others. Your program compiles fine here as g++ foo.cc -lpthread.
1,787,966
1,788,037
what is the capacity of an empty vector?
Looks like a stupid question. But comment to my answer to one of the SO question made me to think again. [ comment says, capacity need not be zero for empty vector] By default my answer would be 0 as there are no elements inside vector. It makes sense to keep the capacity as 0 and on the first allocation it can be increased without any performance hits. But standard does not say anything one this. ( I checked in Josuttis book as well). Is it purely implementation specific? Does any STL vendor use some arbitrary number as capcity for the empty vector? Any thoughts...
C++ Standard 23.2.4.2 only says that vector::capacity is The total number of elements that the vector can hold without requiring reallocation. That means that the actual value is fully implementation specific.
1,788,035
1,788,066
Sharing methods between two implementations of a virtual base class in C++
I have a virtual base class and two classes that implement the various methods. The two classes have the same functionality for one of the methods. Is there away I can share the implementation between the two classes to eliminate redundant code? I tried making the first class a parent of the second class in addition to the virtual base class but got a bunch of errors. EDIT - Thanks everyone for the replies. One thing I should have mentioned is that I cannot modify the virtual base class so just adding the code to the base class will not work.
Say, A is the base class, and B and C are classes that inherit from the base class. The method whose logic is shared between B and C is called SomeMethod. One of the following should do the trick, regardless of your use case: Take the logic for B::SomeMethod and C::SomeMethod and copy-and-paste it into A::SomeMethod Create a class D that provides the shared version of SomeMethod and have B and C derive from D, which will derive from A Create a class SomeMethodImpl that just provides the implementation you want, and then the implementation of B::SomeMethod and C::SomeMethod will just delegate the method call to a private instance of SomeMethodImpl::SomeMethod
1,788,043
1,788,057
Why do I see 64-bit pointers in C++ on my 32-bit Mac OS X system?
So I've read a lot of related posts on SO and elsewhere such as: Is the sizeof(some pointer) always equal to four? It makes total sense to me that on a 32-bit system I would expect 4-byte pointers and on a 64-bit system I would expect 8-byte pointers. So I'm running this code: int main() { cout << "sizeof(int) = " << sizeof(int) << endl; cout << "sizeof(void*) = " << sizeof(void*) << endl; } And this is the corresponding output: sizeof(int) = 4 sizeof(void*) = 8 I'm running in 32-bit mode on Mac OS X 10.6.1. Here's the output of "uname -a": Darwin brents-macbook.local 10.0.0 Darwin Kernel Version 10.0.0: Fri Jul 31 22:47:34 PDT 2009; root:xnu-1456.1.25~1/RELEASE_I386 i386 i386 Here's the version of g++ I'm running (default that came with the system): i686-apple-darwin10-g++-4.2.1 (GCC) 4.2.1 (Apple Inc. build 5646) So I realize that the sizes of pointers are not guaranteed from system to system and they're completely dependent on compiler and architecture, but does this result strike anyone else as illogical? Is this just an idiosyncrasy of Mac OS X 10.6 or my setup? Or is there a good reason I'm seeing pointers of this size? ================================================== Post-Answer Addition Extra details for anyone who wants them... I was originally compiling with this command line: g++ -Wall -o TestClass1 TestClass1.cpp And it generated this output: sizeof(int) = 4 sizeof(void*) = 8 After the suggestion below, I changed my command line to this: g++ -Wall -o TestClass1 -arch i386 TestClass1.cpp And the output changes to this: sizeof(int) = 4 sizeof(void*) = 4
You're running a 32-bit kernel, but you're compiling the code into a 64-bit executable. Both 32- and 64-bit code can run in OS X, regardless of which kernel is in use. If you want to compile the code into a 32-bit executable, pass the -arch i386 flag to gcc. The corresponding flag for 64-bit is -arch x86_64, but it is the default on Snow Leopard.
1,788,259
1,788,295
Crash when utilising a std:map
In my SDL program, I am using a map construct to simulate an "infinite" array of objects within a certain class. The code manages to compile fine, but when I run the program, as soon as one of the functions using the maps is trigger, the program crashes, returning a value of 3. So, here's exactly what I'm doing: class MyClass { public: int MyFunction(); protected: std::map< int, MyObject > MyMap; } int MyClass::MyFunction() { ... int i; if( MyMap.empty() ) { i = 1; } else { i = MyMap.size() + 1; } MyMap[ i ] = PreviouslyDefinedObject; return i; } When MyFunction() is called from a MyClass object, the crash occurs. It seems to happen whenever anything of use is done with MyMap: it crashes if you comment out the penultimate line and just try to return i, and it crashes if you just set i = 1 and then assign an object to MyMap[i] This is the first time I've ever used a map, so I'm not certain I'm using them right. Is this a basic mistake somewhere? Can anyone point me in the right direction? Cheers.
Maybe you are calling the function from an uninitialized pointer, like this: MyClass *obj; obj->MyFunction();
1,788,550
1,804,259
Should the conditional operator evaluate all arguments?
When writing this: 1: inline double f( double arg ) { 2: return arg == 0.0 ? 0.0 : 1./arg; 3: } 4: const double d = f( 0.0 ); The microsoft visual studio 2005 64-bit compiler came with line 4: warning C4723: potential divide by 0 While you and I can clearly see that a div-by-zero is never going to happen... Or is it?
It's an obvious bug, beyond doubt. The intent of the warning is NOT to warn about all divisions in a program. That would be far too noisy in any reasonable program. Instead, the intent is to warn you when you need to check an argument. In this case, you did check the argument. Hence, the compiler should have noted that, and shut up. The technical implementation of such a feature is done by labelling variables in code branches with certain attributes. One of the most common attributes is the tri-state "Is null". Before the branch, arg is an external variable and arg [[Isnull]] is unknown. But after the check on arg there are two branches. In the first branch arg [[Isnull]] is true. In the second branch arg [[Isnull]] is false. Now, when it comes to generating divide-by-zero and null pointer warnings, the [[IsNull] attribute should be checked. If true, you have a severe warning/error. If unknown, you should generate the warning shown above - a potential problem, beyond what the compiler can prove. But in this case, the [[isNull]] attribute is False. The compiler by the same formal logic as humans, knows that there is no risk. But how do we know that the compiler is using such an [[Isnull]] attribute internally? Recall the first paragraph : without it, it would have to either warn always or never. We know it warns sometimes, ergo there must be an [[IsNull]] attribute.
1,788,659
1,788,682
Seemingly basic C++ question
Alright, so this is annoying the hell out of me and I'm sure its a simple thing to do. Basically, I'm working with an open source C++ client called POCO to make a email client for a class... Basically, I have a pop3 client object that retrieves emails from my email server, and then puts the emails in an object called MailMessage. Now, I want to be able to get my attachments, and the only functionality it seems that I have to do that is the following function: static const std::string & contentTransferEncodingToString( ContentTransferEncoding encoding ); Problem is, I had no idea what the following was: ContentTransferEncoding encoding After digging into the source code, I found out it has something to do with "enums" (this is public by the way): enum ContentTransferEncoding { ENCODING_7BIT, ENCODING_8BIT, ENCODING_QUOTED_PRINTABLE, ENCODING_BASE64 }; Basically, the attachment I'm trying to open uses 7 bit encoding. Does ANYONE know how to deal with these enums, and how I can pass them into the contentTransferEncodingToString function? Thank you so much for your efforts :) EDIT: So, unreal, but I didn't realize that the function I was trying to access was protected, it wasn't the enums, so the way you all suggested to access the enums was correct! And I guess the way I was trying to access them was also correct =P. Just a big stupid mistake. But thanks for all your efforts!!! Great community :)
You can either say const std::string& s = contentTransferEncodingToString(ENCODING_7BIT) or const std::string& s = contentTransferEncodingToString(ContentTransferEncoding::ENCODING_7BIT)
1,788,702
1,788,775
Visual Studio fails to display some watched expressions
In Visual Studio, most of my objects and variables cannot be resolved during a debugging session for various reasons. This means I cannot inspect or watch objects or their invoke their functions making it extremely difficult to debug my code because most of my expressions simply won't work. Some typical errors I get when adding an expression to the watch window include: CXX0019: Error: bad type cast CXX0059: Error: left operand is class not a function name CXX0058: Error: overloaded operator not found Most often these expressions involve overloaded operators and/or template class objects. Why is this happening? how do you fix it?
The errors you have are due to limitations in the debugger, there are not bugs as Daniel implies. The watch window cannot call overloaded operators. If you have e.g. a std::vector<int> vecSomething you cannot put vecSomething[0] into the watch window, because std::vector<int>::operator[] is an overloaded operator. Consequently, for a vector of objects, you cannot do vecObject[0].SomeMemberVariableOfObject in the watch window. You could write vecObject._Myfirst[0].SomeMemberVariableOfObject. In Visual Studio's STL implementation, _Myfirst is a member of vector pointing at the first element. If you add your own variables and types to the watch window, add watches to the data members directly. It is no problem to follow chains of pointers like member.memberStruct.ptrToObj->memberOfObj. Edit: Actually Visual Studio can call code in the Watch window: http://geekswithblogs.net/sdorman/archive/2009/02/14/visual-studio-2008-debugging-ndash-the-watch-window.aspx Thus, it is slightly mysterious why overloaded operators cannot be used.
1,789,035
1,789,150
Sending message to different thread
Is there any API to send message to a thread? Basically I have only threadId available and I want to send a custom message to that thread.
PostThreadMessage. Not very reliable though. See The Old New Thing blog here and here for details on why. Basically modal message loops make a mess of the whole idea. Since a message posted to a thread has no window handle, calling DispatchMessage will throw the message away. Any modal loop you run - directly or indirectly - will call DispatchMessage, so a good proportion of the time this strategy will fail and your message will disappear into the ether.
1,789,063
1,792,079
not able to install hooks for all threads in a process
I am hooking keyboard in application . Requirement is to hook keyboard in all threads in the process. I used SetWindowsHookEx API SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)::KeyboardHookProc, hInst, 0); The hook is created for all the threads in process. This works fine until calling thread exists .As soon as calling thread terminates hook stop working. Is there any way to hook on process rather than threads in process.
This fine print in the SDK docs for LowLevelKeyboardProc is crucial: This hook is called in the context of the thread that installed it. The call is made by sending a message to the thread that installed the hook. Therefore, the thread that installed the hook must have a message loop. In other words, you must keep the thread alive and the thread must pump a message loop. The behavior you see now is entirely by design.
1,789,195
1,789,211
How to debug a program that is terminating in an unhandled exception?
I am programming in C++ on Linux platform. My program terminates with this (unhandled???) exception: "terminate called after throwing an instance of 'long'" Aborted The code that is throwing the exception is inside try-catch block, then why should this happen?? The exception is thrown while returning from a function. I am used to C programming and have very little experience in C++ (which is the main problem). I don't know how to debug this issue. I don't expect a solution but a direction/pointer for debugging this problem. Thanks in advance.
you are probably catching the wrong exception type use catch(long) or catch(...)
1,789,320
1,789,655
How to find out if a thread has message queue?
Is there any way to find out from threadId , if a thread has message queue or not? Basically there are some windows api which only work if a thread has message queue.window
You can use PostThreadMessage with the ID of the thread. If PostThreadMessage returns false and GetLastError returns ERROR_INVALID_THREAD_ID, the thread ID is invalid or the thread does not have a message queue. More information http://msdn.microsoft.com/en-us/library/ms644946(VS.85).aspx
1,789,341
1,789,356
Can we use pthread instead of NSThread in iPhone apps
Well I have an application that uses both Objective C & c++ but for portability reasons I have tried to use c++ as much as possible.... Now I am confronted with some problem that requires threads I was thinking of using pthread instead of NSThread... is it Okay to use pthread? Will Apple punish me for using it by rejecting my app on the appstore...?
NSThread is built around pthread anyway I can't see any reason why using pthread would lead to rejection from Apple's part
1,789,421
1,790,762
NULL pointer is the same as deallocating it?
I was working on a piece of code and I was attacked by a doubt: What happens to the memory allocated to a pointer if I assign NULL to that pointer? For instance: A = new MyClass(); {...do something in the meantime...} A = NULL; The space is still allocated, but there is no reference to it. Will that space be freed later on, will it be reused, will it remain on stack, or what?
A = new MyClass(); {...do something in the meantime...} A = NULL; The way I keep track of it is that there are two separate objects. Somewhere on the heap, a MyClass instance is allocated by new. And on the stack, there is a pointer named A. A is just a pointer, there is nothing magical about out, and it doesn't have some special connection to the heap-allocated MyClass object. It just happens to point to that right now, but that can change. And on the last line, that is exactly what happens. You change the pointer to point to something else. That doesn't affect other objects. It doesn't affect the object it used to point to, and it doesn't affect the object (if any) that it is set to point to now. Again, A is just a dumb raw pointer like any other. It might be NULL, or it might point to an object on the stack, or it might point to an object on the heap, or it might be uninitialized and point to random garbage. But that's all it does. It points, it doesn't in any way take ownership of, or modify, the object it points to.
1,789,768
1,790,124
Can I change dll-interface without recompilation exe-file?
I have an abstract class in my DLL. class Base { virtual char * First() = 0; virtual char * Second() = 0; virtual char * Third() = 0; }; This dinamic library and this interface are used for a long time. There is my mistake in my code. Now I want to change this interface class Base { virtual const char * First() const = 0; virtual const char * Second() = 0; virtual char * Third() const = 0; }; Some EXE-program uses my DLL. Will the EXE-program work without recompilation? Consider changes in each line of new interface independently. Note: of course, EXE-program does not change functions results.
It "shouldn't" work, but you never know your luck. Because of overloading, char *First() and const char *First() const are different functions. You could have both in the same class. So any name-mangling scheme has to map them to different names, which obviously is a problem when it comes to binding. But, these are virtual calls, and you have three functions replaced by their equivalents in the same order. I don't know any details of MSVC's vtable scheme, in particular whether the offsets are statically determined or dynamically bound. If the former, it's possible that the exe can bind against the new vtable. The function pointers might just so happen to work, because the calling convention doesn't depend on cv-qualification (that is, a const char* is returned the same way a char* is, and const this is passed the same way non-const this is). Even if it does work, I wouldn't want to rely on it unless it's something that MS specifically addresses and guarantees.
1,789,883
1,790,061
Grab exclusively/release mouse in application (Windows, C++)
I have lost many hours trying to grab exclusively the mouse in my application and re-releasing it. Right now, I am grabbing it correctly: the mouse cursor disappears from screen and I can read its properties fine. However, I can't release it correctly! The mouse cursor reappears on screen but no other application is receiving any mouse clicks any more; except mine. Here is the problematic code : IDirectInputDevice8* mMouse; void Win32Mouse::grab(bool grab) { if (mGrabMouse == grab) return; mMouse->Unacquire(); if (grab) { // grab = true; seems to work fine coopSetting &= ~DISCL_BACKGROUND; coopSetting &= ~DISCL_NONEXCLUSIVE; coopSetting |= DISCL_FOREGROUND | DISCL_EXCLUSIVE; } else { // grab = false; this surely isn't working as it should coopSetting &= ~DISCL_FOREGROUND; coopSetting &= ~DISCL_EXCLUSIVE; coopSetting |= DISCL_BACKGROUND | DISCL_NONEXCLUSIVE; } if( FAILED(mMouse->SetCooperativeLevel(mHwnd, coopSetting)) ) { std::cout << "Failed to set coop level\n"; } HRESULT hr = mMouse->Acquire(); if (FAILED(hr) && hr != DIERR_OTHERAPPHASPRIO) { std::cout << "Failed to aquire mouse!\n"; } mGrabMouse = grab; } Could the problem be that I have Windows7?!
Possibly it because of this http://doc.51windows.net/Directx9_SDK/?url=/directx9_sdk/input/ref/ifaces/idirectinputdevice9/setcooperativelevel.htm ""An application that acquires the mouse or keyboard device in exclusive mode should always unacquire the devices when it receives WM_ENTERSIZEMOVE and WM_ENTERMENULOOP messages. Otherwise, the user cannot manipulate the menu or move and resize the window."" May be its not totally answer But try also to check if may be you not unacquire mouse on some other messeges. For example on WM_LOSTFOCUS, etc.
1,790,084
1,790,103
std::string a container
Is std::string a container class in standard c++ library, restricted to hold only char elements?
It's a typedef of std::basic_string<char>, actually. std::basic_string is a container class specifically designed for string operations. This container can be used for wide characters (wchar_t) as well; for that case its typedef would be wstring.