question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
2,949,587
2,949,655
Why are argument substitutions not replaced during rescanning?
Consider the following macro definitions and invocation: #define x x[0] #define y(arg) arg y(x) This invocation expands to x[0] (tested on Visual C++ 2010, g++ 4.1, mcpp 2.7.2, and Wave). Why? Specifically, why does it not expand to x[0][0]? During macro replacement, A parameter in the replacement list...is replaced by the corresponding argument after all macros contained therein have been expanded. Before being substituted, each argument’s preprocessing tokens are completely macro replaced (C++03 §16.3.1/1). Evaluating the macro invocation, we take the following steps: The function-like macro y is invoked with x as the argument for its arg parameter The x in the argument is macro-replaced to become x[0] The arg in the replacement list is replaced by the macro-replaced value of the argument, x[0] The replacement list after substitution of all the parameters is x[0]. After all parameters in the replacement list have been substituted, the resulting preprocessing token sequence is rescanned...for more macro names to replace (C++03 §16.3.4/1). If the name of the macro being replaced is found during this scan of the replacement list...it is not replaced. Further, if any nested replacements encounter the name of the macro being replaced, it is not replaced (C++03 §16.3.4/2). The replacement list x[0] is rescanned (note that the name of the macro being replaced is y): x is identified as an object-like macro invocation x is replaced by x[0] Replacement stops at this point because of the rule in §16.3.4/2 preventing recursion. The replacement list after rescanning is x[0][0]. I have clearly misinterpreted something since all of the preprocessors I've tested say I am wrong. In addition, this example is a piece of a larger example in the C++0x FCD (at §16.3.5/5) and it too says that the expected replacement is x[0]. Why is x not replaced during rescanning? C99 and C++0x effectively have the same wording as C++03 in the quoted sections.
I believe you've quoted the crucial paragraph, you just stopped too soon. 16.3.4/2 (emphasis mine): If the name of the macro being replaced is found during this scan of the replacement list (not including the rest of the source file’s preprocessing tokens), it is not replaced. Further, if any nested replacements encounter the name of the macro being replaced, it is not replaced. These nonreplaced macro name preprocessing tokens are no longer available for further replacement even if they are later (re)examined in contexts in which that macro name preprocessing token would otherwise have been replaced. So, when x is replaced with x[0] during the parameter substitution of y, it is fully macro replaced, meaning that it is rescanned at that point, and x is caught by the recursion rule. This means that the x in x[0] is no longer eligible for further replacement, including during the rescanning of the partly-expanded result of y(x).
2,949,833
2,949,864
List of functions references
I'm using boost::function for making references to the functions. Can I make a list of references? For example: boost::function<bool (Entity &handle)> behaviorRef; And I need in a list of such pointers. For example: std::vector<behaviorRef> listPointers; Of course it's wrong code due to behaviorRef isn't a type. So the question is: how can I store a list of pointers for the function?
typedef boost::function<bool (Entity&)> behaviorRef_type; std::vector<behaviorRef_type> listPointers;
2,949,892
2,951,795
Auto scrolling control (WinAPI)?
In C# (.Net) you can create a panel and set autoscroll to true. you can then add controls into it, including beyond it's size, then it will scroll. I was wondering if when using the real WinAPI in c++ (not .net) how one could acheive the same result. Must I keep track of the controls inside and move them all when I scroll or is there an easier way like in C#. Thanks
For an edit control (textbox), you can supply ES_AUTOVSCROLL when creating it via CreateWindow or CreateWindowEx. For adding a scrollbar for multiple controls in a window, I believe you have to do it manually. Write a function to sum the vertical height of all the child controls + spacing between them and if it's smaller than the window, add a vertical scroll bar, if it's larger, remove the vertical scroll bar (if it exists). Be sure to call this after adding/removing child controls and on window resize.
2,949,976
2,950,008
why must you provide the keyword const in operator overloads
Just curious on why a param has to be a const in operation overloading CVector& CVector::operator= (const CVector& param) { x=param.x; y=param.y; return *this; } couldn't you have easily done something like this ?? CVector& CVector::operator= (CVector& param) //no const { x=param.x; y=param.y; return *this; } Isn't when something becomes a const, it is unchangeable for the remainder of the applications life ?? How does this differ in operation overloading ???
A const parameter is const throughout the function using it, it does not change its constness outside of it. In this case you want to declare a const argument so that your assignment operator accepts both non-const variables and const variables; the latter case, in particular, includes the result of expressions, which is a temporary const variable and which you generally want to support in assignments.
2,950,029
2,950,722
What does 'unsigned temp:3' in a struct or union mean?
Possible Duplicate: What does this C++ code mean? I'm trying to map a C structure to Java using JNA. I came across something that I've never seen. The struct definition is as follows: struct op { unsigned op_type:9; //---> what does this mean? unsigned op_opt:1; unsigned op_latefree:1; unsigned op_latefreed:1; unsigned op_attached:1; unsigned op_spare:3; U8 op_flags; U8 op_private; }; You can see some variable being defined like unsigned op_attached:1 and I'm unsure what would that mean. Would that effect the number of bytes to be allocated for this particular variable?
This construct specifies the length in bits for each field. The advantage of this is that you can control the sizeof(op), if you're careful. the size of the structure will be the sum of the sizes of the fields inside. In your case, size of op is 32 bits (that is, sizeof(op) is 4). The size always gets rounded up to the next multiple of 8 for every group of unsigned xxx:yy; construct. That means: struct A { unsigned a: 4; // 4 bits unsigned b: 4; // +4 bits, same group, (4+4 is rounded to 8 bits) unsigned char c; // +8 bits }; // sizeof(A) = 2 (16 bits) struct B { unsigned a: 4; // 4 bits unsigned b: 1; // +1 bit, same group, (4+1 is rounded to 8 bits) unsigned char c; // +8 bits unsigned d: 7; // + 7 bits }; // sizeof(B) = 3 (4+1 rounded to 8 + 8 + 7 = 23, rounded to 24) I'm not sure I remember this correctly, but I think I got it right.
2,950,044
2,950,270
Work with function references
I have another one question about functions reference. For example, I have such definition: typedef boost::function<bool (Entity &handle)> behaviorRef; std::map< std::string, ptr_vector<behaviorRef> > eventAssociation; The first question is: how to insert values into such map object? I tried: eventAssociation.insert(std::pair< std::string, ptr_vector<behaviorRef> >(eventType, ptr_vector<behaviorRef>(callback))); But the error: no matching function for call to ‘boost::ptr_vector<boost::function<bool(Entity&)> >::push_back(Entity::behaviorRef&)’ And I undersatnd it, but can't make workable code. The second question is how to call such functions? For example, I have one object of behaviorRef, how to call it with boost::bind with passing my own values?
PART 1 There's no need to use a ptr_vector. boost::function has value semantics, so can be stored in a standard container. So the following should work: typedef boost::function<bool (Entity &handle)> behaviorRef; std::map< std::string, std::vector<behaviorRef> > eventAssociation; eventAssociation.insert(std::make_pair(eventType, vector<behaviorRef>(1, callback))); Note the two arguments to the vector constructor. If you did need a ptr_vector (because you were using a noncopyable type), you'd need something like the following, since ptr_vector doesn't have a constructor that populates the vector: ptr_vector<behaviorRef> behaviours; behaviours.push_back(new behaviourRef(callback)); eventAssociation.insert(std::make_pair(eventType, behaviours)); PART 2 There's no need to use boost::bind for calling the function (although you can use it to make it in the first place). The syntax for calling it is the same as for a normal function: behaviourRef behaviour; Entity entity; bool result = behaviour(entity);
2,950,194
7,760,666
QGraphicsItem repaint
I want to change text color inside a rectangle periodically. Here is my trial: TrainIdBox::TrainIdBox() { boxRect = QRectF(0,0,40,15); testPen = QPen(Qt:red); i=0; startTimer(500); } QRectF TrainIdBox::boundingRect() const { return boxRect; } void TrainIdBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { Q_UNUSED(widget); Q_UNUSED(option); painter->setPen(QPen(drawingColor,2)); painter->drawRect(boxRect); painter->setPen(testPen); painter->drawText(boxRect,Qt::AlignCenter,"TEST"); } void TrainIdBox::timerEvent(QTimerEvent *te) { testPen = i % 2 == 0 ? QPen(Qt::green) : QPen(Qt::yellow); i++; update(boxRect); } This code does not working properly. What is wrong?
If you inherit from QGraphicsObject ... I give here an example: Declare: class Text : public QGraphicsObject { Q_OBJECT public: Text(QGraphicsItem * parent = 0); void paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget ); QRectF boundingRect() const ; void timerEvent ( QTimerEvent * event ); protected: QGraphicsTextItem * item; int time; }; implementation: Text::Text(QGraphicsItem * parent) :QGraphicsObject(parent) { item = new QGraphicsTextItem(this); item->setPlainText("hello world"); setFlag(QGraphicsItem::ItemIsFocusable); time = 1000; startTimer(time); } void Text::paint ( QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget ) { item->paint(painter,option,widget); } QRectF Text::boundingRect() const { return item->boundingRect(); } void Text::timerEvent ( QTimerEvent * event ) { QString timepass = "Time :" + QString::number(time / 1000) + " seconds"; time = time + 1000; qDebug() << timepass; } good luck
2,950,260
2,952,243
Alternative to C++ exception
I'm writing a reactive software, which repeatedly recieves input, processes it and emits relevant output. The main loop looks something like: initialize(); while (true) { Message msg,out; recieve(msg); process(msg,out); //no global state is saved between loop iterations! send(out); } I want that whatever error occured during the proccess phase, whetehr it is out of memory error, logical error, invalid assertion etc, the program will clean up whatever it did, and keep running. I'll assume it is invalid input, and simply ignore it. C++'s exception are exceptionally good for that situation, I could surround process with try/catch clause, and throw exception whenever something goes wrog. The only thing I need to make sure that I clean up all my resources before throwing an exception. This could be verified by RAII, or by writing a global resource allocator (for instance, if your destructor might throw an exception), and use it exclusively for all resources. Socket s = GlobalResourceHandler.manageSocket(new Socket()); ... try { process(msg,out); catch (...) { GlobalResourceHandler.cleanUp(); } However, using exception is forbidden in our coding standard (also in Google's C++ standard BTW), as a result all the code is compiled with exceptions off, and I believe nobody's going to change the way everything work just for my design problem. Also, this is code for embedded platform, so the less C++ extra feature we use, the faster the code becomes, and the more portable it is. Is there an alternative design I can consider? update: I appreciate everyones answer about idiotic code standard. The only thing I can say is, in big organizations you have to have strict and sometimes illogical rules, to make sure no idiot would come and make your good code unmaintainable. The standard is more about people than about technicalities. Yes, bad man can make every code a mess, but it's much worse if you give him extra tools for the task. I'm still looking for a technical answer.
Coding these kind of services all day long I understand your problem. Although we do have exceptions within our code, we don't return them to the external libraries that invoke it, instead we have a simple 'tribool'. enum ReturnCode { OK = 0, // OK (there is a reason for it to be 0) KO, // An error occurred, wait for next message FATAL // A critical error occurred, reboot }; I must say FATAL is... exceptional. There isn't any code path in the application that returns it, apart from the initialization (can't do much if you're not initialized properly). C++ here brings much with RAII, since it laughs multiple paths of return off and guarantees deterministic release of the objects it holds. For the actual code checking, you can simply use some macros: // Here is the reason for OK being 0 and KO and Fatal being something else #define CHECK_RETURN(Expr) if (ReturnCode code = (Expr)) return code; #define CHECK_BREAK(Expr) if (ReturnCode code = (Expr)) \ if (KO == code) break; else return code; Then you can use them like so: CHECK_RETURN( initialize() ) while(true) { Message msg,out; CHECK_BREAK( receive(msg) ) CHECK_BREAK( process(msg,out) ) CHECK_BREAK( send(out) ) } As noted, the real bummer is about constructors. You can't have "normal" constructors with such a situation. Perhaps can you use boost::optional, if you can't, I would really suggest duplicating the functionality. Combine that with systemic factory functions in lieu of constructors and you're off to go: boost::optional<MyObject> obj = MyObject::Build(1, 2, 3); if (!obj) return KO; obj->foo(); Looks much like a pointer, except that it's stack allocated and thus involves near zero overhead.
2,950,332
2,950,358
Why does a C-Array have a wrong sizeof() value when it's passed to a function?
Complete example: #include <stdio.h> void test(int arr[]) { int arrSize = (int)(sizeof(arr) / sizeof(arr[0])); printf("%d\n", arrSize); // 2 (wrong?!) } int main (int argc, const char * argv[]) { int point[3] = {50, 30, 12}; int arrSize = (int)(sizeof(point) / sizeof(point[0])); printf("%d\n", arrSize); // 3 (correct :-) ) test(point); return 0; } Before passing it to a function, sizeof gives me the correct value. Doing the exact same thing on the exact same array in the function gives weird results. There's one element missing. Why?
When you pass an array into a function in C, the array decays into a pointer to its first element. When you use sizeof on the parameter, you are taking the size of the pointer, not the array itself. If you need the function to know the size of the array, you should pass it as a separate parameter: void test(int arr[], size_t elems) { /* ... */ } int main(int argc, const char * argv[]) { int point[3] = {50, 30, 12}; /* ... */ test(point, sizeof(point)/sizeof(point[0])); /* ... */ } Also note that, for a similar reason (taking the sizeof a pointer), the sizeof(point)/sizeof(point[0]) trick doesn't work for a dynamically allocated array, only an array allocated on the stack.
2,950,501
2,950,518
Iterating through std queue
I'm trying to use BOOST_FOREACH for iterating through the std::queue. But there isn't iterators in that class cause I have an error: std::queue<std::string> someList; BOOST_FOREACH(std::string temp, someList) { std::cout << temp; } >no matching function for call to begin(...) >no type named ‘iterator’ in ‘class std::queue<std::basic_string<char> >’ I need in structure like: the first comes, the first goes away.
std::deque supports efficient insert and removal at the beginning and end of the data structure. You can do queue operations manually using push_back and pop_front. A queue uses a deque internally by default. It's a wrapper that only exposes queue operations (hence why you can't iterate over it). I asked a similar question a while back, and the best answer gave me good insight into the real use of std::queue. One should use std::queue not because one needs a queue, but to make it clear that only queue-like operations are legal on a given data structure. It sounds like you need more freedom than that, so go with deque, list, or some other structure with O(1) insert and remove at both ends.
2,950,512
2,950,560
In C++, I want to implement a ring iterator for a deque that contains a personally defined class
I have a function of a "Table" class that should add a player to the table. I decided that if the seat is taken, the function should try and go through all the seats and add the player to the next available seat. How do I implement this in my addPlayer function? int Table::addPlayer(Player player, int position) { deque<Player>::iterator it; if(playerList[position] != "(empty seat)") { //What goes here? } playerList.put(player,it); cout >> "Player " >> player.toString >> " sits at position " >> position >> endl; }
Instead of using position, use the iterator to point to that position, using something like this: it = playerList.begin() + position; Then, check if the seat is taken using the iterator. If the seat is taken, increment the iterator, but check for end, like this: while (no empty seat found yet) { ++it; if (it==playerList.end()) it = playerList.begin(); } Of course, if all seats have been taken, this will result in an endless loop. Therefore, also keep the iterator you started from (let's call this itStart), and add a check on it: while (no empty seat found yet) { ++it; if (it==playerList.end()) it = playerList.begin(); if (it==itStart) break; // We tried all seats }
2,950,573
2,950,605
MSXML problem in VC++ 6
I have this bit of code: typedef CComQIPtr<MSXML::IXMLDOMDocument2> XML_DocumentPtr; then inside some class: XML_DocumentPtr m_spDoc; then inside some function: XML_NodePtr rn=m_spDoc->GetdocumentElement(); I cannot find anywhere in the MSDN documentation what that GetDocumentElement() is supposed to do? Can anyone tell me why it doesn't seem to be part of IXMLDOMDocument2 interface? And which interface does have it?
IXMLDocument2 inherits from IXMLDocument. The GetDocumentElement() method is defined in that interface. See here. Basically GetdocumentElement returns the root element of the XML document. The property is read/write. It returns an IXMLDOMElement that represents the single element that represents the root of the XML document tree. It returns Null if no root exists. When setting the documentElement property, the specified element node is inserted into the child list of the document after any document type node. To precisely place the node within the children of the document, call the insertBefore method of theIXMLDOMNode. The parentNode property is reset to the document node as a result of this operation.
2,950,639
2,950,851
printing 2d table (headers)
Is there are a better way than this one to print 2d table? std::cout << std::setw(25) << left << "FF.name" << std::setw(25) << left << "BB.name" << std::setw(12) << left << "sw.cycles" << std::setw(12) << left << "hw.cycles" << "\n" << std::setw(25) << left << "------" << std::setw(25) << left << "------" << std::setw(12) << left << "---------" << std::setw(12) << left << "---------" << "\n";
You could put the headers into an array or vector, then generate the correct widths automatically: boost::array<std::string, 4> head = { ... } BOOST_FOREACH(std::string& s, head) { int w = 5*(s.length()/5 + 1); std::cout << std::setw(w) << left << s; } std::cout << '\n'; BOOST_FOREACH(std::string& s, head) { int w = 5*(s.length()/5 + 1); std::cout << std::string(w,'-'); } std::cout << std::endl; Might be worthwhile if you have lots of headers I guess.
2,950,811
2,950,920
C++ linker unresolved external symbol (again;) from other source file *.obj file. (VC++ express)
I'm back to C/C++ after some break. I've a following problem: I've a solution where I've several projects (compilable and linkable). Now I need to add another project to this solution which depends on some sources from other projects. My new project compiles without any problems (I've added "existing sources" to my project). the error: 1>Linking... 1>LicenceManager.obj : error LNK2019: unresolved external symbol "int __cdecl saveLic(char *,struct Auth *)" (?saveLic@@YAHPADPAUAuth@@@Z) referenced in function "public: void __thiscall LicenceManager::generateLicence(int,char *)" (?generateLicence@LicenceManager@@QAEXHPAD@Z) 1>LicenceManager.obj : error LNK2019: unresolved external symbol "void __cdecl getSysInfo(struct Auth *)" (?getSysInfo@@YAXPAUAuth@@@Z) referenced in function "public: void __thiscall LicenceManager::generateLicence(int,char *)" (?generateLicence@LicenceManager@@QAEXHPAD@Z) Functions saveLic, and getSysInfo are defined in files which I've added to my new project from existing ones. There is object file created during compilation with those functions in target dir, but my LicenceManager class doesn't want to link. I use some extern "C" , and #pragma pack somewhere, but no more fancy stuff. I think every directory, lib and other necessary dependencies are visible in settings for this project. Thanks for any advice.
Seems like you need to make sure the functions are declared properly as C functions: #ifdef __cplusplus extern "C" { #endif int saveLic(char *,struct Auth *); void getSysInfo(struct Auth *); #ifdef __cplusplus } #endif In a header file included by LicenceManager.cpp.
2,950,863
2,951,354
How to prevent removal of slots from a certain signal?
Is it possible to block the removal of certain slots from a signal in the boost.signals library? If so how should a code that does such a thing will look like? Do I need to create a derived class just for that specific signal to do so?
Supply your own slot connection function that fails to return the connection. Without the connection the client can't break it. Edit: code example: struct my_class { boost::signals::connection listen_event1(boost::function<void (my_class const&)> const& f) { return signal1.connect(f); } void listen_event2(boost::function<void my_class const&)> const& f) { signal2.connect(f); } private: typedef boost::signals::signal<void(my_class const&)> sig_t; sig_t signal1; sig_t signal2; }; signal2 connections cannot be disconnected.
2,951,117
2,951,138
How to manage member variable in C++
In brief, my question is about member variables as pointers in unmanaged C++. In java or c#, we have "advanced pointer". In fact, we can't aware the "pointer" in them. We usually initialize the member of a class like this: member = new Member(); or member = null; But in c++, it becomes more confusing. I have seen many styles: using new, or leave the member variable in stack. In my point of view, using boost::shared_ptr seems friendly, but in boost itself source code there are news everywhere. It's the matter of efficiency,isn't it? Is there a guildline like "try your best to avoid new" or something? EDIT I realize it's not proper to say "leave them in stack", here's a more proper way to say: when i need an object to be my member variable, should i prefer a object than a object*?
The Boost source code is not a good example for how you should write your source code. The Boost libraries are designed to wrap up all the tedious, difficult, and error-prone code so that you don't have to worry about it in your code. Your best bet is to follow two general rules in your code: Don't use pointers where you don't need to use pointers Where you do need to use pointers, use smart pointers (like shared_ptr or scoped_ptr)
2,951,273
2,951,294
pure-specifier on function-definition
While compiling on GCC I get the error: pure-specifier on function-definition, but not when I compile the same code using VS2005. class Dummy { //error: pure-specifier on function-definition, VS2005 compiles virtual void Process() = 0 {}; }; But when the definition of this pure virtual function is not inline, it works: class Dummy { virtual void Process() = 0; }; void Dummy::Process() {} //compiles on both GCC and VS2005 What does the error means? Why cannot I do it inline? Is it legal to evade the compile issue as shown in the second code sample?
Ok, I've just learned something. A pure virtual function must be declared as follows: class Abstract { public: virtual void pure_virtual() = 0; }; It may have a body, although it is illegal to include it at the point of declaration. This means that to have a body the pure virtual function must be defined outside the class. Note that even if it has a body, the function must still be overridden by any concrete classes derived from Abstract. They would just have an option to call Abstract::pure_virtual() explicitly if they need to. The details are here.
2,951,361
2,951,386
Can multiple threads access a vector at different places?
Lets say I have a vector of int which I've prefilled with 100 elements with a value of 0. Then I create 2 threads and tell the first thread to fill elements 0 to 49 with numbers, then tell thread 2 to fill elements 50 to 99 with numbers. Can this be done? Otherwise, what's the best way of achieving this? Thanks
Yes, this should be fine. As long as you can guarantee that different threads won't modify the same memory location, there's no problem.
2,951,388
2,951,426
Encrypting a file in win API
hi I have to write a windows api code that encrypts a file by adding three to each character. so I wrote this now its not doing anything ... where i go wronge #include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { HANDLE filein,fileout; filein=CreateFile (L"d:\\test.txt",GENERIC_READ,0,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); fileout=CreateFile (L"d:\\test.txt",GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL); DWORD really; //later this will be used to store how many bytes I succeed to read do { BYTE x[1024]; //the buffer the thing Im using to read in ReadFile(filein,x,1024,&really,NULL); for(int i=0 ; i<really ; i++) { x[i]= (x[i]+3) % 256; } DWORD really2; WriteFile(fileout,x,really,&really2,NULL); }while(really==1024); CloseHandle(filein); CloseHandle(fileout); return 0; } and if Im right how can i know its ok
First, you can't overwrite a file that's in use. You will need to use different pathnames for your input and output, and then rename files at the end.
2,951,464
2,951,496
Byte from string/int in C++
I'm a beginning user in C++ and I want to know how to do this: How can I 'create' a byte from a string/int. So for example I've: string some_byte = "202"; When I would save that byte to a file, I want that the file is 1 byte instead of 3 bytes. How is that possible? Thanks in advance, Tim
I would use C++'s String Stream class <sstream> to convert the string to an unsigned char. And write the unsigned char to a binary file. so something like [not real code] std::string some_byte = "202"; std::istringstream str(some_byte); int val; if( !(str >> val)) { // bad conversion } if(val > 255) { // too big } unsigned char ch = static_cast<unsigned char>(val); printByteToFile(ch); //print the byte to file.
2,951,472
2,962,040
MySql UDF using shared library won't load
I am attempting to create a mysql UDF which will match a fingerprint using Digital Persona's free linux SDK library. I have written a trivial UDF as a learning experience which worked fine. However, when I added a dependency to Digital Persona's shared object I can no longer get MySql to load my UDF. I added includes to DP's headers and compiled my UDF using: gcc -fPIC -Wall -I/usr/src/mysql-5.0.45-linux-i686-icc-glibc23/include -shared -o dp_udf.so dp_udf.cc I also tried adding the -static argument, but whenever I restart MySql, I get the error: Can't open shared library 'dp_udf.so' (errno: 0 /usr/local/mysql/lib/plugin/dp_udf.so: undefined symbol: MC_verifyFeaturesEx) MC_verifyFeaturesEx is a function defined "dpMatch.h" which I included, and is implemented in libdpfpapi.so which I have tried placing in the same location as my dp_udf.so and in /usr/lib. Am I doing something wrong with my call to gcc (my C++ skills are rusty) or does MySql not allow UDFs to use additional shared objects?
Your problem is that your library depends on another, bu MySQL/dl doesn't know this and therefore doesn't load it. You need to explicitly link your library against Digital Persona's library. You can do this by using the -l{libname} (and maybe -L/lib/path).
2,951,541
2,951,743
How to generate RSA-SHA256 digital signature with OpenSSL libraries?
I need to generate a digital signature from C++ code, using OpenSSL libraries. I understood that I need for that DSA \ DSA_do_sign, but didn't understand how exactly to use it. Does someone have an example for that, or a reference for better than OpenSSL's supplied docs? Thanks in advance!
You seem to have RSA and DSA confused. However, if you want to sign using RSA-sha256, then use the EVP interface for signing. You can initialize with the EVP_SignInit_ex() method with EVP_sha256() for the type argument.
2,951,576
2,951,662
int ** vs int [ROWS][COLS]
Possible Duplicate: casting char[][] to char** causes segfault? I have a 2D array declared like this: int arr[2][2]={ {1,2},{3,4}}; Now if I do: int ** ptr=(int**) arr; and: cout<<**ptr; I am getting a segmentation fault (using g++-4.0). Why so? Shouldn't it be printing the value 1 (equal to arr[0][0])?
You are attempting to assign a double pointer variable to an array... this has been covered exhaustively, see here for information on this. Furthermore, since you declared int arr[2][2] = ...; and then try to assign arr to a double pointer int ** ptr = ... ; which is guaranteed to not work, hence a segmentation fault. Furthermore, that statement int ** ptr=(int**) arr; is actually cast ing one type (i.e. [][]) to another type (i.e. **) despite they are of type 'int'. They are both different and the compiler will interpret that very differently... You could do it this way: int *ptr = &arr; Now *(ptr + 1) will refer to the 0'th row, *(ptr + 2) will refer to the 1'st row and so on. The only onus on you is to not overstep the markers of where arr is used otherwise an overflow can happen or even a segmentation fault...
2,951,586
2,951,700
Default Struct Initialization in C++
Say I have a struct that looks like this (a POD): struct Foo { int i; double d; }; What are the differences between the following two lines: Foo* f1 = new Foo; Foo* f2 = new Foo();
The first one leaves the values uninitialised; the second initialises them to zero. This is only the case for POD types, which have no constructors.
2,951,605
2,951,653
How to pass function reference into arguments
I'm using boost::function for making function-references: typedef boost::function<void (SomeClass &handle)> Ref; someFunc(Ref &pointer) {/*...*/} void Foo(SomeClass &handle) {/*...*/} What is the best way to pass Foo into the someFunc? I tried something like: someFunc(Ref(Foo));
In order to pass a temporary object to the function, it must take the argument either by value or by constant reference. Non-constant references to temporary objects aren't allowed. So either of the following should work: void someFunc(const Ref&); someFunc(Ref(Foo)); // OK, constant reference to temporary void someFunc(Ref); someFunc(Ref(Foo)); // OK, copy of temporary void someFunc(Ref&); someFunc(Ref(Foo)); // Invalid, non-constant reference to temporary Ref ref(Foo); someFunc(ref); // OK, non-constant reference to named object By the way, calling the type Ref and the instance pointer when it's neither a reference nor a pointer could be a bit confusing.
2,951,703
2,952,730
Working with sockets in MFC
I'm trying to make a MFC application(client) that connects to a server on ("localhost",port 1234), the server replies to the client and the client reads from the server's response. The server is able to receive the data from the client and it sends the reply back to the socket from where it received it, but I am unable to read the reply from within the client. I am making a CAsyncSocket to connect to the server and send data and a CAsyncSocket with overloaded methods onAccet and onReceive to read the reply from the server. Please tell me what I'm doing wrong. class ServerSocket:public CAsyncSocket{ public: void OnAccept(int nErrorCode){ outputBox->SetWindowTextA("RECEIVED DATA"); CAsyncSocket::OnAccept(nErrorCode); } }; //in ApplicationDlg I have: socket.Create(); socket.Connect("127.0.0.1",1234); socket.Send(temp,strlen(temp)); //this should be sending the initial message if(!serverSocket.Create()) //this should get the response i guess... AfxMessageBox("Could not create server socket"); if(!serverSocket.Listen()) AfxMessageBox("Could not listen to socket");
You should be aware that all network operations are potentially time-consuming operations. Now, since you're using MFC's CAsyncSocket class, it performs all the operations asynchronously (doesn't block you). But return from the function doesn't mean it's already completed. Let's look at the following lines of code: socket.Connect("127.0.0.1",1234); socket.Send(temp,strlen(temp)); //this should be sending the initial message The first is the call to Connect, which most probably doesn't complete immediately. Next, you call Send, but your socket isn't connected yet! It definitely returns you an error code, but since you don't bother checking its return value - you just happily wait to receive something. So, the next rule for you, my friend, should be checking every return value for every function that you call, especially when it comes to networking where errors are legitimate and happen frequently. You should only start sending after OnConnect has been called.
2,951,773
2,957,543
How to construct objects based on XML code?
I have XML files that are representation of a portion of HTML code. Those XML files also have widget declarations. Example XML file: <message id="msg"> <p> <Widget name="foo" type="SomeComplexWidget" attribute="value"> inner text here, sets another attribute or inserts another widget to the tree if needed... </Widget> </p> </message> I have a main Widget class that all of my widgets inherit from. The question is how would I create it? Here are my options: Create a compile time tool that will parse the XML file and create the necessary code to bind the widgets to the needed objects. Advantages: No extra run-time overhead induced to the system. It's easy to bind setters. Disadvantages: Adds another step to the build chain. Hard to maintain as every widget in the system should be added to the parser. Use of macros to bind the widgets. Complex code Find a method to register all widgets into a factory automatically. Advantages: All of the binding is done completely automatically. Easier to maintain then option 1 as every new widget will only need to call a WidgetFactory method that registers it. Disadvantages: No idea how to bind setters without introducing a maintainability nightmare. Adds memory and run-time overhead. Complex code What do you think is better? Can you guys suggest a better solution?
Create the tool, include it into your build steps and everything will be fine. See comments to my previous answer for additional details.
2,951,780
2,951,933
How do I compile variadic templates conditionally?
Is there a macro that tells me whether or not my compiler supports variadic templates? #ifdef VARIADIC_TEMPLATES_AVAILABLE template<typename... Args> void coolstuff(Args&&... args); #else ??? #endif If they are not supported, I guess I would simulate them with a bunch of overloads. Any better ideas? Maybe there are preprocessor libraries that can ease the job?
It looks like the current version of Boost defines BOOST_NO_VARIADIC_TEMPLATES if variadic templates are unavailable. This is provided by boost/config.hpp; see here for config.hpp documentation. If variadic templates are unavailable, then you'll probably have to simulate them with a bunch of overloads, as you said. The Boost.Preprocessor library can help here; it's designed to automate all sorts of repetitive source code, including template overloads. You can search the Boost source trees for BOOST_NO_VARIADIC_TEMPLATES for examples on using it to simulate variadic templates.
2,952,216
2,952,398
delegating into private parts
Sometimes, C++'s notion of privacy just baffles me :-) class Foo { struct Bar; Bar* p; public: Bar* operator->() const { return p; } }; struct Foo::Bar { void baz() { std::cout << "inside baz\n"; } }; int main() { Foo::Bar b; // error: 'struct Foo::Bar' is private within this context Foo f; f->baz(); // fine } Since Foo::Bar is private, I cannot declare b in main. Yet I can call methods from Foo::Bar just fine. Why the hell is this allowed? Was that an accident or by design? Oh wait, it gets better: Foo f; auto x = f.operator->(); // :-) x->baz(); Even though I am not allowed to name the type Foo::Bar, it works just fine with auto... Noah wrote: type names defined within a class definition cannot be used outside their class without qualification. Just for fun, here is how you can get at the type from outside: #include <type_traits> const Foo some_foo(); typedef typename std::remove_pointer<decltype( some_foo().operator->() )>::type Foo_Bar;
Trying to find anything in the standard that would spell it out in detail but I can't. The only thing I can find is 9.9: Type names obey exactly the same scope rules as other names. In particular, type names defined within a class definition cannot be used outside their class without qualification. Essentially, the name of Foo::Bar is private to Foo, not the definition. Thus you can use Bars outside of Foo, you just can't refer to them by type since that name is private. The name lookup rules for members would also seem to have some effect on this. I don't see anything that specifically references "nested class" and thus they wouldn't be allowed to (if my lack of finding anything in fact is because it's not there).
2,952,407
2,952,636
Sorting 1000-2000 elements with many cache misses
I have an array of 1000-2000 elements which are pointers to objects. I want to keep my array sorted and obviously I want to do this as quick as possible. They are sorted by a member and not allocated contiguously so assume a cache miss whenever I access the sort-by member. Currently I'm sorting on-demand rather than on-add, but because of the cache misses and [presumably] non-inlining of the member access the inner loop of my quick sort is slow. I'm doing tests and trying things now, (and see what the actual bottleneck is) but can anyone recommend a good alternative to speeding this up? Should I do an insert-sort instead of quicksorting on-demand, or should I try and change my model to make the elements contigious and reduce cache misses? OR, is there a sort algorithm I've not come accross which is good for data that is going to cache miss? Edit: Maybe I worded this wrong :), I don't actually need my array sorted all the time (I'm not iterating through them sequentially for anything) I just need it sorted when I'm doing a binary chop to find a matching object, and doing that quicksort at that time (when I want to search) is currently my bottleneck, because of the cache misses and jumps (I'm using a < operator on my object, but I'm hoping that inlines in release)
Simple approach: insertion sort on every insert. Since your elements are not aligned in memory I'm guessing linked list. If so, then you could transform it into a linked list with jumps to the 10th element, the 100th and so on. This is kind of similar to the next suggestion. Or you reorganize your container structure into a binary tree (or what every tree you like, B, B*, red-black, ...) and insert elements like you would insert them into a search tree.
2,952,631
2,952,665
format specifier for short integer
I don't use correctly the format specifiers in C. A few lines of code: int main() { char dest[]="stack"; unsigned short val = 500; char c = 'a'; char* final = (char*) malloc(strlen(dest) + 6); snprintf(final, strlen(dest)+6, "%c%c%hd%c%c%s", c, c, val, c, c, dest); printf("%s\n", final); return 0; } What I want is to copy at final [0] = a random char final [1] = a random char final [2] and final [3] = the short array final [4] = another char .... My problem is that i want to copy the two bytes of the short int to 2 bytes of the final array. thanks.
I'm confused - the problem is that you are saying strlen(dest)+6 which limits the length of the final string to 10 chars (plus a null terminator). If you say strlen(dest)+8 then there will be enough space for the full string. Update Even though a short may only be 2 bytes in size, when it is printed as a string each character will take up a byte. So that means it can require up to 5 bytes of space to write a short to a string, if you are writing a number above 10000. Now, if you write the short to a string as a hexadecimal number using the %x format specifier, it will take up no more than 2 bytes.
2,952,706
2,954,182
OpenGL Vertex Buffer Object code giving bad output
My Vertex Buffer Object code is supposed to render textures nicely but instead the textures are being rendered oddly with some triangle shapes. What happens - http://godofgod.co.uk/my_files/wrong.png What is supposed to happen - http://godofgod.co.uk/my_files/right.png This function creates the VBO and sets the vertex and texture coordinate data: extern "C" GLuint create_box_vbo(GLdouble size[2]){ GLuint vbo; glGenBuffers(1,&vbo); glBindBuffer(GL_ARRAY_BUFFER, vbo); GLsizeiptr data_size = 8*sizeof(GLdouble); GLdouble vertices[] = {0,0, 0,size[1], size[0],0, size[0],size[1]}; glBufferData(GL_ARRAY_BUFFER, data_size, vertices, GL_STATIC_DRAW); data_size = 8*sizeof(GLint); GLint textcoords[] = {0,0, 0,1, 1,0, 1,1}; glBufferData(GL_ARRAY_BUFFER, data_size, textcoords, GL_STATIC_DRAW); return vbo; } Here is some relavant code from another function which is supposed to draw the textures with the VBO. glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glColor4d(1,1,1,a/255); glBindTexture(GL_TEXTURE_2D, texture); glTranslated(offset[0],offset[1],0); glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexPointer(2, GL_DOUBLE, 0, 0); glEnableClientState(GL_VERTEX_ARRAY); glTexCoordPointer (2, GL_INT, 0, 0); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glDrawArrays(GL_TRIANGLES, 0, 3); glDrawArrays(GL_TRIANGLES, 1, 3); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisableClientState(GL_VERTEX_ARRAY); glBindBuffer(GL_ARRAY_BUFFER, 0); I would have hoped for the code to use the first three coordinates (top-left,bottom-left,top-right) and the last three (bottom-left,top-right,bottom-right) to draw the triangles with the texture data correctly in the most efficient way. I don't see why triangles should make it more efficient but apparently that's the way to go. It, of-course, fails for some reason. I am asking what is broken but also am I going about it in the right way generally? Thank you.
If you want to use the one VBO for both vertex and texture coordinates you need to group them using a struct. Define your data: typedef struct { GLdouble x, y; GLint s, t; } VertexData; VertexData data[] = { // x y s t {0.0, 0.0, 0, 0}, {0.0, size[1], 0, 1}, {size[0], 0.0, 1, 0}, {size[0], size[1], 1, 1} }; Copy it into VBO: glBindBuffer(GL_ARRAY_BUFFER, vbo); glBufferData(GL_ARRAY_BUFFER, sizeof(data), (GLvoid*)data, GL_STATIC_DRAW); Set pointers. Note that stride is your struct's size and pointer itself serves as offset: glBindBuffer(GL_ARRAY_BUFFER, vbo); glVertexPointer(2, GL_DOUBLE, sizeof(VertexData), (GLvoid*)offsetof(VertexData, x)); glTexCoordPointer(2, GL_INT, sizeof(VertexData), (GLvoid*)offsetof(VertexData, s)); glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); And draw. EDIT: Implemented offset with offsetof() as Bahbar suggested.
2,952,707
2,952,744
Heap Behavior in C++
Is there anything wrong with the optimization of overloading the global operator new to round up all allocations to the next power of two? Theoretically, this would lower fragmentation at the cost of higher worst-case memory consumption, but does the OS already have redundant behavior with this technique, or does it do its best to conserve memory? Basically, given that memory usage isn't as much of an issue as performance, should I do this?
The default memory allocator is probably quite smart and will deal well with large numbers of small to medium sized objects, as this is the most common case. For all allocators, the number of bytes requested is never always the amount allocated. For example, if you say: char * p = new char[3]; the allocator almost certainly does something like: char * p = new char[16]; // or some minimum power of 2 block size Unless you can demonstrate that you have an actual problem with allocations, you should not consider writing your own version of new.
2,952,715
2,952,791
Any problems with this C++ const reference accessor interface idiom?
I was converting a struct to a class so I could enforce a setter interface for my variables. I did not want to change all of the instances where the variable was read, though. So I converted this: struct foo_t { int x; float y; }; to this: class foo_t { int _x; float _y; public: foot_t() : x(_x), y(_y) { set(0, 0.0); } const int &x; const float &y; set(int x, float y) { _x = x; _y = y; } }; I'm interested in this because it seems to model C#'s idea of public read-only properties. Compiles fine, and I haven't seen any problems yet. Besides the boilerplate of associating the const references in the constructor, what are the downsides to this method? Any strange aliasing issues? Why haven't I seen this idiom before?
There is an aliasing issue in that because you expose a reference to the foo_t's internal data, it's possible for code external to a foo_t object to hold on to references into its data beyond the object's lifetime. Consider: foo_t* f = new foo_t(); const int& x2 = f->x; delete f; std::cout << x2; // Undefined behavior; x2 refers into a foo_t object that was deleted Or, even simpler: const int& x2 = foo_t().x; std::cout << x2; // Undefined behvior; x2 refers into a foo_t object that no longer exists These aren't particularly realistic examples, but this is a potential issue whenever an object exposes or returns a reference to its data (public or private). Of course, it's just as possible to hold on to a reference to the foo_t object itself beyond its lifetime, but that might be harder to miss or to do by accident. Not that this is an argument against what you're doing. In fact I've used this pattern before (for a different reason) and I don't think there's anything inherently wrong with it, aside from the lack of encapsulation, which you seem to recognize. The above issue is just something to be aware of.
2,952,755
2,952,775
Trouble assigning a tr1::shared_ptr
I've got a class that has a tr1::shared_ptr as a member, like so: class Foo { std::tr1::shared_ptr<TCODBsp> bsp; void Bar(); } In member function Bar, I try to assign it like this: bsp = newTCODBsp(x,y,w,h); g++ then gives me this error no match for ‘operator=’ in ‘((yarl::mapGen::MapGenerator*)this)->yarl::mapGen::MapGenerator::bsp = (operator new(40u), (<statement>, ((TCODBsp*)<anonymous>)))’ /usr/include/c++/4.4/tr1/shared_ptr.h:834: note: candidates are: std::tr1::shared_ptr<TCODBsp>& std::tr1::shared_ptr<TCODBsp>::operator=(const std::tr1::shared_ptr<TCODBsp>&) in my code, Foo is actually yarl::mapGen::MapGenerator. What am I doing wrong?
call .reset(new TCODBsp) or say bsp = std::tr1::shared_ptr(new TCODBsp). Shared pointers are explicit. You can't just assign the ptr type to them.
2,952,895
2,952,932
copying a short int to a char array
I have a short integer variable called s_int that holds value = 2 unsighed short s_int = 2; I want to copy this number to a char array to the first and second position of a char array. Let's say we have char buffer[10];. We want the two bytes of s_int to be copied at buffer[0] and buffer[1]. How can I do it?
The usual way to do this would be with the bitwise operators to slice and dice it, a byte at a time: b[0] = si & 0xff; b[1] = (si >> 8) & 0xff; though this should really be done into an unsigned char, not a plain char as they are signed on most systems. Storing larger integers can be done in a similar way, or with a loop.
2,953,086
2,953,113
subscript requires array or pointer ERROR
I know what is my mistake can't figer how to solve it. Im writing an winAPI that counts how many 'a' characters are found is a givien file. Im still getting the error " subscript requires array or pointer " (please find the comment in the code) #include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { WCHAR str=L'a'; HANDLE A; TCHAR *fn; fn=L"d:\\test.txt"; A= CreateFile(fn,GENERIC_READ,0,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL); if(A==INVALID_HANDLE_VALUE) { _tprintf(L"cannot open file \n"); } else { DWORD really; int countletter; int stringsize; do { BYTE x[1024]; ReadFile(A,x,1024,&really,NULL); stringsize = sizeof(really); for(int i =0;i<stringsize;i++) { if(really[i]==str) //here Im getting the error countletter++; } }while(really==1024); CloseHandle(A); _tprintf(L"NUmbers of A's found is %d \n",countletter); } return 0; } now I know I can't make comparesion between array and a WCHAR but hw to fix it ?
ReadFile() puts the data into the second parameter, in your case x. In your code, really is the number of bytes read. It's just a number. You can't put an subscript on a plain number, thus the error message. So change if(really[i]==str) To if (x[i] == str) But you're going to hit another problem: DWORD really; int countletter; int stringsize; do { BYTE x[1024]; bool bResult = ReadFile(A, x, 1024, &really, NULL); // must save the result if (bResult) break; // Error! // stringsize = sizeof(really); // <== NO NO NO will always return 8 stringsize = really; // this is what you need for (int i = 0; i < stringsize; i++) { if(x[i] == str) countletter++; } } while (really == 1024); You'll need some error handling of course, and you really need meaningful variable names. Your problem would have been obvious if you had used inputBuffer and bytesRead instead of x and really. Edited to add: Your comment is correct, my previous edit went too far. It's true that the next-to-last read should return 1024 bytes, while the last will return < 1024. But I would still check for bytesRead == 0 right after the read, because it's easier to understand.
2,953,111
2,953,244
Start Windows GUI Application Development With C++
I'm looking into creating a GUI program for Windows in C++, I have a good knowledge of C++ in the command line and also in game creation. But I'm not sure where to start with GUI application development. I have Visual Studio 2010 and have created new projects with a GUI but these templates are complex and leaves me not understanding whats happening and how to modify it. So I'm asking where do I start? Preferably good websites that you can recommend or tutorials, rather than books being a poor student :)
Having written Windows code since Win2.0, I have to say: start with C#. It's a very easy language to learn after C++, and many of the new features (like built-in event handling) were put there to make writing GUI applications easier. Then, once you're used to the basic concepts of window management and messaging, then drop down into C++. I say this for the same reason that assembly is not a good first language. There is an enormous amount of housekeeping code in a Windows application, and in C++ you see it all. Better to use a language that hides much of it until you're grounded.
2,953,230
2,954,487
More elegant way to make a C++ member function change different member variables based on template parameter?
Today, I wrote some code that needed to add elements to different container variables depending on the type of a template parameter. I solved it by writing a friend helper class specialized on its own template parameter which had a member variable of the original class. It saved me a few hundred lines of repeating myself without adding much complexity. However, it seemed kludgey. I would like to know if there is a better, more elegant way. The code below is a greatly simplified example illustrating the problem and my solution. It compiles in g++. #include <vector> #include <algorithm> #include <iostream> namespace myNS{ template<class Elt> struct Container{ std::vector<Elt> contents; template<class Iter> void set(Iter begin, Iter end){ contents.erase(contents.begin(), contents.end()); std::copy(begin, end, back_inserter(contents)); } }; struct User; namespace WkNS{ template<class Elt> struct Worker{ User& u; Worker(User& u):u(u){} template<class Iter> void set(Iter begin, Iter end); }; }; struct F{ int x; explicit F(int x):x(x){} }; struct G{ double x; explicit G(double x):x(x){} }; struct User{ Container<F> a; Container<G> b; template<class Elt> void doIt(Elt x, Elt y){ std::vector<Elt> v; v.push_back(x); v.push_back(y); Worker<Elt>(*this).set(v.begin(), v.end()); } }; namespace WkNS{ template<class Elt> template<class Iter> void Worker<Elt>::set(Iter begin, Iter end){ std::cout << "Set a." << std::endl; u.a.set(begin, end); } template<> template<class Iter> void Worker<G>::set(Iter begin, Iter end){ std::cout << "Set b." << std::endl; u.b.set(begin, end); } }; }; int main(){ using myNS::F; using myNS::G; myNS::User u; u.doIt(F(1),F(2)); u.doIt(G(3),G(4)); } User is the class I was writing. Worker is my helper class. I have it in its own namespace because I don't want it causing trouble outside myNS. Container is a container class whose definition I don't want to modify, but is used by User in its instance variables. doIt<F> should modify a. doIt<G> should modify b. F and G are open to limited modification if that would produce a more elegant solution. (As an example of one such modification, in the real application F's constructor takes a dummy parameter to make it look like G's constructor and save me from repeating myself.) In the real code, Worker is a friend of User and member variables are private. To make the example simpler to write, I made everything public. However, a solution that requires things to be public really doesn't answer my question. Given all these caveats, is there a better way to write User::doIt?
After reading Emile Cormier's comment, I thought of a way to both keep from repeating myself and to also eliminate the Worker class: make two trivial non-template doIt functions for F and G and have each call a third templated doIt function with the variable to change passed as a parameter. Here is the modified code. #include <vector> #include <algorithm> #include <iostream> namespace myNS{ template<class Elt> struct Container{ std::vector<Elt> contents; template<class Iter> void set(Iter begin, Iter end){ contents.erase(contents.begin(), contents.end()); std::copy(begin, end, back_inserter(contents)); } }; struct F{ int x; explicit F(int x):x(x){} }; struct G{ double x; explicit G(double x):x(x){} }; struct User{ Container<F> a; Container<G> b; template<class Elt> void doIt(Elt x, Elt y, Container<Elt>& cont, const char*name){ std::vector<Elt> v; v.push_back(x); v.push_back(y); cont.set(v.begin(), v.end()); std::cout << "Set " << name << std::endl; } void doIt(F x, F y){ doIt(x,y,a,"a"); } void doIt(G x, G y){ doIt(x,y,b,"b"); } }; } int main(){ using myNS::F; using myNS::G; myNS::User u; u.doIt(F(1),F(2)); u.doIt(G(3),G(4)); }
2,953,251
2,953,685
Is it safe to make GL calls with multiple threads?
I was wondering if it was safe to make GL calls with multiple threads. Basically I'm using a GLUtesselator and was wondering if I could divide the objects to draw into 4 and assign a thread to each one. I'm just wondering if this would cause trouble since the tesselator uses callback functions. Can 2 threads run the same callback at the same time as long as that callback does not access ant global variables? Are there also other ways I could optimize OpenGL drawing using multithreading?
The answer to "Can 2 threads run the same callback at the same time as long as that callback does not access ant global variables?" is a clear YES. However, you will get problems when you modify the state of OpenGL in your callback functions, especially when using glBegin / glEnd (eg if you generate a DisplayList). As long as you don't use the GPU (eg if you use a mesh), you can do tesselation with multithreading. If you want to optimize your drawing, you may want to use the geometry shader for tesselation instead. This requires Shader Model 4.
2,953,334
2,953,353
problem passing listener class to a function
I'm using a library that manipulates a binary search tree. In this library is a function that traverses the tree and passes each node it finds to a callback class: bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback *callback, void *userData) ITCODBspCallback is a base class in the library from which the user is supposed to derive his own callback class to pass to the function. Here is the base class: class ITCODBspCallback { public : virtual bool visitNode(TCODBsp *node, void *userData) = 0; }; Here's my derived class: class MyCallback: public ITCODBspCallback { public: virtual bool visitNode(TCODBsp*, void*); // defined in my implementation file }; I then pass MyCallback to the function like this: bsp->traverseInvertedLevelOrder(new MyCallback(), NULL); and g++ gives me the following errors: expected type-specifier before 'MyCallback' expected ')' before 'MyCallback' no matching function for call to 'TCODBsp::traverseInvertedLevelOrder(int*, NULL)' note: candidates are: bool TCODBsp::traverseInvertedLevelOrder(ITCODBspCallback*, void*) Anyone know what's wrong? I'm curious why it thinks MyCallback is an int*, in particular.
This all looks like you forgot to include the MyCallback header. Since its parser doesn't interpret MyCallback as a type if it doesn't know it is one, it comes up with an own type, and ignores MyCallback(), i think. The type it comes up with is int*. Notice that your code leaks because you need to call delete on any new'ed object. There is nothing wrong with creating objects like this: MyCallback b; bsp->traverseInvertedLevelOrder(&b, NULL); In this case you are free'd of memory management.
2,953,459
2,953,719
strnicmp equivalent for UTF-8?
What do I use to perform a case-insensitive comparison on two UTF-8 encoded sub-strings? Essentially, I'm looking for a strnicmp function for UTF-8.
Case conversion rules in various Unicode scripts are murderously difficult, it requires large case conversion tables. You cannot get this right yourself, you'll need a library. ICU is one of them.
2,953,483
2,953,584
Does acos, atan functions in stl uses lots of cpu cycles
I wanted to calculate the angle between two vectors but I have seen these inverse trig operations such as acos and atan uses lots of cpu cycles. Is there a way where I can get this calculation done without using these functions? Also, does these really hit you when you in your optimization?
There are no such functions in the STL; those are in the math library. Also, are you sure it's important to be efficient here? Have you profiled to see if there's function calls like this in the hot spots? Do you know that the performance is bad when using these functions? You should always answer these questions before diving into such microoptimizations. In order to give advice, what are you going to do with it? How accurate does it have to be? If you need the actual angle to a high precision, you probably can't do better. If you need it for some comparison, you can use absolute values and the dot product to get the cosine of the angle. If you don't need precision, you can do that and use an acos lookup table. If you're using it as input for another calculation, you might be able to use a little geometry or maybe a trig identity to avoid having to find an arccosine or arctangent. In any case, once you've done what optimization you're going to do, do before and after timing runs to see if you've made any significant difference.
2,953,491
2,953,498
Finding the position of the maximum element
Is there a standard function that returns the position (not value) of the maximum element of an array of values? For example: Suppose I have an array like this: sampleArray = [1, 5, 2, 9, 4, 6, 3] I want a function that returns the integer of 3 that tells me that sampleArray[3] is the largest value in the array.
In the STL, std::max_element provides the iterator (which can be used to get index with std::distance, if you really want it). int main(int argc, char** argv) { int A[4] = {0, 2, 3, 1}; const int N = sizeof(A) / sizeof(int); cout << "Index of max element: " << distance(A, max_element(A, A + N)) << endl; return 0; }
2,953,530
2,953,868
unique_ptr boost equivalent?
Is there some equivalent class for C++1x's std::unique_ptr in the boost libraries? The behavior I'm looking for is being able to have an exception-safe factory function, like so... std::unique_ptr<Base> create_base() { return std::unique_ptr<Base>(new Derived); } void some_other_function() { std::unique_ptr<Base> b = create_base(); // Do some stuff with b that may or may not throw an exception... // Now b is destructed automagically. } EDIT: Right now, I'm using this hack, which seems like the best I can get at this point... Base* create_base() { return new Derived; } void some_other_function() { boost::scoped_ptr<Base> b = create_base(); // Do some stuff with b that may or may not throw an exception... // Now b is deleted automagically. }
It's not possible to create something like unique_ptr without C++0x (where it's part of the standard library, and so Boost doesn't need to provide it). Specifically without rvalue references, which are a feature in C++0x, a robust implementation of unique_ptr is impossible, with or without Boost. In C++03, there are a few possible alternatives, although each have their flaws. boost::shared_ptr is probably the simplest replacement in terms of capabilites. You can safely use it anywhere you'd otherwise use a unique_ptr and it'd work. It just wouldn't be as efficient, because of the added reference counting. But if you're looking for a simple drop-in replacement that's able to handle everything unique_ptr can do, this is probably your best bet. (Of course, a shared_ptr can do a lot more as well, but it can also simply be used as a drop-in replacement for unique_ptr.) boost::scoped_ptr is similar to unique_ptr but does not allow transfer of ownership. It works great as long as the smart pointer is meant to retain exclusive ownership throughout its lifetime. std::auto_ptr works very similar to unique_ptr, but has a few limitations, mainly that it can not be stored in standard library containers. If you're simply looking for a pointer that allows transfer of ownership, but which is not meant to be stored in containers or copied around, this is probably a good bet.
2,953,554
2,953,570
Recycle Freed Objects
suppose I need to allocate and delete object on heap frequently (of arbitrary size), is there any performance benefit if instead of deleting those objects, I will return it back to some "pool" to be reused later? would it give benefit by reduce heap allocation/deallocation?, or it will be slower compared to memory allocator performance, since the "pool" need to manage a dynamic collection of pointers. my use case: suppose I create a queue container based on linked list, and each node of that list are allocated on the heap, so every call to push() and pop() will allocate and deallocate that node: ` template <typename T> struct QueueNode { QueueNode<T>* next; T object; } template <typename T> class Queue { void push(T object) { QueueNode<T>* newNode = QueueNodePool<T>::get(); //get recycled node if(!newNode) { newNode = new QueueNode<T>(object); } // push newNode routine here.. } T pop() { //pop routine here... QueueNodePool<T>::store(unusedNode); //recycle node return unusedNode->object; } } `
Pooling is a very common technique to avoid frequent allocations and deallocations. Some treat it as a design pattern. There are typically existing implementations, so there is no benefit to reinventing the wheel. You may want to take a look at the question Object pool vs. dynamic allocation
2,953,611
2,953,925
Are variadic constructors supposed to hide the implicitly generated ones?
Are variadic constructors supposed to hide the implicitly generated ones, i.e. the default constructor and the copy constructor? struct Foo { template<typename... Args> Foo(Args&&... x) { std::cout << "inside the variadic constructor\n"; } }; int main() { Foo a; Foo b(a); } Somehow I was expecting this to print nothing after reading this answer, but it prints inside the variadic constructor twice on g++ 4.5.0 :( Is this behavior correct? It also happens without variadic templates: struct Foo { Foo() { std::cout << "inside the nullary constructor\n"; } template<typename A> Foo(A&& x) { std::cout << "inside the unary constructor\n"; } }; int main() { Foo a; Foo b(a); } Again, both lines are printed.
Declaration of the implicitly declared copy constructor is not, in fact, being suppressed. It's just not being called due to the rules of overload resolution. The implicitly declared copy constructor has the form Foo(const Foo&). The important part of this is that it takes a const reference. Your constructor template takes a non-const reference. a is not const, so the non-const user-declared constructor template is preferred over the implicitly-declared copy constructor. To call the implicitly-declared copy constructor, you can make a const: const Foo a; Foo b(a); or you can use static_cast to obtain a const reference to a: Foo a; Foo b(static_cast<const Foo&>(a)); The overload resolution rules that describe this are found mostly in §13.3.3.2/3 of the C++0x FCD. This particular scenario, with a combination of lvalue and rvalue references, is sort of described by the various examples on page 303. A variadic constructor template will suppress the implicitly declared default constructor because a variadic constructor template is user-declared and the implicitly declared default constructor is only provided if there are no user-declared constructors (C++0x FCD §12.1/5): If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted. A variadic constructor template will not suppress the implicitly declared copy constructor because only a non-template constructor can be a copy constructor (C++0x FCD §12.8/2, 3, and 8): A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments. A non-template constructor for class X is a move constructor if its first parameter is of type X&&, const X&&, volatile X&&, or const volatile X&&, and either there are no other parameters or else all other parameters have default arguments. If the class definition does not explicitly declare a copy constructor and there is no user-declared move constructor, a copy constructor is implicitly declared as defaulted.
2,953,684
2,953,783
Why doesn't ADL find function templates?
What part of the C++ specification restricts argument dependent lookup from finding function templates in the set of associated namespaces? In other words, why does the last call in main below fail to compile? namespace ns { struct foo {}; template<int i> void frob(foo const&) {} void non_template(foo const&) {} } int main() { ns::foo f; non_template(f); // This is fine. frob<0>(f); // This is not. }
This part explains it: C++ Standard 03 14.8.1.6: [Note: For simple function names, argument dependent lookup (3.4.2) applies even when the function name is not visible within the scope of the call. This is because the call still has the syntactic form of a function call (3.4.1). But when a function template with explicit template arguments is used, the call does not have the correct syntactic form unless there is a function template with that name visible at the point of the call. If no such name is visible, the call is not syntactically well-formed and argument-dependent lookup does not apply. If some such name is visible, argument dependent lookup applies and additional function templates may be found in other namespaces. namespace A { struct B { }; template<int X> void f(B); } namespace C { template<class T> void f(T t); } void g(A::B b) { f<3>(b); //ill-formed: not a function call A::f<3>(b); //well-formed C::f<3>(b); //ill-formed; argument dependent lookup // applies only to unqualified names using C::f; f<3>(b); //well-formed because C::f is visible; then // A::f is found by argument dependent lookup }
2,953,702
2,953,722
searching for hidden files using winapi
HI i want to search for a hidden files and directories in a specefic given path but I don't know how to do it for hidden files i do know how to search for normal files and dir i did this code but im stuck can't make it search for only hidden files #include "stdafx.h" #include <windows.h> int _tmain(int argc, _TCHAR* argv[]) { TCHAR *fn; fn=L"d:\\*"; HANDLE f; WIN32_FIND_DATA data; { FILE_ATTRIBUTE_HIDDEN; } f=FindFirstFile(fn,&data); if(f==INVALID_HANDLE_VALUE){ printf("not found\n"); return 0; } else{ _tprintf(L"found this file: %s\n",data.cFileName); while(FindNextFile(f,&data)){ _tprintf(L"found this file: %s\n",data.cFileName); } } FindClose(f); return 0; }
The WIN32_FIND_DATA structure isn't telling FindFirstFile/FindNextFile what to search for; it's returning the results of the search. You need to do a bit mask on the dwFileAttributes member to determine if the file is hidden or not. if ((data.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0)
2,953,992
2,967,856
breakpoint inside QComboBox subclass not working
I have subclassed QComboBox to customize it for special needs. The subclass is used to promote QComboBoxes in a ui file from QtDesigner. Everything works except that when I put a break point in a slot, the program does not stop at the breakpoint. I do however know that it is being called from the result it generates. I checked other slots in my program and they work fine with breakpoints. Doing a clean and rebuild all did not fix it. What could be causing this and is there anything I can do about it? The slot in question is the only one in the subclass and is called "do_indexChanged()". You can find the slot on line 37 of the class header below and the signal-slot connection on line 10 of the class source file. CLASS HEADER: #ifndef WVQCOMBOBOX_H #define WVQCOMBOBOX_H #include <QWidget> #include <QObject> #include <QComboBox> #include <QVariant> class wvQComboBox : public QComboBox { Q_OBJECT //Q_PROPERTY(bool writeEnable READ writeEnable WRITE setWriteEnable) public: explicit wvQComboBox(QWidget *parent = 0); bool writeEnable() { return this->property("writeEnable").toBool(); } void setWriteEnable(const bool & writeEnable){ this->setProperty("writeEnable",writeEnable); } bool newValReady() { return this->property("newValReady").toBool(); } void setNewValReady(const bool & newValReady){ this->setProperty("newValReady",newValReady); } QString getNewVal(); int getNewValIndex(); int oldVal; //comboBox Index before user edit began private slots: void do_indexChanged(){ this->setWriteEnable(true); if(oldVal!=currentIndex()){ this->setNewValReady(true); oldVal=currentIndex(); } } protected: void focusInEvent ( QFocusEvent * event ); //void focusOutEvent ( QFocusEvent * event );//dont need because of currentIndexChanged(int) }; #endif // WVQCOMBOBOX_H #include "wvqcombobox.h" wvQComboBox::wvQComboBox(QWidget *parent) : QComboBox(parent) { this->setWriteEnable(true); this->setNewValReady(false); oldVal=this->currentIndex(); connect(this,SIGNAL(currentIndexChanged(int)),this,SLOT(do_indexChanged())); } void wvQComboBox::focusInEvent ( QFocusEvent * event ) { this->setWriteEnable(false); oldVal=this->currentIndex(); } QString wvQComboBox::getNewVal(){ setNewValReady(false); return this->currentText(); } int wvQComboBox::getNewValIndex(){ setNewValReady(false); return this->currentIndex(); }
I found the problem. All I needed to do was to put the function definition in the .cpp file.
2,954,184
2,954,191
the scope of a pointer?
Ok, so I did find some questions that were almost similar but they actually confused me even more about pointers. C++ Pointer Objects vs. Non Pointer Objects In the link above, they say that if you declare a pointer it is actually saved on the heap and not on the stack, regardless of where it was declared at. Is this true ?? Or am I misunderstanding ??? I thought that regardless of a pointer or non pointer, if its a global variable, it lives as long as the application. If its a local variable or declared within a loop or function, its life is only as long as the code within it.
The variable itself is stored on the stack or DATA segment, but the memory it points to after being allocated with new is within the heap.
2,954,212
2,954,249
Extract a portion of a Qt .ui file into its own .ui file
We have a designer creating a user interface for an application. The main window has several QStackedWidgets used for in place panel switching. What I'd like to be able to do is extract each individual panel that makes up each page of the QStackedWidget into it its own .ui file. Is there an easy way to accomplish this from within Qt Designer, or are there any other tools to help accomplish this task short of redesigning all of the panels in their own .ui files?
You can cut/paste each panel into a blank QWidget (created with File > New), and save these widgets in their own .ui file.
2,954,399
2,954,430
Convert CString to string (VC6)
I want to convert CString to string. (Yup. I know what am I doing. I know the returned string will be incorrect, if CString value range is outside ANSI, but That's Is OK!) The following code will work under VC2008. std::string Utils::CString2String(const CString& cString) { // Convert a TCHAR string to a LPCSTR CT2CA pszConvertedAnsiString (cString); // construct a std::string using the LPCSTR input std::string strStd (pszConvertedAnsiString); return strStd; } But VC6 doesn't have CT2CA macro. How I can make the code to work as well in both VC6 and VC2008?
Microsoft says that CT2CA replaces T2CA, so try the latter and see if that works.
2,954,473
2,954,601
"variable tracking" is eating my compile time!
I have an auto-generated file which looks something like this... static void do_SomeFunc1(void* parameter) { // Do stuff. } // Continues on for another 4000 functions... void dispatch(int id, void* parameter) { switch(id) { case ::SomeClass1::id: return do_SomeFunc1(parameter); case ::SomeClass2::id: return do_SomeFunc2(parameter); // This continues for the next 4000 cases... } } When I build it like this, the build time is enormous. If I inline all the functions automagically into their respective cases using my script, the build time is cut in half. GCC 4.5.0 says ~50% of the build time is being taken up by "variable tracking" when I use -ftime-report. What does this mean and how can I speed compilation while still maintaining the superior cache locality of pulling out the functions from the switch? EDIT: Interestingly enough, the build time has exploded only on debug builds, as per the following profiling information of the whole project (which isn't just the file in question, but still a good metric; the file in question takes the most time to build): Debug: 8 minutes 50 seconds Release: 4 minutes, 25 seconds If you're curious, here are a few sample do_func's, context removed. As you can see, I simplified the problem definition a bit to only show the relevant parts. In case you're wondering, all the self->func calls are calls to boost::signal's. static void do_Match_Login(Registry* self, const uint8_t* parameters, uint16_t length) { const uint8_t* paramPtr = parameters; std::string p0 = extract_string(parameters, &paramPtr, length); std::string p1 = extract_string(parameters, &paramPtr, length); int32_t p2 = extract_int32(parameters, &paramPtr, length); uint32_t p3 = extract_uint32(parameters, &paramPtr, length); tuple<Buffer, size_t, size_t> p4 = extract_blob(parameters, &paramPtr, length); return self->Match_Login(p0, p1, p2, p3, p4); } static void do_Match_ResponseLogin(Registry* self, const uint8_t* parameters, uint16_t length) { const uint8_t* paramPtr = parameters; int32_t p0 = extract_int32(parameters, &paramPtr, length); std::string p1 = extract_string(parameters, &paramPtr, length); array<uint16_t, 3> p2 = extract_vector(parameters, &paramPtr, length); std::string p3 = extract_string(parameters, &paramPtr, length); uint8_t p4 = extract_uint8(parameters, &paramPtr, length); uint8_t p5 = extract_uint8(parameters, &paramPtr, length); uint64_t p6 = extract_MUID(parameters, &paramPtr, length); bool p7 = extract_bool(parameters, &paramPtr, length); tuple<Buffer, size_t, size_t> p8 = extract_blob(parameters, &paramPtr, length); return self->Match_ResponseLogin(p0, p1, p2, p3, p4, p5, p6, p7, p8); }
You can turn off variable tracking. Variable tracking is used to make the debug information a bit more valuable, but if this code is auto-generated and you're not really going to be debugging it much then it's not really useful. You can just turn it off for that file only. gcc -fno-var-tracking ... Should do the trick. As I said, I think you can just do it for that file.
2,954,582
2,954,623
how to write a constructor
is that correct to write a constructor like this? class A { A(const A& a) { .... } }; if yes, then is it correct to invoke it like this: A* other; ... A* instance = new A(*(other)); if not, what do you suggest? Thanks
Almost correct. When declaring the constructor in the class, simply write A, not A::A; you would use A::A when giving a definition for the constructor outside of the class declaration. Otherwise, yes. Also, as James points out, unless you are copying from an object that you are accessing via a pointer, you don't need to do any dereferencing (if it is a value or a reference). One typically does not use pointers unless it is necessary to do so. On that principle, you would have something like: A x; // Invoke default constructor // ... // do some thing that modify x's state // ... A cpy(x); // Invokes copy constructor // cpy now is a copy of x. Note, though, that the first statement A x invokes the default constructor. C++ will provide a default implementation of that constructor, but it might not be what you want and even if it is what you want, it is better style, IMHO, to give one explicitly to let other programmers know that you've thought about it. Edit C++ will automatically provide an implementation of the default constructor, but only if you don't provide any user-defined constructors -- once you provide a constructor of your own, the compiler won't automatically generate the default constructor. Truth be told, I forgot about this as I've been in the habit of giving all constructor definitions myself, even when they aren't strictly necessary. In C++0x, it will be possible to use = default, which will provide the simplicity of using the compiler-generated constructor while at the same time making the intention to use it clear to other developers.
2,954,586
2,954,605
Thread Proc for an instancable class?
Basically I have a class and it is instincable (not static). Basically I want the class to be able to generate its own threads and manage its own stuff. I don't want to make a global callback for each instance I make, this doesnt seem clean and proper to me. What is the proper way of doing what I want. If I try to pass the threadproc to CreateThread and it is the proc from a class instance the compiler says I cannot do this. What is the best way of achieving what I want? Thanks
class Obj { static ULONG WINAPI ThreadProc(void* p) { Obj* pThis = (Obj*)p; ... do stuff ... return 0; } void StartMemberThread() { CreateThread(... ThreadProc, this, ... ); } }; Trickiest part is making sure the thread doesn't use pThis after the object goes away.
2,954,802
2,954,931
how to play rtsp streamming in QT
I am trying to find a way to play in Qt 4.6 rtsp streaming, that i got from youtube api can it be done somehow?
Live555 has some very useful libraries on this subject.
2,954,815
2,954,824
Works on debug but not release
I have a thread that sets a value to true when it is done. Until then I wait: while(1) { if(done[0] == true) { break; } } This code works just fine in Debug but in Release it stays in the loop forever even though the debugger clearly says that it is true and not false. Why would this not work? Thanks
This is symptomatic of not marking done as volatile. Without volatile the optimising compiler can cache the value in a register. e.g. private volatile int i;
2,954,821
2,955,115
Using an iterator without its container
I am mixing some C and C++ libraries and have only a single pointer available to do some work in a callback function. All I need to do is iterate through a vector. Here's a simplified, untested example: bool call_back(void* data){ done=... if (!done) cout << *data++ << endl; return done; } Note that this function is in an extern "C" block in C++. call_back will be called until true is returned. I want it to cout the next element each time it's called. data is a pointer to something that I can pass from elsewhere in the code (an iterator in the above example, but can be anything). Something from data will likely be used to calculate done. I see two obvious options to give to data: Have data point to my vector. Have data point to an iterator of my vector. I can't use an iterator without having the .end() method available, right? I can't use a vector alone (unless maybe I start removing its data). I could make a struct with both vector and iterator, but is there a better way? What would you do?
Why not have data point to a structure with all the information you need. The point about the old "C" style callbacks is that a void* can point to any object. Your callback function knows what the type is, but it can be anything. typedef struct Plop { std::vector<int>::iterator begin; std::vector<int>::iterator end; } Plop; bool call_back(void* data) { // Or static_cast<> for the pedantic. // I like reinterpret_cast<> because it is a clue to humans that this is dangerious // and as long as the object was originally a Plop* pointer it is guaranteed to work. Plop* info = reinterpret_cast<Plop*>(data); bool done= info.begin == info.end; if (!done) cout << *data++ << endl; return done; }
2,955,082
2,955,163
one line assert to test if STL container is sorted
Is there a way to write a one line condition that would return true if STL container is sorted? The container in question is std::vector I intend to use it in an assert
Use adjacent_find in combination with less or greater functor. Restriction: You should know whether the container is sorted in ascending or descending. If the vector is supposed to be sorted in ascending order: //Checks the first element where adjacent value where elem > nextElem //returns end if the vector is sorted! //Complexity is O(n) vector<int>::iterator pos = std::adjacent_find (aVec.begin(), aVec.end(), // range std::greater<int>()); if (pos == aVec.end()) { std::cout<<" sorted"<<endl; } else { std::cout<<"Not sorted"<<endl; }
2,955,220
2,955,401
Gzip In-Memory Compression
Quick and simple question. There are examples online about achieving in-memory gzip compression with zlib (C++) WITHOUT external libraries (like boost or such)? I just need to compress and decompress a block of data without much options. (it must be gzip as its the same format used by another mine C# program (the data is to be shared)) Tried to search to no avail... Thanks!
This isn't a complete answer to your question, but you will probably be interested in How can I decompress a gzip stream with zlib?. There is a little bit of poorly documented magic that you need to supply in order for zlib to work with gzip streams. The zlib API has many functions for doing in-memory compression that don't depend on actual files on disk.
2,955,379
2,955,829
Operators vs Functions in C/C++
Someone recently asked me the difference between a C++ standard operator (e.g. new,delete,sizeof) and function (e.g. tan,free, malloc). By "standard" I mean those provided by default by the compiler suite, and not user defined. Below were the answers I gave, though neither seemed satisfactory. (1) An operator doesn't need any headers to be included to use it : E.g. you can have a call to new without including any headers. However, a function (say free() ) does need headers included, compulsorily. (2) An operator is defined as such (ie as a class operator) somewhere in the standard headers. A function isn't. Can you critique these answers and give me a better idea of the difference?
Operators are keywords with a fixed syntax. Those which can be overloaded might vary a bit in syntax, but that's within the boundaries. The new operator is still spelled new, even when overloaded and the syntax of invoking it is always the same. Function names are identifiers, which can be almost arbitrary. There's no syntactic reason you couldn't do away with malloc() and use bool my_fancy_alloc(void*& memory, unsigned char size, bool zero_it); instead. (Mark: There are other reasons, though. Like your fellow-workers' sanity.)
2,955,398
2,955,765
How do I insert format str and don't remove the matched regular expression in input string in boost::regex_replace() in C++?
I want to put space between punctuations and other words in a sentence. But boost::regex_replace() replaces the punctuation with space, and I want to keep a punctuation in the sentence! for example in this code the output should be "Hello . hi , " regex e1("[.,]"); std::basic_string<char> str = "Hello.hi,"; std::basic_string<char> fmt = " "; cout<<regex_replace(str, e1, fmt)<<endl; Can you help me?
You need to use a replacement variable in your fmt string. If I understand the documentation correctly, then in the absence of a flags field, you'll want to use a Boost-Extended format string. In that sub-language, you use $& to mean whatever was matched, so you should try defining fmt as: std::basic_string<char> fmt = " $& "; That should change each punctuation into that same character, surrounded by spaces.
2,955,797
2,956,061
How to address thread-safety of service data used for maintaining static local variables in C++?
Consider the following scenario. We have a C++ function with a static local variable: void function() { static int variable = obtain(); //blahblablah } the function needs to be called from multiple threads concurrently, so we add a critical section to avoid concurrent access to the static local: void functionThreadSafe() { CriticalSectionLockClass lock( criticalSection ); static int variable = obtain(); //blahblablah } but will this be enough? I mean there's some magic that makes the variable being initialized no more than once. So there's some service data maintained by the runtime that indicates whether each static local has already been initialized. Will the critical section in the above code protect that service data as well? Is any extra protection required for this scenario?
C++ says that your static variable should only be initialized once - however C++ doesn't deal with threads(yet). gcc(atleast on *nix systems) does the proper magic to safely guard multiple threads initializing such a static variable. According to this link, msvc does not - and in such a case you'll have to lock the initialization yourself. Guarding the initialization with a critical section should protect all this - i.e. your functionThreadSafe() is ok - (unless obtain() itself calls functionThreadSafe() This blog article is worth a read in this regard. Personally, to avoid surprises I'd try to rewrite this so you can initialize variable yourself, once, before you create any threads - e.g. static int variable = 0; void init_variable() //call this once, at the start of main() { variable = obtain(); } void function() { //use variable, lock if you write to it }
2,955,858
2,956,260
How to use Application Verifier to find memory leaks
I want to find memory leaks in my application using standard utilities. Previously I used my own memory allocator, but other people (yes, you AlienFluid) suggested to use Microsoft's Application Verifier, but I can't seem to get it to report my leaks. I have the following simple application: #include <iostream> #include <conio.h> class X { public: X::X() : m_value(123) {} private: int m_value; }; void main() { X *p1 = 0; X *p2 = 0; X *p3 = 0; p1 = new X(); p2 = new X(); p3 = new X(); delete p1; delete p3; } This test clearly contains a memory leak: p2 is new'd but not deleted. I build the executable using the following command lines: cl /c /EHsc /Zi /Od /MDd test.cpp link /debug test.obj I downloaded Application Verifier (4.0.0665) and enabled all checks. If I now run my test application I can see a log of it in Application Verifier, but I don't see the memory leak. Questions: Why doesn't Application Verifier report a leak? Or isn't Application Verifier really intended to find leaks? If it isn't which other tools are available to clearly report leaks at the end of the application (i.e. not by taking regular snapshots and comparing them since this is not possible in an application taking 1GB or more), including the call stack of the place of allocation (so not the simple leak reporting at the end of the CRT) If I don't find a decent utility, I still have to rely on my own memory manager (which does it perfectly).
CRT memory leaks detection (without stack trace): // debug_new.h #pragma once #include "crtdbg.h" #ifdef _DEBUG #ifndef DEBUG_NEW #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__) #endif #endif All .cpp files: #include "debug_new.h" ... // After all other include lines: #ifdef _DEBUG #define new DEBUG_NEW #endif ... Write this once in the program initialization code: _CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_LEAK_CHECK_DF); In MFC, all this is already implemented in MFC headers. You only need to ensure, that every cpp file contains these lines: #ifdef _DEBUG #define new DEBUG_NEW #endif Restrictions: this catches only "new" memory leaks, all leaks, caused by another functions, like malloc, are not caught. Don't make any allocations inside of .h files - they will be printed without source lines, because DEBUG_NEW is defined after all #include lines.
2,955,921
3,090,741
Thread-safe initialization of function-local static const objects
This question made me question a practice I had been following for years. For thread-safe initialization of function-local static const objects I protect the actual construction of the object, but not the initialization of the function-local reference referring to it. Something like this: namespace { const some_type& create_const_thingy() { lock my_lock(some_mutex); static const some_type the_const_thingy; return the_const_thingy; } } void use_const_thingy() { static const some_type& the_const_thingy = create_const_thingy(); // use the_const_thingy } The idea is that locking takes time, and if the reference is overwritten by several threads, it won't matter. I'd be interested if this is safe enough in practice? safe according to The Rules? (I know, the current standard doesn't even know what "concurrency" is, but what about trampling over an already initialized reference? And do other standards, like POSIX, have something to say that's relevant to this?) The reason I want to know this is that I want to know whether I can leave the code as it is or whether I need to go back and fix this. For the inquiring minds: Many such function-local static const objects I used are maps which are initialized from const arrays upon first use and used for lookup. For example, I have a few XML parsers where tag name strings are mapped to enum values, so I could later switch over the tags' enum values. Since I got some answers as to what to do instead, but haven't got an answer to my actual questions (see 1. and 2. above), I'll start a bounty on this. Again: I am not interested in what I could do instead, I do really want to know about this.
This is my second attempt at an answer. I'll only answer the first of your questions: safe enough in practice? No. As you're stating yourself you're only ensuring that the object creation is protected, not the initialization of the reference to the object. In absence of a C++98 memory model and no explicit statements from the compiler vendor, there are no guarantees that writing to the memory representing the actual reference and the writing to the memory that holds the value of the initialization flag (if that is how it is implemented) for the reference are seen in the same order from multiple threads. As you also say, overwriting the reference several times with the same value should make no semantic difference (even in the presence of word tearing, which is generally unlikely and perhaps even impossible on your processor architecture) but there's one case where it matters: When more than one thread races to call the function for the first time during program execution. In this case it is possible for one or more of these threads to see the initialization flag being set before the actual reference is initialized. You have a latent bug in your program and you need to fix it. As for optimizations I'm sure there are many besides using the double-checked locking pattern.
2,956,097
2,956,142
Is there performance to be gained by moving storage allocation local to a member function to its class?
Suppose I have the following C++ class: class Foo { double bar(double sth); }; double Foo::bar(double sth) { double a,b,c,d,e,f a = b = c = d = e = f = 0; /* do stuff with a..f and sth */ } The function bar() will be called millions of times in a loop. Obviously, each time it's called, the variables a..f have to be allocated. Will I gain any performance by making the variables a..f members of the Foo class and just initializing them at the function's point of entry? On the other hand, the values of a..f will be dereferenced through this->, so I'm wondering if it isn't actually a possible performance degradation. Is there any overhead to accessing a value through a pointer? Thanks!
Access to stack-allocated variables is faster than to class members. Stack variables are dereferenced using stack pointer, without using of a class pointer. Add new class members only if it is required by program algorithm. Initialize stack variables directly in declaration: double a = 0.0, b = 0.0 ...
2,956,309
2,956,350
UIDs for data objects in MySQL
I am using C++ and MySQL. I have data objects I want to persist to the database. They need to have a unique ID for identification purposes. The question is, how to get this unique ID? Here is what I came up with: 1) Use the auto_increment feature of MySQL. But how to get the ID then? I am aware that MySQL offers this "SELECT LAST_INSERT_ID()" feature, but that would be a race condition, as two objects could be inserted quite fast after each other. Also, there is nothing else that makes the objects discernable. Two objects could be created pretty much at the same time with exactly the same data. 2) Generate the UID on the C++ side. No dice, either. There are multiple programs that will write to and read from the database, who do not know of each other. 3) Insert with MAX(uid)+1 as the uid value. But then, I basically have the same problem as in 1), because we still have the race condition. Now I am stumped. I am assuming that this problem must be something other people ran into as well, but so far, I did not find any answers. Any ideas?
The query: SELECT LAST_INSERT_ID() will return the last ID inserted on your specific connection, not globally. So there is no race condition, unless your own code is multi-threaded, in which case you would want to surround the INSERT and the SELECT with an MT lock of some sort.
2,956,331
2,956,375
How to use cppcheck's inline suppression filter option for C++ code?
I would like to use Cppcheck for static code analysis of my C++ code. I learned that I can suppress some kind of warnings with --inline-suppr command. However, I can't find what "suppressed_error_id" I should put in the comment: // cppcheck-suppress "suppressed_error_id"
According to the cppcheck help: The error id is the id that you want to suppress. The easiest way to get it is to use the --xml command line flag. Copy and paste the id string from the xml output. So run cppcheck against some code that contains the error with the --xml flag, and then look in the generated XML file to find its name.
2,956,394
2,957,000
Problem with "write" function in linux
I am trying to write 2 server/client programs under Linux, in which they communicate through named pipes. The problem is that sometimes when I try to write from the server into a pipe that doesn't exist anymore (the client has stopped), I get a "Resource temporarily unavailable" error and the server stops completely. I understand that this is caused by using a O_NONBLOCK parameter when opening the fifo chanel, indicating the point where the program would usually wait until it could write again in the file, but is there a way to stop this behavior, and not halt the entire program if a problem occurs (shouldn't the write command return -1 ad the program continue normally)? And another strange thing is that this error only occurs when running the programs outside the ide (eclipse). If I run both programs inside eclipse, on error the write function just returns -1 and the programs continues normally.
If you wish that write() to returns -1 on error (and set errno to EPIPE) instead of stopping your server completly when the write end of your pipe is unconnected, you must ignore the SIGPIPE signal with signal( SIGPIPE, SIG_IGN ).
2,956,398
2,956,993
Static libpng link with visual studio 2010
I'm trying to add PNG support to my application and thus I want to include libpng. I know it needs zlib and thus I downloaded that as well. I went into the png folder/projects/vstudio and I opened the solution. I compiled it and it went just fine. I added some headers from it into my application and I copied the lib files. My program is a dll written in c++ which is later used from C#. When I run it in C# it complains about not finding my dll (tough if I remove the png part it works fine). I've had this problem before and it usually means a dll dependency is wrong. Now... libpng compiled both some .lib files and some .dll files. The dll files are bigger. My only guess is that it needs the dll files as well but I've seen that people can link to libpng without a dll. So my questions is: How can I compile libpng(and zlib for that instance) into just static libraries and how can I include those in my projects? I've searched around the internet and I couldn't find anything useful.
To make all your libraries static, you would have to recompile everything "from scratch" as static libraries. This simply means you should create a set of projects for each library you have in your sequence and set the output type to static library. After that you should eliminate library dependencies between the libraries themselves (this means you should link the output of some projects to another projects, e.g. if your "libpng" library uses "libzip", it means you should first compile the "libzip" and link that output (static library) to your "libpng" project. In the very end you would have a big set of static libraries compiled for your platform, which you can use in your projects. Also to mention, try googling more carefully. I'm sure someone has this done and you would probably need to download a package of .lib files for your platform (I know that very often the "dev" bundle of libraries only includes an import library paired with appropriate .dll file, but there are a lot of enthusiasts like you :)
2,956,404
2,956,481
Type casting in C++ by detecting the current 'this' object type
My question is related to RTTI in C++ where I'm trying to check if an object belongs to the type hierarchy of another object. The BelongsTo() method checks this. I tried using typeid, but it throws an error and I'm not sure about any other way how I can find the target type to convert to at runtime. #include <iostream> #include <typeinfo> class X { public: // Checks if the input type belongs to the type heirarchy of input object type bool BelongsTo(X* p_a) { // I'm trying to check if the current (this) type belongs to the same type // hierarchy as the input type return dynamic_cast<typeid(*p_a)*>(this) != NULL; // error C2059: syntax error 'typeid' } }; class A : public X { }; class B : public A { }; class C : public A { }; int main() { X* a = new A(); X* b = new B(); X* c = new C(); bool test1 = b->BelongsTo(a); // should return true bool test2 = b->BelongsTo(c); // should return false bool test3 = c->BelongsTo(a); // should return true } Making the method virtual and letting derived classes do it seems like a bad idea as I have a lot of classes in the same type hierarchy. Or does anybody know of any other/better way to the do the same thing? Please suggest. Update: b.BelongsTo(a) should detect if the input object type (a) is an ancestor of the current object (b) in the type hierarchy.
This doesn't make sense - the very fact that you can call the function means that the parameter belongs to the X hierarchy, as that is the type of the parameter. Dynamic casts are intended to find out the actual type within a known hierarchy. The syntax error in your code: return dynamic_cast<typeid(*p_a)*>(this) != NULL; is because a typeid is not a type - you simply cannot use it as a type with dynamic_cast like that. If as Naveen suggests you want to find out if an instance belongs to a sub-hierarchy, use: if ( dynamic_cast <A*>( some_x_ptr ) ) { // yes, belongs to A sub-hierarchy } Edit: You have: A <- P <- X A <- Q <- Y Then: A * a = new X; dynamic_cast <P *>( a ); // not null dynamic_cast <Q *>( a ); // null
2,956,419
2,956,732
C++ template-function -> passing a template-class as template-argument
i try to make intensive use of templates to wrap a factory class: The wrapping class (i.e. classA) gets the wrapped class (i.e. classB) via an template-argument to provide 'pluggability'. Additionally i have to provide an inner-class (innerA) that inherits from the wrapped inner-class (innerB). The problem is the following error-message of the g++ "gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5)": sebastian@tecuhtli:~/Development/cppExercises/functionTemplate$ g++ -o test test.cpp test.cpp: In static member function ‘static classA<A>::innerA<iB>* classA<A>::createInnerAs(iB&) [with iB = int, A = classB]’: test.cpp:39: instantiated from here test.cpp:32: error: dependent-name ‘classA::innerA<>’ is parsed as a non-type, but instantiation yields a type test.cpp:32: note: say ‘typename classA::innerA<>’ if a type is meant As you can see in the definition of method createInnerBs, i intend to pass a non-type argument. So the use of typename is wrong! The code of test.cpp is below: class classB{ public: template < class iB> class innerB{ iB& ib; innerB(iB& b) :ib(b){} }; template<template <class> class classShell, class iB> static classShell<iB>* createInnerBs(iB& b){ // this function creates instances of innerB and its subclasses, // because B holds a certain allocator return new classShell<iB>(b); } }; template<class A> class classA{ // intention of this class is meant to be a pluggable interface // using templates for compile-time checking public: template <class iB> class innerA: A::template innerB<iB>{ innerA(iB& b) :A::template innerB<iB>(b){} }; template<class iB> static inline innerA<iB>* createInnerAs(iB& b){ return A::createInnerBs<classA<A>::template innerA<> >(b); // line 32: error occurs here } }; typedef classA<classB> usable; int main (int argc, char* argv[]){ int a = 5; usable::innerA<int>* myVar = usable::createInnerAs(a); return 0; } Please help me, i have been faced to this problem for several days. Is it just impossible, what i'm trying to do? Or did i forgot something? Thanks, Sema
Line 32 should read: return A::template createInnerBs<innerA>(b); since createInnerBs is dependent on the template parameter A. You'll also need to make the constructors of innerA and innerB public.
2,956,608
2,956,751
write a MIDI file in C++
Hi I Have some problems finding the right information about this and would be glad if someone could point me in the right direction. How do you code a midifile? e.g. how can I write a snippet that plays a random tone for 1 second. Basically what I would need to get done is representing differnet midi melodys as vectors of some sort? How can I do this..
You could also read up on the MIDI file spec (quick search turned up this) and generate the file yourself. Using a library is probably easier, but the MIDI file format isn't too complicated, especially if you already know how MIDI works (eg. note on/note off messages).
2,956,637
2,956,927
QT4 Designer - Implement Widget
I'm currently trying to get into QT4 and figure out a workflow for myself. While trying to create a widget which allows the user to connect to a hostname:port some questions appeared. The widget itself contains a LineEdit for entering the hostname, a SpinBox for entering the port and a PushButton which should emit a connect(QString hostname, unsigned int port) signal. In QTDesigner I created the necessary Form. It is saved as a .ui-File. Now the big question is how could I implement the widget? Is there a place in QTDesigner where I could add my signal to the Widget? Where could I add custom Properties? I've learned in another tutorial, which showed how to create a Widget in C++, how signals, slots, Q_PROPERTIES etc are defined and added to the widget. But there is no sourcecode in QTDesigner. Another option would be to generate sourcecode using uic. But the header says, that another generate would overwrite any changes to the sourcefiles. So how can I create a QT-widget completely with my own signals, slots and properties by using the QTDesigner for creating the UI and not having to recode everything whenever the UI is changing. Is there some kind of Roundtrip-Engineering? If thats not possible: Whats the sense of creating a Widget with QTDesigner then?
I think I've found the answer myself. (Why does it need 2-3h of reading through tutorials etc until I give up and ask the question at Stackoverflow and then 5min after continuing to search, I find the solution myself? -.-) I think the chapter of the QT-Documentation is describing how to use uic-generated files in an own widget in a usable way. http://doc.qt.nokia.com/4.0/porting4-designer.html#uic-output My next step will be to use the second approach to create a Widget with my needed signal and properties.
2,957,062
2,957,601
Using an array of derived objects as an array of base objects when the sizes are the same (CComVariant/VARIANT)
I'm using code that treats an array of derived objects as an array of base objects. The size of both objects is the same. I'm wondering: Is this safe in practice, bearing in mind that the code will only ever be compiled on Microsoft compilers? Here's my example: BOOST_STATIC_ASSERT(sizeof(VARIANT)==sizeof(CComVariant)); //auto_array deletes[] the pointer if detach() isn't called at the end of scope auto_array<CComVariant> buffer(new CComVariant[bufferSize]); //...Code that sets the value of each element... //This takes a range specified as two VARIANT* - the AtlFlagTakeOwnership option //causes delete[] to be called on the array when the object pEnum referes to //is released. pEnum->Init(buffer.ptr,buffer.ptr+bufferSize,0,AtlFlagTakeOwnership); buffer.detach();
Yes, CComVariant was designed to be a direct substitute for VARIANT. It derives from the variant structure and adds no virtual members nor fields (and no virtual destructor) to ensure the memory layout is the same. Lots of little helper classes like that in ATL/MFC, like CRect, CPoint etc.
2,957,352
2,957,469
Code assistance in Netbeans on Linux
My IDE (NetBeans) thinks this is wrong code, but it compiles correctly: std::cout << "i = " << i << std::endl; std::cout << add(5, 7) << std::endl; std::string test = "Boe"; std::cout << test << std::endl; It always says unable to resolve identifier .... (.... = cout, endl, string); So I think it has something to do with the code assistance. I think I have to change/add/remove some folders. Currently, I have these include folders: C compiler: /usr/local/include /usr/lib/gcc/i486-linux-gnu/4.4.3/include /usr/lib/gcc/i486-linux-gnu/4.4.3/include-fixed /usr/include C++ compiler: /usr/include/c++/4.4.3 /usr/include/c++/4.4.3/i486-linux-gnu /usr/include/c++/4.4.3/backward /usr/local/include /usr/lib/gcc/i486-linux-gnu/4.4.3/include /usr/include What could be causing this, and how can I make NetBeans mark it as valid code?
It works fine for me. I'm using NetBeans 6.8; the only undefined reference I got was for the add() function. Can you test with a new project to see if you can reproduce the problem? EDIT (reply): Yep, tested on Linux. No includes added in project properties. In the global C/C++ options I have an extra include path for C, /usr/include/i486-linux-gnu. For C++ I have: /usr/include/c++/4.4 /usr/include/c++/4.4/i486-linux-gnu /usr/include/c++/4.4/backward /usr/local/include /usr/lib/gcc/i486-linux-gnu/4.4.3/include /usr/lib/gcc/i486-linux-gnu/4.4.3/include-fixed /usr/include/i486-linux-gnu /usr/include These are my defaults, haven't touched them. HTH I also use gcc-4.4.3 (Ubuntu 10.04).
2,957,715
3,151,685
right click event in opencv
I am developing a computer vision program using OpenCV (IDE = devcpp). I am able to get the hand contour , move cursor position according to our our hand. i want to implement right click functionality .Please help me with it . i am using event SetCursorPos(x,y) to set the cursor position on the screen. is there any simple function to implement rightclick the same way .??
Maybe this will help: http://www.codeguru.com/forum/showthread.php?t=377394 void RightClick ( ) { INPUT Input={0}; // right down Input.type = INPUT_MOUSE; Input.mi.dwFlags = MOUSEEVENTF_RIGHTDOWN; ::SendInput(1,&Input,sizeof(INPUT)); // right up ::ZeroMemory(&Input,sizeof(INPUT)); Input.type = INPUT_MOUSE; Input.mi.dwFlags = MOUSEEVENTF_RIGHTUP; ::SendInput(1,&Input,sizeof(INPUT)); } And to use: RightClick(); The link shows examples for left clicking, mouse move, etc. too.
2,957,759
2,957,897
Using gprof with sockets
I have a program I want to profile with gprof. The problem (seemingly) is that it uses sockets. So I get things like this: ::select(): Interrupted system call I hit this problem a while back, gave up, and moved on. But I would really like to be able to profile my code, using gprof if possible. What can I do? Is there a gprof option I'm missing? A socket option? Is gprof totally useless in the presence of these types of system calls? If so, is there a viable alternative? EDIT: Platform: Linux 2.6 (x64) GCC 4.4.1 gprof 2.19
The socket code needs to handle interrupted system calls regardless of profiler, but under profiler it's unavoidable. This means having code like. if ( errno == EINTR ) { ... after each system call. Take a look, for example, here for the background.
2,957,872
2,957,899
C++: Print only one char
When I read one char* from std::cin and I want to write it to std::cout, it prints until it finds a \0 in memory. So what did was: char c; cin >> c; char* pChar = &c; pChar++; *pChar = '\0'; println(&c); // My own method: void println(char * str) { cout << str << endl; } But I don't think this is a safe action. Is there a safer way to do this?
Simply: char c; cin >> c; cout << c;
2,957,923
2,958,067
boost::filesystem - how to create a boost path from a windows path string on posix platforms?
I'm reading path names from a database which are stored as relative paths in Windows format, and try to create a boost::filesystem::path from them on a Unix system. What happens is that the constructor call interprets the whole string as the filename. I need the path to be converted to a correct Posix path as it will be used locally. I didn't find any conversion functions in the boost::filesystem reference, nor through google. Am I just blind, is there an obvious solution? If not, how would you do this? Example: std::string win_path("foo\\bar\\asdf.xml"); std::string posix_path("foo/bar/asdf.xml"); // loops just once, as part is the whole win_path interpreted as a filename boost::filesystem::path boost_path(win_path); BOOST_FOREACH(boost::filesystem::path part, boost_path) { std::cout << part << std::endl; } // prints each path component separately boost::filesystem::path boost_path_posix(posix_path); BOOST_FOREACH(boost::filesystem::path part, boost_path_posix) { std::cout << part << std::endl; } Edit: of course I can just replace the backslashes, but is there a solution that "just works(tm)" for both Windows and Unix plattforms?
Unfortunately the Windows path grammar is conditionally compiled, and only included when compiling on Windows. I don't understand why they have done this. Anyway, this means you have at most two parsers available at all times; the portable one, which is the same as the Posix one, and the native one, which depends on which platform you currently are compiling for. What could "just work" was to have all paths stored in the portable (Posix) format. You could parse this equally simply on all platforms.
2,957,984
2,958,064
Why I have to redeclare a virtual function while overriding [C++]
#include <iostream> using namespace std; class Duck { public: virtual void quack() = 0; }; class BigDuck : public Duck { public: // void quack(); (uncommenting will make it compile) }; void BigDuck::quack(){ cout << "BigDuckDuck::Quack\n"; } int main() { BigDuck b; Duck *d = &b; d->quack(); } The code above doesn't compile. However, when I declare the virtual function in the subclass, then it compiles fine. If the compiler already has the signature of the function that the subclass will override, then why is a redeclaration required? Any insights?
The redeclaration is needed because: The standard says so. It makes the compiler's work easier by not climbing up the hierarchy to check if such function exists. You might want to declare it lower in the hierarchy. In order to instantiate the class the compiler must know that this object is concrete.
2,958,007
2,958,014
What does the "L" mean at the end of an integer literal?
I have this constant: #define MAX_DATE 2958465L What does the L mean in this sense?
It is a long integer literal. Integer literals have a type of int by default; the L suffix gives it a type of long (Note that if the value cannot be represented by an int, then the literal will have a type of long even without the suffix).
2,958,114
2,958,261
Handling EINTR (with goto?)
Background: This is a follow-up question to this thread about handling EINTR for system calls in C++ (Linux/GCC). Regardless of whether or not I intend to profile my application, it seems like I should be handling system calls setting errno to EINTR as a special case. There are many, many, many opinions about the use of goto. My question: is a system call setting errno to EINTR a case where goto is considered nominal? If not, then how would you suggest converting the following code to handle EINTR? if ( ( sock_fd = ::socket( domain, type, protocol ) ) < 0 ) { throw SocketException( "Socket::Socket() -> ::socket()", errno ); } Thanks in advance! Cheers, -Chris UPDATE: Based on the answers below, I wound up writing the following macro: #define SOCK_SYSCALL_TRY(call,error) \ while ( (call) < 0 ) { \ switch ( errno ) { \ case EINTR: \ continue; \ default: \ throw SocketException( (error), errno ); \ } \ } \ Which is used to transform my original snippet to this example: SOCK_SYSCALL_TRY( sock_fd = ::socket( domain, type, protocol ), "Socket::Socket() -> ::socket()" ) Hope this helps someone else!
As far as I know the socket system call can't return with errno set to EINTR. For other cases I use a loop: while ((::connect(sock, (struct sockaddr *)&destAddress, sizeof(struct sockaddr))) == -1) { if (errno == EINTR) { LOGERROR("connect interrupted, retry"); continue; } else if (errno == EINPROGRESS) { break; } else { LOGERROR("connect failed, errno: " << errno); return -1; } }
2,958,137
2,958,260
cannot not find library files in eclipse cdt
properties/C/C++ Build/Settings GCC C++ Linker/Libraries Under libraries(-I) I have libbost_system libbost_filesystem ... and under Library search path(-L) I have /home/etobkru/boost_1_43_0/boostBinaries/lib but when I compile I get g++ -L/home/etobkru/boost_1_43_0/boostBinaries/lib/ -o"searchDirs" ./main.o -llibboost_system -llibboost_filesystem -llibboost_regex /usr/lib/gcc/i586-suse-linux/4.1.2/../../../../i586-suse-linux/bin/ld: cannot find -llibboost_system I have tried with libbost_system.so and libbost_system.a but i get the same error. What am I doing wrong and why cant eclipse find the files. Because they are there?
You don't need the "lib" part in the name. Just link with -lboost_system -lboost_filesystem -lboost_regex
2,958,142
2,958,315
How do boost operators work?
boost::operators automatically defines operators like + based on manual implementations like += which is very useful. To generate those operators for T, one inherits from boost::operators<T> as shown by the boost example: class MyInt : boost::operators<MyInt> I am familiar with the CRTP pattern, but I fail to see how it works here. Specifically, I am not really inheriting any facilities since the operators aren't members. boost::operators seems to be completely empty, but I'm not very good at reading boost source code. Could anyone explain how this works in detail? Is this mechanism well-known and widely used?
There's a big multiple inheritance chain, at the top of which there are a number of classes that implement the operators, but do so as friend functions, thus placing them in the enclosing namespace rather than as members of the class. For example, the final implementation of operator+ becomes: template <class T, class U, class B = ::boost::detail::empty_base<T> > struct addable2 : B { friend T operator +( T lhs, const U& rhs ) { return lhs += rhs; } friend T operator +( const U& lhs, T rhs ) { return rhs += lhs; } };
2,958,226
2,970,441
How do I create a set with std::pair thats sorted based on the ::second pair member using bind
I know I could use the following: template <typename Pair> struct ComparePairThroughSecond : public std::unary_function<Pair, bool> { bool operator ()(const Pair& p1, const Pair& p2) const { return p1.second < p2.second; } }; std::set<std::pair<int, long>, ComparePairThroughSecond> somevar; but wondered if it could be done with boost::bind
How about the following one. I'm using boost::function to 'erase' the actual type of the comparator. The comparator is created using boost:bind itself. typedef std::pair<int, int> IntPair; typedef boost::function<bool (const IntPair &, const IntPair &)> Comparator; Comparator c = boost::bind(&IntPair::second, _1) < boost::bind(&IntPair::second, _2); std::set<IntPair, Comparator> s(c); s.insert(IntPair(5,6)); s.insert(IntPair(3,4)); s.insert(IntPair(1,2)); BOOST_FOREACH(IntPair const & p, s) { std::cout << p.second; }
2,958,285
2,958,332
C++ refactor common code with one different statement
I have two methods f(vector<int>& x, ....) and g(DBConn& x, ....) where the (....) parameters are all identical. The code inside the two methods are completely identical except for one statement where we do different actions based on the type of x: in f(): we do x.push_back(i) in g(): we do x.DeleteRow(i) What is the simplest way to extract the common code into one method and yet have the two different statements? I am thinking of having a templated functor that overloads operator () (int a) but that seems overkill.
You could write a simple adapter with two implementations, each calling the desired method of a different class. class MyInterface { public: virtual doIt(int i) = 0; } class VectorImp : public MyInterface { public: vector<int>& v; VectorImp(vector<int>& theVector) : v(theVector) {} doIt(int i) { x.push_back(i); } } class DbImp : public MyInterface { public: DBConn& c; VectorImp(DBConn& conn) : c(conn) {} doIt(int i) { c.DeleteRow(i); } }
2,958,398
2,958,415
GNU C++ how to check when -std=c++0x is in effect?
My system compiler (gcc42) works fine with the TR1 features that I want, but trying to support newer compiler versions other than the systems, trying to accessing TR1 headers an #error demanding the -std=c++0x option because of how it interfaces with library or some hub bub like that. /usr/local/lib/gcc45/include/c++/bits/c++0x_warning.h:31:2: error: #error This file requires compiler and library support for the upcoming ISO C++ standard, C++0x. This support is currently experimental, and must be enabled with the -std=c++0x or -std=gnu++0x compiler options. Having to supply an extra switch is no problem, to support GCC 4.4 and 4.5 under this system (FreeBSD), but obviously it changes the picture! Using my system compiler (g++ 4.2 default dialect): #include <tr1/foo> using std::tr1::foo; Using newer (4.5) versions of the compiler with -std=c++0x: #include <foo> using std::foo; Is there anyway using the pre processor, that I can tell if g++ is running with C++0x features enabled? Something like this is what I'm looking for: #ifdef __CXX0X_MODE__ #endif but I have not found anything in the manual or off the web. At this rate, I'm starting to think that life would just be easier, to use Boost as a dependency, and not worry about a new language standard arriving before TR4... hehe.
If you compile with -std=c++0x, then __GXX_EXPERIMENTAL_CXX0X__ will be defined.
2,958,416
2,958,481
Call c++ library from c#
This question might seem a repeat of previous ones. I have read through a series of posts, but not completely clear for my situation. I have a c++ library which is created using momentics IDE. I have to be able to use this library into a c# project. Someone had been working on this project before being handed over to me. Currently, there are 2 layers for making this possible. First, a c++ project includes the complete library with a c++ wrapper. This project creates a dll as the output. This c++ dll is then fed to a c# project, which has dllimport calls to the c++ dll. This c# project again creates a dll. Finally, in order to use the library in c# application, I have to include a reference to both of these dlls. Is this the correct way to get it working? I was thinking probably there should be a way to simplify the process. Can someone please help me with this question?
Given that you're using a C++ library, I'm assuming it takes advantage of C++ semantics like classes, rather than just exposing procedures. If this is the case, then the way this is typically done is via a manually-created managed C++ interop library. Basically, you create a managed C++ library in Visual Studio, reference your existing C++ library, and create a managed wrapper around your existing C++ classes. You then reference this (managed) C++ assembly in your C# project and include the original (unmanaged) C++ library in your C# assembly just as a file that gets placed in the build directory. This is required because there is no way to reference things like C++ classes via P/Invoke (DllImport) calls. If your base library is just a series of functions, then you can reference that directly in the C# project via P/Invoke functions. Either way, all of the libraries mentioned above (for the first, the unmanaged C++ library, the managed C++ assembly, and the C# project, or, for the second, the unmanaced C++ library and the C# project) must be included in any project that references them. You cannot statically link the unmanaged library into the managed assembly.
2,958,457
15,554,949
gcc -Wshadow is too strict?
In the following example: class A { public: int len(); void setLen(int len) { len_ = len; } // warning at this line private: int len_; }; gcc with -Wshadow issue a warning: main.cpp:4: warning: declaration of `len' shadows a member of `this' function len and integer len are of different type. Why the warning? Update I see there's a wide consensus of what "shadow" means. And from a formal point of view, the compiler does exactly what it's meant to do. However IMHO, the flag is not practical. For example commonly used setter/getter idiom : class A { void prop(int prop); // setter int prop() const; // getter int prop; }; It would be nice if there was a warning flag that won't issue warning in the case, but will warn in case "int a" hides "int a". Adding -Wshadow on my legacy code issues tons of warnings, while from time to time I discover bugs caused by "shadowing" problem. I don't mind how it will be called "-Wmuch_more_practical_and_interesting_shadow" or "-Wfoooooo". So, are there other gcc warning flags that do what I described? Update 2 I'm not the only one who thinks -Wshadow is somehow not useful link text. I'm not alone :) Less strict checking could be much more useful.
This seems to be solved on newer versions of GCC. From version 4.8 changelog: The option -Wshadow no longer warns if a declaration shadows a function declaration, unless the former declares a function or pointer to function, because this is a common and valid case in real-world code. And it references Linus Torvalds's thoughts on the subject: https://lkml.org/lkml/2006/11/28/253 Unfortunately the newest compiler of the embedded system where I'm currently working is still based on gcc 4.6.
2,958,610
3,882,067
Event Log Oldest Record Number
I'm trying to use the new event log API to get the oldest record number from a windows event log, but cannot get the the API to return the same answer as event viewer displays (looking at the details EventRecordID). Some sample code I'm using is below: EVT_HANDLE log = EvtOpenLog(NULL, _logName, EvtOpenChannelPath); EVT_VARIANT buf; DWORD need = 0; int vlen = sizeof(EVT_VARIANT); ZeroMemory(&buf, vlen); EvtGetLogInfo(log, EvtLogOldestRecordNumber, vlen, &buf, &need); UINT64 old = buf.UInt64Val; EvtClose(log); What the API appears to be doing is returning the record number of the oldest event in the log, but not the oldest accessible event... What I mean by that is lets say you have 10 records in your log, 1-10 and you clear your log. The next 10 events inserted will be 11-20. If you use the API, it will return 1, not 11 like event viewer displays. If you try to retrieve event 1 using EvtQuery/EvtNext it will fail and not return an event -- as I would expect. Does anyone have experience with this method? What am I doing wrong? I have used the method successfully with other properties (i.e. EvtLogNumberOfLogRecords), but cannot get this property (EvtLogOldestRecordNumber) to behave as expected. http://msdn.microsoft.com/en-us/library/aa385385(v=VS.85).aspx
I was not able to get the new API to work for the oldest record number and had to revert to using the legacy API to retrieve the oldest record number. msdn.microsoft.com/en-us/library/aa363665(VS.85).aspx
2,958,648
4,241,547
What are the pitfalls of ADL?
Some time ago I read an article that explained several pitfalls of argument dependent lookup, but I cannot find it anymore. It was about gaining access to things that you should not have access to or something like that. So I thought I'd ask here: what are the pitfalls of ADL?
There is a huge problem with argument-dependent lookup. Consider, for example, the following utility: #include <iostream> namespace utility { template <typename T> void print(T x) { std::cout << x << std::endl; } template <typename T> void print_n(T x, unsigned n) { for (unsigned i = 0; i < n; ++i) print(x); } } It's simple enough, right? We can call print_n() and pass it any object and it will call print to print the object n times. Actually, it turns out that if we only look at this code, we have absolutely no idea what function will be called by print_n. It might be the print function template given here, but it might not be. Why? Argument-dependent lookup. As an example, let's say you have written a class to represent a unicorn. For some reason, you've also defined a function named print (what a coincidence!) that just causes the program to crash by writing to a dereferenced null pointer (who knows why you did this; that's not important): namespace my_stuff { struct unicorn { /* unicorn stuff goes here */ }; std::ostream& operator<<(std::ostream& os, unicorn x) { return os; } // Don't ever call this! It just crashes! I don't know why I wrote it! void print(unicorn) { *(int*)0 = 42; } } Next, you write a little program that creates a unicorn and prints it four times: int main() { my_stuff::unicorn x; utility::print_n(x, 4); } You compile this program, run it, and... it crashes. "What?! No way," you say: "I just called print_n, which calls the print function to print the unicorn four times!" Yes, that's true, but it hasn't called the print function you expected it to call. It's called my_stuff::print. Why is my_stuff::print selected? During name lookup, the compiler sees that the argument to the call to print is of type unicorn, which is a class type that is declared in the namespace my_stuff. Because of argument-dependent lookup, the compiler includes this namespace in its search for candidate functions named print. It finds my_stuff::print, which is then selected as the best viable candidate during overload resolution: no conversion is required to call either of the candidate print functions and nontemplate functions are preferred to function templates, so the nontemplate function my_stuff::print is the best match. (If you don't believe this, you can compile the code in this question as-is and see ADL in action.) Yes, argument-dependent lookup is an important feature of C++. It is essentially required to achieve the desired behavior of some language features like overloaded operators (consider the streams library). That said, it's also very, very flawed and can lead to really ugly problems. There have been several proposals to fix argument-dependent lookup, but none of them have been accepted by the C++ standards committee.
2,958,694
3,042,040
Recommended migration strategy for C++ project in Visual Studio 6
For a large application written in C++ using Visual Studio 6, what is the best way to move into the modern era? I'd like to take an incremental approach where we slowly move portions of the code and write new features into C# for example and compile that into a library or dll that can be referenced from the legacy application. Is this possible and what is the best way to do it? Edit: At this point we are limited to the Express editions which I believe don't allow use of the MFC libraries which are heavily used in our current app. It's also quite a large app with a lot of hardware dependencies so I don't think a wholesale migration is in the cards. Edit2: We've looked into writing COM-wrapped components in C# but having no COM experience this is scary and complicated. Is it possible to generate a C# dll with a straight-C interface with all the managed goodness hidden inside? Or is COM a necessary evil?
Faced with the same task, my strategy would be something like: Identify what we hope to gain by moving to 2010 development - it could be improved quality assurance: unit testing, mocking are part of modern development tools slicker UI: WPF provides a modern look and feel. productivity: in some areas, .NET development is more productive than C++ development support: new tools are supported with improvements and bugfixes. Identify which parts of the system will not gain from being moved to C#: hardware access, low-level algorithmic code pretty much most bespoke non-UI working code - no point throwing it out if it already works Identify which parts of the system need to be migrated to c#. For these parts, ensure that the current implementation in C++ is decoupled and modular so that those parts can be swapped out. If the app is a monolith, then considerable work will be needed refactoring the app so that it can be broken up and select pieces reimplemented in c#. (It is possible to refactor nothing, instead just focus on implementing new application functionality in c#.) Now that you've identified which parts will remain in C++ and which parts will be implemented in c#, (or just stipulate that new features are in c#) then focus turns to how to integrate c# and c++ into a single solution use COM wrappers - if your existing C++ project makes good use of OO, this is often not as difficult as it may seem. With MSVC 6 you can use the ATL classes to expose your classes as COM components. Integrate directly the native and c# code. Integrating "legacy" compiled code requires an intermediate DLL - see here for details. Mixing the MFC UI and c# UI is probably not achieveable, and not adviseable either as it would produce a UI mix of two distinct styles (1990s grey and 2010 vibe). It is simpler to focus on achieving incremental migration, such as implementing new application code in c# and calling that from the native C++ code. This keeps the amount of migrated c# code small to begin with. As you get more into the 2010 development, you can then take the larger chunks that cannot be migrated incrementally, such as the UI.
2,958,747
2,958,802
What is the nicest way to parse this in C++?
In my program, I have a list of "server address" in the following format: host[:port] The brackets here, indicate that the port is optional. host can be a hostname, an IPv4 or IPv6 address (possibly in "bracket-enclosed" notation). port, if present can be a numeric port number or a service string (like: "http" or "ssh"). If port is present and host is an IPv6 address, host must be in "bracket-enclosed" notation (Example: [::1]) Here are some valid examples: localhost localhost:11211 127.0.0.1:http [::1]:11211 ::1 [::1] And an invalid example: ::1:80 // Invalid: Is this the IPv6 address ::1:80 and a default port, or the IPv6 address ::1 and the port 80 ? ::1:http // This is not ambigous, but for simplicity sake, let's consider this is forbidden as well. My goal is to separate such entries in two parts (obviously host and port). I don't care if either the host or port are invalid as long as they don't contain a non-bracket-enclosed : (290.234.34.34.5 is ok for host, it will be rejected in the next process); I just want to separate the two parts, or if there is no port part, to know it somehow. I tried to do something with std::stringstream but everything I come up to seems hacky and not really elegant. How would you do this in C++ ? I don't mind answers in C but C++ is prefered. Any boost solution is welcome as well. Thank you.
Have you looked at boost::spirit? It might be overkill for your task, though.
2,958,836
2,958,887
What is this conversion called?
Is there a name or a term for this type of conversion in the c++ community? Has anyone seen this conversion be referred to as "implicit conversion"? class ALPHA{}; class BETA{ public: operator ALPHA(){return alpha;} private: ALPHA alpha; }; void func(ALPHA alpha){} int main(){ BETA beta; func(beta); return 0; }
It's normally called a conversion function. It isn't an implicit conversion per se, but does allow implicit conversion to the target type. Edit: just checked to be sure -- §12.3.2 of the standard uses the phrase "conversion function". Edit2: I checked in the official standard, which isn't (at least supposed to be) freely available (though you can buy it from the ISO or most member standards organizations such as ANSI, BSI, etc.) A lot of people prefer to save the money and use the final committee draft, which is free.
2,959,069
2,959,080
C++ memcpy from double array to float array
Is is possible to memcpy from a double array to a float array safely?
Depends on what you want. The values certainly won't be preserved. If you need that, use std::copy. #include <algorithm> int main() { double a[] = {1.618, 3.1416, 2.7, 0.707, 1.0}; float b[5]; std::copy(a, a + 5, b); }
2,959,164
2,959,210
Extract a C/C++ header file from a C# class exposed to COM
I'm not sure I've setup everything I've needed to in my C# class to properly, but it does work in COM. I've been looking for an example of a C# class that was successfully used in a C/C++ project, but haven't come across anything. I've tried using the OLE/COM Object View app to open the .tlb file and save as .h, but it gives some errors: MIDL1009: unknown argument ignored; MIDL1001: cannot open input file Studio "Studio" isn't the name of the file, it's Syslog, so that raises a red flag to me. Any ideas?
If you have a tlb you do not need a header file. #import of the tlb will generate it for you automatically. #import "my.tlb" named_guids raw_interfaces_only See more about #import here.
2,959,297
2,959,376
Is there any C\C++ Cross-platform library for sharing data between app's?
Is there any C\C++ Cross-platform library for sharing data between app's?
Google's Protocol Buffers might fit the bill.
2,959,473
2,959,829
Setting Environment Variables For NMAKE Before Building A 'Makefile Solution'
I have an MSVC Makefile Project in which I need to set an environment variable before running NMAKE. For x64 builds I needs to set it to one value, and for x86 builds I need to set it to something else. So for example, when doing a build I would want to SET PLATFORM=win64 if I'm building a 64-bit compile, or SET PLATFORM=win32 if I'm building 32-bit. There does not appear to be an option to set environment variables or add a pre-build even for makefile projects. How do I do this? EDIT: Running MSVC 2008
Just edit the Configuration Properties + NMake + Build Command Line. Click the button with the dots and enter something like this: set PLATFORM=win32 nmake -f makefile.mak Repeat for your 64-bit configuration.