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,722,239
2,722,325
Migrating Application Configuration from Windows Registry to SQLite
Currently, I am working on the migration mentioned in the title line. Problem is application configuration that is kept in registry has a tree like structure, for example: X |->Y |->Z |->SomeKey someValue W |->AnotherKey anotherValue and so on. How can I model this structure in SQLite (or any other DB)? If you have experience in similar problems, please send posts. Thanks in advance.
Baris, this structure its similar to a directory/file structure. You can model this with a simple parent<>child relationship on the directories and key value pairs relatade to the directory. Something like Directory: id integer auto_increment; name string not null; parent_id integer not null default 0; Property: id integer auto_increment; key string; value string; directory_id integer not null; With this you can address the root directories searching for directories with parent_id=0, child directories by looking at WHERE parent_id=someid and for properties on that looking for directory_id=someid. Hope this helps :)
2,722,241
2,722,367
List - Strings - Textfiles
I've got a few questions concerning text files,list and strings. I wonder if it is possible to put in a code which reads the text in a textfile,and then using "string line;" or something else to define each new row of the text and turn all of them into one list. So I can sort the rows, remove a row or two or even all of them or search through the text for a specific row.
In C++, you'd typically do this with an std::vector: std::vector<std::string> data; std::string temp; while (std::getline(infile, temp)) data.push_back(temp); Sorting them would then look like: std::sort(data.begin(), data.end()); Deleting row N would look like: data.erase(data.begin() + N);
2,722,421
2,722,623
how to determine value of cxxflags in bjam? Or append to it?
I need to add to compiler flags using bjam. So either I need a way to append to the existing flags -- like CXXFLAGS+=whatever using gmake -- or I need to know the currently-used value of cxxflags so I can replace it with my additions. As usual, the documentation leaves me astonished at the complexity of bjam but no closer to being able to do anything useful with it.
If you are only looking to do this on the command line you can add flags by specifying "feature=value" arguments. In the case of the make CXXFLAGS the corresponding would be "cxxflags=--some-option". Refer to the Boost Build docs section on built-in features for other such possible features to use. If you are using Boost Build as your build system, and hence need to specify them in your Jamfiles, then you need to add requirements to you project and/or targets (see BB projects and BBv2 targets).
2,722,432
2,722,695
how to implement OOP using QT
this is a simple OOP QT question. my app consists of main window (QMainWindow) and a table (QTableWidget). in the main window i have arguments and variables which i would like to pass to the table class, and to access methods in main widnow class from the table class, how should i do it ? mainwindow.h class MainWindow : public QMainWindow { Q_OBJECT private: int a; int b; Spreadsheet *spreadsheet; public: void set_a(int); void set_b(int); spreadsheet.h class Spreadsheet : public QTableWidget { Q_OBJECT public: Spreadsheet(QWidget *parent = 0); atm i define Spreadsheet like this: spreadsheet = new Spreadsheet(this); and i'd like to access set_a() from spreadsheet.cpp...
You can use the parent() method in the Spreadsheet object to get a pointer to your MainWindow. For example, // spreadsheet.cpp MainWindow* mainWindow = (MainWindow*) this->parent(); mainWindow->set_a(123); Of course, the parent object passed to Spreadsheet's constructor should be your MainWindow instance for this to work. However, you should seriously consider oscode's suggestion, since it also points you towards creating a more Qt-like API.
2,722,442
2,722,560
When to choose std::vector over std::map for key-value data?
Considering the positive effect of caching and data locality when searching in primary memory, I tend to use std::vector<> with std::pair<>-like key-value items and perform linear searches for both, if I know that the total amount of key-value items will never be "too large" to severely impact performance. Lately I've been in lots of situations where I know beforehand that I will have huge amounts of key-value items and have therefore opted for std::map<> from the beginning. I'd like to know how you make your decisions for the proper container in situations like the ones described above. Do you always use std::vector<> (or similar)? always use std::map<> (or similar)? have a gut feeling for where in the item-count range one is preferable over the other? something entirely different? Thanks!
I only rarely use std::vector with a linear search (except in conjunction with binary searching as described below). I suppose for a small enough amount of data it would be better, but with that little data it's unlikely that anything is going to provide a huge advantage. Depending on usage pattern, a binary search on an std::vector can make sense though. A std::map works well when you need to update the data regularly during use. In quite a few cases, however, you load up some data and then you use the data -- but after you've loaded the data, it mostly remains static (i.e., it changes very little, if at all). In this case, it can make a lot of sense to load the data into a vector, sort it if necessary, and then do binary searches on the data (e.g. std::lower_bound, std::equal_range). This gives pretty much the best of both worlds -- low-complexity binary searches and good cache usage from high locality of reference (i.e., the vector is contiguous, as opposed to the linked structure of a std::map). The shortcoming, of course, is that insertions and deletions are slow -- but this is one time I have used your original idea -- store newly inserted data separately until it reaches some limit, and only then sort it in with the rest of the data, so a single search consists of a binary search of the main body of the data, followed by a linear search of the (small amount) of newly inserted data.
2,722,522
2,722,549
why do game engines prefer static libraries over dynamic link libraries
I've been reading a few gaming books. And they always prefer to create the engine as a static library over dynamic link. I am new to c++ so I am not highly knowledge when it comes to static libraries and dynamic link libraries. All I know is static libraries increase the size of your program, where DLL link libraries are loaded as you need them within your program. [edit] I've played games where it almost seemed they used DLL's to load in sound, lighting, and what not all individually. as the level was loading up. cause you don't necessarily need that when your at the game menu.
Dynamic link libraries need to be position independent; this can cause performance inefficiencies on some processor architectures. Static libraries can be optimized when included in your program, e.g., by stripping dead code. This can improve cache performance.
2,722,537
2,722,589
How do virtual destructors work?
Few hours back I was fiddling with a Memory Leak issue and it turned out that I really got some basic stuff about virtual destructors wrong! Let me put explain my class design. class Base { virtual push_elements() {} }; class Derived:public Base { vector<int> x; public: void push_elements(){ for(int i=0;i <5;i++) x.push_back(i); } }; void main() { Base* b = new Derived(); b->push_elements(); delete b; } The bounds checker tool reported a memory leak in the derived class vector. And I figured out that the destructor is not virtual and the derived class destructor is not called. And it surprisingly got fixed when I made the destructor virtual. Isn't the vector deallocated automatically even if the derived class destructor is not called? Is that a quirk in BoundsChecker tool or is my understanding of virtual destructor wrong?
Deleting a derived-class object through a base-class pointer when the base class does not have a virtual destructor leads to undefined behavior. What you've observed (that the derived-class portion of the object never gets destroyed and therefore its members never get deallocated) is probably the most common of many possible behaviors, and a good example of why it's important to make sure your destructors are virtual when you use polymorphism this way.
2,722,650
2,722,687
c++ compilation error
i got a compile error which i do not understand. i have a h/cpp file combination that does not contain a class but just defines some utility functions. when i try to use a struct that is defined in another class i get the error: error C2027: use of undefined type 'B::C' so, stripped down to the problem, the h-file looks like this namespace A { void foo(B::C::SStruct const & Var); } the definition of SStruct is in a class which is in another h-file, that is of course included. namespace B { class C { public: struct SStruct { }; }; } the strange thing is, i can use this struct in other classes fine, it just seems to be related to this one h-file which contains just utility functions. what am i missing here? thanks!
After correcting missing semicolons etc. this compiles: namespace B { class C { public: struct SStruct { }; }; } namespace A { void foo(B::C::SStruct const & Var); } Obviously, if the order of the two namespaces were switched, this would not work. Possibly you are #including your headers in the wrong order. If this is the error, that's bad design - you should not allow header order to matter in your code.
2,722,658
2,722,684
What is the best way to expose a callback API - C++
I have a C++ library that should expose some system\ resource calls as callbacks from the linked application. For example: the interfacing application (which uses this library) can send socket management callback functions - send, receive, open, close etc., and the library will use this implementation in stead of the library's implementation. (This way enables the application to manage the sockets by itself, can be useful). This library has to expose also more callbacks, like, for example, a password validation, so I wonder if there is a preferred method to expose the callback sending option in one API. Something like: int AddCallbackFunc (int functionCallbackType, <generic function prototype>, <generic way to pass some additional arguments>) Then within my library I will assign the callback to the appropriate function pointer according to the functionCallbackType parameter. Is there any way to implement it in a generic way which will fit ANY function prototype and ANY additional arguments? Your help will be more than appreciated... Thanks!
Why not have it accept a 0 argument functor and just have the user use boost::bind to build the arguments into it before registering it? Basically example (calls instead of stores, but you get the point): #include <tr1/functional> #include <iostream> void callback(const std::tr1::function<int()> &f) { f(); } int x() { std::cout << "x" << std::endl; return 0; } int y(int n) { std::cout << "y = " << n << std::endl; return 0; } int main(int argc, char *argv[]) { callback(x); callback(std::tr1::bind(y, 5)); } EDIT: There is an option B, which is to basically implement what bind does under the hood with structures to store all the needed info and inheritance for polymorphism... it becomes a mess real quick. I would not recommend it, but it will work. You can also save from grief by forcing a return type of int, but that only saves you a little. #include <iostream> struct func_base { virtual int operator()() = 0; }; // make one of these for each arity function you want to support (boost does this up to 50 for you :-P struct func0 : public func_base { typedef int (*fptr_t)(); func0(fptr_t f) : fptr(f) { } virtual int operator()() { return fptr(); } fptr_t fptr; }; // demonstrates an arity of 1, templated so it can take any type of parameter template <class T1> struct func1 : public func_base { typedef int (*fptr_t)(T1); func1(fptr_t f, T1 a) : fptr(f), a1(a) { } virtual int operator()() { return fptr(a1); } fptr_t fptr; T1 a1; }; void callback(func_base *f) { (*f)(); } int x() { std::cout << "x" << std::endl; return 0; } int y(int n) { std::cout << "y = " << n << std::endl; return 0; } int main(int argc, char *argv[]) { // NOTE: memory leak here... callback(new func0(x)); callback(new func1<int>(y, 5)); }
2,722,696
2,724,055
Caching XSD schema to reuse in several XML DOM parser tasks in Xerces
How can I cache an XSD schema (residing on disk) to be reused when parsing XMLs in Xerces (C++)? I would like to load the XSD schema when starting the process, then, whenever I need to parse an XML, to validate it first using this loaded schema.
I think I found what I need here.
2,722,700
2,722,745
How to convert a char* to a string?
When I convert char* to an string it gives an bad memory allocation error in 'new.cpp' . I used following method to convert char* called 'strData' and 'strOrg' to string. const char* strData = dt.data(); int length2 = dt.length(); string s1(strData); First time it work without any problem. But in the second convertion it gives above error. When I swap the two conversion in the order, it give the error always in the second conversion regardless of the char* I am converting. Whole code is shown in the following. mysqlpp::Query query = conn.query("SELECT data,origin from image where id =2"); mysqlpp::UseQueryResult res = query.use(); mysqlpp::Row eee= res.fetch_row(); mysqlpp::Row::reference dt = eee.at(0); mysqlpp::Row::reference org = eee.at(1); const char* strData = dt.data(); int length2 = dt.length(); string s1(strData); istringstream is1(s1); char * imgData = new char; is1.read(reinterpret_cast<char *> (imgData), length2); delete [] strData; const char* strOrg = org.data(); int length3 = org.length(); string s2(strOrg); istringstream is2(s2); char * imgOrg = new char; is2.read(reinterpret_cast<char *> (imgOrg), length3); delete [] strOrg; This where the error comes from void *__CRTDECL operator new(size_t size) _THROW1(_STD bad_alloc) { void *p; while ((p = malloc(size)) == 0) if (_callnewh(size) == 0) { // report no memory static const std::bad_alloc nomem; _RAISE(nomem); } return (p); } How can I solve this?
Instead of char * imgData = new char; is1.read(reinterpret_cast<char *> (imgData), length2); try char * imgData = new char[length2]; is1.read(reinterpret_cast<char *> (imgData), length2); When you read data from an istringstream using read, the buffer you provide must have enough space to hold the results! If you call new char; you get space for one char. Use new char[n]; to get space for n.
2,722,824
2,722,849
turning a project into a static library
I checked out the microsoft documents. it shows how to create a static library upon creation of the project. but not necessarily on how to convert a previously made project, into a static library. So my question is, where do I go to turn my previously made project, into a static lib. so I can include it in my other projects
Project | Properties -> Configuration Properties -> General -> Configuration Type (Static Library).
2,722,879
2,722,898
Calling constructors in c++ without new
I've often seen that people create objects in C++ using Thing myThing("asdf"); Instead of this: Thing myThing = Thing("asdf"); This seems to work (using gcc), at least as long as there are no templates involved. My question now, is the first line correct and if so should I use it?
Both lines are in fact correct but do subtly different things. The first line creates a new object on the stack by calling a constructor of the format Thing(const char*). The second one is a bit more complex. It essentially does the following Create an object of type Thing using the constructor Thing(const char*) Create an object of type Thing using the constructor Thing(const Thing&) Call ~Thing() on the object created in step #1
2,722,939
16,694,704
C++ resize a docked Qt QDockWidget programmatically?
I've just started working on a new C++/Qt project. It's going to be an MDI-based IDE with docked widgets for things like the file tree, object browser, compiler output, etc. One thing is bugging me so far though: I can't figure out how to programmatically make a QDockWidget smaller. For example, this snippet creates my bottom dock window, "Build Information": m_compilerOutput = new QTextEdit; m_compilerOutput->setReadOnly(true); dock = new QDockWidget(tr("Build Information"), this); dock->setWidget(m_compilerOutput); addDockWidget(Qt::BottomDockWidgetArea, dock); When launched, my program looks like this (bear in mind the early stage of development): However, I want it to appear like this: I can't seem to get this to happen. The Qt Reference on QDockWidget says this: Custom size hints, minimum and maximum sizes and size policies should be implemented in the child widget. QDockWidget will respect them, adjusting its own constraints to include the frame and title. Size constraints should not be set on the QDockWidget itself, because they change depending on whether it is docked Now, this suggests that one method of going about doing this would be to sub-class QTextEdit and override the sizeHint() method. However, I would prefer not to do this just for that purpose, nor have I tried it to find that to be a working solution. I have tried calling dock->resize(m_compilerOutput->width(), m_compilerOutput->minimumHeight()), calling m_compilerOutput->setSizePolicy() with each of its options... Nothing so far has affected the size. Like I said, I would prefer a simple solution in a few lines of code to having to create a sub-class just to change sizeHint(). All suggestions are appreciated.
I just went through this same process. After trying far too many permutations of resize(), adjustSize() and friends on dock widgets and their contained widget, none of which worked, I ended up subclassing QListView and adding that sizeHint() method. Now it works like a charm.
2,723,146
2,723,180
Create object of unknown class (two inherited classes)
I've got the following classes: class A { void commonFunction() = 0; } class Aa: public A { //Some stuff... } class Ab: public A { //Some stuff... } Depending on user input I want to create an object of either Aa or Ab. My imidiate thought was this: A object; if (/*Test*/) { Aa object; } else { Ab object; } But the compiler gives me: error: cannot declare variable ‘object’ to be of abstract type ‘A’ because the following virtual functions are pure within ‘A’: //The functions... Is there a good way to solve this?
Use a pointer: A *object; if (/*Test*/) { object = new Aa(); } else { object = new Ab(); }
2,723,284
2,723,334
How to detect if the Windows DWORD_PTR type is supported, using an ifdef?
There are some new integer types in the Windows API to support Win64. They haven't always been supported; e.g. they aren't present in MSVC6. How can I write an #if condition to detect if these types are supported by <windows.h>? (My code needs to compile under many different versions of Microsoft Visual C++, including MSVC6. So I need to provide my own definitions of these types, with an #if to disable them in newer compilers). (For searchers, the full list of types is: DWORD_PTR, INT_PTR, LONG_PTR, UINT_PTR, ULONG_PTR)
The macro MSC_VER is a value that is within the range [1200, 1300) for MSVC 6. So you can use #if MSC_VER>=1200 && MSC_VER<1300. EDIT: As Anders said, this is not really that valid of a test beyond "is my compiler MSVC 6". However, you can also use: #if defined(MAXULONG_PTR) Since DWORD_PTR is a value type, it has a maximum value defined for it in basetsd.h.
2,723,285
2,723,314
C++ methods which take templated classes as argument
I have a templated class Vector<class T, int N> Where T is the type of the components (double for example) and n the number of components (so N=3 for a 3D vector) Now I want to write a method like double findStepsize(Vector<double,2> v) {..} I want to do this also for three and higher dimensional vectors. Of course I could just introduce further methods for higher dimensions, but the methods would have a lot of redundant code, so I want a more generic solution. Is there a way to create a method which takes a templated class without further specializing it (in this case without specifying T or N)? Like double findStepsize(Vector<T,N> v) ?
Yes it is template<typename T, int N> double findStepsize(Vector<T,N> v) {..} If you call it with a specific Vector<T, N>, the compiler will deduce T and N to the appropriate values. Vector<int, 2> v; // ... fill ... findStepsize(v); /* works */ The above value-parameter matches your example, but it's better to pass user defined classes that need to do work in their copy constructors by const reference (Vector<T, N> const& instead). So you avoid copies, but still can't change the caller's argument.
2,723,505
2,723,530
Starting a C++ project. Should I worry about freeing dynamic allocated memory?
I am pretty proficient with C, and freeing memory in C is a must. However, I'm starting my first C++ project, and I've heard some things about how you don't need to free memory, by using shared pointers and other things. Where should I read about this? Is this a valuable replacement for proper delete C++ functionality? How does it work? EDIT I'm confused, some people are saying that I should allocate using new and use smart pointers for the deallocation process. Other people are saying that I shouldn't allocate dynamic memory in the first place. Others are saying that if I use new I also have to use delete just like C. So which method is considered more standard and more-often used?
Where should I read about this? Herb Sutter's Exceptional C++ and Scott Meyers's More Effective C++ are both excellent books that cover the subject in detail. There is also a lot of discussion on the web (Google or StackOverflow searches for "RAII" or "smart pointer" will no doubt yield many good results). Is this a valuable replacement for proper delete C++ functionality? Absolutely. The ability not to worry about cleaning up resources, especially when an exception is thrown, is one of the most valuable aspects of using RAII and smart pointers.
2,723,671
2,724,034
How to debug packet loss?
I wrote a C++ application (running on Linux) that serves an RTP stream of about 400 kbps. To most destinations this works fine, but some destinations expericence packet loss. The problematic destinations seem to have a slower connection in common, but it should be plenty fast enough for the stream I'm sending. Since these destinations are able to receive similar RTP streams for other applications without packet loss, my application might be at fault. I already verified a few things: - in a tcpdump, I see all RTP packets going out on the sending machine - there is a UDP send buffer in place (I tried sizes between 64KB and 300KB) - the RTP packets mostly stay below 1400 bytes to avoid fragmentation What can a sending application do to minimize the possibility of packet loss and what would be the best way to debug such a situation ?
Don't send out packets in big bursty chunks. The packet loss is usually caused by slow routers with limited packet buffer sizes. The slow router might be able to handle 1 Mbps just fine if it has time to send out say, 10 packets before receiving another 10, but if the 100 Mbps sender side sends it a big chunk of 50 packets it has no choice but to drop 40 of them. Try spreading out the sending so that you write only what is necessary to write in each time period. If you have to write one packet every fifth of a second, do it that way instead of writing 5 packets per second.
2,723,686
2,723,830
C++ memcpy return value
According to http://en.cppreference.com/w/cpp/string/byte/memcpy C++'s memcpy takes three parameters: destination, source and size/bytes. It also returns a pointer. void* memcpy( void* dest, const void* src, std::size_t count ); Why is that so? Aren't the parameters enough to input and copy data? Am I misunderstanding something? The examples don't use the return value.
If a function has nothing specific to return, it is often customary to return one of the input parameters (the one that is seen as the primary one). Doing this allows you to use "chained" function calls in expressions. For example, you can do char buffer[1024]; strcat(strcpy(buffer, "Hello"), " World"); specifically because strcpy returns the original dst value as its result. Basically, when designing such a function, you might want to choose the most appropriate parameter for "chaining" and return it as the result (again, if you have noting else to return, i.e. if otherwise your function would return void). Some people like it, some people don't. It is a matter of personal preference. C standard library often supports this technique, memcpy being another example. A possible use case might be something along the lines of char *clone_buffer(const char *buffer, size_t size) { return memcpy(new char[size], buffer, size); } If memcpy did not return the destination buffer pointer, we'd probably have to implement the above as char *clone_buffer(const char *buffer, size_t size) { char *clone = new char[size]; memcpy(clone, buffer, size); return clone; } which looks "longer". There's no reason for any difference in efficiency between these two implementations. And it is arguable which version is more readable. Still many people might appreciate the "free" opportunity to write such concise one-liners as the first version above. Quite often people find it confusing that memcpy returns the destination buffer pointer, because there is a popular belief that returning a pointer form a function should normally (or always) indicate that the function might allocate/reallocate memory. While this might indeed indicate the latter, there's no such hard rule and there has never been, so the often expressed opinion that returning a pointer (like memcpy does) is somehow "wrong" or "bad practice" is totally unfounded.
2,723,697
2,723,792
C++ Pointer to a function which takes an instance of a templated class as argument
I have trouble compiling a class, which has function pointers as member variables. The pointers are to functions which take an instance of a class as argument. Like template<class T, int N> double (*f)(Vector<T,N> v); I get "error: data member 'f' cannot be a member template" Compiler is gcc 4.2. Edit Before using templates I just had double (*f)(Vector v); This also works double (*f)(Vector<double,2> v) But I would like to have a function pointer for a function which takes a generic Vector as argument..
Use a member typedef: template <typename T, int N> class Vector { public: /// type of function pointer typedef double (*FuncPtr)( const Vector& ); }; // concrete type typedef Vector<double,10> VecDouble10; // actual function double func( const VecDouble10>& ); // usage VecDouble10::FuncPtr fp = func;
2,724,110
2,724,193
Can't link Hello World!
Guys that is code copied from a book (Programming Windows 5th edition): #include <windows.h> int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow) { MessageBox (NULL, TEXT ("Hello, Windows 98!"), TEXT ("HelloMsg"), 0) ; return 0 ; } Link to the topic in which this book is recommended. Can't compile it with VS2010. What am I doing wrong? Error 1 error LNK2001: unresolved external symbol _WinMainCRTStartup Thanks.
It will depend on how you set up the project. In VS2010, if I create a new project via File->New->Project, Visual C++, Empty Project, then add a new C++ file, and copy your code in, it compiles and runs just fine. If you've created a different type of project, it may be using different link libraries. Try right-clicking on your project in Solution Explorer, going to Properties->Linker->System, and setting SubSystem to "Windows (/SUBSYSTEM:WINDOWS) The Win32 APIs are old, but for the most part are perfectly usable if you want to do native Windows programming. Windows has done a great deal of work to ensure that as long as you've followed the documentation, old APIs will not change. You can still compile 16-bit Windows 3.1 code from 1992 and run it on 32-bit Windows 7. Edit: It could also be that in Properties->C/C++->Advanced, you have Omit Default Library Name set to "Yes", you probably want it set to "No" Or also Properties->Linker->Input->Ignore Default Libs should be set to No.
2,724,170
2,730,073
OpenGL texture randomly not shown
I have got a very, very strange problem in my C++ OpenGL application. I simply load a texture and apply it to a quadric: glGenTextures(1, &tex); glBindTexture(GL_TEXTURE_2D, tex); glTexImage2D(GL_TEXTURE_2D, 0, 3, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); Then glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, tex); gluQuadricDrawStyle(quad,GLU_FILL); gluQuadricTexture(quad,GL_TRUE); gluCylinder(quad,1,0,2,20,1); glDisable(GL_TEXTURE_2D); Now: it works perfectly 9 times out of ten, but sometimes the texture isn't shown (the quadric stays white). The image is correctly loaded, so the problem should be with OpenGL. I have tried with several different images too. Always GL_NO_ERROR. Any idea ? It is driving me crazy...
Found :) It was the GLint texture member that wasn't correctly reallocated in the copy constructor. However, i still don't understand why it worked sometimes...
2,724,197
2,724,213
Is this not downcasting?
If I do double d = 34.56; int i = (int)d; Am I not "downcasting"? OR Is this term only used in terms of classes and objects? I am confused because in this case we are "downcasting" from a bigger double to a smaller int, but in case of classes, we "downcast" from a smaller base class to a bigger derived class. Aren't these two conventions, in some sense, opposite?
No, you are not down casting. You are just casting, and you're chopping off anything after the decimal. Down casting doesn't apply here. The primitives int and double are not objects in C++ and are not related to each other in the way two objects in a class hierarchy are. They are separate and primitive entities. Down casting refers to the act of casting one object into another object that derives from it. It refers to the act of moving down from the root of the class hierarchy. It has nothing to do with the sizes of types in question.
2,724,242
2,724,476
Multi color Edit Field (Win32)
I want to create a program that will parse text for key words and make these words a certain color. What type of control supports many different colors? Would I have to create my own, or override the OnPaint() of a basic control or something? (Id like to avoid making my own control from scratch) Thanks
One option would be to use the rich edit control: http://www.codeproject.com/KB/edit/RichEditLog_Demo.aspx Another option would be to build a custom control: http://www.codeproject.com/KB/edit/brainchild.aspx
2,724,252
2,728,312
Qt 4.x: how to implement drag-and-drop onto the desktop or into a folder?
I've written a little file-transfer application written in C++ using Qt 4.x ... it logs into a server, shows the user a list of files available on the server, and lets the user upload or download files. This all works fine; you can even drag a file in from the desktop (or from an open folder), and when you drop the file icon into the server-files-list-view, the dropped file gets uploaded to the server. Now I have a request for the opposite action as well... my users would like to be able to drag a file out of the server-files-list-view and onto the desktop, or into an open folder window, and have that file get downloaded into that location. That seems like a reasonable request, but I don't know how to implement it. Is there a way for a Qt application to find out the directory corresponding to where "drop event" occurred, when the icon was dropped onto the desktop or into an open folder window? Ideally this would be a Qt-based platform-neutral mechanism, but if that doesn't exist, then platform-specific mechanisms for MacOS/X and Windows (XP or higher) would suffice. Any ideas?
Look at QMimeData and its documentation, it has a virtual function virtual QVariant retrieveData ( const QString & mimetype, QVariant::Type type ) const this means to do you drag to the outside you implement this functions accordingly class DeferredMimeData : public QMimeData { DeferredMimeData(QString downloadFilename) : m_filename(downloadFilename) virtual QVariant retrieveData (const QString & mimetype, QVariant::Type type) const { if (mimetype matches expected && type matches expected) { perform download with m_filename } } } The delayed encoding examples shows this principle. You will probably also have to override hasFormat and formats to provide the appropriate types, application/octet-stream probably being the one that might get you the most play, you will probably have to read up on how windows specifically handles drag and drop using mime types. I don't know how you will supply the file name under which the file is saved, but you will probably have to get into the windows side of things. Looking at the source of QWindowsMime might also help. There might me a multiple step process where you will get requests for text/uri-list data for the filenames and then application/octet-stream for the data. Hope this helps
2,724,316
2,724,465
C++: Efficiently adding integers to strings
I know how to add integers to strings, but I'm not sure I'm doing it in an efficient matters. I have a class where I often have to return a string plus an integer (a different integer each time), in Java I would do something like public class MyClass { final static String S = "MYSTRING"; private int id = 0; public String getString() { return S + (id++); } } But in C++ I have to do; class MyClass { private: std::string S; // For some reason I can't do const std::string S = "MYSTRING"; int id; public: MyClass() { S = "MYSTRING"; id = 0; } std::string getString() { std::ostringstream oss; oss << S << id++; return oss.str(); } } An additional constraint: I don't want (in fact, in can't) use Boost or any other librairies, I'll have to work with the standard library. So the thing is; the code works, but in C++ I have to create a bunch of ostringstream objects, so it seems inefficient. To be fair, perhaps Java do the same and I just don't notice it, I say it's inefficient mostly because I know very little about strings. Is there a more efficient way to do this ?
std::ostringstream is the "standard" way to do this in C++. You might be able to make something more efficient via some custom coding, or laboriously comparing the performance of ostringstream, itoa, and sprintf on all the systems where you'll be deploying this program, but it's probably not worth the effort. I'd say the real problem with the std::ostringstream solution is not about efficiency. The real problem is that the code just looks too complicated. I know you don't want to use Boost, but if you look at Herb Sutter's The String Formatters of Manor Farm, you could just copy the (very tiny) definition of the lexical_cast<>() template into your program. Then your code would look like this: std::string getString() { return S + lexical_cast<std::string>(id++); } Whether this is more efficient than your existing solution depends on a lot of factors (how well your compiler inlines template instantiations, for example), but it definitely looks cleaner.
2,724,343
2,724,515
Reading File in C++ throwing Seg Fault
When trying to read tokens from a file in C++, I receive a seg fault. Just to play with some things, I tried reading over the file and just printing and surprisingly if you uncomment the code for the first file read and then read the second file everything works fine. If you leave the commented code commented, you receive the seg fault upon closing the first file. This could be an issue with the library on my school machine... The stack trace is below for the segfault (below the code itself). It's also interesting to note that I do not have to do this 'hack' for each file I open, once the dummy-commented-code has been executed all subsequent streams open just fine. int main() { ifstream myfile1; ifstream myfile2; int m; //number of elements in 1st file int n; //number of elements in 2nd file int counter = 0; int x = 0; int y = 0; int theta = 0; Minutiae* minutiae; minutiae = new Minutiae(x,y,theta,0); Minutiae* file1_minutiaes; Minutiae* file2_minutiaes; int num; //Some Error is caused with segfault if i Try to fill the minutiae array and then close the file unless i do this first /*//////////////////// myfile1.open("2a"); if (myfile1.is_open()) { counter = 0; while (!myfile1.eof() ) { myfile1 >> x >> y >> theta; minutiae = new Minutiae(x,y,theta,counter); counter++; } myfile1.close(); } else { cout << "unable to open file1" << endl; return(0); } *///////////////////////////////////// myfile1.open("2a"); if (myfile1.is_open()) { counter = 0; myfile1 >> m; file1_minutiaes = new Minutiae[m]; while (!myfile1.eof() ) { myfile1 >> x >> y >> theta; //minutiae = new Minutiae(x,y,theta,counter); //file1_minutiaes[counter] = *minutiae; file1_minutiaes[counter] = *(new Minutiae(x,y,theta,counter)); counter++; } myfile1.close(); cout << "closing file1" << endl; } else { cout << "unable to open file1" << endl; return(0); } //////////////////////////////// } And the stack trace: Starting program: /cs/student/dick_man_chini/Desktop/a.out Program received signal SIGSEGV, Segmentation fault. 0x00c47a72 in _int_free () from /lib/libc.so.6 (gdb) up #1 0x006d9342 in operator delete(void*) () from /usr/lib/libstdc++.so.6 (gdb) up #2 0x006d939e in operator delete[](void*) () from /usr/lib/libstdc++.so.6 (gdb) up #3 0x00686130 in std::basic_filebuf<char, std::char_traits<char> >::_M_destroy_internal_buffer() () from /usr/lib/libstdc++.so.6 (gdb) up #4 0x006874d1 in std::basic_filebuf<char, std::char_traits<char> >::close() () from /usr/lib/libstdc++.so.6 (gdb) up #5 0x006894a6 in std::basic_ifstream<char, std::char_traits<char> >::close() () from /usr/lib/libstdc++.so.6 (gdb) up #6 0x08048e96 in main () (gdb) up Initial frame selected; you cannot go up. (gdb) Thanks in advance.
The common process for reading files: myfile1.open("2a"); // Note the change in the next line if (!myfile1) { cout << "unable to open file1" << endl; return(0); } counter = 0; // Note, this line differs between the two examples. myfile1 >> m; file1_minutiaes = new Minutiae[m]; // Note the change in the following line while (myfile1 >> x >> y >> theta) { //minutiae = new Minutiae(x,y,theta,counter); //file1_minutiaes[counter] = *minutiae; file1_minutiaes[counter] = *(new Minutiae(x,y,theta,counter)); counter++; } myfile1.close(); cout << "closing file1" << endl; I suggest you use a std::vector instead of an array: std::vector<Minutiae> file1_minutiaes; When processing data files, a good idea is to use dynamic containers.
2,724,359
2,724,668
Are there any modern platforms with non-IEEE C/C++ float formats?
I am writing a video game, Humm and Strumm, which requires a network component in its game engine. I can deal with differences in endianness easily, but I have hit a wall in attempting to deal with possible float memory formats. I know that modern computers have all a standard integer format, but I have heard that they may not all use the IEEE standard for floating-point integers. Is this true? While certainly I could just output it as a character string into each packet, I would still have to convert to a "well-known format" of each client, regardless of the platform. The standard printf() and atod() would be inadequate. Please note, because this game is a Free/Open Source Software program that will run on GNU/Linux, *BSD, and Microsoft Windows, I cannot use any proprietary solutions, nor any single-platform solutions. Cheers, Patrick
I think it is safe to assume that each platform has an implementation of the IEEE-754 spec that you can rely on. However, even if they all implement the same spec, there is no guarantee that each platform has the exact same implementation, has the same FP control flags set, does the same optimizations, or implements the same non-standard extensions. This makes floating-point determinism very hard to control and somewhat unreliable to use for this kind of thing (where you'll be communicating FP values over the network). For more information on that; read http://gafferongames.com/networking-for-game-programmers/floating-point-determinism/ Another problem to tackle is handling clients that don't have a floating-point unit; most of the time these will be low-end CPUs, consoles or embedded devices. Make sure to take this into account if you want to target them. FP emulation can be done but tends to be very slow on these devices so you'll have to get a hang of doing fixed-point calculations. Be advised though: writing elaborate classes to abstract floating point and fixed point calculations to the same code sounds like a plan but on most devices it isn'ta good one. It doesn't allow you to squeeze out the maximum precision and performance when dealing with fixed point values. Yet another problem is handling the endianness of the floating point values because you cannot just swap bytes and stack 'm in a floating point register again (the bytes might get a different meaning, see http://www.dmh2000.com/cpp/dswap.shtml on that). My advice would be to convert the floats to fixed point intermediate values, do an endian correction if needed and transmit that. Also, don't assume that two floating point calculations on different machines will yield the same results; they don't. However, floating point implementations other than IEEE-754 are rare. For example GPUs tended to use fixed point, but are more likely to have a subset of IEEE-754 these days because they don't want to deal with division-by-zero exceptions but they will have extensions for half-floats that fit in 16 bits. Also, realize that there are libraries out there that have already solved this problem (sending low-level data formats in a gaming context) for you. One such library is RakNet: specifically, its BitStream class is designed to send these kinds of data reliably to different platforms while keeping the overhead to a minimum. For example, RakNet goes through quite some trouble not to waste any bandwidth on sending strings or vectors.
2,724,366
2,727,053
protecting COM interfaces from exceptions
I have several dozen objects exposed through COM interfaces, each of which with many methods, totaling a few hundred methods. These interfaces expose business objects from my app to a scripting engine. I have been given the task of protecting every single one of these methods from exceptions being thrown (to catch them and return an error using COM's Error() function, which incidentally I can find no documentation on because it's impossible to google). To my understanding, this requires that I add a try/catch around the guts of each one of these methods. The catch blocks are going to be similar or identical for each and every one of these hundreds of methods, which strongly smells of a problem (massively violates the DRY principle), but I can't think of any way to avoid changing every method. As far as I can tell, these methods are invoked directly by COM, with no intervening code that I can hook into to catch the exceptions. My current best idea is to make a macro for the catch block, but that has it's own sort of code-smell. Can anyone come up with a better approach? BTW, my app's exceptions do not derive from std::exception, so if there is some way of COM automatically handling standard exceptions, it won't help. And I sadly cannot change the existing exceptions to derive from std::exception.
The most reliable C++ way is to use macros here. I' ready to accept downvotes for saying this, but we've been using this solution for years and haven't seen any serious problems so far. Define a "begin method" macro for clearing IErrorInfo and try { and "end method" for } catch and the error handling. If you design the macros right - put all except the most necessary error handling code into helper functions it will be a tolerable and reliable solution with clean-looking moderately maintainable code. Yes, that doesn't look good at all, but at least it is reliable and standard-compliant way of achieving what you want.
2,724,402
2,724,413
Is there any standard delete functor?
I am looking for a functor that deletes its argument: template<class T> struct delete_functor { void operator()(T* p) { delete p; } }; Is there something like this in std, tr1 or boost?
C++0x will add std::default_delete to the standard library to support std::unique_ptr. It has effectively the same functionality as your delete_functor, but is also specialized to call delete[] for array type objects.
2,724,530
2,724,559
Opt-out of copy constructor
This might be a silly question, but... I've been writing a number of classes that utilize non-copyable members. These classes are never initialized via the copy constructor in my source. When I try to compile without supplying my own copy-constructor, g++ throws out many errors about how it can't build a default copy constructor, due to the non-copyable member objects. Is there a way to tell the compiler to just not give me a copy constructor? EDIT: Yeah... feels silly... I had a case where I was invoking the copy-constructor by accident in a boost::bind call. Lesson learned.
If you don't actually cause the copy-constructor to be called then it is not an error if the compiler would be unable to generate one. It sounds like you are (possibly indirectly) causing the copy-constructor to be used. You can suppress the compiler generated one by declaring your own copy-constructor (you don't need to define it if you're not using it). You can place it in the private section of your class. If this changes the error to say that the copy-constructor is inaccessible or you get link errors then you really are causing the copy-construtor to be used and you need to analyze why this is.
2,724,579
2,724,596
Can I cause a new C++ class instance to fail if certain conditions in the constructor are not met?
As I understand it, when a new class is instantiated in C++, a pointer to the new class is returned, or NULL, if there is insufficient memory. I am writing a class that initializes a linked list in the constructor. If there is an error while initializing the list, I would like the class instantiator to return NULL. For example: MyClass * pRags = new MyClass; If the linked list in the MyClass constructor fails to initialize properly, I would like pRags to equal NULL. I know that I can use flags and additional checks to do this, but I would like to avoid that, if possible. Does anyone know of a way to do this?
The common approach here is to throw an exception (and handle it somewhere higher up). One of the benefits of the exception mechanism is that it allows you to throw an exception from within a class constructor. In that case, you never reach the situation where a pointer is returned to the invalid. You would "get control" at the corresponding catch block. If the pointer was only declared within the try block (or in some other method invoked by the try block), it would be outside your scope in that catch block. That is not a hack - it is quite legitimate and a common programming technique. For example, if your class constructor allocates memory dynamically (e.g., for an internal buffer) and this allocation failed, you would want to throw an exception because at the end of the constructor body you would not have a valid object. Here is an example (I've been doing Java for the past 10 years, so my C++ code below is likely messed up here, maybe someone can edit this for me) // Begin C++ code written by a Java programmer... :) class Myclass { public: Myclass(int length) { if(length<=0) throw BadBufferSizeException("Bla bla bla"); this->buffer = (char*)malloc(length*sizeof(char)); // don't remember the new syntax } void doSomething() { // Code for placing stuff in the buffer } private: char* buffer; }; int main() { try { int len; len = getLengthFromUser(); MyClass* pMyClass = new MyClass(len); myClass->doSomething(); } catch(const Exception & e) { // Whatever... Note how pMyClass is not even accessible here } } Note that if you defined pMyclass to be null outside the try block, and then only reassigned it within the try block when you create the class, in the case of failure you would likely still have null, but you would never have executed doSomething(). If you are concerned about initialization, you could also move the doSomething() call to outside the try-catch block, but you would want to make sure that your pointer is not null. Also note that C++ gives you more (too much?) freedom when it comes to throwing things than other languages. I usually like having a hierarchy of exception classes or using an existing library with such a hierarchy.
2,724,651
2,724,688
Drawing continuously in drawing application
I was wondering how drawing applications draw the entire time the mouse is down without having empty gaps. What I mean is, for example if the program only drew circles at the mouse's X, y coordinate, then if the mouse went too quicly it would seem like a bunch of little circles rather than a nice continuous line. How can this be done without constantly drawing a short straight line between where the mouse was 0.001 seconds ago and where the mouse now is. Thanks
It can't be done without constantly drawing a line between the current mouse point and the previous point, which is why this is what drawing programs generally do do. Fancier drawing programs will fit curvy lines to multiple previous points to achieve a more natural drawing stroke, but the principle is the same. Update: Based on a comment, it appears that you have a timer involved in your drawing code. This is surely unnecessary, since your application will generate a MouseMove event whenever the mouse is moved at all, and you can use that event to draw the next line.
2,724,708
2,724,815
Is it a good practice to pass struct object as parameter to a function in c++?
I tried an example live below: typedef struct point { int x; int y; } point; void cp(point p) { cout<<p.x<<endl; cout<<p.y<<endl; } int main() { point p1; p1.x=1; p1.y=2; cp(p1); } The result thats printed out is: 1 2 which is what I expected. My question is: Does parameter p get the full copy of object p1? If so, I wonder if this is a good practice? (I assumed when the struct gets big in size, this will create a lot of copy overhead).
There is nothing wrong with passing structs as parameters. Everything is passed by value in C++ so a full copy is indeed made. The struct you gave in your example is small so it's probably not a problem if you pass it by value. But if you work with bigger data structures, you may want to pass it by reference. Beware though, passing by reference means that if you modify the struct inside your function, your original struct will be modified. Be sure to use the const keyword in every case where you don't modify the struct. This will give you an immediate information about if your functions do modify the information or not. Your example could be modified to work with references this way : typedef struct point { int x; int y; } point; void cp(const point& p) // You can know that cp doesn't modify your struct { cout<<p.x<<endl; cout<<p.y<<endl; } void mod_point(point& p) // You can know that mod_points modifies your struct { p.x += 1; p.y += 1; } int main() { point p1; p1.x=1; p1.y=2; cp(p1); mod_point(p1); cp(p1); // will output 2 and 3 }
2,724,722
2,724,782
C++ new memory allocation fragmentation
I was trying to look at the behavior of the new allocator and why it doesn't place data contiguously. My code: struct ci { char c; int i; } template <typename T> void memTest() { T * pLast = new T(); for(int i = 0; i < 20; ++i) { T * pNew = new T(); cout << (pNew - pLast) << " "; pLast = pNew; } } So I ran this with char, int, ci. Most allocations were a fixed length from the last, sometimes there were odd jumps from one available block to another. sizeof(char) : 1 Average Jump: 64 bytes sizeof(int): 4 Average Jump: 16 sizeof(ci): 8 (int has to be placed on a 4 byte align) Average Jump: 9 Can anyone explain why the allocator is fragmenting memory like this? Also why is the jump for char so much larger then ints and a structure that contains both an int and char.
There are two issues: most allocators store some additional data prior to the start of the block (typically block size and a couple of pointers) there are usually alignment requirements - modern operating systems typically allocate to at least an 8 byte boundary. So you'll nearly always get some kind of gap between successive allocations. Of course you should never rely on any specific behaviour for something like this, where the implementation is free to do as it pleases.
2,725,044
2,725,129
Can I assume (bool)true == (int)1 for any C++ compiler?
Can I assume (bool)true == (int)1 for any C++ compiler ?
According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0. The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE. A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.
2,725,123
2,725,127
Is there a way to make C macros keyword agnostic?
Is there a way to concatenate keywords in a macro and get C to behave in a more dynamic fashion as in: #define macro(fun,ction,var,iable) function(variable) I know this kind of thing exists in other languages.
You can use ## to concatinate names in macros fun##ction ...
2,725,285
2,725,486
When should I use temporary variables?
Specifically, I'm wondering which of these I should write: { shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock(); if (subMenu) subMenu->setVisible(false); } or: { if (items[j].subMenu.lock()) items[j].subMenu.lock()->setVisible(false); } I am not required to follow any style guidelines. After optimization, I don't think either choice makes a difference in performance. What is generally the preferred style and why? EDIT: the type of items[j].subMenu is boost::weak_ptr. lock() creates a shared_ptr out of it. There is actually an ambiguous difference in the two versions above, regarding how long the temporary shared_ptr lasts, so I wrapped my two examples in { braces } to resolve the ambiguity there.
An alternative method: if(shared_ptr<GuiContextMenu> subMenu = items[j].subMenu.lock()) { subMenu->setVisible(false); } //subMenu is no longer in scope I'm assuming subMenu is a weak_ptr, in which case your second method creates two temporaries, which might or might not be an issue. And your first method adds a variable to a wider scope than it needs to. Personally, I try to avoid assignments within if statements, but this is one of the few cases where I feel its more useful than the alternatives.
2,725,348
2,725,468
How can a class's memory-allocated address be determined from within the constructor?
Is it possible to get the memory-allocated address of a newly-instantiated class from within that class's constructor? I am developing a linked list where multiple classes have multiple pointers to like classes. Each time a new class instantiates, it needs to check its parent's list to make sure it is included. If I try to do something like this: MyClass() // constructor { extern MyClass * pParent; for ( int i = 0; i < max; i++ ) { pParent->rels[i] == &MyClass; // error } } I get this error: error C2275: 'namespace::MyClass' : illegal use of this type as an expression Any thoughts or suggestions would be appreciated. Thanks.
Did you mean to do: pParents->rels[i] = this;
2,725,369
2,725,628
Problem with GetDefaultPrinter() over a VPN c++
I am writing an application that gets its dimensions from the paper ratio of the default printer of the local computer. This all works well unless the default printer is over a VPN. When this is the case, calling GetDefaultPrinter() takes too long. I need to find a way to put a time constraint on GetDefaultPrinter() and if it exceeds that constraint, break out of the function. Any possible solutions would be great. Thanks, Ian
Would putting this sort of functionality into a separate thread be acceptable?
2,725,674
2,725,696
Can my loop be optimized any more?
Below is my innermost loop that's run several thousand times, with input sizes of 20 - 1000 or more. This piece of code takes up 99 - 99.5% of execution time. Is there anything I can do to help squeeze any more performance out of this? I'm not looking to move this code to something like using tree codes (Barnes-Hut), but towards optimizing the actual calculations happening inside, since the same calculations occur in the Barnes-Hut algorithm. Any help is appreciated! Edit: I'm running in Windows 7 64-bit with Visual Studio 2008 edition on a Core 2 Duo T5850 (2.16 GHz) typedef double real; struct Particle { Vector pos, vel, acc, jerk; Vector oldPos, oldVel, oldAcc, oldJerk; real mass; }; class Vector { private: real vec[3]; public: // Operators defined here }; real Gravity::interact(Particle *p, size_t numParticles) { PROFILE_FUNC(); real tau_q = 1e300; for (size_t i = 0; i < numParticles; i++) { p[i].jerk = 0; p[i].acc = 0; } for (size_t i = 0; i < numParticles; i++) { for (size_t j = i+1; j < numParticles; j++) { Vector r = p[j].pos - p[i].pos; Vector v = p[j].vel - p[i].vel; real r2 = lengthsq(r); real v2 = lengthsq(v); // Calculate inverse of |r|^3 real r3i = Constants::G * pow(r2, -1.5); // da = r / |r|^3 // dj = (v / |r|^3 - 3 * (r . v) * r / |r|^5 Vector da = r * r3i; Vector dj = (v - r * (3 * dot(r, v) / r2)) * r3i; // Calculate new acceleration and jerk p[i].acc += da * p[j].mass; p[i].jerk += dj * p[j].mass; p[j].acc -= da * p[i].mass; p[j].jerk -= dj * p[i].mass; // Collision estimation // Metric 1) tau = |r|^2 / |a(j) - a(i)| // Metric 2) tau = |r|^4 / |v|^4 real mij = p[i].mass + p[j].mass; real tau_est_q1 = r2 / (lengthsq(da) * mij * mij); real tau_est_q2 = (r2*r2) / (v2*v2); if (tau_est_q1 < tau_q) tau_q = tau_est_q1; if (tau_est_q2 < tau_q) tau_q = tau_est_q2; } } return sqrt(sqrt(tau_q)); }
Inline the calls to lengthsq(). Change pow(r2,-1.5) to 1/(r2*sqrt(r2)) to lower the cost of the computing r^1.5 Use scalars (p_i_acc, etc.) inside the innner most loop rather than p[i].acc to collect your result. The compiler may not know that p[i] isn't aliased with p[j], and that might force addressing of p[i] on each loop iteration unnecessarily. 4a. Try replacing the if (...) tau_q = with tau_q=minimum(...,...) Many compilers recognize the mininum function as one they can do with predicated operations rather than real branches, avoiding pipeline flushes. 4b. [EDIT to split 4a and 4b apart] You might consider storing tau_..q2 instead as tau_q, and comparing against r2/v2 rather than r2*r2/v2*v2. Then you avoid doing two multiplies for each iteration in the inner loop, in trade for a single squaring operation to compute tau..q2 at the end. To do this, collect minimums of tau_q1 and tau_q2 (not squared) separately, and take the minimum of those results in a single scalar operation on completion of the loop] [EDIT: I suggested the following, but in fact it isn't valid for the OP's code, because of the way he updates in the loop.] Fold the two loops together. With the two loops and large enough set of particles, you thrash the cache and force a refetch from non-cache of those initial values in the second loop. The fold is trivial to do. Beyond this you need to consider a) loop unrolling, b) vectorizing (using SIMD instructions; either hand coding assembler or using the Intel compiler, which is supposed to be pretty good at this [but I have no experience with it], and c) going multicore (using OpenMP).
2,725,737
2,725,745
Lock-Free Data Structures in C++ Compare and Swap Routine
In this paper: Lock-Free Data Structures (pdf) the following "Compare and Swap" fundamental is shown: template <class T> bool CAS(T* addr, T exp, T val) { if (*addr == exp) { *addr = val; return true; } return false; } And then says The entire procedure is atomic But how is that so? Is it not possible that some other actor could change the value of addr between the if and the assignment? In which case, assuming all code is using this CAS fundamental, it would be found the next time something "expected" it to be a certain way, and it wasn't. However, that doesn't change the fact that it could happen, in which case, is it still atomic? What about the other actor returning true, even when it's changes were overwritten by this actor? If that can't possibly happen, then why? I want to believe the author, so what am I missing here? I am thinking it must be obvious. My apologies in advance if this seems trivial.
He is describing an atomic operation which is given by the implementation, "somehow." That is pseudo-code for something implemented in hardware.
2,725,802
2,726,327
C++ arrays as parameters, EDIT: now includes variable scoping
Alright, I'm guessing this is an easy question, so I'll take the knocks, but I'm not finding what I need on google or SO. I'd like to create an array in one place, and populate it inside a different function. I define a function: void someFunction(double results[]) { for (int i = 0; i<100; ++i) { for (int n = 0; n<16; ++n) //note this iteration limit { results[n] += i * n; } } } That's an approximation to what my code is doing, but regardless, shouldn't be running into any overflow or out of bounds issues or anything. I generate an array: double result[16]; for(int i = 0; i<16; i++) { result[i] = -1; } then I want to pass it to someFunction someFunction(result); When I set breakpoints and step through the code, upon entering someFunction, results is set to the same address as result, and the value there is -1.000000 as expected. However, when I start iterating through the loop, results[n] doesn't seem to resolve to *(results+n) or *(results+n*sizeof(double)), it just seems to resolve to *(results). What I end up with is that instead of populating my result array, I just get one value. What am I doing wrong? EDIT Oh fun, I have a typo: it wasn't void someFunction(double results[]). It was: void someFunction(double result[])... So perhaps this is turning into a scoping question. If my double result[16] array is defined in a main.cpp, and someFunction is defined in a Utils.h file that's included by the main.cpp, does the result variable in someFunction then wreak havoc on the result array in main? EDIT 2: @gf, in the process of trying to reproduce this problem with a fresh project, the original project "magically" started working. I don't know how to explain it, as nothing changed, but I'm pretty sure of what I saw - my original description of the issue was pretty clear, so I don't think I was hallucinating. I appreciate the time and answers...sorry for wasting your time. I'll update again if it happens again, but for the meantime, I think I'm in the clear. Thanks again.
Just a point about the variable scope part of the question - there is no issue of variable scope here. result/results in your someFunction definition is a parameter -> it will take on the value passed in. There is no relation between variables in a called function and it's caller -> the variables in the caller function are unknown to the called function unless passed in. Also, variable scoping issues do not occur between routines in C++ because there are no nested routines. The following pieces of code would demonstrate scoping issues: int i = 0; { int i = 0; i = 5; //changes the second i, not the first. //The first is aliased by the second i defined first. } i = 5; //now changes the first i; the inner block is gone and so is its local i so if C++ did have nested routines, this would cause variable scoping void main() { double results[16]; double blah[16]; doSomething(blah); void doSomething(double * results) { //blah doing something here uses our parameter results, //which refers to blah, but not to the results in the higher scope. //The results in the higher scope is hidden. } }
2,725,803
2,725,826
What does '#if _LFS64_LARGEFILE-0' mean to CPP?
What does #if _LFS64_LARGEFILE-0 mean to the C Preprocessor for g++? Is that a minus zero or is that part of the symbol? If it is minus zero, how does that affect whether the #if is triggered?
That is a more robust version of: #if _LFS64_LARGEFILE i.e. that the code should be conditionally included if _LFS64_LARGEFILE has a true value. Adding the - 0, prevents you from getting a warning (#if with no expression) when _LFS64_LARGEFILE is not defined.
2,725,815
2,726,175
Link Error : xxx is already defined in *****.LIB :: What exactly is wrong?
Problem: I'm trying to use a library named DCMTK which used some other external libraries ( zlib, libtiff, libpng, libxml2, libiconv ). I've downloaded these external libraries (*.LIB & *.h files ) from the same website. Now, when I compile the DCMTK library I'm getting link errors (793 errors) like this: Error 2 error LNK2005: __encode_pointer already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 3 error LNK2005: __decode_pointer already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 4 error LNK2005: __CrtSetCheckCount already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 5 error LNK2005: __invoke_watson already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 6 error LNK2005: __errno already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 7 error LNK2005: __configthreadlocale already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Error 8 error LNK2005: _exit already defined in MSVCRTD.lib(MSVCR90D.dll) LIBCMTD.lib dcmmkdir Documentation: This seems to be a popular error for this library so, they do have a FAQ entry addressing this issue which ( http://forum.dcmtk.org/viewtopic.php?t=35 ) says: The problem is that the linker tries to combine different, incompatible versions of the Visual C++ runtime library into a single binary. This happens when not all parts of your project and the libraries you link against are generated with the same code generation options in Visual C++. Do not use the /NODEFAULTLIB workaround, because strange software crashes may follow. Fix the problem! DCMTK is by default compiled with the "Multithreaded" or "Multithreaded Debug" code generation option (the latter for Debug mode). Either change the project settings of all of your code to use these code generation options, or change the code generation for all DCMTK modules and re-compile. MFC users beware: DCMTK should be compiled with "Multithreaded DLL" or "Multithreaded DLL Debug" settings if you want to link the libraries into an MFC application. Solution to same problem for others: Huge Amount of Linker Issues with Release Build Only says: It seems that your release build is trying to link to something that was built debug. You probably have a broken dependency in your build, (or you missed rebuilding something to release by hand if your project is normally built in pieces). More technically, you seem to be linking projects built with different C Run Time library settings, one with "Multi-Threaded", another one with "Multi-Threaded Debug". Adjust the settings for all the projects to use the very same flavour of the library and the issue should go away Questions: Till now I used to think that Name mangling is the only problem that may cause linking failures if its not been standardized. Just now I knew there are other things also which can cause same effect. Whats up with the "Debug Mode" (Multi-Threaded Debug) and "Release Mode" (Multi-Threaded)? What exactly is happening under the hood? Why exactly this thing is causing linking error? I wonder if there is something called "Single-Threaded Debug" and "Single-Threaded" which again causes the same thing. Documentation talks something about "Code Generation Options". What Code Generation Options? WTH are they? Documentation specifically warns us not to use /NODEFAULTLIB workaround. (example /NODEFAULTLIB :msvcrt ). Why? How would I cause troubles? what exactly is it? Please explain the last point in the documentation for MFC users. Because I'm going to use MFC later in this project. Explain Why should we do it? What troubles would it cause if I don't. Anything more you'd like to mention? I mean regarding similar errors. I'm very interested in Linker & its problems. So, if there are any similar things you can mentions them or some keywords atleast.
Whats up with the "Debug Mode" (Multi-Threaded Debug) and "Release Mode" (Multi-Threaded)? What exactly is happening under the hood? Why exactly this thing is causing linking error? The linker drags in libraries for several different reasons. The simplest is that a library is listed on the linker command line, or in the linker answer file on the linker command line. But any object files, whether compiled in your project or packed into a library, can also contain linker options including requesting particular libraries be linked in. In fact, the Visual C++ compiler automatically embeds such linker options matching the project options you use when compiling. At link time, all the linker options from all object files and objects in static library files get combined. If more than one CRT library filename is requested, the linker reads in all of them and them you get naming conflicts, where the linker doesn't know which one to use. I wonder if there is something called "Single-Threaded Debug" and "Single-Threaded" which again causes the same thing. There used to be, but the last few versions of Visual C++ have only shipped multi-thread compatible libraries. Documentation talks something about "Code Generation Options". What Code Generation Options? WTH are they? Look inside your project options. Documentation specifically warns us not to use /NODEFAULTLIB workaround. (example /NODEFAULTLIB :msvcrt ). Why? How would I cause troubles? what exactly is it? If you use /NODEFAULTLIB, all the linker settings stored within object files and objects in libraries get ignored. You'll end up with no runtime library and maybe missing other libraries. You can add them back in by hand, but it's still a big mess. Please explain the last point in the documentation for MFC users. Because I'm going to use MFC later in this project. Explain Why should we do it? What troubles would it cause if I don't. Anything more you'd like to mention? I mean regarding similar errors. I'm very interested in Linker & its problems. So, if there are any similar things you can mentions them or some keywords atleast. MFC applications and the MFC library have to use the same memory management functions, so that memory allocated by MFC can be freed by the application and vice-versa. FILE handles and other resources are also shared. The MFC DLLs are already compiled to use the CRT in a DLL, and in order to be able to share resources you need to use the same CRT, which means using a DLL too.
2,725,823
2,725,853
How do i get the screen to pause?
Possible Duplicate: How to stop C++ console application from exiting immediately? So im learning c++ and i was given this example and i wanted to run it. But i cannot get it to stay up, unless i change it. How do i get Microsoft visual 2010 to keep up the screen when it gets to the end of the program after I release it? #include<iostream> using namespace std; int area(int length, int width); /* function declaration */ /* MAIN PROGRAM: */ int main() { int this_length, this_width; cout << "Enter the length: "; /* <--- line 9 */ cin >> this_length; cout << "Enter the width: "; cin >> this_width; cout << "\n"; /* <--- line 13 */ cout << "The area of a " << this_length << "x" << this_width; cout << " rectangle is " << area(this_length, this_width); return 0; } /* END OF MAIN PROGRAM */ /* FUNCTION TO CALCULATE AREA: */ int area(int length, int width) /* start of function definition */ { int number; number = length * width; return number; } /* end of function definition */ /* END OF FUNCTION */
In Visual C++ you can either: Put a breakpoint at the closing brace of main and run attached to the debugger (Debug -> Start Debugging). When the breakpoint is hit you will be able to view the console window. Run detached from the debugger (Debug -> Start Without Debugging). When the application terminates, the console window will stay open with a "Press any key to continue..." prompt.
2,726,012
2,726,064
Dynamic 2d array in c++ and memory leaks
I wrote this code. It runs OK, but when I check it under Valgrind it catches 2 problems. Since I can not interpret valgrind's messages i will appreciate if anyone explain me more and tell me where is the problem!!! Here is the code: #include <iostream> #define width 70000 #define height 10000 using namespace std; int main(void) { int** pint; pint = new int*[height]; for(int i = 0; i < height; i++) pint[i] = new int[width]; for(int i = 0; i < height; i++){ delete[] pint[i]; pint[i] = NULL; } delete[] pint; pint = NULL; return 1; }
Okay, there are a couple of Valgrind warnings I get with 3.4 but only the first is important. new/new[] failed and should throw an exception, but Valgrind cannot throw exceptions and so is aborting instead. Sorry. new throws an exception when it is out of memory (unless you use the nothrow version of new). Unfortunately, Valgrind cannot handle that and gives up before your code completes. Because valgrind aborts, you code to free up memory is never executed which shows up as memory leaks. That said, you are not handling the case where new throws so your program will die due to an unhandled exception if you run out of memory. You need to wrap your code with a try/except block.
2,726,079
2,726,121
C++ Beginner Delete code
I am attempting to dynamically allocate memory to the heap and then delete the allocated memory. Below is the code that is giving me a hard time: // String.cpp #include "String.h" String::String() {} String::String(char* source) { this->Size = this->GetSize(source); this->CharArray = new char[this->Size + 1]; int i = 0; for (; i < this->Size; i++) this->CharArray[i] = source[i]; this->CharArray[i] = '\0'; } int String::GetSize(const char * source) { int i = 0; for (; source[i] != '\0'; i++); return i; } String::~String() { delete[] this->CharArray; } Here is the error I get when the compiler tries to delete the CharArray: 0xC0000005: Access violation reading location 0xccccccc0. And here is the last call on the stack: msvcr100d.dll!operator delete(void * pUserData) Line 52 + 0x3 bytes C++ I am fairly certain the error exists within this piece of code but will provide you with any other information needed. Oh yeah, using VS 2010 for XP. Edit: Heres my String.h // String.h - string class #pragma once #define NOT_FOUND -1 class String { public: String(); String(char* source); static int GetSize(const char * source); int Find(const char* aChar, int startPosition = 0); ~String(); private: char* CharArray; int Size; };
Change your default ctor; given the error you're getting, the delete call is trying to delete a pointer that has never been initialized. String::String() : Size(0), CharArray(NULL) {} Also, beware of the "copy constructor". You might want to make it private just to be sure you're not triggering it implicitly. (It doesn't need to be implemented if you don't intend to call it, just stick the function prototype into your class definition.) Might as well similarly "disable" the assignment operator. class String { // other stuff private: String(String&); String& operator=(String&); }; This addition fulfills the "Rule of Three," which says that if any class needs a destructor, a copy constructor, or an assignment operator, it probably needs all three. Edit: see http://en.wikipedia.org/wiki/Rule_of_three_%28C%2B%2B_programming%29
2,726,130
2,732,789
Double Linked List Insertion Sorting Bug
I have implemented an insertion sort in a double link list (highest to lowest) from a file of 10,000 ints, and output to file in reverse order. To my knowledge I have implemented such a program, however I noticed in the ouput file, a single number is out of place. Every other number is in correct order. The number out of place is a repeated number, but the other repeats of this number are in correct order. Its just strange how this number is incorrectly placed. Also the unsorted number is only 6 places out of sync. I have looked through my program for days now with no idea where the problem lies, so I turn to you for help. Below is the code in question, (side note: can my question be deleted by myself? rather my colleges dont thieve my code, if not how can it be deleted?) void DLLIntStorage::insertBefore(int inValue, node *nodeB) { node *newNode; newNode = new node(); newNode->prev = nodeB->prev; newNode->next = nodeB; newNode->value = inValue; if(nodeB->prev==NULL) { this->front = newNode; } else { nodeB->prev->next = newNode; } nodeB->prev = newNode; } void DLLIntStorage::insertAfter(int inValue, node *nodeB) { node *newNode; newNode = new node(); newNode->next = nodeB->next; newNode->prev = nodeB; newNode->value = inValue; if(nodeB->next == NULL) { this->back = newNode; } else { nodeB->next->prev = newNode; } nodeB->next = newNode; } void DLLIntStorage::insertFront(int inValue) { node *newNode; if(this->front == NULL) { newNode = new node(); this->front = newNode; this->back = newNode; newNode->prev = NULL; newNode->next = NULL; newNode->value = inValue; } else { insertBefore(inValue, this->front); } } void DLLIntStorage::insertBack(int inValue) { if(this->back == NULL) { insertFront(inValue); } else { insertAfter(inValue, this->back); } } ifstream& operator>> (ifstream &in, DLLIntStorage &obj) { int readInt, counter = 0; while(!in.eof()) { if(counter==dataLength) //stops at 10,000 { break; } in >> readInt; if(obj.front != NULL ) { obj.insertion(readInt); } else { obj.insertBack(readInt); } counter++; } return in; } void DLLIntStorage::insertion(int inValue) { node* temp; temp = this->front; if(temp->value >= inValue) { insertFront(inValue); return; } else { while(temp->next!=NULL && temp!=this->back) { if(temp->value >= inValue) { insertBefore(inValue, temp); return; } temp = temp->next; } } if(temp == this->back) { insertBack(inValue); } } Thankyou for your time.
I don't like this part else { while(temp->next!=NULL && temp!=this->back) { if(temp->value >= inValue) { insertBefore(inValue, temp); return; } temp = temp->next; } } if(temp == this->back) { insertBack(inValue); } Imagine what happens if inValue is greater than all values except this->back->value. It gets inserted at the end instead before this->back. By the way, You are inserting equal integers in the reversed order, they are read. For integers it doesn't matter that much, but it could if You inserted other objects. I would change the code of the insertion method to this: node* temp; temp = this->front; while(temp!=NULL) { if(temp->value > inValue) { insertBefore(inValue, temp); return; } temp = temp->next; } insertBack(inValue);
2,726,146
2,726,155
Convert "this" to a reference-to-pointer
Let's say I have a struct struct Foo { void bar () { do_baz(this); } /* See edit below void do_baz(Foo*& pFoo) { pFoo->p_sub_foo = new Foo; // for example } */ Foo* p_sub_foo; } GCC tells me that temp.cpp: In member function ‘void Foo::bar()’: temp.cpp:3: error: no matching function for call to ‘Foo::do_baz(Foo* const)’ temp.cpp:5: note: candidates are: void Foo::do_baz(Foo*&) So, how do I convert what is apparently a const Foo* to a Foo*&? EDIT: I didn't use a very good example. do_baz should read void do_baz(Foo*& pFoo) { if (pFoo == NULL) { pFoo = new Foo; return; } //other stuff do_baz(pFoo->p_sub_foo); //more stuff }
You can't. Firstly, this is not necessarily a const Foo *. this would be a const Foo * is a const method of the class Foo. In a non-const method this is just Foo *. (Actually your error message mentions Foo* const. Where did you see const Foo *?) Secondly, and more importantly, this is not an lvalue. You can't have a pointer to this. You can't have a non-constant reference to this. The only thing that you can have is a const reverence to this, i.e. a reference of type Foo *const &. It (Foo *const &) will work in your case. void do_baz(Foo* const& pFoo) { pFoo->p_sub_foo = new Foo; } But I don't see the point of all this. Just declare a normal Foo * pointer as parameter for your do_baz method void do_baz(Foo* pFoo) { pFoo->p_sub_foo = new Foo; } and get the same result. What do you think you need that reference for? EDIT: Taking into account your edit, what you are trying to do cannot be done with a single do_baz function, since in the first call you'd potentially (semantically) attempt to modify this, which is impossible (even if the modifying code will never be executed in practice). Whether you want it or not, you can't have a non-const reference to this, even if you don't intend to write anything through it. You'll probably have to implement the very first call with a different function void do_baz(Foo*& pFoo) { if (pFoo == NULL) { pFoo = new Foo; return; } //other stuff do_baz(pFoo->p_sub_foo); //more stuff } void do_baz_root(Foo* pFoo) { assert(pFoo != NULL); //other stuff do_baz(pFoo->p_sub_foo); //more stuff } and then make the first call as void bar() { do_baz_root(this); }
2,726,176
2,726,351
Can I get the amount of time for which a key is pressed on a keyboard
I am working on a project in which I have to develop bio-passwords based on user's keystroke style. Suppose a user types a password for 20 times, his keystrokes are recorded, like holdtime : time for which a particular key is pressed. digraph time : time it takes to press a different key. suppose a user types a password " COMPUTER". I need to know the time for which every key is pressed. something like : holdtime for the above password is C-- 200ms O-- 130ms M-- 150ms P-- 175ms U-- 320ms T-- 230ms E-- 120ms R-- 300ms The rational behind this is , every user will have a different holdtime. Say a old person is typing the password, he will take more time then a student. And it will be unique to a particular person. To do this project, I need to record the time for each key pressed. I would greatly appreciate if anyone can guide me in how to get these times. Editing from here.. Language is not important, but I would prefer it in C. I am more interested in getting the dataset.
You mentioned you'd prefer it in C, but since you tagged it Python... :) Also, since you say you're looking for building a dataset, I assume you'll have to invite users to type in arbitrary text, so you'll need some sort of interface (graphical or otherwise). Here's a quick example using pygame. You can trivially modify it to ask users to type specific words, but, as it is, it'll just let the user type in arbitrary text, record pressing times for all keypresses, and print each hold and digraph times, in the order that the user typed it, when it exits (i.e., when the user presses Esc). As Kibibu noticed, showing the user what he's typing in realtime introduces a delay which might mask real key-pressing times, so this code only displays what the user has typed when he types "Enter". Update: it now calculates digraph as well as hold times (excluding Enter in both cases). Update2: Per Adi's request, changed from displaying average to displaying each individual time, in order. import sys from collections import defaultdict from time import time import pygame from pygame.key import name as keyname from pygame.locals import * # Mapping of a key to a list of holdtimes (from which you can average, etc) holdtimes = defaultdict(list) # Mapping of a key pair to a list of digraph times digraphs = defaultdict(list) # Keys which have been pressed down, but not up yet. pending = {} # Last key to be de-pressed, corresponding time). last_key = None # Text that the user has typed so far (one sublist for every Enter pressed) typed_text = [[]] def show_times(): all_text = [k for line in typed_text for k in line] print "Holdtimes:" for key in all_text: print "%s: %.5f" % (key, holdtimes[key].pop(0)) print "Digraphs:" for key1, key2 in zip(all_text, all_text[1:]): print "(%s, %s): %.5f" % (key1, key2, digraphs[(key1, key2)].pop(0)) def time_keypresses(events): global last_key for event in events: if event.type == KEYDOWN: # ESC exits the program if event.key == K_ESCAPE: show_times() sys.exit(0) t = pending[event.key] = time() if last_key is not None: if event.key != K_RETURN: digraphs[(last_key[0], keyname(event.key))].append(t - last_key[1]) last_key = None elif event.type == KEYUP: if event.key == K_RETURN: update_screen() typed_text.append([]) pending.pop(event.key) last_key = None else: t = time() holdtimes[keyname(event.key)].append(t - pending.pop(event.key)) last_key = [keyname(event.key), t] typed_text[-1].append(keyname(event.key)) # Any other event handling you might have would go here... def update_screen(): global screen screen.fill((255, 255, 255)) header_font = pygame.font.Font(None, 42) header = header_font.render("Type away! Press 'Enter' to show.", True, (0, 0, 0)) header_rect = header.get_rect() header_rect.centerx = screen.get_rect().centerx header_rect.centery = screen.get_rect().centery - 100 text_font = pygame.font.Font(None, 32) user_text = text_font.render("".join(typed_text[-1]) if typed_text[-1] else "...", True, (0, 0, 255)) text_rect = user_text.get_rect() text_rect.centerx = screen.get_rect().centerx text_rect.centery = screen.get_rect().centery screen.blit(header, header_rect) screen.blit(user_text, text_rect) pygame.display.update() if __name__ == '__main__': pygame.init() window = pygame.display.set_mode((800, 600)) screen = pygame.display.get_surface() update_screen() while True: time_keypresses(pygame.event.get())
2,726,204
2,726,221
C++ preprocessor #define-ing a keyword. Is it standards conforming?
Help settle the debate that's going on in the comments at this question about bool and 1: Can a standards-conforming C++ preprocessor allow one to use #define to redefine a language keyword? If so, must a standards-conforming C++ preprocessor allow this? If a C++ program redefines a language keyword, can that program itself be standards conforming?
In C++, the closest thing to forbidding #defineing a keyword is §17.4.3.1.1/2, which only disallows it in a translation unit that includes a standard library header: A translation unit that includes a header shall not contain any macros that define names declared or defined in that header. Nor shall such a translation unit define macros for names lexically identical to keywords. The second sentence of that paragraph has been changed in C++0x to outright forbid #defineing a keyword (C++0x FCD §17.6.3.3.1): A translation unit shall not #define or #undef names lexically identical to keywords. Edit: As pointed out by Ken Bloom in comments to his answer, the rules have not changed in C++0x; the text has just been rearranged to confuse people like me. :-)
2,726,340
2,726,347
Unresolved external symbol error in c++
I am trying to do a simple hw problem involving namespace, static data members and functions. I am getting an unresolved external symbol error Error 1 error LNK2001: unresolved external symbol "private: static double JWong::SavingsAccount::annualInterestRate" (?annualInterestRate@SavingsAccount@JWong@@0NA) SavingsAccount.obj SavingsAccount And I don't see why I am getting this error. Maybe I don't know something about static variables compared to regular data members that is causing this error. Here is my code: SavingsAccount.h file #ifndef JWONG_SAVINGSACCOUNT_H #define JWONG_SAVINGSACCOUNT_H namespace JWong { class SavingsAccount { public: // default constructor SavingsAccount(); // constructor SavingsAccount(double savingsBalance); double getSavingsBalance(); void setSavingsBalance(double savingsBalance); double calculateMonthlyInterest(); // static functions static void modifyInterestRate(double newInterestRate); static double getAnnualInterestRest(); private: double savingsBalance; // static members static double annualInterestRate; }; } #endif SavingsAccount.cpp file #include <iostream> #include "SavingsAccount.h" // default constructor, set savingsBalance to 0 JWong::SavingsAccount::SavingsAccount() : savingsBalance(0) {} // constructor JWong::SavingsAccount::SavingsAccount(double savingsBalance) : savingsBalance(savingsBalance) {} double JWong::SavingsAccount::getSavingsBalance() { return savingsBalance; } void JWong::SavingsAccount::setSavingsBalance(double savingsBalance) { this->savingsBalance = savingsBalance; } // returns monthly interest and sets savingsBalance to new amount double JWong::SavingsAccount::calculateMonthlyInterest() { double monthlyInterest = savingsBalance * SavingsAccount::annualInterestRate / 12; setSavingsBalance(savingsBalance + monthlyInterest); return monthlyInterest; } void JWong::SavingsAccount::modifyInterestRate(double newInterestRate) { SavingsAccount::annualInterestRate = newInterestRate; } double JWong::SavingsAccount::getAnnualInterestRest() { return SavingsAccount::annualInterestRate; }
I'm presuming you are actually compiling the .cpp file (because the other functions link). The error is likely due to not defining the annualInterestRate static variable. You have declared it (in the class header), but it's not defined. In your cpp file add: // static member definition double JWang::SavingsAccount::annualInterestRate = ...; See an article highlighting the difference between declaration and definition of static members. Section 9.4.2 of the C++ Standard says "The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition."
2,726,356
2,726,363
the "new" operator in c++, pointer question
Dumb question, but whenever you call new, do you always have a pointer? SomeClass *person = new SomeClass(); And is that because you need a pointer to point to that new space of memory that was allocated for the SomeClass variable person? Thanks!
If new completes successfully, it always returns a pointer (if it doesn't complete successfully, an exception is thrown, and nothing is returned). The pointer is to the object that was created, or in the case of an array, a pointer to the first element of the array.
2,726,370
2,726,374
how to make a name from random numbers?
my program makes a random name that could have a-z this code makes a 16 char name but :( my code wont make the name and idk why :( can anyone show me what's wrong with this? char name[16]; void make_random_name() { byte loop = -1; for(;;) { loop++; srand((unsigned)time(0)); int random_integer; random_integer = (rand()%10)+1; switch(random_integer) { case '1': name[loop] = 'A'; break; case '2': name[loop] = 'B'; break; case '3': name[loop] = 'C'; break; case '4': name[loop] = 'D'; break; case '5': name[loop] = 'E'; break; case '6': name[loop] = 'F'; break; case '7': name[loop] = 'G'; break; case '8': name[loop] = 'Z'; break; case '9': name[loop] = 'H'; break; } cout << name << "\n"; if(loop > 15) { break; } } }
random_integer is an integer, you are comparing it to a bunch of characters from the ASCII character set - '1' as a character literal is actually 49 in decimal. As 49 is not in the range of your random numbers, it'll never get hit. Try changing your case statements to case 1: ... instead of case '1': ...
2,726,408
2,726,534
What is the proper way to declare a specialization of a template for another template type?
The usual definition for a specialization of a template function is something like this: class Foo { [...] }; namespace std { template<> void swap(Foo& left, Foo& right) { [...] } } // namespace std But how do you properly define the specialization when the type it's specialized on is itself a template? Here's what I've got: template <size_t Bits> class fixed { [...] }; namespace std { template<size_t Bits> void swap(fixed<Bits>& left, fixed<Bits>& right) { [...] } } // namespace std Is this the right way to declare swap? It's supposed to be a specialization of the template function std::swap, but I can't tell whether the compiler is seeing it as such, or whether it thinks that it's an overload of it or something.
Your solution isn't a template specialization, but an overload of a function in the std namespace, which is "undefined behavior" per the c++ standard. This question is exactly your question. Scott Meyers discusses this in Effective C++, and there is a followup thread on usenet's comp.lang.c++. He suggests that you define it in fixed's own namespace. Make sure 'fixed' is in a namespace. Don't prefix calls to swap with 'std::'. Let Koenig (a.k.a. argument dependent) lookup find the right swap function. If you're seeing compilation errors when trying to define this in namespace std, it's likely due to your unfortunate choice of class names :) When within namespace std "fixed" is being seen as std::fixed, the floating point precision operator.
2,726,413
2,726,453
C++ Translation Phase Confusion
Can someone explain why the following doesn't work? int main() // Tried on several recent C++ '03 compilers. { #define FOO L const wchar_t* const foo = FOO"bar"; // Will error out with something like: "identifier 'L' is undefined." #undef FOO } I thought that preprocessing was done in an earlier translation phase than string literal operations and general token translation. Wouldn't the compiler be more or less seeing this: int main() { const wchar_t* const foo = L"bar"; } It would be great if someone could cite an explanation from the standard.
Use: #define FOO L\ without the trailing \ there will be a space between L and the string on macro substitution. This is from the result of g++ -E : const wchar_t* const foo = L "bar";
2,726,422
2,733,538
using declarations in main (C++)
Although you wouldn't want to do this, if you have a namespace COMPANY, and a class in that namespace SOMECLASS. Why is it that in the .cpp file, you might define the functions as COMPANY::SOMECLASS::someFunction() {} But in main, I get errors for doing: int main() { COMPANY::SOMECLASS::someFunction(); } but instead you declare the namespace and do something like: using COMPANY::SOMECLASS; int main() { someFunction(); } My compile errors are: 1>c:\documents and settings\wongj\desktop\main.cpp(14) : error C2065: 'saver1' : undeclared identifier 1>c:\documents and settings\wongj\desktop\main.cpp(14) : error C2277: 'JWong::SavingsAccount::{ctor}' : cannot take address of this member function 1>c:\documents and settings\wongj\desktop\main.cpp(14) : error C2061: syntax error : identifier '{ctor}' SavingsAccount.cpp: #include "SavingsAccount.h" // initialize static data member double JWong::SavingsAccount::annualInterestRate = 0; // default constructor, set savingsBalance to 0 JWong::SavingsAccount::SavingsAccount() : savingsBalance(0) {} // constructor JWong::SavingsAccount::SavingsAccount(double savingsBalance) : savingsBalance(savingsBalance) {} double JWong::SavingsAccount::getSavingsBalance() { return savingsBalance; } void JWong::SavingsAccount::setSavingsBalance(double savingsBalance) { this->savingsBalance = savingsBalance; } // added these functions to make program cleaner double JWong::SavingsAccount::getMonthlyInterest() { return monthlyInterest; } void JWong::SavingsAccount::setMonthlyInterest(double monthlyInterest) { this->monthlyInterest = monthlyInterest; } // returns monthly interest and sets savingsBalance to new amount double JWong::SavingsAccount::calculateMonthlyInterest() { double monthlyInterest = savingsBalance * SavingsAccount::annualInterestRate / 12; setSavingsBalance(savingsBalance + monthlyInterest); setMonthlyInterest(monthlyInterest); return monthlyInterest; } void JWong::SavingsAccount::modifyInterestRate(double newInterestRate) { SavingsAccount::annualInterestRate = newInterestRate; } double JWong::SavingsAccount::getAnnualInterestRest() { return SavingsAccount::annualInterestRate; } SavingsAccount.h #ifndef JWONG_SAVINGSACCOUNT_H #define JWONG_SAVINGSACCOUNT_H namespace JWong { class SavingsAccount { public: // default constructor SavingsAccount(); // constructor SavingsAccount(double savingsBalance); double getSavingsBalance(); void setSavingsBalance(double savingsBalance); double calculateMonthlyInterest(); double getMonthlyInterest(); void setMonthlyInterest(double monthlyInterest); // static functions static void modifyInterestRate(double newInterestRate); static double getAnnualInterestRest(); private: double savingsBalance; // static members static double annualInterestRate; double monthlyInterest; }; } #endif main.cpp: #include <iostream> #include <iomanip> #include "SavingsAccount.h" using std::cout; using std::setprecision; using std::fixed; //using JWong::SavingsAccount; int main() { JWong::SavingsAccount::SavingsAccount *saver1 = new JWong::SavingsAccount::SavingsAccount(2000.00); }
The problem is simply in your declaration in main - you're accessing constructor, not the type, and you can't really reference the constructor directly. Change main to: int main() { JWong::SavingsAccount *saver1 = new JWong::SavingsAccount(2000.00); } ...and you should be good to go.
2,726,560
2,727,027
Creating a Transparent Bitmap with GDI?
I want to implement a layering system in my application and was thinking of creating a bunch of transparent bitmaps, adding content to them then blitting them on top of each other, how can this be done without setting each pixel to (0,0,0,0). I'm using Pure win32, not MFC, thanks.
What do you mean by transparent? If you are looking for partial (to full) transparency, then AlphaBlend is the GDI API to use. Loading bitmaps with alpha is tricky - The only format the base windows API supports for loading bitmaps with alpha is a 32bpp .BMP file with an alpha channel in the top 8 bits of each byte - and the lower bytes should to be pre-multiplied. It is possible to use GDI+ to load a variety of image formats with alpha - PNG is probably the best to go for, and blit onto a 32bpp DIBSection so you can use AlphaBlend and plain-old GDI functions. If you want a simple transparency mask rather than a full alpha channel you can use TransparentBlt along with a color key to mask out areas of a bitmap when blitting it.
2,726,960
2,726,968
C++ "delayed" template argument
Is there direct way to do the following: template < class > struct f {}; template < class F > void function() { F<int>(); //for example // ? F template <int>(); } function < f >(); I have workaround by using extra class around template struct. I am wondering if it's possible to do so directly. Thanks
The proper syntax for template template-parameters is as follows template < class > struct f {}; template < template <class> class F > void function() { F<int>(); //for example } ... function < f >()
2,726,993
2,727,033
How to specify preference of library path?
I'm compiling a c++ program using g++ and ld. I have a .so library I want to be used during linking. However, a library of the same name exists in /usr/local/lib, and ld is choosing that library over the one I'm directly specifying. How can I fix this? For the examples below, my library file is /my/dir/libfoo.so.0. Things I've tried that don't work: my g++ command is g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp adding /my/dir to the beginning or end of my $PATH en` variable adding /my/dir/libfoo.so.0 as an argument to g++
Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...) Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library. Careful with using LD_LIBRARY_PATH - in short (from link): ..implications..: Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable! Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system! Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug. OR Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option): -Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH) This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories. If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line: LD_LIBRARY_PATH=/some/custom/dir ./fooo You can check what libraries linker knows about using (example): /sbin/ldconfig -p | grep libpthread libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0 And you can check which library your application is using: ldd foo linux-gate.so.1 => (0xffffe000) libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000) libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000) librt.so.1 => /lib/librt.so.1 (0xb7e65000) libm.so.6 => /lib/libm.so.6 (0xb7d5b000) libc.so.6 => /lib/libc.so.6 (0xb7c2e000) /lib/ld-linux.so.2 (0xb7fc7000) libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000) libz.so.1 => /lib/libz.so.1 (0xb7c18000)
2,727,031
2,727,130
Makefile can not find boost libraries installed by macports
I just installed boost 1.42.0 from macports using sudo port install boost. Everything worked fine. Now I have a project that I'm trying to build using a makefile. Everything builds fine until it comes to the file that needs the boost library. It says: src/graph.h:20:42: error: boost/graph/adjacency_list.hpp: No such file or directory That file is actually located in two places: /opt/local/include/boost/graph/adjacency_list.hpp and /opt/local/var/macports/software/boost/1.42.0_0/opt/local/include/boost/graph/adjacency_list.hpp In the file src/graph.h where it's looking for boost/graph/adjacency_list.hpp, the include statement is here: #include<boost/graph/adjacency_list.hpp> How do I make this work?
You need to tell the compiler the base directory where Boost is intalled. You can do that with the compiler's -I command line option: g++ -I/opt/local/include ...
2,727,139
2,727,281
format, iomanip, c++
I'm trying to learn to use namespaces declarations more definitive than not just say "using namespace std". I'm trying to format my data to 2 decimal places, and set the format to be fixed and not scientific. This is my main file: #include <iostream> #include <iomanip> #include "SavingsAccount.h" using std::cout; using std::setprecision; using std::ios_base; int main() { SavingsAccount *saver1 = new SavingsAccount(2000.00); SavingsAccount *saver2 = new SavingsAccount(3000.00); SavingsAccount::modifyInterestRate(.03); saver1->calculateMonthlyInterest(); saver2->calculateMonthlyInterest(); cout << ios_base::fixed << "saver1\n" << "monthlyInterestRate: " << saver1->getMonthlyInterest() << '\n' << "savingsBalance: " << saver1->getSavingsBalance() << '\n'; cout << "saver2\n" << "monthlyInterestRate: " << saver2->getMonthlyInterest() << '\n' << "savingsBalance: " << saver2->getSavingsBalance() << '\n'; } On Visual Studio 2008, when I run my program, I get an output of "8192" before the data I want. Is there a reason for that? Also, I don't think I am setting the fixed part or 2 decimal places correctly since I seem to get scientific notation once I added the setprecision(2). Thanks.
You want std::fixed (the other one just inserts its value into the stream, which is why you see 8192), and I don't see a call to std::setprecision in your code anywhere. This'll fix it: #include <iostream> #include <iomanip> using std::cout; using std::setprecision; using std::fixed; int main() { cout << fixed << setprecision(2) << "saver1\n" << "monthlyInterestRate: " << 5.5 << '\n' << "savingsBalance: " << 10928.8383 << '\n'; cout << "saver2\n" << "monthlyInterestRate: " << 4.7 << '\n' << "savingsBalance: " << 22.44232 << '\n'; }
2,727,228
2,729,091
Load a Lua script into a table named after filename
I load scripts using luaL_loadfile and then lua_pcall from my game, and was wondering if instead of loading them into the global table, I could load them into a table named after their filename? For example: I have I file called "Foo.lua", which contains this: function DoSomething() --something end After loading it I want to be able to access it like: Foo.DoSomething() Thanks!
Try something like this. Don't forget to add error checking... lua_newtable(L); lua_setglobal(L,filename); luaL_loadfile(L,filename); lua_getglobal(L,filename); lua_setfenv(L,-2); lua_pcall(L,...);
2,727,287
2,727,344
Why is floating point byte swapping different from integer byte swapping?
I have a binary file of doubles that I need to load using C++. However, my problem is that it was written in big-endian format but the fstream >> operator will then read the number wrong because my machine is little-endian. It seems like a simple problem to resolve for integers, but for doubles and floats the solutions I have found won't work. How can I (or should I) fix this? I read this as a reference for integer byte swapping: How do I convert between big-endian and little-endian values in C++? EDIT: Though these answers are enlightening, I have found that my problem is with the file itself and not the format of the binary data. I believe my byte swapping does work, I was just getting confusing results. Thanks for your help!
The most portable way is to serialize in textual format so that you don't have byte order issues. This is how operator>> works so you shouldn't be having any endian issues with >>. The principal problem with binary formats (which would explain endian problems) is that floating point numbers consist of a number of mantissa bits, a number of exponent bits and a sign bit. The exponent may use an offset. This mean that a straight byte re-ordering may not be sufficient, depending on the source and target format. If you are using and IEEE-754 on both machines then you may be OK with a straight byte reversal as this standard specifies a bit-string interchange format that should be portable (byte order issues aside). If you have to convert between two machine architectures and you have to use a raw byte memory dump, then so long as the basic number format is the same (i.e. they have the same bit counts in each part of the number), you can read the data into an array of unsigned char, use some basic byte and bit swapping routines to correct the storage format and then copy the raw bytes into a variable of the appropriate type.
2,727,293
2,727,307
fftw in Visual Studio?
I'm trying to link my project with fftw and so far, I've gotten it to compile, but not link. As the site said, I generated all the .lib files (even though I'm only using double precision), and copied them to C:\Program Files\Microsoft Visual Studio 9.0\VC\lib, the .h file to C:\Program Files\Microsoft Visual Studio 9.0\VC\include and the .dll to C:\windows\system32. I've copied the tutorial program, and the exact error I am getting is: 1>hw10.obj : error LNK2019: unresolved external symbol __imp__fftw_free referenced in function "bool __cdecl test(void)" (?test@@YA_NXZ) 1>hw10.obj : error LNK2019: unresolved external symbol __imp__fftw_destroy_plan referenced in function "bool __cdecl test(void)" (?test@@YA_NXZ) 1>hw10.obj : error LNK2019: unresolved external symbol __imp__fftw_execute referenced in function "bool __cdecl test(void)" (?test@@YA_NXZ) 1>hw10.obj : error LNK2019: unresolved external symbol __imp__fftw_plan_dft_1d referenced in function "bool __cdecl test(void)" (?test@@YA_NXZ) 1>hw10.obj : error LNK2019: unresolved external symbol __imp__fftw_malloc referenced in function "bool __cdecl test(void)" (?test@@YA_NXZ) So, what could be wrong with my project setup? Thanks!
Have you actually linked against the library in the project you're building? Project -> Properties -> Linker -> Input -> Additional dependencies You need to add the library's filename to that field.
2,727,402
2,727,428
Difference of function argument as (const int &) and (int & a) in C++
I know that if you write void function_name(int& a), then function will not do local copy of your variable passed as argument. Also have met in literature that you should write void function_name(const int & a) in order to say compiler, that I dont want the variable passed as argument to be copied. So my question: what is the difference with this two cases (except that "const" ensures that the variable passed will not be changed by function!!!)???
You should use const in the signature whenever you do not need to write. Adding const to the signature has two effects: it tells the compiler that you want it to check and guarantee that you do not change that argument inside your function. The second effect is that enables external code to use your function passing objects that are themselves constant (and temporaries), enabling more uses of the same function. At the same time, the const keyword is an important part of the documentation of your function/method: the function signature is explicitly saying what you intend to do with the argument, and whether it is safe to pass an object that is part of another object's invariants into your function: you are being explicit in that you will not mess with their object. Using const forces a more strict set of requirements in your code (the function): you cannot modify the object, but at the same time is less restrictive in your callers, making your code more reusable. void printr( int & i ) { std::cout << i << std::endl; } void printcr( const int & i ) { std::cout << i << std::endl; } int main() { int x = 10; const int y = 15; printr( x ); //printr( y ); // passing y as non-const reference discards qualifiers //printr( 5 ); // cannot bind a non-const reference to a temporary printcr( x ); printcr( y ); printcr( 5 ); // all valid }
2,727,582
2,727,653
multiple definition in header file
Given this code sample: complex.h : #ifndef COMPLEX_H #define COMPLEX_H #include <iostream> class Complex { public: Complex(float Real, float Imaginary); float real() const { return m_Real; }; private: friend std::ostream& operator<<(std::ostream& o, const Complex& Cplx); float m_Real; float m_Imaginary; }; std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } #endif // COMPLEX_H complex.cpp : #include "complex.h" Complex::Complex(float Real, float Imaginary) { m_Real = Real; m_Imaginary = Imaginary; } main.cpp : #include "complex.h" #include <iostream> int main() { Complex Foo(3.4, 4.5); std::cout << Foo << "\n"; return 0; } When compiling this code, I get the following error: multiple definition of operator<<(std::ostream&, Complex const&) I've found that making this function inline solves the problem, but I don't understand why. Why does the compiler complain about multiple definition? My header file is guarded (with #define COMPLEX_H). And, if complaining about the operator<< function, why not complain about the public real() function, which is defined in the header as well? And is there another solution besides using the inline keyword?
The problem is that the following piece of code is a definition, not a declaration: std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } You can either mark the function above and make it "inline" so that multiple translation units may define it: inline std::ostream& operator<<(std::ostream& o, const Complex& Cplx) { return o << Cplx.m_Real << " i" << Cplx.m_Imaginary; } Or you can simply move the original definition of the function to the "complex.cpp" source file. The compiler does not complain about "real()" because it is implicitly inlined (any member function whose body is given in the class declaration is interpreted as if it had been declared "inline"). The preprocessor guards prevent your header from being included more than once from a single translation unit ("*.cpp" source file"). However, both translation units see the same header file. Basically, the compiler compiles "main.cpp" to "main.o" (including any definitions given in the headers included by "main.cpp"), and the compiler separately compiles "complex.cpp" to "complex.o" (including any definitions given in the headers included by "complex.cpp"). Then the linker merges "main.o" and "complex.o" into a single binary file; it is at this point that the linker finds two definitions for a function of the same name. It is also at this point that the linker attempts to resolve external references (e.g. "main.o" refers to "Complex::Complex" but does not have a definition for that function... the linker locates the definition from "complex.o", and resolves that reference).
2,727,803
2,731,329
Cannot insert a breakpoint in shared Library
Friends While debugging an application of of the function is defined in a shared library which is written by another vendor . and I get an error like warning: Cannot insert breakpoint 0: in /opt/trims/uat/lib/libTIPS_Oleca.sl warning: This is because your shared libraries are not mapped private. To attach to a process and debug its shared libraries you must prepare the program with **"/opt/langtools/bin/pxdb -s on a.out or "chatr +dbg enable a.out ".**** warning: Add this to your Makefile for debug builds warning: so that each rebuilt debuggable a.out would warning: have this feature turned on. Temporarily disabling shared library breakpoints:0 Now the problem is I cannot modify the shared library . How do I resolve this error ? Many Thanks
You don't need to modify the shared library. Instead, you must modify your main executable (by running pxdb -s or chatr +dbg enable on it). The a.out in the message you are getting refers to your main executable -- it's a UNIX convention that the output from linker is called a.out if you don't explicitly name it.
2,727,834
2,727,872
C++ standard: dereferencing NULL pointer to get a reference?
I'm wondering about what the C++ standard says about code like this: int* ptr = NULL; int& ref = *ptr; int* ptr2 = &ref; In practice the result is that ptr2 is NULL but I'm wondering, is this just an implementation detail or is this well defined in the standard? Under different circumstances a dereferencing of a NULL pointer should result in a crash but here I'm dereferencing it to get a reference which is implemented by the compiler as a pointer so there's really no actual dereferencing of NULL.
Dereferencing a NULL pointer is undefined behavior. In fact the standard calls this exact situation out in a note (8.3.2/4 "References"): Note: in particular, a null reference cannot exist in a well-defined program, because the only way to create such a reference would be to bind it to the “object” obtained by dereferencing a null pointer, which causes undefined behavior. As an aside: The one time I'm aware of that a NULL pointer can be "dereferenced" in a well-defined way is as the operand to the sizeof operator, because the operand to sizeof isn't actually evaluated (so the dereference never actually occurs).
2,727,860
2,727,904
From Java/C++ to XML
I know Java and C++ but am looking to get in to XML. I don't want to waste time reading over the basics of programming in a book, so has anyone any recommendations for resources for learning XML that assume a knowledge of programming already, or even better highlight how to switch from Java/C++ to XML ie. main differences etcs.
XML is not a programming language. It is a markup language. It's mainly used to store/transmit data in a structured manner. If you know Java and C++, there are libraries out there that can load and parse XML files. Adding to Soto's answer, you can technically use it to describe behavior (e.g. XAML, processing instructions), but most of the time it's for storing and transmitting data in a certain way. In your case, XML can be used to describe the GUI layout of an Android application.
2,727,890
2,727,902
C++ struct sorting error
I am trying to sort a vector of custom struct in C++ struct Book{ public:int H,W,V,i; }; with a simple functor class CompareHeight { public: int operator() (Book lhs,Book rhs) { return lhs.H-rhs.H; } }; when trying : vector<Book> books(X); ..... sort(books.begin(),books.end(), CompareHeight()); it gives me exception "invalid operator <" What is the meaning of this error? Thanks
sort expects a function that returns bool, which is true iff the lhs precedes the rhs: bool operator() (const Book& lhs, const Book& rhs) { return lhs.H < rhs.H; } Also note the change to const Book& parameters, to avoid copying.
2,728,078
2,728,235
Is there an easy way to check a fundamental type
In < Modern C++ Design >,it introduces a way to check if a type fundamental type by introducing the so called type list. but what if I don't want to include so many loki code and just want a simple function to implement that? What is the simplest way to do that?
You can use template specialization to get what you want. // General template template<typename T> struct IsFundamentalType { enum { result = false }; }; // Template specializations for each fundamental type template<> struct IsFundamentalType<char> { enum { result = true }; }; template<> struct IsFundamentalType<int> { enum { result = true }; }; template<> struct IsFundamentalType<short> { enum { result = true }; }; template<> struct IsFundamentalType<float> { enum { result = true }; }; // And so on for other fundamental types ... class NonFundamentalType { }; template<typename T> void DoSomething(const T& var) { if(IsFundamentalType<T>::result) { printf("I'm fundamental type!\n"); } else { printf("I'm not a fundamental type!\n"); } } int main() { int i = 42; char c = 42; short s = 42; float f = 42.0f; NonFundamentalType nft; DoSomething(i); DoSomething(c); DoSomething(s); DoSomething(f); DoSomething(nft); } In this code, if you pass in a type such as int or char, the compiler will use the specialization of IsFundamentalType (given that you've defined the specializations for all fundamental types). Otherwise, the compiler will use the general template, as it is the case for the NonFundamentalType class. The important thing is that the specialized ones have a result member defined as true, while the general template also has a result member defined as false. You can then use the result member for the if statement. Optimizing compilers should be able to elide the if statement seeing that the expression reduces to a constant true/false value, so doing something like this should not impose a runtime penalty.
2,728,190
2,728,318
How are iterators and pointers related?
Code with iterators looks pretty much like code with pointers. Iterators are of some obscure type (like std::vector<int>::iterator for example). What I don't get is how iterators and pointer are related to each other - is an iterator a wrapper around a pointer with overloaded operations to advance to adjacent elements or is it something else?
Iterators are a generalization of pointers. An iterator (depending on the variants) have to implement * and ++ So a pointer IS an iterator. But not necessarily the other way round. If you want to iterate over a complex structure (a tree, a graph...), the iterator will be much more than a pointer, and doesn't make any reference to some actual place in the ram.
2,728,239
2,728,305
C++ delete[] operator
Is this the right way to use delete[] operator? int* a=new int[size]; delete[] a; If yes, Who (compiler or GC or whoever) will determine the size of the newly created array? and where will it store the array size? Thanks
For each chunk of memory allocated, the memory allocator stores the size of the chunk (that's why it is inefficient to allocate many small blocks compared to one big one for example). When delete frees the memory, the allocator knows how large the memory chunk is the pointer points to.
2,728,255
2,728,322
C++: getting the address of the start of an std::vector?
Sometimes it is useful to use the starting address of an std::vector and temporarily treat that address as the address of a regularly allocated buffer. For instance replace this: char* buf = new char[size]; fillTheBuffer(buf, size); useTheBuffer(buf, size); delete[] buf; With This: vector<char> buf(size); fillTheBuffer(&buf[0], size); useTheBuffer(&buf[0], size); The advantage of this is of course that the buffer is deallocated automatically and I don't have to worry about the delete[]. The problem I'm having with this is when size == 0. In that case the first version works ok. An empty buffer is "allocated" and the subsequent functions do nothing size they get size == 0. The second version however fails if size == 0 since calling buf[0] may rightly contain an assertion that 0 < size. So is there an alternative to the idiom &buf[0] that returns the address of the start of the vector even if the vector is empty? I've also considered using buf.begin() but according to the standard it isn't even guaranteed to return a pointer.
I guess you'd just have to check. Perhaps a utility function: template <class T, class Alloc> T* data(std::vector<T, Alloc>& vec) { return vec.empty() ? 0 : &vec[0]; } template <class T, class Alloc> const T* data(const std::vector<T, Alloc>& vec) { return vec.empty() ? 0 : &vec[0]; }
2,728,299
2,728,427
Why is comparing against "end()" iterator legal?
According to C++ standard (3.7.3.2/4) using (not only dereferencing, but also copying, casting, whatever else) an invalid pointer is undefined behavior (in case of doubt also see this question). Now the typical code to traverse an STL containter looks like this: std::vector<int> toTraverse; //populate the vector for( std::vector<int>::iterator it = toTraverse.begin(); it != toTraverse.end(); ++it ) { //process( *it ); } std::vector::end() is an iterator onto the hypothetic element beyond the last element of the containter. There's no element there, therefore using a pointer through that iterator is undefined behavior. Now how does the != end() work then? I mean in order to do the comparison an iterator needs to be constructed wrapping an invalid address and then that invalid address will have to be used in a comparison which again is undefined behavior. Is such comparison legal and why?
You're right that an invalid pointer can't be used, but you're wrong that a pointer to an element one past the last element in an array is an invalid pointer - it's valid. The C standard, section 6.5.6.8 says that it's well defined and valid: ...if the expression P points to the last element of an array object, the expression (P)+1 points one past the last element of the array object... but cannot be dereferenced: ...if the result points one past the last element of the array object, it shall not be used as the operand of a unary * operator that is evaluated...
2,728,518
2,728,548
class foo; in header file
Is some one able to explain why header files have something like this? class foo; // This here? class bar { bar(); }; Do you need an include statement when using this? Thanks.
The first class foo; is called a forward declaration of the class foo. It simply lets the compiler know that it exists and that it names a class. This makes foo what is called an "incomplete type" (unless the full declaration of foo has already been seen). With an incomplete type, you can declare pointers of that type, but you cannot allocate instances of that type or do anything that requires knowing its size or members. Such forward declarations are frequently used when two types each may have pointers to each other, in which case both need to be able to express the notion of a pointer to the other type, and so you would have a circular dependency without such a thing. This is needed mostly because C++ uses a single pass mechanism for resolving types; in Java, you can have circular dependencies without forward declarations, because Java uses multiple passes. You may also see forward declarations where the author is under the misguided impression that using forward declarations instead of including the required header reduces compile time; that, of course, is not the case, because you need to include the full declaration (i.e. the header), anyway, and if preprocessor guards are used, then there is basically no difference in compile time. To answer your question on whether you need the include or not... assuming you only need a partial type, then your header does not need to directly include the header for the type that has been forward declared; however, whoever makes use of your header, when they use your type will need to include the header for the forward declared type, and so you might as well just include the other header.
2,728,576
2,728,723
what is the difference between Template Explicit Specialization and ordinary function?
template <class T> void max (T &a ,T &b) {}//generic template #1 template<> void max(char &c, char &d) {} //template specializtion #2 void max (char &c, char &d) {}//ordinary function #3 what is difference between 1 ,2, and 3?
is a template function is a total specialization of the previous template function (doesn't overload!) is an overload of the function Here is an excerpt from C++ Coding Standards: 101 Rules, Guidelines, and Best Practices: 66) Don't specialize function templates Function template specializations never participate in overloading: Therefore, any specializations you write will not affect which template gets used, and this runs counter to what most people would intuitively expect. After all, if you had written a nontemplate function with the identical signature instead of a function template specialization, the nontemplate function would always be selected because it's always considered to be a better match than a template. The book advises you to add a level of indirection by implementing the function template in terms of a class template: #include <algorithm> template<typename T> struct max_implementation { T& operator() (T& a, T& b) { return std::max(a, b); } }; template<typename T> T& max(T& a, T& b) { return max_implementation<T>()(a, b); } See also: Why Not Specialize Function Templates? Template Specialization and Overloading
2,728,658
2,794,749
Are there any Visual Studio add-ins for true 'smart tabs'?
'Smart Tabs' concept allows to automatically insert tab character for block indentation and space characters for in-block formatting. It's described here. Unfortunately, Visual Studio's 'smart tabs' option in text editor settings just indents text on enter press. Same name, completely different and near useless thing :). So, maybe someone knows of a visual studio addin that can change how 'tab' key work so it will insert tab characters and space characters according to rules mentioned above? Any hints are welcome. Update: I need it for C++. According to comments, ReSharper can do something like this, but only for Basic and C#.
If no one comes up with an "as-you-type" utility, then Astyle with its convert-tabs and indent=tab options will reformat code after-the-fact.
2,728,880
2,733,665
Modifying an image with OpenGL?
I have a device to acquire XRay images. Due to some technical constrains, the detector is made of heterogeneous pixel size and multiple tilted and partially overlapping tiles. The image is thus distorted. The detector geometry is known precisely. I need a function converting these distorted images into a flat image with homogeneous pixel size. I have already done this by CPU, but I would like to give a try with OpenGL to use the GPU in a portable way. I have no experience with OpenGL programming, and most of the information I could find on the web was useless for this use. How should I proceed ? How do I do this ? Image size are 560x860 pixels and we have batches of 720 images to process. I'm on Ubuntu.
You might find this tutorial useful (it's a bit old, but note that it does contain some OpenGL 2.x GLSL after the Cg section). I don't believe there are any shortcuts to image processing in GLSL, if that's what you're looking for... you do need to understand a lot of the 3D rasterization aspect and historical baggage to use it effectively, although once you do have a framework for inputs and outputs set up you can forget about that and play around with your own algorithms in shader code relatively easily. Having being doing this sort of thing for years (initially using Direct3D shaders, but more recently with CUDA) I have to say that I entirely agree with the posts here recommending CUDA/OpenCL. It makes life much simpler, and generally runs faster. I'd have to be pretty desperate to go back to a graphics API implementation of non-graphics algorithms now.
2,728,944
2,728,954
On C++ global operator new: why it can be replaced
I wrote a small program in VS2005 to test whether C++ global operator new can be overloaded. It can. #include "stdafx.h" #include "iostream" #include "iomanip" #include "string" #include "new" using namespace std; class C { public: C() { cout<<"CTOR"<<endl; } }; void * operator new(size_t size) { cout<<"my overload of global plain old new"<<endl; // try to allocate size bytes void *p = malloc(size); return (p); } int main() { C* pc1 = new C; cin.get(); return 0; } In the above, my definition of operator new is called. If I remove that function from the code, then operator new in C:\Program Files (x86)\Microsoft Visual Studio 8\VC\crt\src\new.cpp gets called. All is good. However, in my opinion, my implementations of operator new does NOT overload the new in new.cpp, it CONFLICTS with it and violates the one-definition rule. Why doesn't the compiler complain about it? Or does the standard say since operator new is so special, one-definition rule does not apply here? Thanks.
Yes, global operator new is special in that programs may provide a replacement implementation for it. Replaceable forms are the single object and array forms of operator new and operator delete and the "no throw" variants. Other forms, such as placement new are not replaceable.
2,728,951
2,736,704
Simple menubar using Qt4
i'm trying to make a simple GUI with QT 4.6. i made a separete class that represents the menu bar: MenuBar::MenuBar() { aboutAct = new QAction(tr("&About QT"), this); aboutAct->setStatusTip(tr("Show the application's About box")); connect(aboutAct, SIGNAL(triggered()), this, SLOT(about())); quitAct = new QAction(tr("&Quit"),this); quitAct->setStatusTip(tr("Exit to the program")); //connect(quitAct, SIGNAL(triggered()), &QApp, SLOT(quit())); menuFile = new QMenu("File"); menuFile->addAction(quitAct); menuLinks = new QMenu("Links"); menuAbout = new QMenu("Info"); menuAbout->addAction(aboutAct); addMenu(menuFile); addMenu(menuLinks); addMenu(menuAbout); } i can't connect the signal of the quitAct with the quit slot of the main application probably because it is not visible from the MenuBar class.. //connect(quitAct, SIGNAL(triggered()), &QApp, SLOT(quit())); how can i do it?
You have a typo. :) In: connect(quitAct, SIGNAL(triggered()), &QApp, SLOT(quit())); The variable's name is qApp, not QApp. That aside, balpha said it all. So it's either: connect(quitAct, SIGNAL(triggered()), qApp, SLOT(quit())); or connect(quitAct, SIGNAL(triggered()), QApplication::instance(), SLOT(quit()));
2,729,202
2,729,360
Aborted core dumped C++
I have a large C++ function which uses OpenCV library and running on Windows with cygwin g++ compiler. At the end it gives Aborted(core dumped) but the function runs completely before that. I have also tried to put the print statement in the end of the function. That also gets printed. So I think there is no logical bug in code which will generate the fault. Please explain. I am also using assert statements.But the aborted error is not due to assert statement. It does not say that assertion failed. It comes at end only without any message. Also the file is a part of a large project so I cannot post the code also. gdb results: Program received signal SIGABRT, Aborted. 0x7c90e514 in ntdll!LdrAccessResource () from /c/WINDOWS/system32/ntdll.dll
It looks like a memory fault (write to freed memory, double-free, stack overflow,...). When the code can be compiled and run under Linux you can use valgrind to see if there are memory issues. Also you can try to disable parts of the application until the problem disappears, to get a clue where the error happens. But this method can also give false positives, since memory related bugs can cause modules to fail which are not the cause of the error. Also you can run the program in gdb. But also here the position the debugger points to may not be the position where the error happened.
2,729,280
2,729,403
Adding a string or char array to a byte vector
I'm currently working on a class to create and read out packets send through the network, so far I have it working with 16bit and 8bit integers (Well unsigned but still). Now the problem is I've tried numerous ways of copying it over but somehow the _buffer got mangled, it segfaulted, or the result was wrong. I'd appreciate if someone could show me a working example. My current code can be seen below. Thanks, Xeross Main #include <iostream> #include <stdio.h> #include "Packet.h" using namespace std; int main(int argc, char** argv) { cout << "#################################" << endl; cout << "# Internal Use Only #" << endl; cout << "# Codename PACKETSTORM #" << endl; cout << "#################################" << endl; cout << endl; Packet packet = Packet(); packet.SetOpcode(0x1f4d); cout << "Current opcode is: " << packet.GetOpcode() << endl << endl; packet.add(uint8_t(5)) .add(uint16_t(4000)) .add(uint8_t(5)); for(uint8_t i=0; i<10;i++) printf("Byte %u = %x\n", i, packet._buffer[i]); printf("\nReading them out: \n1 = %u\n2 = %u\n3 = %u\n4 = %s", packet.readUint8(), packet.readUint16(), packet.readUint8()); return 0; } Packet.h #ifndef _PACKET_H_ #define _PACKET_H_ #include <iostream> #include <vector> #include <stdio.h> #include <stdint.h> #include <string.h> using namespace std; class Packet { public: Packet() : m_opcode(0), _buffer(0), _wpos(0), _rpos(0) {} Packet(uint16_t opcode) : m_opcode(opcode), _buffer(0), _wpos(0), _rpos(0) {} uint16_t GetOpcode() { return m_opcode; } void SetOpcode(uint16_t opcode) { m_opcode = opcode; } Packet& add(uint8_t value) { if(_buffer.size() < _wpos + 1) _buffer.resize(_wpos + 1); memcpy(&_buffer[_wpos], &value, 1); _wpos += 1; return *this; } Packet& add(uint16_t value) { if(_buffer.size() < _wpos + 2) _buffer.resize(_wpos + 2); memcpy(&_buffer[_wpos], &value, 2); _wpos += 2; return *this; } uint8_t readUint8() { uint8_t result = _buffer[_rpos]; _rpos += sizeof(uint8_t); return result; } uint16_t readUint16() { uint16_t result; memcpy(&result, &_buffer[_rpos], sizeof(uint16_t)); _rpos += sizeof(uint16_t); return result; } uint16_t m_opcode; std::vector<uint8_t> _buffer; protected: size_t _wpos; // Write position size_t _rpos; // Read position }; #endif // _PACKET_H_
Since you're using an std::vector for your buffer, you may as well let it keep track of the write position itself and avoid having to keep manually resizing it. You can also avoid writing multiple overloads of the add function by using a function template: template <class T> Packet& add(T value) { std::copy((uint8_t*) &value, ((uint8_t*) &value) + sizeof(T), std::back_inserter(_buffer)); return *this; } Now you can write any POD type to your buffer. implicitly: int i = 5; o.write(i); or explictly: o.write<int>(5); To read from the buffer, you will need to keep track of a read position: template <class T> T read() { T result; uint8_t *p = &_buffer[_rpos]; std::copy(p, p + sizeof(T), (uint8_t*) &result); _rpos += sizeof(T); return result; } You will need to explicitly pass a type parameter to read. i.e. int i = o.read<int>(); Caveat: I have used this pattern often, but since I am typing this off the top of my head, there may be a few errors in the code. Edit: I just noticed that you want to be able to add strings or other non-POD types to your buffer. You can do that via template specialization: template <> Packet& add(std::string s) { add(string.length()); for (size_t i = 0; i < string.length(); ++i) add(string[i]); return *this; } This tells the compiler: if add is called with a string type, use this function instead of the generic add() function. and to read a string: template <> std::string read<>() { size_t len = read<size_t>(); std::string s; while (len--) s += read<char>(); return s; }
2,729,371
2,729,485
Creating multiple MFC dialogs through COM, strange behaviour
Updated: please see this other thread instead, all this COM stuff is not part of the problem. One of our apps has a COM interface which will launch a dialog, e.g: STDMETHODIMP CSomeClass::LaunchDialog(BSTR TextToDisplay) { CDialog *pDlg = new CSomeDialog(TextToDisplay); pDlg->BringWindowToTop(); } For some reason when the COM method is called several times at once by the server, we get odd behaviour: We get multiple dialogs, but only one entry in the taskbar Dialog Z-order is based on order created and can't be changed... the first dialog created is always shown under the 2nd one, 2nd under 3rd, etc, even when you drag them around if N dialogs were created, closing one of them closes it and all the others created afterwards. e.g if 5 dialogsa re created and you close the 3rd one, #3,#4,#5 all get closed. It's somehow like the dialogs are siblings but I don't see anything weird going on. Is it perhaps due to COM, or is this a weird MFC/Win32 issue? EDIT: If the interface method is called several times separately, it works as expected. Only when the server component sends several through at once does it seem to mess up. Could threading/timings be to blame? EDIT2: I put this logging in: std::stringstream ss; HWND self = dlg->m_hWnd; HWND parent = dlg->GetParent() ? dlg->GetParent()->m_hWnd : 0; ss<<"Dlg created'. HWND = "<<self<<", Parent = "<<parent<<std::endl; OutputDebugString(ss.str().c_str()); It gave: Dlg created. HWND = 0013014A, Parent = 00000000 Dlg created. HWND = 001B0390, Parent = 0013014A Dlg created. HWND = 000B03B0, Parent = 001B0390 So clearly the problem is the dialogs are being made children of each other. But the question is, WHY?! It seems Windows is doing this automatically... This question seems to be slightly away from the main issue of parenting, so I have tried to separate out the main issue into a new question.
It sounds like the first dialog has been set as the owner of the second, and the second as the owner of the third. Can you change the dialog initialization to explicitly specify the owner window? Is there a window that makes sense to assign? Perhaps the Desktop window, if they're all intended to be top-level? If you want to be able to access all three (or more), then they would need to be modeless. Try using Create(CSomeClass::IDD, CWnd::GetDesktopWindow()), and you ought to see sibling dialogs, all of which show up on the taskbar.
2,729,372
2,729,597
QMetaMethods for regular methods missing?
I'm new in QT, and I'm just testing out the MOC. For a given class: class Counter : public QObject { Q_OBJECT int m_value; public: Counter() {m_value = 0;} ~Counter() {} int value() {return m_value;} public slots: void setValue(int value); signals: void valueChanged(int newValue); }; I want to get a list of all methods in a class, but seem to only be getting a list of signals and slots, although the documentation says it should be all methods? Here's my code: #include <QCoreApplication> #include <QObject> #include <QMetaMethod> #include <iostream> using std::cout; using std::endl; int main(int argc, char *argv[]) { QCoreApplication app(argc, argv); const QMetaObject cntmo = Counter::staticMetaObject; for(int i = 0; i != cntmo.methodCount(); ++i) { QMetaMethod qmm(cntmo.method(i)); cout << qmm.signature() << endl; } return app.exec(); } Please beware this is my best c/p, perhaps I forgot to include some headers. My output: destroyed(QObject*) destroyed() deleteLater() _q_reregisterTimers(void*) valueChanged(int) setValue(int) Does anyone know why this is happening? Does qt not recognise int value() {return m_value;} as a valid method? If so, is there a macro I've forgotten or something like that? P.S. I'm using 4.6.2 UPDATE I forgot the implementation of the setValue method, not that it makes too much a difference to my actual question. void Counter::setValue(int value) { if(value != m_value) { m_value = value; emit valueChanged(value); } }
As far as I remember you can't access all methods of a QObject subclass through the QMetaObject it provides access only for the signals, slots and INVOCABLE methods: class MyClass: public QObject { Q_OBJECT public: Q_INVOCABLE int someMethod(const QString &someParam); }; Maybe it's also provide access to Q_PROPERTY getters and setters. Read articles about Qt object model and meta object system more carefully. Quotation from QMetaObject class description (http://doc.trolltech.com/4.6/qmetaobject.html#details): "method() and methodCount() provide information about a class's meta-methods (signals, slots and other invokable member functions)." There is no information about normal C++ methods access. And actually it's good since reflective techniques are slow.
2,729,417
2,729,474
C++: How to count all instantiated objects at runtime?
I have a large framework consisting of many C++ classes. Is there a way using any tools at runtime, to trace all the C++ objects that are being constructed and currently exist? For example, at a certain time t1, perhaps the application has objects A1, A2 and B3, but at time t2, it has A1, A4, C2 and so on? This is a cross platform framework but I'm familiar with working in Linux, Solaris and (possibly) Mac OS X.
You can inject code in the destructor and constructor of the objects that you want to count: SomeObject::SomeObject() { ++globalSomeObjectCounter; } SomeObject::~SomeObject() { --globalSomeObjectCounter; } Don't forget to increase the counter in all constructors (copy constructors, etc.) EDIT: In this situation one can use the curiously recurring template pattern: template <typename T> struct Counter { Counter() {++counter;} virtual ~Counter() {--counter;} static int counter; }; template <typename T> int Counter<T>::counter(0); and then: class SomeObject : public Counter<SomeObject> { } to automatically generate a counter for each class type.
2,729,512
2,729,563
Calls to singleton library
I have a singleton class, and I will compile it as a library static(lib) or dynamic(dll). Is it guaranteed that calls to same file in a machine always refer to same and unique instance in both cases? Edit: What if a process loads two different library and different functions from these libraries want to use instance of singleton class. Now, they are accessing same instance, am I right? Thanks,
No, different processes will not share a singleton from a common library. Different processes use different memory spaces, so each will instantiate its own singleton. You'll need to use some sort of shared memory or interprocess-communication to share data between processes. If a single process loads libraries A and B, and both those libraries use a singleton from library C, then they will be using the same instance.
2,729,829
2,729,893
Any way to profile code for cache behavior?
As the title says I'd like to somehow get the cache behavior of my code. I'm running Windows 7 64-bit edition, compiling on Visual Studio 2008 Professional Edition, compiling C++ code. I understand that there's Valgrind under Linux, but are there any free alternatives I could use, or methods otherwise?
VTune will give you pretty detailed cache and pipeline analysis. It's not cheap though. I believe some level/edition of VS (I remember it was "team edition" on XP) had a decent profiler.
2,730,000
2,730,116
Serializing struct containing char*
I'm getting an error with serializing a char* string error C2228: left of '.serialize' must have class/struct/union I could use a std::string and then get a const char* from it. but I require the char* string.
The error message says it all, there's no support in boost serialization to serialize pointers to primitive types. You can do something like this in the store code: int len = strlen(string) + 1; ar & len; ar & boost::serialization::make_binary_object(string, len); and in the load code: int len; ar & len; string = new char[len]; //Don't forget to deallocate the old string ar & boost::serialization::make_binary_object(string, len);
2,730,105
2,730,857
C++ Static Initializer - Is it thread safe
Usually, when I try to initialize a static variable class Test2 { public: static vector<string> stringList; private: static bool __init; static bool init() { stringList.push_back("string1"); stringList.push_back("string2"); stringList.push_back("string3"); return true; } }; // Implement vector<string> Test2::stringList; bool Test2::__init = Test2::init(); Is the following code thread safe, during static variable initialization? Is there any better way to static initialize stringlist, instead of using a seperate static function (init)? Although the initialization shall happen before main function (Hence, there can be no threads to simultaneous access the init), my concern is that : I have an exe application. My exe application will load a.dll, b.dll and c.dll a/b/c.dll, in turn will load common.dll. The above code are inside common.dll I had already verify. Since 3 dll are within single process, they will be referring to the same static variable (vector). In this case, to prevent 3 dlls from simultaneous access init (Can I view them as 3 threads? Although doesn't make sense at first thought), for the init function, shall I use a critical section to protect it? I am using Windows XP, VC6 and VC2008 compiler.
I asked a similar question a while back: LoadLibrary and Static Globals When it comes to DLLs, static initialization and the call to DllMain is bracketed by an internal critical section, so they are thread-safe. A second thread will wait until the first is done before it loads the DLL. So in short, your static init is safe.
2,730,110
2,731,671
Why typedef char CHAR
Guys, having quick look in Winnt.h I have discovered that there is a lots of typedefs and one of them is for example CHAR for a char. Why? What was the purpose of these typdefs? Why not use what's already there (char, int etc.)? Thank you.
The WIN32 API needs to be platform agnostic as well. When the compiler adjusts for different word sizes, the types may also change as well. For example, on 16-Bit platforms: typedef WORD unsigned int; typedef DWORD unsigned long; On 32-bit platforms: typedef WORD unsigned short; typedef DWORD unsigned int; This an example, your mileage may vary.
2,730,117
2,730,132
C++ - Efficient container for large amounts of searchable data?
I am implementing a text-based version of Scrabble for a College project. My dictionary is quite large, weighing in at around 400.000 words (std::string). Searching for a valid word will suck, big time, in terms of efficiency if I go for a vector<string> ( O(n) ). Are there any good alternatives? Keep in mind, I'm enrolled in freshman year. Nothing TOO complex! Thanks for your time! Francisco
If you wanted to go for something that is in the standard library, you could use std::set with the word as the key. That would give you logarithmic search time. Since your dictionary is presumably static (i.e. created once and not modified), you could also use a std::vector, sort it using std::sort, and then use std::binary_search on the sorted vector to find a word. This would also give logarithmic search time, and would possibly be more space efficient than a set. If you want to implement your own data structure, a trie would be a good choice.
2,730,604
2,730,666
How do I build boost examples with bjam?
Boost library is full of examples and tests and I would like to build them using bjam if possible. How do I build boost examples with bjam? PS. I wasn't able to locate proper documentation for this option.
It depends on the library. Most of them run the examples from the test directory. Others from the example directory. Go to the lib test or example directory where there is a Jamfile and do just bjam
2,730,663
2,730,767
How (if needed) to free dynamic memory when marshaling CString from C++ to C#?
I have CString cs on C++ side and IntPtr ip on C# side which contains value of cs through marshaling mechanism. Then, I simply get needed String as Marshal.PtrToStringAnsi(ip) and everything works fine, but I am wondering should I and if should, how can I delete unmanaged memory occupied by ip, i.e. cs?
You can't, you have no idea what allocator was used by the unmanaged code to create the CString instance. Moreover, you'd have to call the CString destructor, you can't get its address. You are dead in the water if this CString object is returned as the function return value of a C++ function that you call from C#. It isn't clear from your question. You'll have an uncontrollable memory leak. A wrapper written in C++/CLI will be required to fix that problem. Strings returned as function return values must be allocated by CoTaskMemAlloc() to get properly cleaned up by the P/Invoke marshaller. No C++ code ever does that.
2,730,817
2,730,860
How to extract ALL typedefs and structs and unions from c++ source
I have inherited a Visual Studio project that contains hundreds of files. I would like to extract all the typedefs, structs and unions from each .h/.cpp file and put the results in a file). Each typdef/struct/union should be on one line in the results file. This would make sorting much easier. typdef int myType; struct myFirstStruct { char a; int b;...}; union Part_Number_Serial_Number_Part_2_Response_Message_Type {struct{Message_Response_Head_Type Head; Part_Num_Serial_Num_Part_2_Report_Array Part_2_Report; Message_Tail_Type Tail;} Data; BYTE byData[140];}myUnion; struct { bool c; int d;...}mySecondStruct; My problem is, I do not know what to look for (grammar of typedef/structs/unions) using a regular expression. I cannot believe that nobody has done this before (I googled and have not found anything on this). Does anyone know the regular expressions for these? (Note some are commented out using // others /* */) Or a tool to accomplish this. Edit: I am toying with the idea of autogenerating source code and/or dialogs for modifying messages that use the underlying typedef/struct/union. I was going to use the output to generate an XML file that could be used for this reason. The source for these are in C/C++ and used in almost all my projects. These projects are usually NOT in C/C++. By using the XML version I would only need to update/add the typedef/struct/union only in one place and all the projects would be able to autogen the source and/or dialogs.
I can't imagine a purpose for this except for some sort of documentation effort. If that is what you're looking for I would suggest doxygen. To answer your question, I seriously doubt any amount of regular expressions will be sufficient. What you need to do is actually parse the code. I have heard of a library out there for building compilers and C++ tools that would provide the parsing aspect but I'm sorry to say I have forgotten the name. I know it's out there though so I'd start searching for that.
2,730,963
2,752,445
Complex error handling
I've got a particularly ornery piece of network code. I'm using asio but that really doesn't matter for this question. I assume there is no way to unbind a socket other than closing it. The problem is that open(), bind(), and listen() can all throw a system_error. So I handled the code with a simple try/catch. The code as written in broken. using namespace boost::asio; class Thing { public: ip::tcp::endpoint m_address; ip::tcp::acceptor m_acceptor; /// connect should handle all of its exceptions internally. bool connect() { try { m_acceptor.open( m_address.protocol() ); m_acceptor.set_option( tcp::acceptor::reuse_address(true) ); m_acceptor.bind( m_address ); m_acceptor.listen(); m_acceptor.async_accept( /*stuff*/ ); } catch( const boost::system::system_error& error ) { assert(acceptor.is_open()); m_acceptor.close(); return false; } return true; } /// don't call disconnect unless connect previously succeeded. void disconnect() { // other stuff needed to disconnect is ommited m_acceptor.close(); } }; The error is if the socket fails to connect it will try to close it in the catch block and throw another system_error about closing an acceptor that has never been opened. One solution is to add an if( acceptor.is_open() ) in the catch block but that tastes wrong. Kinda like mixing C-style error checking with c++ exceptions. If I where to go that route, I may as well use the non-throwing version of open(). boost::system::error_code error; acceptor.open( address.protocol, error ); if( ! error ) { try { acceptor.set_option( tcp::acceptor::reuse_address(true) ); acceptor.bind( address ); acceptor.listen(); acceptor.async_accept( /*stuff*/ ); } catch( const boost::system::system_error& error ) { assert(acceptor.is_open()); acceptor.close(); return false; } } return !error; Is there an elegant way to handle these possible exceptions using RAII and try/catch blocks? Am I just wrong headed in trying to avoid if( error condition ) style error handling when using exceptions?
I would suggest just doing separate error handling for open, since there is different cleanup before and after: bool connect() { try { m_acceptor.open( m_address.protocol() ); } catch( const boost::system::system_error& error ) { return false; } try { m_acceptor.set_option( tcp::acceptor::reuse_address(true) ); m_acceptor.bind( m_address ); m_acceptor.listen(); m_acceptor.async_accept( /*stuff*/ ); } catch( const boost::system::system_error& error ) { m_acceptor.close(); return false; } return true; }
2,731,016
2,731,259
Detect if an assembly is available
I'm implementing an installer in Java, that is supposed to download and install an application for non-privileged users in Windows (from XP and up). The application is written in C++, and depend on the usual VC runtime-libraries (msvcm90.dll and friends). In order to save bandwidth, I want to avoid downloading the VC redistributables if they already are available for the user. I do however have a problem finding a reliable method to detect if an assembly is installed. If the assembly is missing, I will deploy it as described here: http://msdn.microsoft.com/en-us/library/ms235291%28VS.80%29.aspx So the question is simply how to detect if a (any) assembly is installed on the machine. It's no requirement that this can be done from Java. I can easily write a small probe in C++ and link it statically for the task. jgaa
If you are willing to write a small test program, then rather than writing one that looks for your dependencies, write one that has the same dependencies as your application. Try to run it. If it runs, the dependencies are in place. If it fails, the probable reason is that the dependencies are missing.