question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,815,172
1,815,214
Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros? (Qt)
Is it possible to see definition of Q_SIGNALS, Q_SLOT, SLOT(), SIGNAL() macros in Qt framework? P.S. Google gave me nothing in this question.
Form qobjectdefs.h, for a non-debug compilation: #define Q_SLOTS #define Q_SIGNALS protected #define SLOT(a) "1"#a #define SIGNAL(a) "2"#a The Q_SLOTS and Q_SIGNALS declarations are only treated specially by the moc run, in the final compilation they reduce to simple method declarations. SIGNAL() and SLOT() create names from the provided signatures.
1,815,202
1,815,209
C++ bindings to jGoodies?
Thus far the best C++ UI libraries I've run into are Qt, GTK, and wxWidgets; Are there existing libraries similar to jGoodies or 'better'. I am interested in mature (yet simple) technologies.
QT is about as good as it gets AFAIK. Binding a Java toolkit to C++ is a rather convoluted idea since in C++ you usually have a direct interface to the OS widgets. going full circle through Java is guaranteed to have uglier results.
1,815,297
1,815,336
How do I convert an image into a buffer so that I can send it over using socket programming? C++
How do I convert an image into a buffer so that I can send it over using socket programming? I'm using C++ socket programming. I am also using QT for my Gui. Also, after sending it over through the socket, how do I put that image back together so it can become a file again? If someone could put up some sample code that would be great :) I was looking around and found something about rfile but still not going through my head. tyty
Assuming that you want to send an image as a file, here is pseudocode to send it through a TCP connection. Client A Set up a connection Open a file in binary mode Loop: read/load N bytes in a buffer send(buffer) Close file Close connection Client B Listen and accept a connection Create a new file in binary mode Loop: n = read(buffer) write n bytes in the file Close file Close connection
1,815,431
1,815,440
error C4430: missing type specifier / error C2143: syntax error : missing ';' before '*'
I am getting both errors on the same line. Bridge *first in the Lan class. What am i missing? #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; class Lan{ Bridge *first; Bridge *second; Host hostList[10]; int id; }; class Bridge{ Lan lanList[5]; }; class Host{ Lan * lan; int id; public: Host(int newId) { id=newId; } }; void main(){ return; }
Declare Bridge before Lan #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; class Bridge; class Lan{ Bridge *first; Bridge *second; Host hostList[10]; int id; }; class Bridge{ Lan lanList[5]; };
1,815,486
1,815,511
C# & C++: "Attempted to read or write protected memory" Error
The following code compile without errors. Basically, the C#2005 Console application calls VC++2005 class library which in turn calls native VC++6 code. I get the following error when I run the C#2005 application: "Unhandled Exception: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt." What is the cause of this error? And how to go about correcting it? Edit1: It crashes at the line StdStringWrapper ssw = w.GetNext(); Edit2: I followed the advice of Naveen and used an integer index instead of iterators and there is no more errors now. A big thanks to all who commented as well! Code Written in C#2005 as Console Application: class Program { static void Main(string[] args) { Class1 test= new Class1(); test.PerformAction(); test.PerformAction(); test.PerformAction(); test.PerformAction(); } } Code Written in VC++2005 as Class Library: public ref class Class1 { public: void PerformAction(); }; void Class1::PerformAction() { DoSomethingClass d; StdStringContainer w; d.PerformAction(w); for(int i=0; i<w.GetSize(); i++) { StdStringWrapper ssw = w.GetNext(); std::cout << ssw.CStr() << std::endl; } } Code Written in VC++6 as Dynamic Link Library: #ifdef NATIVECODE_EXPORTS #define NATIVECODE_API __declspec(dllexport) #else #define NATIVECODE_API __declspec(dllimport) #endif class NATIVECODE_API StdStringWrapper { private: std::string _s; public: StdStringWrapper(); StdStringWrapper(const char *s); void Append(const char *s); const char* CStr() const; }; StdStringWrapper::StdStringWrapper() { } StdStringWrapper::StdStringWrapper(const char *s) { _s.append(s); } void StdStringWrapper::Append(const char *s) { _s.append(s); } const char* StdStringWrapper::CStr() const { return _s.c_str(); } // class NATIVECODE_API StdStringContainer { private: std::vector<StdStringWrapper> _items; std::vector<StdStringWrapper>::iterator _it; public: void Add(const StdStringWrapper& item); int GetSize() const; StdStringWrapper& GetNext(); }; void StdStringContainer::Add(const StdStringWrapper &item) { _items.insert(_items.end(),item); } int StdStringContainer::GetSize() const { return _items.size(); } StdStringWrapper& StdStringContainer::GetNext() { std::vector<StdStringWrapper>::iterator it = _it; _it++; return *it; } // class NATIVECODE_API DoSomethingClass { public: void PerformAction(StdStringContainer &s); }; void DoSomethingClass::PerformAction(StdStringContainer &s) { StdStringWrapper w1; w1.Append("This is string one"); s.Add(w1); StdStringWrapper w2; w2.Append("This is string two"); s.Add(w2); }
The main problem from my point of view is you are storing an iterator to a vector in your stdStringContainer class. Remember that whenever vector resizes all the existing iterators are invalidated. So whenever you do insert operation into the vector it may be possible that it resizes and your existing iterator becomes invalid. If you try to to dereference it in GetNext() then it will access invalid memory location. For checking whether this really the case try to reserve the initial vector size to some relatively big number so that the resizing doesn't happen. You can reserve the size using reserve() method, in which case it is guaranteed that the capacity() of the vector is greater than or equal to the reserved value.
1,815,490
1,815,575
How to get emacs tempo mode working with abbrevs for C/C++?
I've been experimenting with emacs tempo mode and it seems likely to save me lots of typing (always a good thing), but I haven't gotten it to work exactly the way I want it. On the wiki, there is an example for elisp similar to what I want to do which works as expected. Here is the complete .emacs that I tested it on: (require 'tempo) (setq tempo-interactive t) (tempo-define-template "lambda" '(> "(lambda (" p ")" n> r> ")">) nil "Insert a template for an anonymous procedure") (define-abbrev lisp-mode-abbrev-table "lambda" "" 'tempo-template-lambda) This allows me to type "lambda" followed by a space and have it automatically insert (lambda ( ) ) In my buffer with the point on the first closing parenthesis. However, replacing the last two sexp's with the following code (stolen from Joachim Baumann via Sebastien Varrette and modified by me): (tempo-define-template "c-include" '("#include <" r ".h>" > n) nil "Insert a #include <> statement") (define-abbrev c-mode-abbrev-table "c-include" "" 'tempo-template-lambda) Will not cause the template to be inserted after typing "c-include" followed by a space. This is on emacs 22.2.1 running under Ubuntu 9.04. Does anybody have any idea why this might be the case before I go digging deeper into the tempo code and/or (god forbid) the C-mode code?
The last argument to your define-abbrev should be 'tempo-template-c-include . Also, I'm not sure you can have a dash in there, i.e. it might have to be cinclude instead of c-include: (define-abbrev c-mode-abbrev-table "cinclude" "" 'tempo-template-c-include)
1,815,513
1,815,926
Problem with a volumetric fog in OpenGL
Good day. I am trying to make a volumetric fog in OpenGL using glFogCoordfEXT. Why does a fog affect to all object of my scene, even if they're not in fog's volume? And these objects become evenly gray as a fog itself. Here is a pic alt text http://img248.imageshack.us/img248/9281/fogp.jpg Code: void CFog::init() { glEnable(GL_FOG); glFogi(GL_FOG_MODE, GL_LINEAR); glFogfv(GL_FOG_COLOR, this->color); glFogf(GL_FOG_START, 0.0f); glFogf(GL_FOG_END, 1.0f); glHint(GL_FOG_HINT, GL_NICEST); glFogi(GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT); } void CFog::draw() { glBlendFunc(GL_SRC_ALPHA, GL_SRC_ALPHA); glEnable(GL_BLEND); glPushMatrix(); glTranslatef(this->coords[0], this->coords[1], this->coords[2]); if(this->angle[0] != 0.0f) glRotatef(this->angle[0], 1.0f, 0.0f, 0.0f); if(this->angle[1] != 0.0f) glRotatef(this->angle[1], 0.0f, 1.0f, 0.0f); if(this->angle[2] != 0.0f) glRotatef(this->angle[2], 0.0f, 0.0f, 1.0f); glScalef(this->size, this->size, this->size); GLfloat one = 1.0f; GLfloat zero = 0.0f; glColor4f(0.0, 0.0, 0.0, 0.5); glBegin(GL_QUADS); // Back Wall glFogCoordfEXT( one); glVertex3f(-2.5f,-2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f,-2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f, 2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f(-2.5f, 2.5f,-15.0f); glEnd(); GLenum err; if((err = glGetError()) != GL_NO_ERROR) { char * str = (char *)glGetString(err); } glBegin(GL_QUADS); // Floor glFogCoordfEXT( one); glVertex3f(-2.5f,-2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f,-2.5f,-15.0f); glFogCoordfEXT( zero); glVertex3f( 2.5f,-2.5f, 15.0f); glFogCoordfEXT( zero); glVertex3f(-2.5f,-2.5f, 15.0f); glEnd(); glBegin(GL_QUADS); // Roof glFogCoordfEXT( one); glVertex3f(-2.5f, 2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f, 2.5f,-15.0f); glFogCoordfEXT( zero); glVertex3f( 2.5f, 2.5f, 15.0f); glFogCoordfEXT( zero); glVertex3f(-2.5f, 2.5f, 15.0f); glEnd(); glBegin(GL_QUADS); // Right Wall glFogCoordfEXT( zero); glVertex3f( 2.5f,-2.5f, 15.0f); glFogCoordfEXT( zero); glVertex3f( 2.5f, 2.5f, 15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f, 2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f( 2.5f,-2.5f,-15.0f); glEnd(); glBegin(GL_QUADS); // Left Wall glFogCoordfEXT( zero); glVertex3f(-2.5f,-2.5f, 15.0f); glFogCoordfEXT( zero); glVertex3f(-2.5f, 2.5f, 15.0f); glFogCoordfEXT( one); glVertex3f(-2.5f, 2.5f,-15.0f); glFogCoordfEXT( one); glVertex3f(-2.5f,-2.5f,-15.0f); glEnd(); glPopMatrix(); glDisable(GL_BLEND); //glDisable(GL_FOG); }
You seem to not be clear on how GL_fog_coord_EXT works. You're saying that an object is "outside the fog volume" but OpenGL does not have any notion of a fog volume. At any point, either Fog is completely off, or it's on, in which case the fog equation will be applied with a fog coefficient that depends both on the fog mode (LINEAR in your case) and the fog coordinate. Regarding the fog coordinate. when using glFogi(GL_FOG_COORDINATE_SOURCE_EXT, GL_FOG_COORDINATE_EXT); You're telling OpenGL that every time you'll provide a vertex, you'll also provide which fog coordinate to use through glFogCoordfEXT So, what does it mean in your case ? Assuming you're not calling glFogCoordfEXT in your teapot drawing code, you'll end up with the value of your last call to glFogCoordfEXT, which looks like a glFogCoordf(one). So everything drawn in that case will be fully in fog, which is what you observe. Now, I'm not sure exactly what you're trying to achieve, so I don't know how to help you solve the issue, exactly. However, if the goal is to use your quads to mimic fog, simply turn fog off when drawing the scene, and turn it on only when drawing the cube (I'm pretty sure it won't look like nice fog though).
1,815,542
1,821,283
How to let omnicppcomplete automatically close empty argument lists?
Is it possible to let Vim's omnicppcomplete automatically close argument lists for functions or methods that do not take any arguments? For example, assuming v is an STL vector, when auto completing v.clear(), we end up with: v.clear( It would be nice if the closing parenthesis would be automatically added. Is this possible?
It looks like it should be possible: I'm not sure whether I have the latest version of the omnicppcomplete script, but in my autoload/omni/cpp/complete.vim, there is a function called s:ExtendTagItemToPopupItem. In this function, there is: " Formating information for the preview window if index(['f', 'p'], tagItem.kind[0])>=0 let szItemWord .= '(' if g:OmniCpp_ShowPrototypeInAbbr && has_key(tagItem, 'signature') let szAbbr .= tagItem.signature else let szAbbr .= '(' endif endif After the line (#165 in my version) let szItemWord .= '(', add: if (has_key(tagItem, 'signature') == 0) || (tagItem['signature'] =~ '()') let szItemWord .= ')' endif That should do the trick (although I don't use C++ much, so I haven't tested it extensively). It basically checks whether the "signature" of the function contains "()" as opposed to (for example) "(int *major, int *minor)". If the brackets are empty, it adds a closing brace. It could probably be improved by changing '()' to '(\s*\(void\)\?\s*)' for completeness: this would check for "()", "( )", "(void)", "( void )" etc.
1,815,613
1,815,633
What next generation low level language is the best bet when migrating a code base?
Let's say you have a company running a lot of C/C++, and you want to start planning migration to new technologies so you don't end up like COBOL companies 15 years ago. For now, C/C++ runs more than fine and there is plenty dev on the market for it. But you want to start thinking about it now, because given the huge running code base and the data sensitivity, you feel it can take 5-10 years to move to the next step without overloading the budget and the dev teams. You have heard about D, starting to be quite mature, and Go, promising to be quite popular. What would be your choice and why?
D and Go will probably just become as popular as Python and Ruby are today. They each fill a niche, and even though D was supposed to be a full-fledged replacement of C++, it probably will never acquire enough mass to push C++ away. Not to mention that they both aren't stable/mature enough, and it's unknown whether you'll have support for these languages in 10-20 years for the then-current hardware and operating systems. Considering that C/C++ is pretty much the compiled language and is used in the great majority of operating systems and native-code applications, it's very unlikely that it'll go away in the foreseeable future.
1,815,643
1,815,694
How to properly return reference to class member?
class Foo { protected: QPoint& bar() const; private: QPoint m_bar; }; QPoint& Foo::bar() const { return m_bar; } I got this error: error: invalid initialization of reference of type ‘QPoint&’ from expression of type ‘const QPoint’ However it works if I change it to this: QPoint& Foo::bar() const { return (QPoint&) m_bar; } 1) I don't understand why the compiler says that my QPoint is const. 2) Is it ok to leave the cast there?
In a non-const member function of class Foo the this pointer is of the type Foo* const - that is, the pointer is const, but not the instance it points to. In a const member function, however, the this pointer is of the type const Foo* const. This means that the object it points to is constant, too. Therefore, in your example, when you use this->m_bar (of which m_bar is just the short form), then m_bar is a member of a constant object - which is why you cannot return it as a non-const reference. This actually makes sense from a design POV: If that Foo object is a constant object, and you are allowed to invoke Foo::bar for constant objects, then, if this would return a non-const reference to some internals which you can fiddle with, you would be able to change the state of a constant object. Now you have to look at your design and ask yourself how you arrived at this point and what your actual intention is. If that m_bar member isn't really part of the state of the object (for example, it's only there for debugging purposes), then you could consider making it mutable. If it is part of the state of the object, then you have to ask yourself why you want to return a non-const reference to some internal data of a constant object. Either make the member function non-const, or return a const reference, or overload the member function: class Foo { public: const QPoint& bar() const {return m_bar;} QPoint& bar() {return m_bar;} // ... };
1,815,688
1,954,144
How to Use CCache with CMake?
I would like to do the following: If CCache is present in PATH, use "ccache g++" for compilation, else use g++. I tried writing a small my-cmake script containing CC="ccache gcc" CXX="ccache g++" cmake $* but it does not seem to work (running make still does not use ccache; I checked this using CMAKE_VERBOSE_MAKEFILE on). Update: As per this link I tried changing my script to cmake -D CMAKE_CXX_COMPILER="ccache" -D CMAKE_CXX_COMPILER_ARG1="g++" -D CMAKE_C_COMPILER="ccache" -D CMAKE_C_COMPILER_ARG1="gcc" $* but cmake bails out complaining that a test failed on using the compiler ccache (which can be expected).
I personally have /usr/lib/ccache in my $PATH. This directory contains loads of symlinks for every possible name the compiler could be called from (like gcc and gcc-4.3), all pointing to ccache. And I didn't even create the symlinks. That directory comes pre-filled when I install ccache on Debian.
1,815,705
1,815,784
I am new to threads, What does this compile error mean?
Using C++. pthread_t threads[STORAGE]; // 0-99 ... void run() Error>>> int status = pthread_create(&threads[0], NULL, updateMessages, (void *) NULL); if (status != 0) { printf("pthread_create returned error code %d\n", status); exit(-1); } ... void ClientHandler::updateMessages(void *) { string reqUpdate = "91"; // Request for update string recvMSG; while (true) { sleep(5); sending(sock,reqUpdate); // send recvMSG = receiving(sock); // receive QString output(recvMSG); emit signal_chat(output, 0); // Print message to text box } } ... Compile Error: TCPClient.cpp:109: error: argument of type ‘void (ClientHandler::)(void*)’ does not match ‘void* (*)(void*)’ I can't figure out whats wrong. Thanks in advance.
A pointer to a member function is different from a global function with the same signature since the member function needs an additional object on which it operates. Therefore pointers to these two types of functions are not compatible. In this case this means that you cannot pass a member function pointer to pthread_create but only a pointer to a non-member (or static) function. A work around for this problem is to use the forth parameter of pthread_create to pass a pointer to a object to a global function which then calls the method of the passed object: class ClientHandler { public: void updateMessages(); void run(); }; // Global function that will be the threads main function. // It expects a pointer to a ClientHandler object. extern "C" void *CH_updateMessages(void *ch) { // Call "real" main function reinterpret_cast<ClientHandler*>(ch)->updateMessages(); return 0; } void ClientHandler::run() { // Start thread and pass pointer to the current object int status = pthread_create(&threads[0], NULL, CH_updateMessages, (void*)this); ... }
1,815,903
1,815,922
Const correctness in C++ operator overloading returns
I'm a little confused as to why I've been told to return const foo from a binary operator in c++ instead of just foo. I've been reading Bruce Eckel's "Thinking in C++", and in the chapter on operator overloading, he says that "by making the return value [of an over-loading binary operator] const, you state that only a const member function can be called for that return value. This is const-correct, because it prevents you from storing potentially valuable information in an object that will be most likely be lost". However, if I have a plus operator that returns const, and a prefix increment operator, this code is invalid: class Integer{ int i; public: Integer(int ii): i(ii){ } Integer(Integer&); const Integer operator+(); Integer operator++(); }; int main(){ Integer a(0); Integer b(1); Integer c( ++(a + b)); } To allow this sort of assignment, wouldn't it make sense to have the + operator return a non-const value? This could be done by adding const_casts, but that gets pretty bulky, doesn't it? Thanks!
When you say ++x, you're saying "add 1 to x, store the result back into x, and tell me what it was". This is the preincrement operator. But, in ++(a+b), how are you supposed to "store the result back into a+b"? Certainly you could store the result back into the temporary which is presently holding the result of a+b, which would vanish soon enough. But if you didn't really care where the result was stored, why did you increment it instead of just adding one?
1,815,976
1,816,757
Download an Image file from web server using VC++ 9.0
I want to code a VC++ 9 based console application which downloads an image from a webserver. I have code which used to run in VC++ 6, but its giving lot of compilation errors in VC++ 9.0. I need code which compiles in VC++ 9.0 using MS Visual Studio 2008. Also I need only win32 code and not MFC.
To download something from the Web you could use libcurl library. It doesn't use MFC.
1,816,023
1,816,072
Reading/Writing Magnetic Striped ID Cards in Linux
How would I accomplish this? Is there a specific brand of card reader/writer that works easily with linux and windows (linux being more important as I need to deploy these to cheap kiosks).
Googling "magnetic card reader writer linux" will give you lots of hits. Also search for "stripe snoop" - it's open-source software looks like it reads well, but doesn't write yet. It's been my experience with similar devices that if you find one at a price that works for you, then even if the manufacturer doesn't supply a Linux driver or SDK, if you can get units with an RS-232 or RS422 serial interface and reasonable documentation, it just takes a bit of elbow grease to code up a usable communications layer. Other interfaces like USB or Ethernet may require more work or even need a Linux driver from the manufacturer.
1,816,052
1,816,095
big integers with fixed length
I am looking for a library for big integers but with fixed width (128 or 256 would be enough). The reason is I don't want any allocation on the heap. I tried to make them myself but implementing multiplication, division and modulo an efficient way seems to be quite a pain. Does this already exists somewhere ? Thanks
Take a look at the GMP library: www.gmplib.org Quoting from the function categories: Low-level positive-integer, hard-to-use, very low overhead functions are found in the mpn category. No memory management is performed; the caller must ensure enough space is available for the results. (...) That seems to be what you need.
1,816,319
1,816,382
Reading directly from an std::istream into an std::string
Is there anyway to read a known number of bytes, directly into an std::string, without creating a temporary buffer to do so? eg currently I can do it by boost::uint16_t len; is.read((char*)&len, 2); char *tmpStr = new char[len]; is.read(tmpStr, len); std::string str(tmpStr, len); delete[] tmpStr;
std::string has a resize function you could use, or a constructor that'll do the same: boost::uint16_t len; is.read((char*)&len, 2); std::string str(len, '\0'); is.read(&str[0], len); This is untested, and I don't know if strings are mandated to have contiguous storage.
1,816,402
1,816,428
How can I do an HTTP redirect in C++
I'm making an HTTP server in c++, I notice that the way apache works is if you request a directory without adding a forward slash at the end, firefox still somehow knows that it's a directory you are requesting (which seems impossible for firefox to do, which is why I'm assuming apache is doing a redirect). Is that assumption right? Does apache check to see that you are requesting a directory and then does an http redirect to a request with the forward slash? If that is how apache works, how do I implement that in c++? Thanks to anyone who replies.
Determine if the resource represents a directory, if so reply with a: HTTP/1.X 301 Moved Permanently Location: URI-including-trailing-slash Using 301 allows user agents to cache the redirect.
1,816,431
1,824,731
QT Webkit & OpenGL Rendering Context
Would it be possible to create a window with a webpage using a webkit component using QT4, then embed an OpenGL context into the middle in the same way a java applet or a flash applet may appear normally?
Sure, you can embed any QWidget into a web page shown through a QWebView, including a QGLWidget. This would be a starting point in the docs: http://doc.trolltech.com/4.5/qwebpage.html#setPluginFactory .
1,816,451
1,816,470
Are there any CURL alternatives for C++?
I hate CURL it is too bulky with too many dependencies when all I need to do is quickly open a URL. I don't even need to retrieve the contents of the web page, I just need to make the GET HTTP request to the server. What's the most minimal way I can do this and don't say CURL !@#$
There are lots of choices! Try libwww -- but be warned, most people strongly prefer libcurl. It's much easier to use.
1,816,498
1,816,500
Creating custom message types in win32?
Is there a way to define and send custom message types in Win32, to be caught by your Main message handler? For example, my main message handler captures messages such as WM_PAINT, WM_RESIZE, WM_LBUTTONDOWN etc. Can I create my own WM_DOSOMETHING? If so, how would I send this message? Ah, I actually just discovered this was asked before here, however, it doesn't answer how I would actually send this message.
Yes. Just declare a constant in the WM_USER range e.g. #define WM_RETICULATE_SPLINES (WM_USER + 0x0001) You can also register a message by name using the RegisterWindowMessage API. You can then send these messages using SendMessage, PostMessage or any of their variants.
1,816,547
1,816,618
Initialization: T x(value) vs. T x = value when value is of type T
T x(value) is usually the better choice because it will directly initialize x with value, whereas T x = value might create a temporary depending on the type of value. In the special case where value is of type T though, my guess is that the expression T x = value will always result in exactly one copy constructor call. Am I correct? I've asked this question because I'm starting to think that the first syntax is too ugly and harder to understand, especially when value is the result of a function call. e.g: const std::string path(attributes.data(pathAttrib)); const std::string path = attributes.data(pathAttrib);
From the standard, copy-initialization for class types where the cv-unqualified type of the source type is the same as, or a derived class of the destination, has exactly the same behaviour as direct-initialization. The description of these two cases introduce a single paragraph describing the required behaviour which is that only constructors for the destination type are considered and the constructor chosen is used to initialize the destination with the initializer expression as argument. No extra temporary is allowed in these cases. Neither form of initialization prevent the optimizations described in 12.8 [class.copy] from occuring. Though a non-normative example, the example in 12.8/15 uses the copy-initialization form of initializer to demonstrate the elimination of two copies resulting from a function returning a local variable by value to an object initializer. This means that if value in your example is a temporary of type T then it - and the copy operation to x - may be eliminated.
1,816,552
1,816,715
Where does C++ standard define the value range of float types?
As far as I know floating point values are of the form n * 2^e, with float range being n = -(2^23-1) - (2^23-1), and e = -126 - 127, double range being n = -(2^52-1) - (2^52-1), and e = -1022 - 1023 I was looking through the C++ standard, but failed to find the place where the standard specifies this, or mandates the association of the float, double and long double types with ranges defined in other (IEEE) standards. The only related thing I found in 3.9.1.8 is: There are three floating point types: float, double, and long double. The type double provides at least as much precision as float, and the type long double provides at least as much precision as double. The set of values of the type float is a subset of the set of values of the type double; the set of values of the type double is a subset of the set of values of the type long double. The value representation of floating-point types is implementation-defined. And no mention of the minimum range provided by the type. Where/how does the standard specify the (minimum?) value range of the floating point types? Or can a compiler freely choose any value range and still be standard compliant?
Just like integer numberic limits, the limits for float, double and long double are imported from the C standard. The minimum value for constants FLT_MAX, DBL_MAX and LDBL_MAX is 1E+37. For their *_MIN variants the maximum value is 1E-37.
1,816,628
1,816,694
printing ip addresses using gdb
I am debugging a networking code and want to print ip addresses which are declared as int32. when i print it using gdb print command, i get some values which is not much meaningful. How can i possibly print them in meaningful format?
Just use inet_ntoa(3) as so: (gdb) p (char*)inet_ntoa(0x01234567) # Replace with your IP address $1 = 0xa000b660 "103.69.35.1"
1,816,790
1,875,992
Sun C++ Compilers and Boost
I am currently developing on OpenSolaris 2009-06. The Boost::MPL Documentation seems to suggest that sun compilers are not supported (the document was last updated in 2004 ). Boost's top level documentation seems to suggest that the sun compilers 5.10 onwards are supported -- I guess this is a general level of support or does this include MPL ?. Does anyone have any details on the state of the C++ conformance of the sun 5.10 compilers ? I could always compile using GCC.
I guess since an exact answer has not been provided I must post one myself. opensolaris(2009.06) and boost-1.4.1 seem to work well. The ./bjam picks the right switches and boost::mpl seems to work well with the sun compiler present. So, as far as I can tell the mpl documentation on compiler support is quite outdated.
1,816,851
1,817,009
HLSL DirectX9: Is there a getTime() function or similar?
I'm currently working on a project using C++ and DirectX9 and I'm looking into creating a light source which varies in colour as time goes on. I know C++ has a timeGetTime() function, but was wondering if anyone knows of a function in HLSL that will allow me to do this? Regards. Mike.
Use a shader constant in HLSL (see this introduction). Here is example HLSL code that uses timeInSeconds to modify the texture coordinate: // HLSL float4x4 view_proj_matrix; float4x4 texture_matrix0; // My time in seconds, passed in by CPU program float timeInSeconds; struct VS_OUTPUT { float4 Pos : POSITION; float3 Pshade : TEXCOORD0; }; VS_OUTPUT main (float4 vPosition : POSITION) { VS_OUTPUT Out = (VS_OUTPUT) 0; // Transform position to clip space Out.Pos = mul (view_proj_matrix, vPosition); // Transform Pshade Out.Pshade = mul (texture_matrix0, vPosition); // Transform according to time Out.Pshade = MyFunctionOfTime( Out.Pshade, timeInSeconds ); return Out; } And then in your rendering (CPU) code before you call Begin() on the effect you should call: // C++ myLightSourceTime = GetTime(); // Or system equivalent here: m_pEffect->SetFloat ("timeInSeconds ", &myLightSourceTime); If you don't understand the concept of shader constants, have a quick read of the PDF. You can use any HLSL data type as a constant (eg bool, float, float4, float4x4 and friends).
1,816,904
1,816,937
segmentation fault at end of the program
I've got a bit problem. My program throws segmentation fault when returning zero in main. The main function looks like this: int main(int argc, char* argv[]){ ifstream fs("test.dat", ios::binary); cSendStream sendstr(&fs,20); char *zomg=sendstr.data(); //zomg[20]=0; sendstr.read(20); cout<<"Buffer: "<<sendstr.data()<<endl; cout<<"Remaining: "<<sendstr.dataAvailable()<<endl; sendstr.read(2); cout<<"Buffer: "<<zomg<<endl; cout<<"Remaining: "<<sendstr.dataAvailable()<<endl; sendstr.read(10); cout<<"Buffer: "<<zomg<<endl; cout<<"Remaining: "<<sendstr.dataAvailable()<<endl; cout<<"end..."<<endl; return 0; } The commented zomg part is the point which makes the program crash. zomg is pointing on char[20]. My point on that line is to set the end of the array because somehow if I don't do that the stream reads more data than 20 bytes, but it prints just one unnecessary symbol though. Funny thing is that even if I write there some additional code between this and return 0 it throws fault first when returning. Just for the case you wanted to see the cSendStream class: cSendStream.h: class cSendStream{ public: cSendStream(std::istream*, int streamsize); int read(int); int dataAvailable(); char* data(); private: void shift(int); std::istream *source; int streamsize; char* buffer; }; and the cSendStream.cpp: #include "cSendStream.h" cSendStream::cSendStream(std::istream *src, int size){ source=src; streamsize=size; buffer=new char[streamsize]; memset(buffer,0,streamsize); } int cSendStream::read(int i){ if(dataAvailable()<1 || i<=0){ return 0; } if(i>dataAvailable()){ i=dataAvailable()-1; } if(i>streamsize){ i=streamsize; } shift(i); source->read(&(buffer[streamsize-i]),i); return i; } int cSendStream::dataAvailable(){ int current=source->tellg(); source->seekg (0, std::ios::end); int available = (int)(source->tellg())-current; source->seekg (current); return available; } char* cSendStream::data(){ return buffer; } void cSendStream::shift(int i){ char tmp[2048]; memcpy(tmp,buffer,streamsize); memcpy(&(buffer[0]),&(tmp[i]),streamsize-i); }
zomg[20]=0 is writing one past the end of the allocated array, but it is difficult to guess why the segfault is occurring. My guess is that your clever compiler is using alloca for the allocation and you are scribbling on the return address. It might be fun to look at the assembly (usually -S) to see what's happening.
1,816,960
1,816,968
setCurrentDrive? c++ win32
How can I set the current drive in c++? I was unable to find anything on the MSDN site
The string you use to set the directory can be prefixed by the drive letter -- i.e., "c:\program files". Directories are set relative to your programs current working directory. If you start your program from 'X' drive you will not be able to move outside of 'X' using relative conventions/directory addressing. You need to use a directory string prefixed with the correct drive letter.
1,817,048
1,817,127
Qt, how to set text edit scroll bar to the bottom? C++
I have the text edit box as a chat window, but I was wondering if there was a way to set the scroll bar to be at the bottom to show the most updated message. I am currently using Qt3 and C++. chat_box->.... I tried looking and was only able to find "ScrollBarMode" but it only lets me turn it on or off or auto... which doesn't really help. Thanks for the help :D
scotchi's answer would be correct if it was Qt4. Qt3 solution would be something like: QScrollBar *v = chat_box->verticalScrollBar(); v->setValue(v->maxValue()); I didn't test this code since I don't have Qt3 anymore. Check if it works.
1,817,266
1,817,273
Is it better/faster to have class variables or local function variables?
Ok I know the title doesn't fully explain this question. So I'm writing a program that performs a large number of calculations and I'm trying to optimize it so that it won't run quite so slow. I have a function that is a member of a class that gets called around 5 million times. This is the function: void PointCamera::GetRay(float x, float y, Ray& out) { //Find difference between location on view plane and origin and normalize float vpPointx = pixelSizex * (x - 0.5f * (float)width); float vpPointy = pixelSizey * (((float)height - y) - 0.5f * height); //Transform ray to camera's direction out.d = u * vpPointx + v * vpPointy - w * lens_distance; out.d.Normalize(); //Set origin to camera location out.o = loc; } I'm wondering if it is better/faster to declare the variables vpPointx and vpPointy in the class than to declare them each time I call the function. Would this be a good optimization or would it have little effect? And in general, if there is anything here that could be optimized please let me know.
By limiting the scope of your variables, you are giving more opportunity to the compiler optimiser to rearrange your code and make it run faster. For example, it might keep the values of those variables entirely within CPU registers, which may be an order of magnitude faster than memory access. Also, if those variables were class instance variables, then the compiler would have to generate code to dereference this every time you accessed them, which would very likely be slower than local variable access. As always, you should measure the performance yourself and try the code both ways (or better, as many ways as you can think of). All optimisation advice is subject to whatever your compiler actually does, which requires experimentation.
1,817,334
1,817,355
Library redefines NULL
I'm working with a library that redefines NULL. It causes some problems with other parts of my program. I'm not sure what I can do about it. Any idea? My program's in C++, the library's in C. #ifdef NULL #undef NULL #endif /** * NULL define. */ #define NULL ((void *) 0) Oh, and it produces these errors: Generic.h:67: error: default argument for parameter of type 'LCD::LCDBase*' has type 'void*' Generic.cpp: In constructor 'LCD::Generic::Generic(std::string, Json::Value*, int, LCD::LCDBase*)': Generic.cpp:44: error: invalid conversion from 'void*' to 'QObject*' Generic.cpp:44: error: initializing argument 2 of 'LCD::LCDWrapper::LCDWrapper(LCD::LCDInterface*, QObject*)' Generic.cpp: In member function 'void LCD::Generic::BuildLayouts()': Generic.cpp:202: error: invalid conversion from 'void*' to 'LCD::Widget*' Generic.cpp: In member function 'void LCD::Generic::AddWidget(std::string, unsigned int, unsigned int, std::string)': Generic.cpp:459: error: invalid conversion from 'void*' to 'LCD::Widget*' scons: *** [Generic.o] Error 1 Here's the first one: Generic(std::string name, Json::Value *config, int type, LCDBase *lcd = NULL); Edit: Ok, casting explicitly works, but how do I cast for a function pointer?
Can you rebuild the library without that define? That's what I'd try first. NULL is a pretty standard macro, and should be assumed to be defined everywhere. Right now, your problem is that C++ doesn't allow automatic casts from void * to other pointer types like C does. From C++ Reference: In C++, NULL expands either to 0 or 0L. If that doesn't work, just do a global replace in the library: NULL to LIBDEFINEDNULL or something. That way you'll keep the library code intact and avoid the macro collision.
1,817,445
1,817,450
C++: static member functions and variables- redefinition of static variable?
I was trying to incorporate the Singleton design pattern into my code, but I started getting a weird error: main.obj : error LNK2005: "private: static class gameState * gameState::state" (?state@gameState@@0PAV1@A) already defined in gameState.obj If you're not familiar with the singleton pattern, it is basically used to enforce only 1 instance of a certain object in the entire program. Here is the relevant code: gameState.h: class gameState { public: static gameState* Instance() {return state;} . . . private: gameState(); static gameState* state; }; gameState* gameState::state = new gameState(); and right now I'm just using the instance of that object in the main.cpp file: gameState *currState = gameState::Instance(); . . . for_each(currState->getHumanPieces().begin(),currState->getHumanPieces().end(), drawPieces); It would seem I am trying to redefine gameState::state, but can't figure out why... help anyone? that solved that, but one error still remains, which I didn't actually post before as I thought it was just part of the other one: error LNK2019: unresolved external symbol "private: __thiscall gameState::gameState(void)" (??0gameState@@AAE@XZ) referenced in function "void __cdecl `dynamic initializer for 'private: static class gameState * gameState::state''(void)" (??__E?state@gameState@@0PAV1@A@@YAXXZ) any good tip on how to fix that one as well? Thanks both of you, its fixed :D
You need to put the definition of the static gameState* into exactly one source file, i.e. this line: gameState* gameState::state = new gameState(); If you put it in a header which is included by multiple source files, each has a definition of gameState::state which leads to errors at link-time. For the follow-up problem, use Vadakkumpadaths advice: you need to provide a definition for gameStates constructor, not only a declaration.
1,817,508
1,817,526
Is there a way to prevent construction during non-compound operations?
I have a vector class that has addition, multiplication, subtraction, division, etc operators. I'm trying to optimize my program (which does a lot of vector operations) and I'm realizing that about 50% of the time spent is in constructing and destructing vectors. I understand that this is because every time I call a non-compound mathematical operator for a vector, a new vector is constructed. Is there a way to prevent this without using compound operators or expanding vector operations? If I have: Vector a = Vector(x, y, z); Vector b = Vector(a, b, c); Vector c = a + b; I can't use += because c is a completely new vector. I know I can speed it up with this: c.x = a.x + b.x; c.y = a.y + b.y; c.z = a.z + b.z; but that doesn't seem as clean as just using an operator.
I understand that this is because every time I call a non-compound mathematical operator for a vector, a new vector is constructed. Is there a way to prevent this without using compound operators or expanding vector operations? Well, the nature of adding two things together to produce a third thing requires you to construct a third thing...so how is what you're asking even logically possible? That being said, if you're concerned about the temporaries created by using the addition operator, these may be optimized out by the compiler if your compiler supports return value optimization. Alternatively, if your compiler doesn't support this and you really want to cut back on temporaries but keep the + operator, you may want to look into emulating C++0x move semantics, and provide your vector with a rvalue move constructor, which will be invoked when it returns a temporary by value. See the Section titled "Moving Objects" in this article for information on implementing move semantics in C++03. Once C++0x comes out, you can just replace these hacks with real move constructors using the && operator for rvalue references.
1,817,599
1,817,611
c++: Private constructor means no definition of that classes objects inside headers?
Yet another question, go me!... Anyway, I have 2 classes with private constructors and static functions to return an instance of that class. Everything was fine, I have a main.cpp file where I managed to get hold of my gameState object pointer, by doing: gameState *state = gameState::Instance(); But now I seem to have a problem. For the sake of convenience, I wanted both the gameState instance and a actionHandler instance to retain a copy of the pointer to each other. So I tried to include in each other's header files: gameState *state; and actionHandler *handler; This however, doesn't seem to work... I get "error C2143: syntax error : missing ';' before '*'" errors on both of those lines... Can you not define variables of a certain classe's in the header if that class has a private constructor? Or is the problem something else? OR maybe it is because the pointer to teh instance is stored as a static member? EDIT: Thanks guys! It's amazing the amount of c++ knowledge I'm getting these last couple of days.. awsome!
It looks like you need to add a forward declaration of the opposite class to each class's header file. For example: class actionHandler; class gameState { private: actionHandler *handler; ... }; and: class gameState; class actionHandler { private: gameState *state; ... };
1,817,691
1,817,775
How to use unordered_set in STL?
I am in need of a hash_map class in C++(STL). Primary operation is to put pair in the set and then check if it exists or not. I am unable to find a sample code which does it to know if what I am declaration correctly or not. #include <iostream> #include <hash_map> using namespace std; using namespace __gnu_cxx; typedef pair<int,string> pis; struct eqpis { bool operator()(pis p1,pis p2) const { if(p1==p2) return true; return false; } }; int main() { hash_map<pis,int,hash<pis>,eqpis> map; } This one compiles. But if I add the line : map[pis(10,"hello")]=10; then it gives a lot of errors: /usr/include/c++/4.4/backward/hashtable.h: In member function ‘size_t __gnu_cxx::hashtable::_M_bkt_num_key(const _Key&, size_t) const [with _Val = std::pair, std::allocator > >, int>, _Key = std::pair, std::allocator > >, _HashFcn = __gnu_cxx::hash, std::allocator > > >, _ExtractKey = std::_Select1st, std::allocator > >, int> >, _EqualKey = eqpis, _Alloc = std::allocator]’: /usr/include/c++/4.4/backward/hashtable.h:594: instantiated from ‘size_t __gnu_cxx::hashtable::_M_bkt_num(const _Val&, size_t) const [with _Val = std::pair, std::allocator > >, int>, _Key = std::pair, std::allocator > >, _HashFcn = __gnu_cxx::hash, std::allocator > > >, _ExtractKey = std::_Select1st, std::allocator > >, int> >, _EqualKey = eqpis, _Alloc = std::allocator]’ /usr/include/c++/4.4/backward/hashtable.h:1001: instantiated from ‘void __gnu_cxx::hashtable::resize(size_t) [with _Val = std::pair, std::allocator > >, int>, _Key = std::pair, std::allocator > >, _HashFcn = __gnu_cxx::hash, std::allocator > > >, _ExtractKey = std::_Select1st, std::allocator > >, int> >, _EqualKey = eqpis, _Alloc = std::allocator]’ /usr/include/c++/4.4/backward/hashtable.h:789: instantiated from ‘_Val& __gnu_cxx::hashtable::find_or_insert(const _Val&) [with _Val = std::pair, std::allocator > >, int>, _Key = std::pair, std::allocator > >, _HashFcn = __gnu_cxx::hash, std::allocator > > >, _ExtractKey = std::_Select1st, std::allocator > >, int> >, _EqualKey = eqpis, _Alloc = std::allocator]’ /usr/include/c++/4.4/backward/hash_map:216: instantiated from ‘_Tp& __gnu_cxx::hash_map::operator[](const typename __gnu_cxx::hashtable, _Key, _HashFn, std::_Select1st >, _EqualKey, _Alloc>::key_type&) [with _Key = std::pair, std::allocator > >, _Tp = int, _HashFn = __gnu_cxx::hash, std::allocator > > >, _EqualKey = eqpis, _Alloc = std::allocator]’ x.cpp:18: instantiated from here /usr/include/c++/4.4/backward/hashtable.h:590: error: no match for call to ‘(const __gnu_cxx::hash, std::allocator > > >) (const std::pair, std::allocator > >&)’ Thanks
Your problem is that hash<T> is only specialized for certain types. It can't magically make a hash function for any old type. You need to make your own hash function.
1,817,733
1,818,543
Sound Monitoring in C++/Python
I'm looking for an API (or some information as to where to look/start) that will ultimately allow me to monitor sound being played by the computer. My end goal (well, certain to eventually be a stepping-stone) is an oscilloscope. Where should I begin to look (aside from Google, which has yielded unsatisfactory results) to learn more about sound as processed by computers (particularly, Macs) and how to get to it. Thanks!
As @cobbal noted, on Mac OS X you would need to use PortAudio in some way to get the audio as it plays. The only other way to do it would be to use an audio player that has a plugin API, then write your code as a plugin for that one player. But a CoreAudio solution should make it possible for you to monitor all sounds played on the Mac. Your CoreAudio code will not be portable at all to Windows and Linux. There is no portable solution at this time. On Windows you would probably want to use the WaveIn/WaveOut API, unless you have pro gear, in which case you would probably want to use ASIO. On Linux, I'm not sure; I think you could probably hook in to ALSA/PulseAudio to grab audio. Unless you have pro gear, in which case you would probably want to use JACK. If you wanted a portable solution, you might want to look seriously at the plugin option. Find a portable free software media player that works on all your platforms, and make a scope plugin for that. For an oscilloscope, you are going to want to get a book on Digital Signal Processing ("DSP"). You will probably want to use a Discrete Fourier Transform ("DFT") to get frequency information out of your discrete audio samples; a DFT library will likely be called an "FFT" library ("FFT" being short for "Fast Fourier Transform"). My favorite single book on DSP is: Understanding Digital Signal Processing by Richard G. Lyons. EDIT: And by the way, most media players have "visualization" plugins, and some of them are displays based on frequencies. (Some even have names like "scope".) Is it possible that there is a media player that already does exactly the display you want?
1,817,807
1,817,811
Does the hash<char*> function in STL give 1-1 mapping between char* and size_t?
I have a pair I know the value of the pair.first cannot be more than 1000. I also know that the pair.second , the string, is always 1 word. Never more than 1 word. So, to construct the Hash value for the pair I am doing the following: pair<int,string> p; hash<char*> H; hash_vale = H(p.second)*1000 + p.first; I think this will give unique values as long as the hash value of strings is not too huge and that H(p.second) will give 1-1 mappings. Are these assumptions valid? Thanks,
By definition, a hash can't be one-to-one due to the pigeonhole principle. I.E., there are 2^32 possible hash values, but far more possible strings. So there must be two strings with the same hash value. Second of all, you are almost certainly causing overflow by multiplying your hash value by 1000, since a hash should use all 32 bits. You are much better off hashing the int and then mixing the hashes. Boost has a hash_combine function: a + 0x9e3779b9 + (b << 6) + (b >> 2);
1,817,814
1,819,037
c++: Object's variable cannot be evaluated, but variable from reference to the same object can?
Ok, this is veeery weird... I think. What I mean with the title is: inside the act() function from an actionHandler object I have: state->getHumanPieces(); Which gives me an address violation of some sort, apparently 'this' does not have a 'state' variable initialized... It so happens this actionHandler class has a static variable, which is a pointer to an instance of itself, called 'handler'... and if I do: handler->state->getHumanPieces(); It works perfectly.. In order to make this even clearer: That 'handler' pointer, points to the only instance of actionHandler existing in the whole program (singleton pattern).. So basically when I run this act() function from my actionHandler object, it doesn't let me access the 'state' variable, BUT if from that object, I try to access the same variable through a pointer to the same object, it is ok?? I don't get what is going on.. I'm not sure if it is clear, prob a bit confusing, but I hope it is understandable.. Btw, the VS08 debugger is showing what I mean: this: 0x000000 {state=???} handler: someAddress {state= someAddress} handler:... state:... state: CXX0030: ERROR: expression cannot be evaluated I hope that makes it clearer, it's the little tree-structure that shows up on the little window where the current values of the variables are shown (Autos). EDIT: I so get that the this pointer is null, I just don't understand how it can be null.. I'll post some code: actionHandler.h: class gameState; class actionHandler { public: static actionHandler* Instance(){return handler;} void act(int,int); private: actionHandler(); static actionHandler* handler; gameState *state; }; actionHandler.cpp: actionHandler* actionHandler::handler = new actionHandler(); actionHandler::actionHandler() { state = gameState::Instance(); } void actionHandler::act(int x, int y) { state->getHumanPieces(); } now, in gameState.h i have a similar structure(singleton) and an actionHandler* private var, which gets initialised in: gameState::gameState() { handler = actionHandler::Instance(); } and also a getHandler() func which returns the handler. This all should get initialised in main.cpp: gameState *currState = gameState::Instance(); actionHandler *handler = currState->getHandler(); and then is used: handler->act(event->button.x,event->button.y); main.cpp is written in simple .c style, with no header, so yes I suppose the function calling the handler is static... however, I also make calls to the gameState* pointer, which supposedly works exactly in the same way as the actionHandler* one.. Hope this makes it more clear.
Looks like a case of static initialization order fiasco described here. Your both static objects constructors are depending upon each other in a circular fashion which is very odd.
1,818,025
1,818,104
Reading characters outside ASCII
A friend of mine showed me a situation where reading characters produced unexpected behaviour. Reading the character '¤' caused his program to crash. I was able to conclude that '¤' is 164 decimal so it's over the ASCII range. We noticed the behaviour on '¤' but any character >127 seems to show the problem. The question is how would we reliably read such characters char by char? int main(int argc, const char *argv[]) { char input; do { cin >> input; cout << input; cout << " " << setbase(10) << (int)input; cout << " 0x" << setbase(16) << (int)input; cout << endl; } while(input); return 0; } masse@libre:temp/2009-11-30 $ ./a.out ¤ Â -62 0xffffffc2 ¤ -92 0xffffffa4
Your system is using UTF-8 character encoding (as it should) so the character '¤' causes your program to read the sequence of bytes C2 A4. Since a char is one byte, it reads them one at a time. Look into the wchar_t and the corresponding wcin and wcout streams to read multibyte characters, although I don't know which encodings they support or how they play with locales. Also, your program is outputting invalid UTF-8, so you really shouldn't be seeing those two characters — I get question marks on my system. (This is a nitpick and somewhat offtopic, but your while(input) should be while(cin), otherwise you'll get an infinite loop.)
1,818,106
1,819,588
Should we add unsubclass code during dialog destruction?
What will happen when we subclass a windows dialog and dialog is closed? Scenario is that I am subclassing a dialog and application can launch many instances of that dialog. Is it necessary to add unsubclassing code to all the dialogs in thier destruction logic. I think when dialogs get closed there is no need to unsubclass them because dialogs already destroyed.
If you're using instance subclassing (SetWindowLongPtr), then since when the window gets torn down it doesn't matter which WndProc it's using--it's about to vanish anyway. If you're using global subclassing (SetClassLongPtr) then it would probably be a good idea to remove the subclass once the last subclassed window is closed (i.e. not per window) so that any future windows created with that class don't get subclassed--unless that's what you want, of course.
1,818,134
1,818,165
Hashing function for four unsigned integers (C++)
I'm writing a program right now which produces four unsigned 32-bit integers as output from a certain function. I'm wanting to hash these four integers, so I can compare the output of this function to future outputs. I'm having trouble writing a decent hashing function though. When I originally wrote this code, I threw in a simple addition of each of the four integers, which I knew would not suffice. I've tried several other techniques, such as shifting and adding, to no avail. I get a hash, but it's of poor quality, and the function generate a ton of collisions. The hash output can be either a 32-bit or 64-bit integer. The function in question generates many billions of hashes, so collisions are a real problem here, and I'm willing to use a larger variable to ensure that there are as few collisions as possible. Can anyone help me figure out how to write a quality hash function?
Why don't you store the four integers in a suitable data structure and compare them all? The benefit of hashing them in this case appears dubious to me, unless storage is a problem. If storage is the issue, you can use one of the hash functions analyzed here.
1,818,186
1,818,203
Can't quite get Project Euler problem #2 figured out
I'm trying to learn the basics of C++ by going through some Project Euler problems. I've made it to...#2. Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... Find the sum of all the even-valued terms in the sequence which do not exceed four million. My logic: 0, 1, 1, 2, 3, 5 x y z x y z x y z x y z The above is looping through this: x + y = z x = y y = z My code: #include <iostream.h> using namespace std; int main() { int x = 0; int y = 1; int z; int sum; for(y = 1; y <= 4000000; y++) { z = x + y; x = y; y = z; if(y % 2 == 0) { sum += y; } } cout << sum; cin.get(); } That outputs 4613788 The correct answer, though, is 4613732.
You're using y as both the loop variable, and the second term in the sequence. What you mean to do is: int x = 0; int y = 1; int z; int sum = 0; do { z = x + y; x = y; y = z; if (y % 2 == 0) sum += y; } while (y <= 4000000); Noting that you should probably initialize sum as well.
1,818,325
1,818,332
How to stop visual c++ stepping into certain files
Is there some way to filter what files Visual Studio 2005 (C++) steps into? For example, when stepping into SomeFn( a.c_str(), b.c_str(), etc ); I hate how it steps into the standard template library files for c_str() - instead I just want to go into SomeFn(). If there was some way to filter out any source files didn't live in the same path as the solution file that would make my life easier. Does anyone know a way? Thanks
This article describes how to solve it for VC6, VC7 and VC8.
1,818,353
1,818,418
Can every if-else construct be replaced by an equivalent conditional expression?
(I don't have a serious need for this answer, I am just inquisitive.) Can every if-else construct be replaced by an equivalent conditional expression using the conditional operator ?:?
Does every if-else constructs can be replaced by an equivalent conditional expression using conditional operator? No, you've asked this backwards. The "bodies" of if/else contain statements, and it is not possible to turn every statement into an expression, such as try, while, break statements, as well as declarations. Many "statements" are really expressions in disguise, however: ++i; blah = 42; some_method(a,b,c); All of these are statements which consist of one expression (increment, assignment, function-call, respectively) and could be turned into expressions within a conditional. So, let's reverse the question, since it sounds like you really want to know how equivalent if/else statements are to ternary conditional expressions: Can every conditional expression be replaced by equivalent if/else statements? Almost all, yes. A common example is return statements: return cond ? t : f; // becomes: if (cond) return t; else return f; But also other expressions: n = (cond ? t : f); // becomes: if (cond) n = t; else n = f; Which starts to point to where conditional expressions cannot be easily replaced: initializations. Since you can only initialize an object once, you must break up an initialization that uses a conditional into using an explicit temporary variable instead: T obj (cond ? t : f); // becomes: SomeType temp; if (cond) temp = t; else temp = f; T obj (temp); Notice this is much more tedious/cumbersome, and requires something type-dependent if SomeType cannot be default-constructed and assigned.
1,818,596
1,818,621
Linux & C++: Easy way to exchange objects between two processes
I would like to know what is the easiest way (amongst various alternatives) to exchange objects (or some data) between two linux-based systems. It appears socket-programming could be a choice, but I have not done it earlier so I am not sure if it is the best way. Could anyone point me to a reference please? TIA, Sviiya
You could have a look at Boost IPC, as well as Google's Protocol Buffers. Or just generally, read this SO post concerning platform independent IPC, it's not exactly what you want, but should give you some good pointers.
1,818,641
1,818,657
Why don't win32 API functions have overloads and instead use Ex as suffix?
The win32 API has for example two methods StrFormatByteSize and StrFormatByteSizeEx. Even though both the methods symantically do the same thing and the Ex counter part only offers a new parameter to slightly change the behavior then couldn't they have two overloads of the same function? Is it a limitation of c/c++ or what is the possible reason for such an awkward convention?
The Win32 API is a C (not C++) API. The C language doesn't support overloaded functions. Complete aside: The Win32 API uses __stdcall-decorated functions, which include the number of bytes of parameters as part of the function name. __stdcall is not part of the C language, but Windows linkers have to know about it. Microsoft could have used this to implement some kind of overloading, but (since a lot of languages don't understand overloading) that would limit the number of languages that could be used to program Windows.
1,818,666
1,818,722
What's the cost of "as" compared to QueryInterface in COM or dynamic_cast in C++?
I'm still trying to map my deep and old knowledge from C/C++ to my somewhat more shallow .Net knowledge. Today the time has come to "as" (and implicitly "is" and cast) in C#. My mental model of "as" is that it's a QueryInterface or dynamic_cast (a dynamic_cast with pointer argument, not reference, that is) for C#. My question is two-fold: Is my comparison fair? What's the relative cost of "as" compared to QueryInterface or dynamic_cast?
Yes, the comparison is fair, especially when dealing with pointers. Each of the three either succeeds and returns a non-null pointer of the target type, or returns null. You can actually use the as operator when working with COM objects in .NET, making it equivalent to QueryInterface with a small amount of overhead for the managed/COM interop. Inside of the CLR (casting between managed types), the as operator is extremely lightweight compared to QueryInterface in COM or dynamic_cast in C++. For all the places in my code where I had to use dynamic casting for some reason, I've never seen the as operator show even one sample in profiling - and considering I maintain an implementation of a dynamically-typed, runtime-bound language (StringTemplate), I assume that means something. :)
1,818,821
1,819,376
search for multiple indecies with Boost Multi-Index
how do I limit the search in a boost::multi_index by the result of a previous search? As an example: suppose I have a rectangle class with an internal value like this: class MyRect { public: int width; int height; double value; } and I need a data structure of such object to answer queries like "given an input_rectangle - which object MyRect is contained in that rectangle and has the highest value?" I could use a 'multi_index' like this: struct given_value{}; struct given_width{}; struct given_height{}; typedef multi_index_container<MyRect, indexed_by< ordered_non_unique< tag<given_value>, member<MyRect, double, &MyRect::value>, ordered_non_unique< tag<given_width>, member<MyRect, int, &MyRect::width>, ordered_non_unique< tag<given_height>, member<MyRect, int, &MyRect::height>, > > > MyDataStructure; typedef MyDataStructure::index<given_width>::type MyDataStructureGivenWidth; typedef MyDataStructureGivenWidth::iterator WidthIterator; If my input_rectangle has width input_width I could use something like this: WidthIterator start_iter = data_object.get<given_width>().begin(); WidthIterator end_iter = data_object.get<given_width>().upper_bound(input_width); But how do I limit the search for the coresp height by the two given iterators? (And after that find the object with the highest value in that result?)
I don't think you can do an inplace limitation. Store the resulting iterators of the matching widths query in another container and use that container to find the matching heights with remove_if. Then use max_element to find the largest. If you store the elements as pointers, you could use the same MIC to store the results.
1,818,846
1,818,901
Add source code to elf file
I want to add my C++ source code to the corresponding elf binary file and I'm looking for the best way to do this. (I'm using several versions of my code and not every version should be committed into svn). Can I just append the source code without destroying the elf file using bash's >> operator? Or is objcopy --add-section a way to do this? By the way, is there a better idea that just grep'ing all #include lines recursively from the source code files to determine ALL source code files that are used?
If you're using gcc you could use the -M flag to get a file with a list of all included files. It's written to the file specified with -o, like this: gcc -M -c my_file.c -o list_of_included_files.txt
1,818,861
1,818,876
Memory leak/Memory allocation in C++
I have the following function in C++ void func1() { char *p = "Test for memory leak"; } When func1() is called where is the memory for the variable allocated? Whether in the stack or the heap? Should delete p; be called explicitly?
No, the memory is allocated only for the pointer p on the stack. This memory is automatically reclaimed when p goes out of scope. p is just pointing to a string which is stored some where in the read-only section of your program. Ideally it should be defined as const char *p. If you try to delete it, it will be undefined behavior. As a rule, you can remember that for every call to new there needs to be a call of delete
1,818,919
1,818,958
copy to cout with hex flag set
having something like this: void print_signs() { const char* chars[] = {"abcdefghijklmnopqrstuvwxyz0123456789"}; std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout)); cout << hex; //trying to change the way output works for next line std::copy(chars,chars + 1,std::ostream_iterator<const char*>(cout)); } is there a way to have cout print them in hex format (using STL components only)? Thank you.
void print_signs() { const std::string chars("abcdefghijklmnopqrstuvwxyz0123456789"); std::cout << std::hex; std::copy(chars.begin(), chars.end(), std::ostream_iterator<int>(std::cout)); } And If you wan't to preserve the exact typing of the original: void print_signs() { const char* chars[] = {"abcdefghijklmnopqrstuvwxyz0123456789"}; const size_t charCount = strlen(chars[0]); std::cout << std::hex; std::copy(chars[0], chars[0] + charCount, std::ostream_iterator<int>(std::cout)); } If you absolutely don't want to use strlen I you could use: const size_t charCount = std::string(chars[0]).length(); but this is not as efficient as std::string(...) will need to allocate memory from the heap. /A.B.
1,819,024
1,819,035
C++ 2D dynamic array crash
Hi I'm having some problem with 2D dynamic array. int main() { double **M; int M_dimension; int i; M_dimension = 10; M = new double *[M_dimension]; for (i=0;i<M_dimension;i++) { M[i] = new double[M_dimension]; } M[0][0] = 1.0; ... } Program works but I'd like to initialize 2D array using such a function: void initialize2D(double **M,int M_dimension) { int i; M = new double *[M_dimension]; for (i=0;i<M_dimension;i++) { M[i] = new double[M_dimension]; } } Finally the program looks like this: int main() { double **M; int M_dimension; int i; M_dimension = 10; initialize2D(M,M_dimension); M[0][0] = 1.0; //crash ... } Unfortunately it crashes at M[0][0] = 1.0; Thanks for any help or suggestions.
You are passing M by value, instead of by reference. initialize2D needs to change the value of the pointer-to-pointer M such that it points to the memory allocated Try changing your function signature to this instead: void initialize2D(double **&M,int M_dimension) Or void initialize2D(double ***M,int M_dimension) { ... *M = new double *[M_dimension]; ... }
1,819,114
1,968,819
When can typeid return different type_info instances for same type?
Andrei Alexandrescu writes in Modern C++ Design: The objects returned by typeid have static storage, so you don't have to worry about lifetime issues. Andrei continues: The standard does not guarantee that each invocation of, say, typeid(int) returns a reference to the same type_info object. Even though the standard does not guarantee this, how is this implemented in common compilers, such as GCC and Visual Studio? Assuming typeid does not leak (and return a new instance every call), is it one "table" per application, per translation unit, per dll/so, or something completely different? Are there times when &typeid(T) != &typeid(T)? I'm mainly interested in compilers for Windows, but any information for Linux and other platforms is also appreciated.
Are there times when &typeid(T) != &typeid(T)? I'm mainly interested in compilers for Windows, but any information for Linux and other platforms is also appreciated. Yes. Under windows DLL can't have unresolved symbols, thus. If you have: foo.h struct foo { virtual ~foo() {} }; dll.cpp #include "foo.h" ... foo f; cout << &typeid(&f) << endl main.cpp #include "foo.h" ... foo f; cout << &typeid(&f) << endl Would give you different pointers. Because before dll was loaded typeid(foo) should exist in both dll and primary exe More then that, under Linux, if main executable was not compiled with -rdynamic (or --export-dynamic) then typeid would be resolved to different symbols in executable and in shared object (which usually does not happen under ELF platforms) because of some optimizations done when linking executable -- removal of unnecessary symbols.
1,819,189
1,819,236
What range of values can integer types store in C++?
Can unsigned long int hold a ten digits number (1,000,000,000 - 9,999,999,999) on a 32-bit computer? Additionally, what are the ranges of unsigned long int , long int, unsigned int, short int, short unsigned int, and int?
The minimum ranges you can rely on are: short int and int: -32,767 to 32,767 unsigned short int and unsigned int: 0 to 65,535 long int: -2,147,483,647 to 2,147,483,647 unsigned long int: 0 to 4,294,967,295 This means that no, long int cannot be relied upon to store any 10-digit number. However, a larger type, long long int, was introduced to C in C99 and C++ in C++11 (this type is also often supported as an extension by compilers built for older standards that did not include it). The minimum range for this type, if your compiler supports it, is: long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 unsigned long long int: 0 to 18,446,744,073,709,551,615 So that type will be big enough (again, if you have it available). A note for those who believe I've made a mistake with these lower bounds: the C requirements for the ranges are written to allow for ones' complement or sign-magnitude integer representations, where the lowest representable value and the highest representable value differ only in sign. It is also allowed to have a two's complement representation where the value with sign bit 1 and all value bits 0 is a trap representation rather than a legal value. In other words, int is not required to be able to represent the value -32,768.
1,819,282
1,866,723
How to draw Windows 7 taskbar like Shaded Buttons
Windows 7 taskbar buttons are drawn on a shaded background. The color shade somehow reacts on where the mouse is over the button. I'd like to use such buttons in my application. How can i do that ?
The effect is called "Color Hot-track". It does not seem that there is a dedicated API for that. There are some notes in a developer blog about it: I found some source code from Rudi Grobler though doing a similar thing: Make your WPF buttons color hot-track!
1,819,387
1,819,399
Handling large integer on C/C++ using Visual C++ 2008
How do I do to handles some big positive integers (like 9,999,999,999) on Visual C++ 2008 on a 32-bit PC. Please give an example on declaring, printf, scanf of these big positive integers. Please consider using 9,999,999,999 in your example.
unsigned long long foo; scanf("%llu", &foo); printf("%llu", foo);
1,819,562
1,819,847
Plain C callback function pointer as part of iPhone delegate protocol?
Trying to integrate plain C/C++ code into iPhone project as an external static library. So far so good, but now I'm stuck at a point, where I need to register library callbacks. The library should notify my iPhone application, when something happens. Seems like a good place to define a Delegate. ...but the library is expecting C function pointers for callbacks. How do I define those in Objective-C, how do I use those as part of delegate pattern? Sorry, really can't give sample code. Here's something bit similar: first interface I got to use to register, followed by definitions of callbacks. registerCallBack(&aCBack, &bCBack, &cCBack, &dCBack, &eCBack); typedef void (aCBack)(uint32_t magic); typedef void (bCBack)(const NewData* newData); typedef void (cCBack)(uint32_t value, const std::vector<DataStuff*>* stuff); typedef void (dCBack)(uint32_t value, const SomeData* data, const std::string text, uint32_t type); typedef void (eCBack)(uint32_t value, const MoreData* more); ...oh btw, one of the problems is that each Objective-C class method has two hidden arguments. Not sure how to deal with that at all. Besides changing interface of that external library.
You need to use C++/C interfaces for the callbacks which then internally delegate the call to your Objective-C code. Where the callback registrations allow you to pass in user-data of sufficient size, you can conveniently pass something that identifies your context like in this answer. Callbacks that don't get passed any context have to call a class method of your Objective-C part anyway.
1,819,564
1,819,596
g++ produces big binaries despite small project
Probably this is a common question. In fact I think I asked it years ago... but I can't remember the answer. The problem is: I have a project that is composed of 6 source files. All of them no more than 200 lines of code. It uses many STL containers, stdlib.h and iostream. Now the executable is around 800kb in size.... I guess I shouldn't statically link libraries. How to do this with GCC? And in Eclipse CDT? EDIT: As I responses away from what I want I think it's the case for a clarification. What I want to know is why such a small program is so big in size and what is the relationship with static, shared libraries and their difference. If it's a too long story to tell feel free to give pointers to docs. Thank you
If you give g++ dynamic library names, and don't pass the -static flag, it should link dynamically. To reduce size, you could of course strip the binary, and pass the -Os (optimize for size) optimization flag to g++.
1,819,603
1,819,620
How can I set up a map with string as key and ostream as value?
I am trying to use the map container in C++ in the following way: The Key is a string and the value is an object of type ofstream. My code looks as follows: #include <string> #include <iostream> #include <map> #include <fstream> using namespace std; int main() { // typedef map<string, int> mapType2; // map<string, int> foo; typedef map<string, ofstream> mapType; map<string, ofstream> fooMap; ofstream foo1; ofstream foo2; fooMap["file1"] = foo1; fooMap["file2"] = foo2; mapType::iterator iter = fooMap.begin(); cout<< "Key = " <<iter->first; } However, when I try to compile the above code, I get the following error: C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h: In member function `std::basic_ios<char, std::char_traits<char> >& std::basic_ios<char, std::char_traits<char> >::operator=(const std::basic_ios<char, std::char_traits<char> >&)': C:/Dev-Cpp/bin/../lib/gcc/mingw32/3.4.2/../../../../include/c++/3.4.2/bits/ios_base.h:741: error: `std::ios_base& std::ios_base::operator=(const std::ios_base&)' is private hash.cpp:88: error: within this context What is going wrong? If this cannot be done using map, is there some other way to create such key:value pair? Note: If I test my code with map<string, int> foo; it works fine.
Streams do not like being copied. The simplest solution is using a pointer (or better, a smart pointer) to a stream in the map: typedef map<string, ofstream*> mapType;
1,819,680
1,819,756
Usage of boost lambdas
I am new to boost and trying to write some simple programs to understand it. Here in the following piece of code I am trying to fill an array with random numbers. Here is my code: using namespace boost::lambda; srand(time(NULL)); boost::array<int,100> a; std::for_each(a.begin(), a.end(), _1=rand()); But it looks like rand() is getting evaluated only once and my array is containing the same values for every element. Can anybody point what is wrong with this code?
Seems like you need to use delayed function call std::for_each(a.begin(), a.end(), boost::lambda::_1= boost::lambda::bind(rand) ); Here is another interesting situation: Delaying constants and variables
1,819,791
1,824,402
C/C++ library for .wav file encoding
I need a library for MS VC6 which encodes sampled data which is in the form of a float array, to an audio file format preferably wav Also is there a library that can encode the samples into pcm form and play it directly through the sound card without saving a wav file first??
As noted, the WAV file format is very simple. To just play the samples, use the waveOut functions; they're documented. To convert from a float to a signed 16-bit PCM sample, just convert the sample into the 16 bit range. For example, assuming a sample in the range -1.0 to +1.0 multiply by 32767.0 and convert to an integer: int16_t sample = static_cast<int16_t>(32767.0 * float_sample); Once you have those, just use the waveOut* functions to play the samples.
1,819,871
1,819,889
Simple C++ Instant messenger
I want to make a very simple c++ instant messenger for lan networks and internet (direct IP connect). I know little about sockets. I searched the internet, but nothing really helped. I would someone to suggest a howto/tutorial/guide. I just want to send and receive messages (in a console window, I'll create the gui later). I want it to be for both Linux and Windows. Thanks in advance!
Checkout Boost.Asio. It's portable, and it's also got an example that implements a simple chat.
1,819,982
1,820,107
What can cause "corrupted double-linked list" error?
I am having problems with a fairly complex code. I wasn't able to produce a short snippet that reproduces the error, so I'll try to explain the problem in words. The code crashes randomly with the error *** glibc detected *** gravtree: corrupted double-linked list: 0x000000001aa0fc50 *** Debugging showed that it comes from the line where the codes frees an object. There seems to be nothing wrong with the object. It exists, and I can access it's data at the time the error occurs. The object's destructor is trivial and doesn't do anything. So, I'm kind of stuck. In what kind of circumstances do you expect 'free' to fail?
Try running your program under Valgrind. It may point you to an earlier cause, whereas gdb is only breaking in where damage has already occurred.
1,820,069
1,820,092
Public operator new, private operator delete: getting C2248 "can not access private member" when using new
A class has overloaded operators new and delete. new is public, delete is private. When constructing an instance of this class, I get the following error: pFoo = new Foo(bar) example.cpp(1): error C2248: 'Foo:operator delete': cannot access private member declared in class 'Foo' But there's no call to delete here, so what is going on in the twisted mind of the compiler? :) What is the reason for the error? Is it possible to resolve the problem without resorting to a member CreateInstance function?
When you do new Foo() then two things happen: First operator new is invoked to allocate memory, then a constructor for Foo is called. If that constructor throws, since you cannot access the memory already allocated, the C++ runtime will take care of it by passing it to the appropriate operator delete. That's why you always must implement a matching operator delete for every operator new you write and that's why it needs to be accessible. As a way out you could make both of them private and invoke operator new from a public member function (like create()).
1,820,174
1,820,207
Forcing C++ compilers to check for exception handling
I was wondering if there is some compiler parameter, preferably in gcc (g++) which treats the lack of try/catch blocks as errors. This is the standard behavior in java and I was alway fond of it.
Since checked exceptions in Java rely on the throw signature, you can read why you will not want to use throw function signatures in C++ in this question on SO.
1,820,394
1,820,483
C++ character replace
What is the best way to replace characters in a string? Specifically: "This,Is A|Test" ----> "This_Is_A_Test" I want to replace all commas, spaces, and "|" with underscores. (I have access to Boost.)
As the other answers indicated, you can use the various replace methods. However, these approaches have the downside of scanning the string multiple times (one time for each character). I would recommend rolling your own replace method, if you care about speed: void beautify(std::string &s) { int i; for (i = 0; i < s.length(); ++i) { switch (s[i]) { case ' ': case ',': case '|': s[i] = '_'; } } }
1,820,825
1,820,888
Global hotkey with WIN32 API?
I've been able to set local hotkeys like this RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S'); How can I set the hotkey to be global? I want it to be there even when my window is hidden.
I solved it myself but thanks for your reply here's what was wrong... ShowWindow(hwndDlg, SW_HIDE); RegisterHotKey(hwndDlg, 100, MOD_ALT | MOD_CONTROL, 'S'); if you register the hotkey first then hide the window... it ignores the hotkey for some reason... oh well.. it's working now :)
1,821,081
1,821,222
Sorting a listview (Win32/C++)
I'm trying to sort a listview when the user clicks on the column header. I am catching the LVN_COLUMNCLICK notification like so: case LVN_COLUMNCLICK: { NMLISTVIEW* pListView = (NMLISTVIEW*)lParam; BOOL test = ListView_SortItems ( m_hDuplicateObjectsList, ListViewCompareProc, pListView->iSubItem ); break; } However it seems to fail. My test variable is FALSE and my ListViewCompareProc never gets hit (it has a simple return 1 while I am trying to hit a debug point inside of it). Is there something I am missing for sorting a listview?
Are you using the LVS_OWNERDATA style on your control? There are a number of features incompatible with that style, including sorting: http://msdn.microsoft.com/en-us/library/bb774735%28VS.85%29.aspx
1,821,153
1,843,062
Segfault on C++ Plugin Library with Duplicate Symbols
I have a cross platform C++ application that is broken into several shared libraries and loads additional functionality from plugin shared libraries. The plugin libraries are supposed to be self contained and function by themselves, without knowledge of or dependency on the calling application. One of the plugins contains copied code from the main application, so contains symbol names that are duplicate to those in the engine. (Yes I know that's generally a no-no, but at the time the plugin was written the engine was a monolithic binary and couldn't share libraries.) On Windows, everything runs fine. On Linux we were getting segfaults. By looking at the stack trace of the error, it was occurring in the plugin when calling functions in the duplicate class name. It appeared to be a result of the engine and plugin having slightly different versions of the shared code (some class functionality was commented out in the plugin). It was as if the plugin was getting it's symbols runtime linked to the engine's instead of its own. We "fixed" the issue by changing the dlopen's parameters to be dlopen(pFilepath, RTLD_LAZY | RTLD_LOCAL). But when we rewrote the engine to be split into shared libraries (for the eventual purpose of reuse in the plugins), we get the segfault error again. And looking at the stack trace, it goes from the engine -> plugin -> engine. Is there a way to specify for the runtime linker to not map symbols of the plugin to the engine (especially if they are defined in the plugin)? Thanks! Matt Edited 2009-12-3 I first tried to wrap the plugin's code in it's own namespace. That didn't work because it is statically linked to a library that is also linked to the engine. The versions of the static library are different, so segfault! Then I changed the build of the engine and it's libraries to be statically linked. And when I run it, I no longer have the issue. So it appears it was a result of having the shared library symbols exported and then being dynamically relocated into the plugin when it was opened. But when all of the engine's code is in a single executable, it doesn't export its symbols (so it doesn't try to relocate the plugin's symbols into the engine). I still have an issue though, as there is a parallelized version of the program (using Open-MPI) and that still gets the segfault. It appears in that it's still exporting the engine's symbols and relocating the plugin's. That might have to do with how Open-MPI executes the application. Are there any linker flags that could be used on the plugin shared library that would tell it not to dynamically relocate the symbols at runtime? Or to hide it's symbols so they don't get relocated? I've tried -s ("Omit all symbol information") but that apparently didn't change the dynamic symbols (checked using nm -D <plugin>).
I think I've found the solution, the linker flag -Bsymbolic. Essentially this flag adds a flag in the shared library to tell the runtime linker to try and resolve symbol names within itself first. The engine was able to run with the plugin just fine in all cases (monolithic exe, exe w/ shared libs, plugin w/ and w/o wrapping the namespace) when the plugin was linked with that flag. There does seem to be a few detractors with warnings about -Bsymbolic: http://www.technovelty.org/code/c/bsymbolic.html http://software.intel.com/en-us/articles/performance-tools-for-software-developers-bsymbolic-can-cause-dangerous-side-effects/ But considering their warnings and what the intention of the plugin is, I think it's the right option for me. At least for now.
1,821,540
1,828,324
Does anyone know of a VB(A/6) example using GetLocaleInfoEx?
I thought I dug most of what I need out of the header files, but I keep crashing out. Here is the declare I tried using, but I don't think it's just an issue of the declare. I think I'm actually using it wrong. Private Declare Function GetLocaleInfoEx Lib "kernel32" ( _ ByVal lpLocaleName As Long, _ ByVal LCType As Long, _ ByRef lpLCData As Long, _ ByVal cchData As Long _ ) As Long Here is the corresponding documentation. EDIT by MarkJ: Oorang wants to use GetLocaleInfoEx because the MSDN docs say it is preferred on Vista.
EDIT: I couldn't test this because I don't have Vista here at home, but Oorang says it works (in the comments). Private Declare Function GetLocaleInfoEx _ Lib "kernel32" ( _ ByVal lpLocaleName As Long, _ ByVal LCType As Long, _ ByVal lpLCData As Long, _ ByVal cchData As Long _ ) As Long Const LOCALE_SMONTHNAME1 = 56& Dim sLocaleName As String Dim sRetBuffer As String Dim nCharsRet As Long sLocaleName = "en-US" & Chr$(0) sRetBuffer = Space(256) nCharsRet = GetLocaleInfoEx(StrPtr(sLocaleName), _ LOCALE_SMONTHNAME1, StrPtr(sRetBuffer), Len(sRetBuffer)-1) MsgBox Left$(sRetBuffer, nCharsRet) Your original Declare looked wrong to me. You are required to provide a buffer for the return string (wide characters, otherwise known as a UTF-16 Unicode string). You need to pass a pointer to the buffer in the lpLCData argument. So you need to declare that argument as ByVal Long and use StrPtr(string) where string has been filled with characters to make room for the return data.
1,821,703
1,821,723
Help me understand std::erase
In the book 'C++ In A Nutshell', there is the following example code std::vector<int> data ... std::erase(std::remove(data.begin(), data.end(), 42), data.end()); I thought that 'erase' was a member function, so shouldn't that be 'data.erase' rather than 'std::erase'? Is there some way the c++ compiler can tell what member you wanted to call a member function on, or did the book omit any documentation of an erase template function, or is the example wrong?
erase is a member function. The sample provided is incorrect.
1,821,799
1,821,816
What useful functionality do you get out of overriding the 'new' operator?
What new kind of functionalities (for debugging or not) do you find helpful by overriding the new operator?
The main reason I've had to overload new has been for performance. One example is allocating a large number of small objects, which is often fairly slow with a general purpose allocator, but can often be improved a lot with a custom allocator.
1,821,822
1,824,354
#import command line equivalent
Using Visual Studio with Microsoft's C++ compiler, we have several source files which use the Microsoft-specific '#import' directive to import a type library. For instance: #import my_type_lib.tlb I'd like to remove the #import from the source code, and replace it with a command line step to be executed via GNU Make. The necessary interface definitions (.idl source code) are available during the build. How can I remove my dependency on #import and replace it with specialized build tools to be executed via the command line?
As far as I know, there are no separate tools to generate code from the type lib. You could do #import once, and then stash away the generated files and include them as regular source files. But then changes to the type library would need a new supervised build to regenerate the files. Which parts of the generated information are you using? If you only use this to get to IIDs, interfaces and CLSIDs, and you have the .IDL, you can use MIDL.EXE to generate a C++ representation. If you're using the wrapper classes (IxxxPtr), I think you're short on luck -- these are produced by #import.
1,821,858
1,822,030
Iterating over pair elements in a container of pairs (C++)
If I have a container (vector, list, etc) where each element is a std::pair, is there an easy way to iterate over each element of each pair? i.e. std::vector<std::pair<int,int> > a; a.push_back(std::pair(1,3)); a.push_back(std::pair(2,3)); a.push_back(std::pair(4,2)); a.push_back(std::pair(5,2)); a.push_back(std::pair(1,5)); and then being able to iterate over the value: 1,3,2,3,4,2,5,2,1,5? Similarly, what type of functor/function would return to me a container (of the same type) with a flat listing of the pair elements as above?
To flatten your container of pairs into a second container you could also simply write your own inserter: template<class C> struct Inserter { std::back_insert_iterator<C> in; Inserter(C& c) : in(c) {} void operator()(const std::pair<typename C::value_type, typename C::value_type>& p) { *in++ = p.first; *in++ = p.second; } }; template<class C> Inserter<C> make_inserter(C& c) { return Inserter<C>(c); } // usage example: std::list<int> l; std::for_each(a.begin(), a.end(), make_inserter(l));
1,821,988
1,822,005
Yield from C# to C++, dealing with containers
Actually, I have a design question here. Its very simple but the point is: I have one C++ class that has a STL vector declared as a private member. But the clients of that class need to iterate over this vector. In C# we have a very handy statement, the Yield, that in cases like that, you write a function returning an IEnumerable and it "yields" you a nice way to iterate over a private container inside that class. I'm just trying to find an elegant solution for C++, instead of using methods like GetValue(int idx). Any suggestions? Example: class Fat { public: Fat(); // some code here ... private: void LoadSectors(SECT startPoint); std::vector<SECT>sectors; }; class Storage { public: Storage(string CompoundFile); //For example, this method will receive a ref to my fat system and iterate over //the fat array in order to read every sector. LoadStrem(Fat& fat); }; This is far simple example.
There's no syntactic sugar in C++ analogous to yield in C#. If you want to create a class, instances of which should be iterable in the same way stock STL collections are, then you have to implement an iterator for your class, expose it as ::iterator on your type, and provide begin() and end() member functions.
1,822,083
1,822,102
Accessing Linux diagnostic information from JavaScript
Is there a way can I access machine diagnostic information within the Linux OS in realtime? Such diagnostic info as CPU utilization, memory utilization, etc using JavaScript to display on a web page? If there is no direct access from JavaScript, is there any other method where JS code can call functions in shared libraries (dll, etc.)? Since I am sure there is a native library that can exists in the OS.
JavaScript is in general not allowed to access system information - among other things this results from portability and security considerations. If you really need that for some reason you either find some browser-specific solutions (don't know if there are any) or you require the user to install a custom plugin you deliver (probably native with the NPAPI for cross-browser-support) that provides the information to JavaScript. Another alternative would be browser extensions, but with them you lose the cross-browser-portability - if you don't want to lock users onto a specific browser you would have to at least develop seperate extensions for Gecko- and Webkit-based browsers.
1,822,114
1,822,183
C++ map insertion and lookup performance and storage overhead
I would like to store a mapping of an integer key to a float value in-memory. I have roughly 130 million keys (and, accordingly, 130 million values). My focus is on lookup performance -- I have to do many, many millions of lookups. The C++ STL library has a map class for associative arrays of this sort. I have several questions about map. What is the storage overhead of map for a dataset of the size mentioned above? How does storage overhead scale, in general, with map? It looks like the underlying data structure for map is a red-black, balanced binary tree. It sounds like the real-world performance for this is O(log n) for insertion and retrieval. It mentions O(1) for a hinted insertion. My input is pre-sorted, so I believe I should be able to provide a hint for insertion events. How would I provide this hint, using the methods listed here? Is there an STL container that provides better lookup performance? Are there other publicly-available, open-source frameworks with an associate array class that uses an underlying data structure that would perform better than STL map? If writing my own container class would provide better lookup performance, what data structures might I research? I am using GCC 4 for this task, running under either Linux or Mac OS X. I apologize in advance if these are dumb questions. Thank you for your advice.
Given what you've said, I'd think very hard about using an std::vector<pair<int, float> >, and using std::lower_bound, std::upper_bound, and/or std::equal_range to look up values. While the exact overhead of std::map can (and does) vary, there's little or no room for question that it will normally consume extra memory and look up values more slowly than a binary search in a vector. As you've noted, it's normally (and almost unavoidably) implemented as some sort of balanced tree, which imposes overhead for the pointers and the balancing information, and typically means each node is allocated separately as well. Since your nodes are pretty small (typically 8 bytes) that extra data is likely to be at least as much as what you're actually storing (i.e. at least 100% overhead). Separate allocations often mean poor locality of reference, which leads to poor cache usage. Most implementations of std::map use a red-black tree. If you were going to use an std::map, an implementation that uses an AVL tree would probably suit your purposes better -- an AVL tree has slightly tighter constraints on balancing. This gives slightly faster lookup at the expense of slightly slower insertion and deletion (since it has to re-balance more often to maintain its stricter interpretation of "balanced"). As long as your data remains constant during use, however, an std::vector is still almost certainly better. One other possibility worth noting: if your keys are at least fairly even distributed, you might want to try looking up using interpolation instead of bisection. i.e. instead of always starting at the middle of the vector, you do a linear interpolation to guess at the most likely starting point for the lookup. Of course, if your keys follow some known non-linear distribution, you can use a matching interpolation instead. Assuming the keys are reasonably evenly distributed (or at least follow some predictable pattern that's amenable to interpolation), the interpolation search has a complexity of O(log log N). For 130 million keys, that works out to around 4 probes to find an item. To do significantly better than that with (normal/non-perfect) hashing, you need a good algorithm, and you need to keep the load factor in the table quite low (typically around 75% or so -- i.e. you need to allow for something like 32 million extra (empty) spots in your table to improve the expected complexity from four probes to three). I may just be old fashioned, but that strikes me as a lot of extra storage to use for such a small speed improvement. OTOH, it's true that this is nearly the ideal situation for perfect hashing -- the set is known ahead of time, and the key is quite small (important, since hashing is normally linear on the key size). Even so, unless the keys are distributed pretty unevenly, I wouldn't expect any huge improvement -- a perfect hash function is often (usually?) fairly complex.
1,822,143
1,822,198
Null Object Pattern, Recursive Class, and Forward Declarations
I'm interested in doing something like the following to adhere to a Null Object design pattern and to avoid prolific NULL tests: class Node; Node* NullNode; class Node { public: Node(Node *l=NullNode, Node *r=NullNode) : left(l), right(r) {}; private: Node *left, *right; }; NullNode = new Node(); Of course, as written, NullNode has different memory locations before and after the Node class declaration. You could do this without the forward declaration, if you didn't want to have default arguments (i.e., remove Node *r=NullNode). Another option would use some inheritence: make a parent class (Node) with two children (NullNode and FullNode). Then the node example above would be the code for FullNode and the NullNode in the code above would be of type NullNode inheriting from Node. I hate solving simple problems by appeals to inheritence. So, the question is: how do you apply Null Object patterns to recursive data structures (classes) with default arguments (which are instances of that same class!) in C++?
Use extern: extern Node* NullNode; ... Node* NullNode = new Node(); Better yet, make it a static member: class Node { public: static Node* Null; Node(Node *l=Null, Node *r=Null) : left(l), right(r) {}; private: Node *left, *right; }; Node* Node::Null = new Node(); That said, in both existing code, and amendments above, you leak an instance of Node. You could use auto_ptr, but that would be dangerous because of uncertain order of destruction of globals and statics (a destructor of some global may need Node::Null, and it may or may not be already gone by then).
1,822,156
1,822,264
How do I select the client only framework in a Managed Visual C++ project in VS 2008 Sp1?
The title said it all.
Unfortunately, this isn't possible, even with VS 2008 sp1. You set the target framework under the "Common Properties"->"Framework and References" in the project property pages. In 2008sp1, the only choices are: .NET Framework 2.0 .NET Framework 3.0 .NET Framework 3.5
1,822,199
2,256,100
gdb 7.0, signal SIGCONT doesn't break from a pause() call
I'd built a version of gdb 7.0 for myself after being pointed to a new feature, and happened to have that in my path still. Attempting to step through some new code, I'd added a pause() call, expecting to be able to get out like so: (gdb) b 5048 Breakpoint 1 at 0x2b1811b25052: file testca.C, line 5048. (gdb) signal SIGCONT Continuing with signal SIGCONT. Breakpoint 1, FLUSH_SUDF_TEST (h=@0x2b1811b061c0) at testca.C:5048 5048 rc = h.SAL_testcaFlushPagesByUDF( uPrimary - 1, uPrimary ) ; (that was with the system gdb, version 6.6). With gdb 7.0 I never hit the post-pause() breakpoint when I try this. With the various multi process debugging changes in gdb 7, does anybody know if signal handling has to be handled differently and how?
The pause() function does not return unless a signal handler is called (see the specification and the man page). To make it return after your program receives SIGCONT, you must install an handler for SIGCONT. Try and see using the following example: #include <signal.h> #include <stdio.h> #include <string.h> #include <unistd.h> volatile int caught_signal = 0; void handler(int sig) { caught_signal = sig; } int main() { signal(SIGCONT, handler); pause(); printf("Caught signal: %d, %s\n", caught_signal, strsignal(caught_signal)); return 0; } The behavior is correct with gdb 7.0: pause() completely ignores ignored signals (like SIGCHLD, returns on caught signals (SIGCONT), and no signal is delivered when the continue command is issued. (gdb) break 17 Breakpoint 1 at 0x80484b3: file pause.c, line 17. (gdb) continue Continuing. ^C Program received signal SIGINT, Interrupt. 0x0012d422 in __kernel_vsyscall () (gdb) signal SIGCHLD Continuing with signal SIGCHLD. ^C Program received signal SIGINT, Interrupt. 0x0012d422 in __kernel_vsyscall () (gdb) signal SIGCONT Continuing with signal SIGCONT. Breakpoint 1, main () at pause.c:17 17 printf("Caught signal: %d, %s\n", (gdb)
1,822,223
1,822,230
How to find what's new in VC++ v10?
Googling nor binging "VC++ What's new C++0x" gives me nothing that tells me what is new.Is there an official page at msdn or something similiar that contains the information for VC++ 10? I've seen such for C#,there must be one for what I'd enjoy to read. If not, please list the new features available in Visual Studio 2010 for VC++.
The Visual C++ Team Blog has frequent articles about what's new for VC++ in Studio 2010. It's not an exhaustive list, but does detail many of the new additions. There's also an MS site which lists some of whats new.
1,822,260
1,822,274
Help programmatically add text to an existing PDF
I need to write a program that displays a PDF which a third-party supplies. I need to insert text data in to the form before displaying it to the user. I do have the option to convert the PDF in to another format, but it has to look exactly like the original PDF. C++ is the preferred language of choice, but other languages can be investigated (e.g. C#). It need to work on a Windows desktop machine. What libraries, tools, strategies, or other programming languages do you suggest investigate to accomplish this task? Are there any online examples you could direct me to. Thank-you in advance.
What about PoDoFo: The PoDoFo library is a free, portable C++ library which includes classes to parse PDF files and modify their contents into memory. The changes can be written back to disk easily. The parser can also be used to extract information from a PDF file (for example the parser could be used in a PDF viewer). Besides parsing PoDoFo includes also very simple classes to create your own PDF files. All classes are documented so it is easy to start writing your own application using PoDoFo.
1,822,429
1,822,507
A recurring const-connundrum
I often find myself having to define two versions of a function in order to have one that is const and one which is non-const (often a getter, but not always). The two vary only by the fact that the input and output of one is const, while the input and output of the other is non-const. The guts of the function - the real work, is IDENTICAL. Yet, for const-correctness, I need them both. As a simple practical example, take the following: inline const ITEMIDLIST * GetNextItem(const ITEMIDLIST * pidl) { return pidl ? reinterpret_cast<const ITEMIDLIST *>(reinterpret_cast<const BYTE *>(pidl) + pidl->mkid.cb) : NULL; } inline ITEMIDLIST * GetNextItem(ITEMIDLIST * pidl) { return pidl ? reinterpret_cast<ITEMIDLIST *>(reinterpret_cast<BYTE *>(pidl) + pidl->mkid.cb) : NULL; } As you can see, they do the same thing. I can choose to define one in terms of the other using yet more casts, which is more appropriate if the guts - the actual work, is less trivial: inline const ITEMIDLIST * GetNextItem(const ITEMIDLIST * pidl) { return pidl ? reinterpret_cast<const ITEMIDLIST *>(reinterpret_cast<const BYTE *>(pidl) + pidl->mkid.cb) : NULL; } inline ITEMIDLIST * GetNextItem(ITEMIDLIST * pidl) { return const_cast<ITEMIDLIST *>(GetNextItem(const_cast<const ITEMIDLIST *>(pidl)); } So, I find this terribly tedious and redundant. But if I wish to write const-correct code, then I either have to supply both of the above, or I have to litter my "consumer-code" with const-casts to get around the problems of having only defined one or the other. Is there a better pattern for this? What is the "best" approach to this issue in your opinion: providing two copies of a given function - the const and non-const versions or just one version, and then requiring consumers of that code to do their casts as they will? Or is there a better approach to the issue entirely? Is there work being done on the language itself to mitigate or obviate this issue entirely? And for bonus points: do you find this to be an unfortunate by-product of the C++ const-system or do you find this to be tantamount to touching the very heights of mount Olympus? EDIT: If I supply only the first - takes const returns const, then any consumer that needs to modify the returned item, or hand the returned item to another function that will modify it, must cast off the constness. Similarly, if I supply only the second definition - takes non-const and returns non-const, then a consumer that has a const pidl must cast off the constness in order to use the above function, which honestly, doesn't modify the constness of the item itself. Maybe more abstraction is desirable: THING & Foo(THING & it); const THING & Foo(const THING & it); I would love to have a construct: const_neutral THING & Foo(const_neutral THING & it); I certainly could do something like: THING & Foo(const THING & it); But that's always rubbed me the wrong way. I am saying "I don't modify the contents of your THING, but I'm going to get rid of the constness that you entrusted me with silently for you in your code." Now, a client, which has: const THING & it = GetAConstThing(); ... ModifyAThing(Foo(it)); That's just wrong. GetAConstThing's contract with the caller is to give it a const reference. The caller is expected NOT TO MODIFY the thing - only use const-operations on it. Yes, the caller can be evil and wrong and cast away that constness of it, but that's just Evil(tm). The crux of the matter, to me, is that Foo is const-neutral. It doesn't actually modify the thing its given, but its output needs to propagate the constness of its argument. NOTE: edited a 2nd time for formatting.
I don't believe it's the deficiency of const-correctness per se, but rather the lack of convenient ability to generalize a method over cv-qualifiers (in the same way we can generalize over types via templates). Hypothetically, imagine if you could write something like: template<cvqual CV> inline CV ITEMIDLIST* GetNextItem(CV ITEMIDLIST * pidl) { return pidl ? reinterpret_cast<CV ITEMIDLIST *>(reinterpret_cast<CV BYTE *>(pidl) + pidl->mkid.cb) : NULL; } ITEMIDLIST o; const ITEMIDLIST co; ITEMIDLIST* po = GetNextItem(&o); // CV is deduced to be nothing ITEMIDLIST* pco = GetNextItem(&co); // CV is deduced to be "const" Now you can actually do this kind of thing with template metaprogramming, but this gets messy real quick: template<class T, class TProto> struct make_same_cv_as { typedef T result; }; template<class T, class TProto> struct make_same_cv_as<T, const TProto> { typedef const T result; }; template<class T, class TProto> struct make_same_cv_as<T, volatile TProto> { typedef volatile T result; }; template<class T, class TProto> struct make_same_cv_as<T, const volatile TProto> { typedef const volatile T result; }; template<class CV_ITEMIDLIST> inline CV_ITEMIDLIST* GetNextItem(CV_ITEMIDLIST* pidl) { return pidl ? reinterpret_cast<CV_ITEMIDLIST*>(reinterpret_cast<typename make_same_cv_as<BYTE, CV_ITEMIDLIST>::result*>(pidl) + pidl->mkid.cb) : NULL; } The problem with the above is the usual problem with all templates - it'll let you pass object of any random type so long as it has the members with proper names, not just ITEMIDLIST. You can use various "static assert" implementations, of course, but that's also a hack in and of itself. Alternatively, you can use the templated version to reuse the code inside your .cpp file, and then wrap it into a const/non-const pair and expose that in the header. That way, you pretty much only duplicate function signature.
1,822,667
1,822,738
How can I share HWND between 32 and 64 bit applications in Win x64?
MSDN tells me that handles to windows (HWND) can be shared between 32- and 64-bit applications, in Interprocess Communication (MSDN). However, in Win32 a HWND is 32 bits, whereas in 64 bit Windows it is 64 bits. So how can the handles be shared? I guess the same question applies to handles to named objects such as mutexes, semaphores and file handles.
Doesn't the fact that they can be shared imply that only the lower 32 bits are used in Win64 processes? Windows handles are indexes not pointers, at least as far as I can tell, so unless MS wanted to allow more than 2^32 window/file/mutex/etc. handles there's no reason to use the high 32 bits of a void* on Win64.
1,822,876
1,823,032
C++ swap problem in inheritance scenario
I want to add swap functionality to two existing C++ classes. One class inherits from the other. I want each classes' instances to only be swappable with instances of the same class. To make it semi-concrete, say I have classes Foo and Bar. Bar inherits from Foo. I define Foo::swap(Foo&) and Bar::swap(Bar&). Bar::swap delegates to Foo::swap. I want Foo::swap to only work on Foo instances and Bar::swap to only work on Bar instances: I can't figure out how to enforce this requirement. Here's a sample of what's giving me trouble: #include <algorithm> #include <iostream> struct Foo { int x; Foo(int x) : x(x) {}; virtual void swap(Foo &other) { std::cout << __PRETTY_FUNCTION__ << std::endl; std::swap(this->x, other.x); }; }; struct Bar : public Foo { int y; Bar(int x, int y) : Foo(x), y(y) {}; virtual void swap(Bar &other) { std::cout << __PRETTY_FUNCTION__ << " "; Foo::swap(other); std::swap(this->y, other.y); }; }; void display(Foo &f1, Foo &f2, Bar &b34, Bar &b56) { using namespace std; cout << "f1: " << f1.x << endl; cout << "f2: " << f2.x << endl; cout << "b34: " << b34.x << " " << b34.y << endl; cout << "b56: " << b56.x << " " << b56.y << endl; } int main(int argc, char **argv) { { Foo f1(1), f2(2); Bar b34(3,4), b56(5,6); std::cout << std::endl << "Initial values: " << std::endl; display(f1,f2,b34,b56); } { Foo f1(1), f2(2); Bar b34(3,4), b56(5,6); std::cout << std::endl << "After Homogeneous Swap: " << std::endl; f1.swap(f2); // Desired b34.swap(b56); // Desired display(f1,f2,b34,b56); } { Foo f1(1), f2(2); Bar b34(3,4), b56(5,6); std::cout << std::endl << "After Heterogeneous Member Swap: " << std::endl; // b56.swap(f2); // Doesn't compile, excellent f1.swap(b34); // Want this to not compile, but unsure how display(f1,f2,b34,b56); } return 0; } Here's the output: Initial values: f1: 1 f2: 2 b34: 3 4 b56: 5 6 After Homogeneous Swap: virtual void Foo::swap(Foo&) virtual void Bar::swap(Bar&) virtual void Foo::swap(Foo&) f1: 2 f2: 1 b34: 5 6 b56: 3 4 After Heterogeneous Member Swap: virtual void Foo::swap(Foo&) f1: 3 f2: 2 b34: 1 4 b56: 5 6 You can see in the final output group where f1.swap(b34) "sliced" b34 in a potentially nasty way. I'd like the guilty line to either not compile or blow up at runtime. Because of the inheritance involved, I think I run into the same problem if I use a nonmember or friend swap implementation. The code is available at codepad if that helps. This use case arises because I want to add swap to boost::multi_array and boost::multi_array_ref. multi_array inherits from multi_array_ref. It only makes sense to swap multi_arrays with multi_arrays and multi_array_refs with multi_array_refs.
(Somewhat hacky solution) Add a protected virtual method, isBaseFoo(), make it return true in Foo, and false in Bar, the the swap method for Foo could check it's argument has isBaseFoo()==true. Evil, and detects the problem only at run-time, but I can't think of anything better, although Charles Bailey's answer might be better, if you allow dynamic_cast<>.
1,822,887
1,823,024
What is the best way to eliminate MS Visual C++ Linker warning : "warning LNK4221"?
I have a CPP source file that uses #if / #endif to compile out completely in certain builds. However, this generates the following warning. warning LNK4221: no public symbols found; archive member will be inaccessible I was thinking about creating a macro to generate a dummy variable or function that wouldn't actually be used so this error would go away but I want to make sure that it doesn't cause problems such as using the macro in multiple files causing the linker to bomb on multiply defined symbols. What is the best way to get rid of this warning (without simply suppressing the warning on the linker command line) ? FWIW, I would be interested in knowing how to do it by suppressing the warning on the linker command line as well but all my attempts there appear to be simply ignored by the linker and still generate the error. One other requirement: The fix must be able to stand up to individual file builds or unity build (combine CPP file builds) since one of our build configurations is a bulk build (like a unity build but groups of bulk files rather than a single master unity file).
OK, the fix I am going to use is Pavel's suggestion with a minor tweak. The reason I’m using this fix is it’s an easy macro to drop in and it will work in bulk-builds / unity-builds as well as normal builds: Shared Header: // The following macro "NoEmptyFile()" can be put into a file // in order suppress the MS Visual C++ Linker warning 4221 // // warning LNK4221: no public symbols found; archive member will be inaccessible // // This warning occurs on PC and XBOX when a file compiles out completely // has no externally visible symbols which may be dependant on configuration // #defines and options. #define NoEmptyFile() namespace { char NoEmptyFileDummy##__LINE__; } File that may compile out completely: NoEmptyFile() #if DEBUG_OPTION // code #endif // DEBUG_OPTION
1,822,914
1,822,999
Load XML into C++ MSXML from byte array
I'm receiving XML over a network socket. I need to take that XML and load it into the DOM to perform further operations. MSXML requires input strings that are in either UCS-2 or UTF-16 and completely ignores the XML header with the encoding type when loading from a string. It allows the loading of XML fragments, so this makes some sense. I see two possible ways to handle this problem: 1) Write the file out to disk and load it into MSXML via file paths. The extra disk I/O makes this approach far from preferred. 2) Peak into the XML header to manually detect the encoding and then call MultiByteToWideChar to convert into UTF-16 and specify the code page based on the detected encoding. This approach works OK, but I'd like to push the encoding detection onto MSXML. Does anybody have any other ideas on how to accomplish this? I haven't looked at other XML parsers, but would be interested in how non-MSXML DOM parsers accomplish this. Thanks, Paul
Simplest way is pass the load function a safe array. e.g. const char* xml = "<root/>"; SAFEARRAYBOUND rgsabound[1]; rgsabound[0].lLbound = 0; rgsabound[0].cElements = strlen(xml); SAFEARRAY* psa = SafeArrayCreate(VT_UI1, 1, rgsabound); memcpy(psa->pvData, xml, strlen(xml)); VARIANT v; VariantInit(&v); V_VT(&v) = VT_ARRAY | VT_UI1; V_ARRAY(&v) = psa; VARIANT_BOOL fSuccess; pXMLDoc->load(v, &fSuccess); if(fSuccess == VARIANT_TRUE) { /* Do Something */ } Obviously no error checking going on or freeing of resources. Or use CreateStreamOnHGlobal to create an IStream on the data and pass that into load.
1,823,059
1,823,086
Declaring arrays similar to C style (C++)
In C a programmer can declare an array like so: unsigned char Fonts[2][8] { [1] = {0, 31, 0, 31, 0, 31, 0, 31} }; And element [0] is likely random bits. Is there a similar way in C++?
You can do this: unsigned char Fonts[2][8] = { {0}, {0, 31, 0, 31, 0, 31, 0, 31} };
1,823,073
14,837,584
stringstream operator>> fails as function, but works as instance?
I'm writing simple code that will extract a bunch of name, int pairs from a file. I'm modifying existing code that just uses: string chrom; unsigned int size; while ( cin >> chrom >> size ) { // save values } But I want to use another (similar) input file that has the same first two columns, but are followed by other data (that will be ignored). So I write: string chrom; unsigned int size; string line; while ( getline(cin, line) ) { if( stringstream(line) >> chrom >> size ) { // save values } } But this fails to compile, giving the typical obscene std lib template spew: error: no match for "operator>>" in "std::basic_stringstream<char, std::char_traits<char>, std::allocator<char> >(((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >&)((const std::basic_string<char, std::char_traits<char>, std::allocator<char> >*)(& line))), std::operator|(_S_out, _S_in)) >> chrom" istream:131: note: candidates are: std::basic_istream<_CharT, _Traits>& std::basic_istream<_CharT, _Traits>::operator>>(std::basic_istream<_CharT, _Traits>& (*)(std::basic_istream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>] [...another dozen lines...] Right. line isn't a std::string, but some variation of std::basic_string, etc. However, explicitly instantiating the stringstream works. string chrom; unsigned int size; string line; while ( getline(genome, line) ) { stringstream ss(line); if ( ss >> chrom >> size ) { // save values } // Discard remainder of line } Why? What is wrong with the first case? The example basic_io at the always helpful cplusplus.com works, why doesn't my code? Update: Another point of reference: the temporary stringstream works when the first value extracted is an int instead of a string: unsigned int chrom; // works as int... unsigned int size; string line; while ( getline(cin, line) ) { if( stringstream(line) >> chrom >> size ) { // save values } }
Three groups of member functions and one group of global functions overload this "extraction operator" (>>), see http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/. stringstream(line); --created a temporary object stringstream ss(line);-- a normal object. when "chrom" is int, operator >> is overloaded as arithmetic extractor which is member functions. Both the normal object or temporary object work fine. When "chrom" is string, operator >> should be overloaded as istream& operator>> (istream& is, char* str), this is a global functions which should take the object reference as parameter. However, given temporary object, we are not allowed to pass temporary objects by non-const reference in standard C++. The overload function cannot get the reference of the temporary object unless the overload function is defined as istream& operator>> (const istream& is, char* str). Unfortunately, that is not the fact. The function(s) cannot be overloaded in the temporary object case, and hence giving out the error like error: no match for function...
1,823,370
1,823,401
C++ overloading * for polynomial multiplication
So I have been developing a polynomial class where a user inputs: 1x^0 + 2x^1 + 3x^2... and 1,2,3 (the coefficients) are stored in an int array My overloaded + and - functions work, however, * doesnt work. No matter the input, it always shows -842150450 when is should be (5x^0 + x^1) * (-3x^0 + x^1) = -15x^0 + 2x^1 + 1x^2 or (x+5)(x-3) = x^2 +2x - 15 I'm using the overloaded * function like : Polynomial multiply = one * two; Im guessing the problem is strtol(p, &endptr, 10) since it uses a long int, however, adding and subtracting works perfectly My constructor Polynomial::Polynomial(char *s) { char *string; string = new char [strlen(s) + 1]; int length = strlen(string); strcpy(string, s); char *copy; copy = new char [length]; strcpy(copy, string); char *p = strtok(string, " +-"); counter = 0; while (p) { p = strtok(NULL, " +-"); counter++; } coefficient = new int[counter]; p = strtok(copy, " +"); int a = 0; while (p) { long int coeff; char *endptr; coeff = strtol(p, &endptr, 10); //stops at first non number if (*p == 'x') coeff = 1; coefficient[a] = coeff; p = strtok(NULL, " +"); a++; } } and the overloaded * function Polynomial Polynomial::operator * (const Polynomial &right) { Polynomial temp; //make coefficient array int count = (counter + right.counter) - 1; temp.counter = count; temp.coefficient = new int [count]; for (int i = 0; i < counter; i++) { for (int j = 0; j < right.counter; j++) temp.coefficient[i+j] += coefficient[i] * right.coefficient[j]; } return temp; } And heres my entire code: http://pastie.org/721143
You don't appear to initialise the temp.coefficient[i+j] to zero in your operator * (). temp.coefficient = new int [count]; std::memset (temp.coefficient, 0, count * sizeof(int));
1,823,431
1,823,475
which is a better language (C++ or Python) for complex problem solving exercises (ex. Graphs)?
I am trying to work on some problems and algorithms. I know C++ but a friend told me that it would be better if done with Python.As it would be much faster to develop and less time is spent in programming details which does not actually earn anything solution wise. EDIT 2: I plan to use python-graph lib from Google-codes, Please provide example codes if you have used it. EDIT 1: faster - less time && less work to code the solution Thank you all for your help !
I think you're looking for Python, because you can: Focus on the algorithms themselves and not have to worry about other detail like memory management. Do more with less code The syntax is almost like working with pseudo code. There is great built in language support for lists, tuples, list comprehensions, etc... But more specifically... If by better you mean speed of development, then chose Python. If by better you mean sheer execution speed, then chose C++.
1,823,605
1,839,640
Boost: what could be the reasons for a crash in boost::slot<>::~slot?
I am getting such a crash: #0 0x90b05955 in __gnu_debug::_Safe_iterator_base::_M_detach #1 0x90b059ce in __gnu_debug::_Safe_iterator_base::_M_attach #2 0x90b05afa in __gnu_debug::_Safe_sequence_base::_M_detach_all #3 0x000bc54f in __gnu_debug::_Safe_sequence_base::~_Safe_sequence_base at safe_base.h:170 #4 0x000aac05 in __gnu_debug::_Safe_sequence<__gnu_debug_def::vector<boost::signals::trackable const*, std::allocator<boost::signals::trackable const*> > >::~_Safe_sequence at safe_sequence.h:97 #5 0x000ac9c1 in __gnu_debug_def::vector<boost::signals::trackable const*, std::allocator<boost::signals::trackable const*> >::~vector at vector:95 #6 0x000acf65 in boost::signals::detail::slot_base::data_t::~data_t at slot.hpp:32 #7 0x000acf8f in boost::checked_delete<boost::signals::detail::slot_base::data_t> at checked_delete.hpp:34 #8 0x000b081e in boost::detail::sp_counted_impl_p<boost::signals::detail::slot_base::data_t>::dispose at sp_counted_impl.hpp:78 #9 0x0000a016 in boost::detail::sp_counted_base::release at sp_counted_base_gcc_x86.hpp:145 #10 0x0000a046 in boost::detail::shared_count::~shared_count at shared_count.hpp:217 #11 0x000a9fb0 in boost::shared_ptr<boost::signals::detail::slot_base::data_t>::~shared_ptr at shared_ptr.hpp:169 #12 0x000aa459 in boost::signals::detail::slot_base::~slot_base at slot.hpp:27 #13 0x000aad07 in boost::slot<boost::function<bool ()(char, int)> >::~slot at slot.hpp:105 #14 0x001b943b in main at vermes.cpp:102 This is the code: #include <boost/signal.hpp> #include <boost/lexical_cast.hpp> #include <boost/function.hpp> #include <boost/bind.hpp> bool dummyfunc(char,int) { return false; } int main(int argc, char **argv) { boost::signal<bool (char, int)> myslot; myslot.connect(0, &dummyfunc); return 0; } It's the first time I am working with Boost and I am also completly new to the code of the project I am trying to port here. That is why I would like to ask if such a crash could be in any way explained by Boost or if it must be unrelated to Boost. I already tried to understand the crash itself but I got stuck somehow. It seems that probably the std::vector, which is going to be deleted here, is messed up (messed up = memory corrupt). That vector is a member of slot_base::data_t. The deletion is done in the destructor of slot_base::shared_ptr. So perhaps the shared_ptr also was messed up - so perhaps even the whole slot_base was messed up. But in the code I have, I don't really see a reason why that memory could be messed up. It is even the first access at all after the construction of myslot. Addition: What I also don't really understand is why the ~slot_base() is called here at all when I do the connect. But I also didn't found the connect-memberfunction. Is that a magic makro somewhere?
I found the problem. When I enable these preprocessor definitions (my Xcode does that by default in Debug configuration), it crashes: -D _GLIBCXX_DEBUG=1 -D _GLIBCXX_DEBUG_PEDANTIC=1 I guess Boost (bjam) compiled without those and that causes such problems because the STL structures (like vector) look different in binary form when compiled with or without this.
1,823,628
1,823,770
EnumChildWindows or FindWindowEx?
I have option to use any one of the API EnumChildWindows or FindWindowEx. Any suggestions which api is better performance oriented? Is FindWindowEx internally uses EnumChildWindows to get handle to particular window?
This really depends a lot on your scenario. The FindWindowEx function is used to search for windows having a particular class and optionally a particular piece of text in the window. The EnumChildWindows function is simply there to enumerate child windows. I think performance should be your last concern here. The first is choosing the right API. If you are indeed searching for windows of a particular class then use FindWindowEx, otherwise EnumChildWindows. There is no sense in hand implementing a function using EnumChildWindows to have the same behavior as FindWindowEx. Now after choosing the right solution, if a profiler specifically tells you that the solution is too slow, then you should consider hand implementing a more specific function. Not before.
1,823,643
2,024,669
Boost: what exactly is not threadsafe in Boost.Signals?
I read at multiple places that Boost.Signals is not threadsafe but I haven't found much more details about it. This simple quote doesn't say really that much. Most applications nowadays have threads - even if they try to be single threaded, some of their libraries may use threads (for example libsdl). I guess the implementation doesn't have problems with other threads not accessing the slot. So it is at least threadsafe in this sense. But what exactly works and what would not work? Would it work to use it from multiple threads as long as I don't ever access it at the same time? I.e. if I build my own mutexes around the slot? Or am I forced to use the slot only in that thread where I created it? Or where I used it for the first time?
I don't think it's too clear either, and one of the library reviewers said here: I also don't liked the fact that only three times the word 'thread' was named. Boost.signals2 wants to be a 'thread safe signals' library. Therefore some more details and especially more examples concerning on that area should be given to the user. One way of figuring it out is to go to the source and see what they're using _mutex / lock() to protect. Then just imagine what would happen if those calls weren't there. :) From what I can gather, it's ensuring simple things like "if one thread is doing connects or disconnects, that won't cause a different thread which is iterating through the slots attached to those signals to crash". Kind of like how using a thread-safe version of the C runtime library assures that if two threads make valid calls to printf at the same time then there won't be a crash. (Not to say the output you'll get will make any sense—you're still responsible for the higher order semantics.) It doesn't seem to be like Qt, in which the thread a certain slot's code gets run on is based on the target slot's "thread affinity" (which means emitting a signal can trigger slots on many different threads to run in parallel.) But I guess not supporting that is why the boost::signal "combiners" can do things like this.
1,823,666
1,823,674
Program stop to running when calls a process
I am trying to create a program that calls another process using CreateProcess. After some problems, I change my program to just open a known program: if( !CreateProcess( (LPWSTR)"C:\\Program Files\\Opera\\Opera.exe", // No module name (use command line) NULL, , // Command line NULL, // Process handle not inheritable NULL, // Thread handle not inheritable FALSE, // Set handle inheritance to FALSE 0, // No creation flags NULL, // Use parent's environment block NULL, // Use parent's starting directory &si, // Pointer to STARTUPINFO structure &pi ) // Pointer to PROCESS_INFORMATION structure ) I found this example in msdn, but every time I run my program, windows (Vista) shows a error msg: The program stop running... Does anybody know what is the problem? Regards, Leandro Lima
This line is wrong: (LPWSTR)"C:\\Program Files\\Opera\\Opera.exe" LPWSTR is a typedef for wchar_t*. So you're casting a plain string (array of chars, which will decay to a const char*) to a wchar_t*. The end result is likely not even null-terminated! Either use CreateProcessA and drop the cast, or use a wide string: L"C:\\Program Files\\Opera\\Opera.exe",
1,823,721
1,823,749
How to catch the null pointer exception?
try { int* p = 0; *p = 1; } catch (...) { cout << "null pointer." << endl; } I tried to catch the exception like this but it doesn't work,any help?
There's no such thing as "null pointer exception" in C++. The only exceptions you can catch, is the exceptions explicitly thrown by throw expressions (plus, as Pavel noted, some standard C++ exceptions thrown intrinsically by standard operator new, dynamic_cast etc). There are no other exceptions in C++. Dereferencing null pointers, division by zero etc. does not generate exceptions in C++, it produces undefined behavior. If you want exceptions thrown in cases like that it is your own responsibility to manually detect these conditions and do throw explicitly. That's how it works in C++. Whatever else you seem to be looking for has noting to do with C++ language, but rather a feature of particular implementation. In Visual C++, for example, system/hardware exceptions can be "converted" into C++ exceptions, but there's a price attached to this non-standard functionality, which is not normally worth paying.
1,823,883
1,823,914
Updating text in a C Win32 API STATIC control drawn with WS_EX_TRANSPARENT
I have window with some STATIC labels and BUTTONs on it. I make all the LABELS transparent background so I can make the background RED say. In the CALLBACK i process the WM_CTLCOLORSTATIC message, determine the ID of the control with GetDlgCtrlID() and then: SetBkMode((HDC)wParam, TRANSPARENT); // Make STATIC control Bkgd transparent return (INT_PTR)(HBRUSH)GetStockObject(NULL_BRUSH); So far so good. Form is drawn, background is RED and label text is drawn on top. After user interaction I need to change the text, so I issue a SetDlgItemText() message and the new text is draw. The problem is the old text is not erased, and the new text is drawn on top of it. Having read somewhat today, it seems the problem is the controls parent (the form) is responsible for drawing the background. This means that when you change the label text, the control redraws the new text, BUT the form doesn't automatically redraw the background. THe question is HOW do I force the form to redraw the rectangle area of the label control (preferably without subclassing anything)? ADDED: I have tried the following: HWND hctrl; hctrl = GetDlgItem(hwnd, ControlID); RedrawWindow( hctrl, 0, 0, RDW_UPDATENOW || RDW_ALLCHILDREN || RDW_FRAME || RDW_INVALIDATE || RDW_ERASE || RDW_INTERNALPAINT ); // RDW_UPDATENOW and: I am not handling the WM_PAINT message at all, only: case WM_CTLCOLORSTATIC: SetBkMode((HDC)wParam, TRANSPARENT); return (INT_PTR)(HBRUSH)GetStockObject(NULL_BRUSH); int Library::SetControlTxt( int ControlID, string sText ) // Dialog Out { int RetVal; RetVal = SetDlgItemText( hwnd, ControlID, sText.c_str() ); RECT rect; HWND hctrl; hctrl = GetDlgItem(hwnd, ControlID); GetClientRect(hctrl, &rect); MapWindowPoints(hctrl, hwnd, (POINT *)&rect, 2); InvalidateRect(hwnd, &rect, TRUE); return RetVal; } Mark, Thank you this works.
Use InvalidateRect on the rectangle occupied by the control. RECT rect; GetClientRect(hctrl, &rect); InvalidateRect(hctrl, &rect, TRUE); MapWindowPoints(hctrl, hwnd, (POINT *) &rect, 2); RedrawWindow(hwnd, &rect, NULL, RDW_ERASE | RDW_INVALIDATE);
1,823,927
1,824,226
Simulated time in a game loop using c++
I am building a 3d game from scratch in C++ using OpenGL and SDL on linux as a hobby and to learn more about this area of programming. Wondering about the best way to simulate time while the game is running. Obviously I have a loop that looks something like: void main_loop() { while(!quit) { handle_events(); DrawScene(); ... SDL_Delay(time_left()); } } I am using the SDL_Delay and time_left() to maintain a framerate of about 33 fps. I had thought that I just need a few global variables like int current_hour = 0; int current_min = 0; int num_days = 0; Uint32 prev_ticks = 0; Then a function like : void handle_time() { Uint32 current_ticks; Uint32 dticks; current_ticks = SDL_GetTicks(); dticks = current_ticks - prev_ticks; // get difference since last time // if difference is greater than 30000 (half minute) increment game mins if(dticks >= 30000) { prev_ticks = current_ticks; current_mins++; if(current_mins >= 60) { current_mins = 0; current_hour++; } if(current_hour > 23) { current_hour = 0; num_days++; } } } and then call the handle_time() function in the main loop. It compiles and runs (using printf to write the time to the console at the moment) but I am wondering if this is the best way to do it. Is there easier ways or more efficient ways?
I've mentioned this before in other game related threads. As always, follow the suggestions by Glenn Fiedler in his Game Physics series What you want to do is to use a constant timestep which you get by accumulating time deltas. If you want 33 updates per second, then your constant timestep should be 1/33. You could also call this the update frequency. You should also decouple the game logic from the rendering as they don't belong together. You want to be able to use a low update frequency while rendering as fast as the machine allows. Here is some sample code: running = true; unsigned int t_accum=0,lt=0,ct=0; while(running){ while(SDL_PollEvent(&event)){ switch(event.type){ ... } } ct = SDL_GetTicks(); t_accum += ct - lt; lt = ct; while(t_accum >= timestep){ t += timestep; /* this is our actual time, in milliseconds. */ t_accum -= timestep; for(std::vector<Entity>::iterator en = entities.begin(); en != entities.end(); ++en){ integrate(en, (float)t * 0.001f, timestep); } } /* This should really be in a separate thread, synchronized with a mutex */ std::vector<Entity> tmpEntities(entities.size()); for(int i=0; i<entities.size(); ++i){ float alpha = (float)t_accum / (float)timestep; tmpEntities[i] = interpolateState(entities[i].lastState, alpha, entities[i].currentState, 1.0f - alpha); } Render(tmpEntities); } This handles undersampling as well as oversampling. If you use integer arithmetic like done here, your game physics should be close to 100% deterministic, no matter how slow or fast the machine is. This is the advantage of increasing the time in fixed time intervals. The state used for rendering is calculated by interpolating between the previous and current states, where the leftover value inside the time accumulator is used as the interpolation factor. This ensures that the rendering is is smooth, no matter how large the timestep is.
1,824,087
1,824,193
How do I factor code to ease testability?
I am learning about Unit Testing and want to know how to write testable code. But, I'm not sure how to write testable code without making it complex. I'll take famous Car and Engine problem to describe the problem. class Car { private: Engine m_engine; public: Car(); // Rest of the car } I came up with following solutions to make the above code testable. Changing the Car's constructor to take Engine as a parameter. Then mock the Engine and do the testing. But, if I don't have different kinds of Engines, it seems inappropriate to parameterize the constructor just to make it testable. Using a setter and then pass a mock Engine to the setter. Same flow as the above. Testing the Engine first and then testing the Car with proven Engine (or using a stub Engine). What are the alternatives I have to make above code testable? What are the strenghts and weaknesses of each method?
If you only have one Engine type, why are you trying to make it a new object? If you don't plan on swapping engines, don't create another abstraction layer. Just make the engine part of the car. You might be decomposing to reduce complexity, rather than to reuse components. Good call. In which case, I'd say that 3 is your best bet - validate your lower level components, then use higher level code that calls the lower level objects. In reality, Engine is more likely to be something like Database. And you will want to change your constructors to use a different Database (for test reasons, or other reasons), but you can leave that lie for a while.
1,824,118
1,824,135
What may cause losing object at the other end of a pointer in c++?
EDIT: I have found the error: I did not initialize an array with a size. question can be closed. I have a class V, and another class N. An object of N will have an array of pointers to objects of class V (say V **vList). So, N has a function like V **getList(); Now in some function of other classes or simply a driver function, if I say V **theList = (N)n.getList(); Q1: theList would be pointing at the 1st element of the array? Given that the size of array is known, can I loop through with index i and say V *oneV = *vList[i]? Please correct me if what I'm doing above is wrong. I have been using debugger to trace through the whole process of my program running, the thing I found was that after using V *oneV = vList[i], the value of the pointers in the array, vList, were the same as when they were created, but if I follow the pointer to where it is pointing at, the object was gone. I'm guessing that might be the reason why I am getting seg fault or bus error. Could it be the case? WHY did I 'loose' the object at the other end of a pointer? What did I do wrong? and yes, I am working on a school assignment, that's why I do not want to print out my codes, I want to finish it myself, but I need help finding a problem. I think I still need explanation on array of pointers. Thank you
Q1 is right. For the second part, V *oneV = vList[i] would be the correct syntax. In your syntax you are dereferencing one more time (treating an object of type V as a pointer to such an object) which obviously is crashing your code. EDIT: Since you are using the correct syntax, the reason of segfaults would depend on your memory management of the objects of type V. If you have inserted addresses of objects created on the stack (automatic vars, not by new or malloc) inside a function and are trying to access them outside of it, then the pointers would be dangling and your code will crash.