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
6,892,272
6,943,819
boost T_CONTLINE token doesn't work
What i think is that there is a bug in the boost token ids. But I'm not sure. The boost token iterators are not able to detect the T_CONTLINE token which is '\ \' followed by '\n' See: http://www.boost.org/doc/libs/1_46_1/libs/wave/doc/token_ids.html For the sample test, I have a test file: testfile.h 1 #define Funti...
Yes, this token is not exposed on the iterator level, it is just handled internally very early in the processing. It's not a bug, but expected behavior. I will add a note to the documentation.
6,892,395
6,892,648
Set breakpoint for class member function not successful
I have a class looks like this: namespace madoka { class polarizable_sites { public: void resize(const size_t dim_); void clear(void); }; } in gdb, I could set breakpoint on clear by b 'madoka::polarizable_sites::clear()' however, for member function resize, a b 'madoka::polarizable_sites::resize(const size_t)' doe...
Probably the function is inlined. Try adding __asm int 3 if it's x86 code in GDB syntax and walk the code. This trick has saved me a lot of time when debugging MSVC x86 code.
6,892,500
6,892,572
boost::Serialize VS std::fstream
Hey so i guess i'm a little confused on the purpose of boost::serialize: Having to add a boost::serialize function to every class you plan to save seems to kind of defeat the purpose of the library, as instead of boosting/ decreasing development time it seems like it would add a HUGE amount of time since you have to g...
Writing directly to a standard stream would still require you to write a serialization/deserialization function pair. Not only the iostream component of the standard library does not support I/O of custom classes, but just writing and reading back sizeof(yourObject) bytes wouldn't work. Just think about what would happ...
6,892,586
6,892,738
how to define a constant array in c/c++?
How to define constant 1 or 2 dimensional array in C/C++? I deal with embedded platform (Xilinx EDK), so the resources are limited. I'd like to write in third-party header file something like #define MYCONSTANT 5 but for array. Like #define MYARRAY(index) { 5, 6, 7, 8 } What is the most common way to do this?
In C++ source file extern "C" const int array[] = { 1, 2, 3 }; In header file to be included in both C and C++ source file #ifdef __cplusplus extern "C" { #endif extern const int array[]; #ifdef __cplusplus } #endif
6,892,622
6,893,312
How to mark a zlib licensed library as altered/edited by my name?
Hey so i've recently taken some pretty old source code from a GUI library, code that has been abandoned and forgotten, and did a massive amount of editing/fixing on it to the point where 50% of the code is now mine. This library is licensed though, so if I wanted to put out there for others to use, how would i give my...
IANAL. This is going to be a partial answer. According to the zlib license you have to mark altered versions as such: 2 . Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. However, you may not alter the license notice: 3 . This notice may not be re...
6,892,627
7,032,979
Automatically insert prototype functions from .h with Emacs
How do I configure emacs to automatically insert prototype functions from .h when opening the corresponding .cc file?.
I have something like this that I used for doing this when I was doing more C++ coding, using the member-functions package: (require 'member-function) ;;expand member functions automatically when entering a cpp file (defun c-file-enter () "Expands all member functions in the corresponding .h file" (let* ((c-file (...
6,892,651
6,892,701
Boost.Python: Weak reference to object?
Is there a way to get a weak reference to a Python object? With boost::python::object you get a strong/shared reference so as long as either C++ or Python holds a reference to that object, it will not get deleted. I want only Python to hold a strong reference to an object, and C++ a weak one. Is that possible?
You need to go into the CPython API for that. Use PyWeakReference type from weakrefobject.h. The header exposes an API that's similar to weakref module — see the docs.
6,892,754
6,892,829
Creating a simple configuration file and parser in C++
I am trying to create a simple configuration file that looks like this url = http://mysite.com file = main.exe true = 0 when the program runs, I would like it to load the configuration settings into the programs variables listed below. string url, file; bool true_false; I have done some research and this link seemed ...
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one. In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter,...
6,892,784
6,892,807
Improving space complexity while reading from a file
I have an arbitrarily long line of integers (or floating point values) separated by commas in a file: 1,2,3,4,5,6,7,8,2,3,4,5,6,7,8,9,3,... (can go upto >100 MB) Now, I have to read these values and store them in an array. My current implementation looks like this: float* read_line(int dimension) { float *v...
Something like this? float val; while (file >> val) { values[count++] = val; char comma; file >> comma; // skip comma }
6,893,116
6,893,141
Is writing to memory an observable behaviour?
I've looked at the standard but couldn't find any indication that simply writing to memory would be considered observable behaviour. If not, that would mean the compiled code need not actually write to that memory. If a compiler choose to optimize away such access anything involving mapper memory, or shared memory, may...
This kind of thing is what volatile exists for. Else, writing to memory and never apparently reading from it is not observable behaviour. However, in the general case, it would be quite impossible for the optimizer to prove that you never read it back except in relatively trivial examples, so it's not usually an issue....
6,893,145
6,900,995
BackgroundWorker in VS2010 doesn't run in another thread
I created a WinForm in Visual Studio 2010 (c++), almost the same as this example: http://msdn.microsoft.com/en-us/library/waw3xexc.aspx but when I click on the button that "lunch" the BackgroundWorker it "stucks" the WinForm, so I can't move it or click on "stop button" for the time the function runs. The function runs...
I found the problem. The BackgroundWorker actually runs on another thread but it send Events of update progress too often and those events "lunch" function in the main form - that updates ProgressBar - and this funcion "stucks" the form.
6,893,195
6,893,211
How to cast from unsigned long to void*?
I am trying to pwrite some data at some offset of a file with a given file descriptor. My data is stored in two vectors. One contains unsigned longs and the other chars. I thought of building a void * that points to the bit sequence representing my unsigned longs and chars, and pass it to pwrite along with the accumul...
You cannot meaningfully cast an unsigned long to a void *. The former is a numeric value; the latter is the address of unspecified data. Most systems implement pointers as integers with a special type (that includes any system you're likely to encounter in day-to-day work) but the actual conversion between the types is...
6,893,218
6,893,501
How do I read headers from a QNetworkReply
How can one read headers for example a cookie out of a QNetworkReply?
Consulting the documentation, there are a few methods related to reading headers: header, rawHeader, rawHeaderList, and rawHeaderPairs. For the specific case of getting a cookie, you can use the header method. It would look something like this: QNetworkReply *reply; // somehow give reply a value QVariant cookieVar = re...
6,893,285
6,893,288
Why do function pointer definitions work with any number of ampersands '&' or asterisks '*'?
Why do the following work? void foo() { cout << "Foo to you too!\n"; }; int main() { void (*p1_foo)() = foo; void (*p2_foo)() = *foo; void (*p3_foo)() = &foo; void (*p4_foo)() = *&foo; void (*p5_foo)() = &*foo; void (*p6_foo)() = **foo; void (*p7_foo)() = **********************foo; ...
There are a few pieces to this that allow all of these combinations of operators to work the same way. The fundamental reason why all of these work is that a function (like foo) is implicitly convertible to a pointer to the function. This is why void (*p1_foo)() = foo; works: foo is implicitly converted into a pointe...
6,893,414
6,893,425
memory usage of in class - converting double to float didn't reduce memory usage as expected
I am initializing millions of classes that are of the following type template<class T> struct node { //some functions private: T m_data_1; T m_data_2; T m_data_3; node* m_parent_1; node* m_parent_2; node* m_child; } The purpose of the template is to enable the user to choose float or double precision, w...
If you are compiling for 64-bit, then each pointer will be 64-bits in size. This also means that they may need to be aligned to 64-bits. So if you store 3 floats, it may have to insert 4 bytes of padding. So instead of saving 12 bytes, you only save 8. The padding will still be there whether the pointers are at the beg...
6,893,493
7,187,654
How do I avoid UnsatisfiedLinkError when calling C++ from java from C++ application?
I'm embedding Java into a C++ application. As part of this I need to expose native functions to java, as well as calling java functions from C++. Do I need to put the functions I want to call from java into a shared library? Or can they be compiled into the host application somehow? Here's what I've tried so far, but i...
Normally the JVM expects to find native method definitions in a shared library that has been loaded via System#load or System#loadLibrary, and in most cases that is the most convenient approach. However, there does exist an alternative for situations like yours, where you would prefer to include the implementations dir...
6,893,700
6,894,191
How to construct std::array object with initializer list?
Possible Duplicate: How do I initialize a member array with an initializer_list? You can construct an std::array just fine with an initializer list: std::array<int, 3> a = {1, 2, 3}; // works fine However, when I try to construct it from an std::initializer_list as a data member or base object in a class, it does...
An std::array<> has no constructor that takes an std::initializer_list<> (initializer list constructor) and there is no special language support for what it may mean to pass a std::initializer_list<> to a class' constructors such that that may work. So that fails. For it to work, your derived class needs to catch all ...
6,893,922
6,893,992
C++ checksum reading nonexistent newline
I am doing a very basic checksum on files by reading the input file into a character array, and then iterating over that array and adding each character into the checksum. The problem is that when I do this all of my checksums are 10 too high (10 is the ascii decimal value for the newline character). How is it newline ...
Your problem is here: num <= fileLength It should be: num < fileLength For example. If the length is 1. Then the only valid character is charArray[0] Also note. Doing this: inputFile.read(charArray, fileLength); is dangerious as fileLength may be larger than the size of the array. A better solution would be to use a...
6,894,169
6,901,973
Splitting up Code into Multiple Files
I know this has been asked a billion times before, but I'm still having trouble. I began with one main.cpp file that contained all of my code. Say it looked like this: int a = 0; void foo() { a+1; } void bar() { a+2; } int main() { foo(); bar(); a + 3; } Now I want to split up this code into mult...
I think the bigger problem is you are implementing something in a header file. The problem is when you include the header into more than one object file, you will run into problem at linker time. Don't do it. Use a define for this sort of thing. They difference is that a define, being a preprocessor macro, doesn't crea...
6,894,176
6,894,232
C++ Reading From File Loop Messing Up
I have a problem with a simple file read. I have 4 four long lines of T/F's with a count at the beginning. I read in with a myfile >> count, and myfile >> value to get the values with a while with the count to finish it off the line and goto the next but I have a problem going to the third line for some reason. Not ...
You appear to be attempting to read the count twice per line: at the beginning and end of the while loop.
6,894,202
6,895,975
See if mouse click was handled
I'm currently making a whimsical iPhone app that will allow you to change your windows cursor into a space ship controlled by the iPhone (simple rotation and such), and currently I have the movement and clicking handled, however I'd like to add additional features, such as bullets that you can shoot around the screen w...
The most reliable route would be the Microsoft Active Accessibility interface. Many tools to help visually impaired people need to answer the question "Is this a button?", and MSAA answers that question. Overlaying the screen is trvial in a Windows environment; just create a window :). It can be partially transparent, ...
6,894,370
6,894,391
Difference between ".", "::" and, "->"
In c++ is there any difference between these 3 blocks of code: MyClass->m_Integer // 1 MyClass::m_Integer // 2 MyClass.m_Integer // 3
The -> and . operators are way to access members of an instance of a class, and :: allows you to access static members of a class. The difference between -> and . is that the arrow is for access through pointers to instances, where the dot is for access to values (non-pointers). For example, let's say you have a class ...
6,894,388
6,894,779
about condition variable in C++
I am going through condition variable article at following location http://software.intel.com/en-us/blogs/2010/10/01/condition-variable-support-in-intel-threading-building-blocks/ Here we have following code as example #include "tbb/compat/condition_variable" using namespace std; condition_variable my_condition; tbb...
Why are we using mutex here while we are using condition variable? The basics of the condition variable require a lock to work correctly. Only the thread with the lock should be trying to change the state of the condition variable (ie by calling one of the condition variable functions (it is also to protect the objec...
6,894,487
6,894,693
Alternatives to graphics.h
We have an introductory course to Computer Graphics this semester in college. There is no recommended way on how to go about the Lab exercises. Most of the students are resorting to Turbo C and the inbuilt graphics.h header file. I'm a little apprehensive about this, Turbo C is a thing of the 70's and to learn stuff on...
Allegro or SDL libraries may be for you. I would also suggest not to use Bloodshed Dev-C++ as it is also a little outdated. You may use MS VC++ Express or Code::Blocks which are both free.
6,894,566
6,895,219
How do you make Tree Data Structures in C++?
I'm taking a class in AI Methods along with a friend of mine, and we've partenered for the final project, which is coding Othello & an AI for it using C++ and OpenGL. So far we have the board and the Othello Engine (I'm using an MVC type approach). But the one thing thats proving difficult to grasp is the AI. We're su...
The tree for alpha-beta pruning is usually implicit. It is a way of preventing your AI search algorithm from wasting time on bad solutions. Here is the pseudocode from Wikipedia: function alphabeta(node, depth, α, β, Player) if depth = 0 or node is a terminal node return the heuristic value of nod...
6,894,600
7,535,652
How to use itkvtkglue to use ITK with VTK?
I wanted to make the example which combines ITK with VTK called IO/ImageFileReader from wiki examples. I downloaded itkvtkglue, extracted to a folder, configured with cmake and built with visual studio 2010. but i can't use it when i try to configure the example given. Even though cmake finds the ItkVtkGlue_DIR by itse...
This is almost certainly one of the very common problems: If the path to your tools contains a [space] character in it, then you must protect the file path from being split apart by encapsulating it in quotations "". To be safe, you should always place file paths in quotations just incase one of your future collaborato...
6,894,768
6,894,838
reCAPTCHA for C++ server
I am not able to find any recaptcha support for c++ at http://code.google.com/apis/recaptcha/ how can I use it in my c++ server code ? if not is there any other captcha which I can use in c++ ?
You can use recapcha API for using it in C++. for eg: Recapcha validation API And These API are not bounded to any specific language.
6,894,872
6,894,931
C++ code run very slow in a predominantly Objective-c project
I was required to add an exotic image format to a project. The client supplied only a c++ library. The library does it's work extremely slow once compiled in a predominantly Objective-C project (that is, a project with all the rest of the code in objective-c) I've compared performance with c++ implementations on a Mac ...
I've compared performance with c++ implementations on a Mac and a PC, a ported C# implementation on a pc - all on similar computers CPU and memory-wise. The slow performance is only in an Objective-C project, much more evident on a device than on the simulator. iOS devices are relatively powerful considering th...
6,894,894
6,894,949
does STL has hashmap data structure?
I have used unsorted_map from TR1. I never know any data structure from STL is hashmap. My coworker insists that STL has hashmap, which he cannot (or not willing )find for me. Could anybody judge this argue? Thanks.
Standard C++98 does not have a hash map, but many implementation of the STL, like the original SGI implementation, do have a hash_map class.
6,894,947
6,895,581
FindwindowEx for outlook 2010
Hi created the addin for the outlook 2007. Now addin need to support to outlook 2010 also. But the following code fails while checking to get outlook window handle. hWnd = ::FindWindowEx(*pExplorerWnd, NULL, _T("rctrl_renwnd32"), ""); rctrl_renwnd32 is classname for outlook 2007 whether its same for outlook 2010.? Ple...
Yes the classname is rctrl_renwnd32. See what happens if you specify hwndParent as NULL
6,894,977
6,895,124
How to call a non static member function from a static member function without passing class instance
I need to call a non static member function from a static member function of the same class. The static function is a callback. It can receive only void as data, though which i pass a char*. So i cannot directly provide the class instance to the callback. I can pass a structure instead of char to the callback function....
Normally such a callback would look like this: void Callback( void* data) { CMyClass *myClassInstance = static_cast<CMyClass *>(data); myClassInstance->MyInstanceMethod(); } Of course, you need to make sure, data points to an instance of your class. E.g. CMyClass* data = new CMyClass(); FunctionCallingMyCallba...
6,895,020
6,895,060
C++: What's happen when I use "using namespace xyz" before #include<headerxy>
Possible Duplicate: Ordering of using namespace std; and includes? I heard that it is strongly prohibited to use "using namespace xy" before "#include ". E.g. #include <iostream> using namespace std; int main() { ... } What's the technical reason for that? I tried following and it worked without any problems: usi...
No, it is not strongly prohibited (otherwise it would be a compilation or preprocessing error). The using keyword puts all functions and variable into the current namespace, and it is discouraged to use it in the header files.
6,895,062
6,895,087
Keep getting error LNK2019: unresolved external symbol
The IDE I use is Visual Studio 2010 Professional, and the library I use is ICU4C 4.8.1 for Win32 for MSVC10. I have rebuilt all the source codes according to the manual for both Debug and Release, and all tests are successfully passed. Then I do in the way I do with Boost. I included \include in C/C++ > Additional Incl...
Apart from setting additional include directories and library directories, you have to actually link to the library. Go to Project Properties -> Linker -> Input and write the name to the .lib in Additional dependencies textbox. HTH
6,895,327
6,895,358
opening and reading a file whose name is given at runtime
My problem is how to use correctly the function infile.open(). I have a class that, among the others, has the following public properties: class myclass { public: int rows int columns const char* array_file } All values are given at run-time. When I call the function that uses a member of the class I have (pt is a poi...
infile.open gets as its first parameter the filename: void open ( const char * filename, ios_base::openmode mode = ios_base::in ); (source) I don't know what your filename is but maybe something like this (just a guess based on variable types) could do: infile.open(pt->array_file); of course you have to ensure that ...
6,895,408
6,895,775
To inline or not to inline
I've been writing a few classes lately; and I was wondering whether it's bad practice, bad for performance, breaks encapsulation or whether there's anything else inherently bad with actually defining some of the smaller member functions inside a header (I did try Google!). Here's an example I have of a header I've writ...
Inlining increases coupling, and increases "noise" in the class definition, making the class harder to read and understand. As a general rule, inlining should be considered as an optimization measure, and only used when the profiler says it's necessary. There are a few exceptions: I'll always inline the virtual destr...
6,895,479
6,895,535
How to tokenize a string without boost?
I am working in C++. I have the following string: 2011-07-01T14:32:39.1846579+02:00 Can someone tell me how can I extract 2011-07-01 14:32 in another string?
I think that sscanf is what you are looking for : http://www.cplusplus.com/reference/clibrary/cstdio/sscanf/ You can then use snprintf to reformat the data.
6,895,522
6,895,543
Is 0 a decimal literal or an octal literal?
Zero is always zero, so it doesn't matter. But in a recent discussion with a friend he said that octal literals are almost unused today.† Then it dawned upon me that actually almost all integer literals in my code are octal, namely 0. Is 0 an octal literal according to the C++ grammar? What does the standard say? † The...
Yes, 0 is an Octal literal in C++. As per the C++ Standard: 2.14.2 Integer literals [lex.icon] integer-literal: decimal-literal integer-suffixopt octal-literal integer-suffixopt hexadecimal-literal integer-suffixopt decimal-literal: nonzero-digit decimal-literal digit octal-literal:...
6,895,681
6,895,744
How to write on multiple lines in a QMessageBox in QtCreator?
I would like to have in a message box the following lines: name: surname: data: test: After each : I'll programmatically fill the line. I would like to ask how can I have this structure in a QMessageBox. It is possible? I am a beginner in Qt Creator. Currently I learned to do this: QMessageBox noc; std::st...
QString str; str = QString("name: %1\nsurname: %2\ndata: %3").arg(...).arg(...).arg(...); QMessageBox::information(0, "Title", str); Take a look at QMessageBox::information() and QString::arg().
6,896,239
6,897,137
error: glibc detected when using vector
I used arrays in my code, and now I changed them to vector and I get these errors(its in linux): glibc detected *** double free or corruption glibc detected malloc memory corruption My code is so long and I can't paste it here, here's how I use vector: Declared: vector:vector<double>x;//i didnt define anysize for ve...
You say that you didn't define any size for the vector. That means it has size zero. In that case, this code x.insert(x.begin()+i,i) is invalid for any i other than zero.
6,896,252
6,896,315
Variable arguments weirdness
Ok, so this piece of code works fine in the Debug but not in Release build. int AddString(LPCTSTR lpszString, ...) { RArray<LPCTSTR> strings; va_list args; va_start(args, lpszString); do { strings.Add(lpszString); } while (lpszString = va_arg(args, LPCTSTR)); va_end(args); // ....
You're doing it the wrong way and you're just lucky with the debug build. Notice that va_arg does not determine either whether the retrieved argument is the last argument passed to the function (or even if it is an element past the end of that list). The function should be designed in such a way that the amount of para...
6,896,334
6,896,372
Is it OK to return a literal by const reference?
Is this safe? const int& f() { return 1; } What I'm trying to do is to return a some value to const &
It is not okay. Returning reference to a temporary is not okay because accessing it outside the function causes Undefined Behavior.
6,896,533
6,912,571
Fast divisibility tests (by 2,3,4,5,.., 16)?
What are the fastest divisibility tests? Say, given a little-endian architecture and a 32-bit signed integer: how to calculate very fast that a number is divisible by 2,3,4,5,... up to 16? WARNING: given code is EXAMPLE only. Every line is independent! Just obvious solution using modulo operation is slow on many proces...
It is not a bad idea AT ALL to figure out alternatives to division instructions (which includes modulo on x86/x64) because they are very slow. Slower (or even much slower) than most people realize. Those suggesting "% n" where n is a variable are giving foolish advice because it will invariably lead to the use of the d...
6,896,698
6,896,748
Shortening a nested variable name
In the code below Node_T is a std::shared_ptr, element_type will be Node< T,U >, and this type has member called root_; Is there a way to shorten somehow this: Node_T::element_type::root_ to just root_? template<class Node_T> const Node_T& root(Node_T& node) { Node_T::element_type::root_ = node; w...
If you are using C++0x; then the first line of function root(Node_T&) can be, auto &root_ = Node_T::element_type::root_; // use root_ now onwards
6,897,114
6,897,334
Basic question on C++ templates
Consider this overly simple test: class foo { public: foo(int i); template< typename T > foo(T); }; template<> foo::foo(int i) {} Now, GCC is happy to accept this when compiling, but the RVCT compiler issues an error: test.cpp", line 11: Error: #792: "foo::foo(int)" is not an entity that can be e...
You are attempting to do an explicit specialization of template<typename T> foo(T) where T=int. Did you actually want this? template<typename T> foo::foo(T) { } --- EDIT --- Just to make it clear: "explicit specialization" is legal in C++, but apparently your compiler does not support it (on individual methods anyway,...
6,897,204
6,897,310
xmlserialization without managed code?
Is there a possibility to use xmlwriter (xmlserialization) without managed code (cli)? using namespace System::Xml; using namespace System::Xml::Schema; using namespace System::Xml::Serialization; My XML serialization managed code: void TXML_Interface::LoadXML( String^ filename ) { XmlSerializer^ serializer = gcnew Xm...
Yes and no. Yes it is possible to do XML maniuplation (including serialisation) without managed code - I'd normally do this using MSXML however there are various ways to perform xml serialisation in C++ (I'm not really a C++ person but Google is almost certainly the first place to look). However this is using a differe...
6,897,662
6,897,689
Matching an overloaded function to its polymorphic argument
Okay, the title is a mouthful and I think that's probably why it has been tough to find an answer through google or this site. It might just be that I don't know how to express the problem correctly but here goes: I have a series of methods in a SimpleOpenGLRenderer class that all take a single argument that extends th...
Overloads in C++ are resolved at compile time, based on the static type of the argument. There's a technique known as "double-dispatch" that might be of use: class Model { virtual void dispatchRender(Renderer &r) const = 0; }; class Cube : public Model { virtual void dispatchRender(Renderer &r) const { ...
6,897,734
7,150,028
Overriding a method defined by another kext?
I need to override a method defined by a kext to do my own processing and return my own value, so whenever the kext calls the method, it will get routed to mine. So what I want to do is to define this method in my own kernel extension, and then load it. The problem is that I don't know how to swap the methods so mine g...
You can certainly achieve this via hacking the vtable, though I don't have a specific idea of how you'd go about that. I know the C++ kext loading and unloading mechanism manages vtables and vtable versioning; the source should be available, so have a look at that. However, vtable patching should really be a last resor...
6,897,737
6,897,865
Using The [] Operator Efficiently With C++ unordered_map
Firstly could someone clarify whether in C++ the use of the [] operator in conjunction with an unordered_map for lookups wraps a call to the find() method, or is using the [] operator quicker than find()? Secondly, in the following piece of code I suspect in cases where the key is not already in the unordered_map I am ...
operator[] will insert an entry for you with a default-constructed value, if one isn't already there. It is equivalent to, but will probably be implemented more efficiently than: iterator iter = map.find(key); if(iter == map.end()) { iter = map.insert(value_type(key, int())).first; } return *iter; operator[] can...
6,897,755
6,902,572
Intellisense for C++ in VS2010
All, I have a strange issue with Intellisense for C++ projects. Background: I have recently installed VS2010 Sp1 and had a loss of Intellisense with SQL Server 2008 R2. I tried installing Cumulative Update 7 (CU7) as recommended and this did not work. Reinstalling SQL Server 2008 R2 however, did. I then updated using ...
Note: My second answer. Based on a comment by Cory Nelson, so I don't claim credit. If I understand you correctly, you want that Intellisense pops up the moment you type 'p'. The answer is: No, VS2010 won't do that. Intellisense will kick in for "::p" or "std::p", but not for a plain "p". This has nothing to do with pr...
6,897,981
6,898,033
Declaring a reference is a regular instruction or just a second name?
When I write, T &t = obj; Is this considered an instruction (which generates machine code) or just a second name of obj?
I don't think that the standard ever uses the word instruction, except for generated code. The line T &t = obj; is a declaration statement which is a definition; it's a statement, but so are things like using std::string;. It may or may not result in executable code being generated, depending on a lot of things. Also...
6,898,149
6,898,413
Is Type name = name; ever useful in C++?
The following code is allowed in C++: int a = a; or Type name = name; Both lead to an uninitialized object being initialized by itself, which often leads to undefined behavior. Is such code ever needed or reasonable? Are there cases of such code being useful?
You are allowed to use the name of the variable in its initializer. The code Type name = name; is probably not useful, but the code Type name = f(&name); might be. There are many places where the language syntax doesn't forbid useless constructs. :-)
6,898,205
6,898,708
RealTime graph using wxWidgets
How can I make a real time graph using wxWidgets in Windows?
You can try some of the wxWidget specific controls linked to below. I have only ever worked with wxMathPlot which fitted my needs but is not necessarily fast - it depends on your time requirements for real time and amount of data you are trying to plot. wxMathPlot wxPlot & plplot wxChart wxFreeChart gpPanel - seems to ...
6,898,261
6,898,334
Calling member function of templated member
This program compiles fine but seg faults when running the value->getSmall in Period::display(). I'm working on linux with g++. I've provided a getSmall function for all the classes that may be used as T. Just to be sure I added the debug lines and found that the segfault is caused when type of value ie T is Class* . I...
You assume T to be a pointer, but never give it a value in Period. That way you have an uninitialized pointer that is likely to segfault.
6,898,567
6,912,272
Qt xmlWriter/xmlReader
I want to write and read an xml file using Qt. Is there a simple example code, which generates an XML file dynamically? I've found some Qt xml classes, but does anybody know what they are used to and is there an easy example which uses these classes? QtXml Module (http://doc.qt.nokia.com/latest/qtxml.html) QXmlStreamRe...
Thanks for your answer! I've found these links for generating and reading XML files using QT from Nokia: Writing XML Files: http://developer.nokia.com/community/wiki/Generate_XML_programatically_in_Qt Reading XML Files: http://www.developer.nokia.com/Community/Wiki/Using_QXmlStreamReader_to_parse_XML_in_Qt This are the...
6,898,622
7,021,375
Are there any HTML5 Canvas implementations for embedding in c++
I'm working on a browser based game atm and already looking into options porting it to other platforms such as consoles or devices where playing in a web browser may not be suitable. The game is pretty much all JavaScript with rendering done via a 2d canvas context. What i was hoping for is that there is already a c++...
Qt is a very nice C++ library compatible with LGPL licensing that among other things includes a webkit based widget with javascript support. Also as scripting language Qt uses javascript with a tight integration with C++ (it's easy to write a C++ class and and make it visible at the javascript level). Qt is multi platf...
6,898,693
7,013,451
Why are disabled buttons using high depth colour in CToolBar are just grey boxes?
I've followed the steps from this question: Higher color depth for MFC toolbar icons? The code works. But I have another problem - any disabled buttons are just grey boxes. Once they are enabled - they are exactly as they should be. I suspect that the CToolBar doesn't know how to grey out the supplied images - can anyo...
CToolBar actually accepts up to three imagelists each to handle the normal, disabled and highlighted states of the button. To accomplish what I need - just normal and disabled button states. I need two images. One with normal coloured icons and the other with greyed out icons. Add the images as Bitmap resources to you...
6,898,759
6,898,793
Create FILE* from String
I'm using a library where they used paths to define input and output files where data gets read from/written to. App1 writes the input file, App2 reads that input file and creates an output file. Then, App1 reads the output and everyone is happy. Now, we get the requirement that for the communication between App1 and ...
For IPC you can use pipes, it is easy to make FILE* from winapi HANDLE created for pipe. This code will show how: HANDLE read_hnd; HANDLE write_hnd; //make sa (SECURITY_ATTRIBUTES) if(!CreatePipe(&read_hnd, &write_hnd, &sa, NULL)) { //error } int fd = _open_osfhandle((intptr_t)read_hnd, _O_RDONLY|_O_TEXT); FILE *pipe_...
6,898,859
6,898,868
Does MSVC10 Visual Studio 2010 support C++ range based loops
Does MSVC10 support the C++0x draft standard's range based loop? http://en.wikipedia.org/wiki/C%2B%2B0x#Range-based_for-loop Example: for (int& p : array) { ... }
No. Stephan T. Lavavej's explains the feature was altered too late in Visual Studio 2010's release cycle. Comments on the Visual Studio Team's blog: http://blogs.msdn.com/b/vcblog/archive/2009/07/13/intellisense-and-browsing-with-c-0x.aspx
6,899,025
6,899,073
Hide user input on password prompt
Possible Duplicate: Read a password from std::cin I don't work normally with the console, so my question is maybe very easy to answer or impossible to do . Is it possible to "decouple" cin and cout, so that what I type into the console doesn't appear directly in it again? I need this for letting the user typing a pa...
From How to Hide Text: Windows #include <iostream> #include <string> #include <windows.h> using namespace std; int main() { HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE); DWORD mode = 0; GetConsoleMode(hStdin, &mode); SetConsoleMode(hStdin, mode & (~ENABLE_ECHO_INPUT)); string s; getline(ci...
6,899,108
7,086,921
Boost.Python: Callbacks to class functions
I have an EventManager class written in C++ and exposed to Python. This is how I intended for it to be used from the Python side: class Something: def __init__(self): EventManager.addEventHandler(FooEvent, self.onFooEvent) def __del__(self): EventManager.removeEventHandler(FooEvent, self.onFooEv...
Without weakref.ref(self.onFooEvent) you will never get your expected behaviour! See my comment.
6,899,125
6,956,161
Understanding C++ codebase with UML-tools
I am trying to understand a C++ codebase. I have used some free tools that will scan the code and produce diagrams, but they are not so easy to understand. What I think would be useful is to manually construct something assisted by the UML tool. What i need is to create something that looks like the data structure at ...
Most tools will only give you a structural view (classes and packages), which honestly doesn't tell you that much of what goes on in runtime. Enterprise Architect from Sparx Systems incorporates a Visual Execution Analyzer, which can generate sequence diagrams from a debug session. It supports C++ but only on Windows s...
6,899,289
6,899,343
C++ logical & operator
Is there a logical & operator in C++? e.g. an operator that works just as && except that it also evaluates later arguments even if some preceding ones have already evaluated to false? The operator & is the bitwise and operator I understand.
The operator & is indeed the bitwise operator. I'm assuming you have something like if ( f() && g() ) { /*do something*/ } and you want both f() and g() to execute, regardless of whether one of them was evaluated to false. I suggest you do something else instead: bool bF = f(); bool bG = g(); if ( bF && bG ) { /*do s...
6,899,392
6,899,457
Generic Hash function for all STL-containers
I'm using an std::unordered_map<key,value> in my implementation. i will be using any of the STL containers as the key. I was wondering if it is possible to create a generic hash function for any container being used. This question in SO offers generic print function for all STL containers. While you can have that, why...
We can get an answer by mimicking Boost and combining hashes. Warning: Combining hashes, i.e. computing a hash of many things from many hashes of the things, is not a good idea generally, since the resulting hash function is not "good" in the statistical sense. A proper hash of many things should be build from the ent...
6,899,868
6,942,018
How to pass java.net.Socket to a C++ DLL function waiting for `BoostSocket.assign(tcp::v4(), nativeSocketFromJava);`
So I wonder is it possible and how to pass socket from java to some DLL library waiting for native for this OS socket? Could any one provide an example? Is it anyhow possible to use org.apache.tomcat.jni.Socket for it?
First thing first - we need to get a file descriptor of java.net.Socket. That is possible to do using reflection mechanism. The idea is to get access to java.io.FileDescriptor on the java.net.SocketImpl and then get a native socket descriptor. See DualStackPlainSocketImpl.java for code snippets (this method is also poi...
6,899,879
6,899,970
C++ templated function creation with raw or smart pointer gets different results
Lets say I have : (this class Is OK) class CCheckSystemEndianess { private: int i; char checker[sizeof(int)]; public: CCheckSystemEndianess() : i(1) { } bool isLittleEndian() { return (checker[0] != 0); } }; But this one acts strange template <bool checker> class CEndian { private: template <type...
In CCheckSystemEndianess, i, and checker are two unrelated objects. The value 1 written to i by the constructor has no bearing on the contents of checker which remain uninitialized. Perhaps your intent was to make a union?
6,899,995
6,917,868
64 bit windows file opening
I'm trying to use a dialog box to open a file in my program. This works perfectly on a 32 bit system, but when I try to use it on 64 bit it is unable to open the file. I've figured out that if the file trying to be opened is in the same directory as my program, it works fine. Trying to open a file from another folder, ...
UAC and file system redirection are related yet different. User account control is a permissions based security to prevent unauthorized users from changing your file system or executing applications which may affect other users. The prompt allows you to override the security by providing administrator privileges tempor...
6,900,195
6,900,243
Try/Catch VS return error code in C++
Possible Duplicate: In C++ what are the benefits of using exceptions and try / catch instead of just returning an error code? I am wondering what's the pros & cons of using Try/Catch VS returning error code ? Should I almost always prefere using try catch in c++ ? Do you still use return error code in your project ?...
Use error codes for incorrect functionalities of your program and try catch in places where you expect the program to crash. try/catch blocks usually make your program run slower. If you suspect an error in your code, it's better to check and return an error code rather than throwing an exception.
6,900,222
6,900,387
MultiThreaded Libcurl
I need to execute parallel HTTP requests using Libcurl. From what I understand I need to create a new handle for each thread and use CURLOPT_WRITEDATA with some kind of Thread Local Storage. Does the multi interface makes this task a little easier? I'm also using cookies, does using CURLOPT_COOKIEFILE and CURLOPT_COOKI...
As you probably know, libcurl is not thread safe, so you should ensure that the libcurl handle is never shared between multiple threads. Each thread will need to store local data (among other things, the connection handle). From this, it ensues that for each handle, i.e., for each thread, libcurl will need to read the ...
6,900,273
6,900,412
Packets Are Stacked When Sent at Regular Intervals
I am trying to send a message over a TCP socket at a regular interval (every second). Sometimes the full message will not be sent or two-four messages will be stacked and sent at once. I have if statements for if the return value is 0 or < 0, but those are never true. I tried the obvious approach of checking the exact ...
TCP provides a reliable stream of bytes, there's no message boundary. If you need to know the length of the message you have to build this into the protocol, eg: send every message with a 2 byte header which specifies the message length.
6,900,459
6,900,522
The new keyword "auto"; When should it be used to declare a variable type?
Possible Duplicate: How much is too much with C++0x auto keyword Have we (as a community) had enough experience to determine when and/or whether auto is being abused? What I am really looking for is a best practices guide on when to use auto when it should be avoided Simple rules of thumb that can quickly be follo...
I think when the type is very well-known amongst the co-programmers who work (or would work) in your project, then auto can be used, such as in the following code: //good : auto increases readability here for(auto it = v.begin(); it != v.end(); ++it) //v is some [std] container { //.. } Or, more generally, //goo...
6,900,502
6,900,838
Why does visual express 2008 not auto complete std::system
Why does visual express 2008 not give me the option of system when typing std:: though I hear it is part of the <cstdlib>?
It could be that system is defined in the toplevel namespace and only included into std by way of a using statement. That way it wouldn't actually be in the namespace std, but rather just be accessible through it. There's just one toplevel or global namespace, ::. So ::global would be that function. If they'd implement...
6,900,780
6,900,829
How to convert a vector<char*> to a vector<string>/string
We have a legacy method that returns a vector of char pointers i.e., vector<char *>. Now, I need to process only strings (std::string). How can I do this? This question may sound simple, but I run into couple of websites which depicted that these sort of considerations might lead to memory leaks. Now, I either want to ...
well, depending on the performance requirements, you could just construct a std::string as needed. Like this: for(std::vector<char*>::const_iterator it = v.begin(); it != v.end(); ++it) { std::string s = *it; // do something with s }
6,900,802
6,900,870
Stack trace running UNIX application
How can I perform a live stack trace on a running UNIX applicaiton, and are there any utilities that are useful in digesting the stack trace once its done? I'm looking to see if any functions are getting called more often than I would have expected them to be - the application works fine, it just recently slowed down a...
Profiling tools will show what bits of the program are taking up the CPU time. If you have to dig deeper, you may need other tooling. Depending on what species of unix you're after, the tools will vary, as this is sometimes quite platform specific. This article discusses process monitoring on Linux. Different versi...
6,900,994
6,907,946
QObject: Cannot create children for a parent that is in a different thread
EDIT: I tried doing what you guys told me in comments ... : Citizen * c = new Citizen(this); QThread thread; c->moveToThread(&thread); connect(&thread, SIGNAL(started()), c, SLOT(ProcessActions())); thread.start(); This produces even more errors: QThread: Destroyed while thread is still running ASSERT failure in QTh...
I will just try to answer why you are seeing QThread: Destroyed while thread is still running error. If you do this void mtMethod () { Citizen * c = new Citizen(this); QThread thread; c->moveToThread(&thread); connect(&thread, SIGNAL(started()), c, SLOT(ProcessActions())); thread.start(); } The thread object ...
6,901,412
6,901,459
Is it necessary to specialize whole class, when differs just with few members?
I am designing class, which is almost the same for 2d and 3d, so I am trying to use templates, to create it as one class typed by vector type (2d od 3d) Some methods and member are very same for 2d and 3d Some (but very few) methods are slightly different, I use trait here - see doSomething() Some members and method ar...
You can derive from different base classes using mpl::if_ or mpl::if_c. In the branch for 3d you can declare the members and methods needed only for 3d case. Something like this: class LocalSpaceBase2 { vector_type m_up; // ... }; template <typename vectortype> class LocalSpace : public boost::mpl::if_c< ...
6,901,494
6,901,544
Crash on accessing reference to string
This code crashes at the cout line. Can anyone explain why this doesn't work? #include <iostream> #include <string> using namespace std; class myclass { const string& m_str; public: myclass(string s) : m_str(s) {} const string& getString() const { return m_str; } }; int main () { const string str("hone...
the myclass constructor is taking a string by value which makes it a temporary. You're then binding this temporary to the m_str member. As soo as the constructor exits your member reference becomes invalid. Instead: myclass(const string& s) : m_str(s) {} Even so that may not be a good idea. Generally speaking using ref...
6,901,540
6,903,656
EvtSubscribe and threading
I am trying to write a log forwarded for Windows. The plan is simple - receive an event notification and then write it over a TCP socket. This MSDN example shows that I should be using EvtSubscribe. However, I am confused as to how I should share the file descriptor for the open TCP socket. Will the EvtSubscribe callba...
The docs are quite sparse in details, but I reckon that it works as follows: If you use the subscription callback, then it will be called in a dedicated thread. So, if you delay in it, it will block further callbacks, but not other thread of the program If you use the SignalEvent, it will get signaled when the event a...
6,901,631
6,901,756
How to resolve this linking error
I have a class A, that is an abstract base class.(C++). Now, I have two classes B and C which inherit from A; I have a virtual destructor in A; The constructor in class A is protected. Now, in the constructors of B and C, I have included a call to A's constructor. B::B():A() { //do something } similarly for C C::C():A...
Firstly, there's really no need to "call" the base class constructor explicitly. The default constructor of the base class will be called for you automatically. Secondly, as @DeadMG already noted, the error you are getting suggests that you explicitly declared the A::A() constructor, but forgot to define it.
6,901,640
6,901,711
Is it possible to declare an object of one class in the constructor of another class in C++?
Is it possible to initialize objects of one class in the constructor of another class in c++? I usually will declare objects only in the main(), however I am curious to know if this is possible and a good practice. What are the implications with "new" and a case without "new" operator. Where does it get destroyed? e.g...
About your actual question, yes this is perfectly good practice (as far as declaring A inside B's constructor goes). This will work and properly call A's destructor. However: About the code snippet you posted, allocating two objects in A's constructor is not good practice. If operator new for h fails, then w will be le...
6,901,745
6,901,974
Function call constant propagation in C++
I couldn't find the answer through searching, so next step is asking. Say I have some code like this: template<class Int> inline Int onbit(Int value, int n) { return value | (static_cast<Int>(1) << n); } If I call the code, like this onbit(A, 4), would the constant 4 be propagated through and optimized, or should I ...
You can't guarantee that all compilers will optimize this code, although most modern compilers (MSVC and gcc) will, at least in most cases (it depends on the context) without regard to const-ness, since the function is so simple. On the other hand, you can't guarantee that any compiler will optimize it strictly better ...
6,901,916
6,953,407
class initialization problem
Program works fine,but memory validator reports error UNINITIALIZED READ on line CProfiles profile; Is that "profile" definition of class CProfiles outside CProfiles body a bad programming practice ? Here is my code: inside profiles.cpp #include "profiles.h" CProfiles profile; // Here it reports the problem KeyProfi...
Update: Actually I found a problem. It is the static initialization order fiasco. More information about the problem is for example here:Constructors - How do I prevent the "static initialization order fiasco"? And here is the solution inside my code: // in profiles.cpp //CProfiles profile; // Insted this, I access th...
6,902,106
6,902,145
simple way to detect that [console] app is running under MSVC
This is for debugging purposes, my C++ console app needs to behave a little differently when it runs under MSVC (2008) vs when it is run notunder MSVC. Is there simple way to detect that it runs under msvc ? Thanks
The IsDebuggerPresent function returns true when running under the debugger. Here's a list of all available debugger related functions.
6,902,195
6,902,223
Functor question in Visual Studio 2010
#include <iostream> class myFunctorClass { public: myFunctorClass(int x) : _x(x) {} int oprator() (int y) {return _x + y;} private: int _x; } int main(void) { myFunctorClass addFive(5); std::cout << addFive(6); std::cin.get(); return 0; } This is example code from here: ...
There are at least two problems here -- in C++, unlike C# / Java, etc., you need a semicolon after your class declaration. The other issue is that you have misspelled "operator."
6,902,348
6,902,436
is std:vector<char[30]> valid, or how to achieve this? (vector of fixed sized array?)
I would like to have a notion of 2d arrays with one dimension fixed. something like a growing list of char arrays of length 30. Can i do something like vector is that valid, or is there a way of achieving this
No: the type stored in a vector (or any other Standard Library container) must be both copyable and assignable. An array is neither. You can (and should) use std::array (or, if your implementation doesn't support that, boost::array). The array class template provides a very lightweight container-like wrapper around ...
6,902,411
6,909,376
Possible ways of implementing a dynamic barrier in mulithreaded programs
I read this in a paper... Consequently, our tool only checkpoints a thread when it is executing at a known safe point: kernel entry, kernel exit, or certain interruptible sleeps in the kernel that we have determined to be safe. The thread that initiates a multithreaded fork creates a barrier on which it waits ...
The paper you're asking about appears to be "Respec: Efficient Online Multiprocessor Replay via Speculation and External Determinism". The paper mentions: We modified the Linux kernel to implement our techniques. and We therefore created a new Linux primitive, called a multithreaded fork, that creates a child proce...
6,902,490
6,902,607
Kind of RAII to manage GUI state in Qt
I would like to know if you think it is reasonable to use a pattern similar to RAII to manage GUI state in Qt. By GUI state I mean the following: I've some widgets (including the mouse cursor state) I want to go (not) visible/enabled/changed after I leave some method, and I don't want to put everything I do in a giant ...
It's completely reasonable. The technique you're after is called ScopeGuard, called ScopeExit in Boost. The idea is that you define some code you want to run at the end of the scope when you first make your changes, and the rest is handled. You can "dismiss" the code if desired. I'd type an example but I'm on my phone...
6,902,550
6,902,830
Adding namespace declarations to many files?
Say I have a lot of c++ files that I want to add namespace declarations to. i.e. I want the file to look like: //pre-processor commands and other stuff not in the namespace namespace foo { //previously existing code } //EOF Any way to do this without having to open each file manually? Best I've been able to come u...
#!/bin/bash for f in *.h do line=`grep -n '^#' $f | tail -1 | cut -f1 -d:` head -$line $f > tempfile echo 'namespace foo {' >> tempfile let line++ tail --lines=+$line $f >> tempfile echo '} // end namespace foo' >> tempfile mv tempfile $f done This will go through each header file in the current director...
6,902,779
6,902,865
Question about () operator overloading
class Message { public: std::string getHeader (const std::string& header_name) const; // other methods... }; class MessageSorter { public: // take the field to sort by in the constructor MessageSorter (const std::string& field) : _field( field ) {} bool operator (con...
You got it - It's probably a typo, it should read bool operator()(const Message& lhs, const Message& rhs)
6,902,981
6,903,048
General programming question about scope
This is more of a general programming question so the code examples I give will just be pseudo-code. I program in C++, Java, and Python so the pseudo-code is a mix of those. I am not too sure what the name of this is called so if you could give me a name for this, I can Google for more information about it I would grea...
I am not too sure what the name of this is called... I am having trouble following your pseudo-code, but you might be able to accomplish what you're looking for via: Inheritance, which allows derived classes to access protected variables from a base class (static or instance variables) Friend functions (C++) (which ...
6,903,107
6,903,167
Fellow C++ programmer needs some help
// rememb-o-matic #include <iostream> #include <new> using namespace std; int main () { int i,n; int * p; cout << "How many numbers would you like to type? "; cin >> i; p= new (nothrow) int [i]; if (p == 0) cout << "Error: memory could not be allocated"; else { for (n=0; n<i; n...
why is their a bracket enclosed in variable i? & Why is it deleting []p instead of the variable p? p= new (nothrow) int [i]; Dynamically Allocates an int array of i elements . delete []p; Deletes the dynamically allocated array. Basic Rules of dynamic allocation in C++ are: If you use new to dynamically allocat...
6,903,383
15,216,417
MySQL Query executes but throws exception
My code: try { sql::Driver *driver; sql::Connection *con; sql::Statement *stmt; /* Create a connection */ driver = get_driver_instance(); con = driver->connect("tcp://127.0.0.1:3306", "root", "123456"); stmt = con->createStatement(); stmt->executeQuery("CREATE USER 'user22'"); del...
You are using executeQuery, which supposed to return sql::ResultSet object, and you are quering "CREATE USER" which returns true or false. There is an execute method for such cases. So... stmt = con->createStatement(); stmt->execute("CREATE USER 'user22'"); won't throw an error. Yeah, i know that the post is 2 years ...
6,903,524
6,903,593
Name of Cocoa widget and its Qt equivalent
This is probably a simple question, but it's hard to Google. What is the name of the widget / way to create a box "coming from under the window" in Cocoa? What I mean is something like the conversion interface in the Mac OS X Calculator: And secondly, is there a widget that can do this in Qt? Thanks
It's a sheet, as Nathanial says. Read about how to make one in Qt on Qt/Mac Special Features.
6,903,540
6,903,570
Xcode and Objective-C++ can't find <cstdio>
I'm writing Cocoa code that uses some classes defined in a C++ library. I give the filename the extension .mm, and things are usually fine. But not always. Sometimes Xcode 4 disappoints me with: "Lexical or Preprocessor issue: 'cstdio' not found". I can't figure out how to make Xcode find it. Nor can I figure out...
It still should be able to find <stdio.h> just fine. Edit: The .mm file should work fine all the time. Make sure in your build settings that Compile Source As is set to According to File Type
6,903,591
6,903,695
Template Implicit Conversions
With the code: template <typename T> class MyClass { public: MyClass(const MyClass& other) { //Explicit, types must both match; } template <typename U> MyClass(const MyClass<U>& other) { //Implicit, types can copy across if assignable. ...
You can't make the compiler generate a pseudo-copy-constructor-template for you. Why? Because MyClass<T> can be something entirely different from MyClass<U> This isn't my original answer. I had misunderstood the question, sorry
6,903,646
6,905,035
Inheriting from a COM class
I'm working in Visual Studio 2005 with a pure unmanaged project (C++). I have a COM class, from a third party, in a OCX file. This class is a control ("widget"). I've been using it through a IDispatch wrapper class generated using the Add Class from Typelib Wizard. I would like to extend this class in a few ways and pu...
It is not possible to inherit from COM classes as you can in C++. There are workarounds though: COM Aggregates Forwarding COM aggregates is only useful if you want to add an interface (with implementation) to an existing COM class. You cannot intercept calls to the aggregated object. Forwarding means that if you have...
6,903,932
6,904,121
Uninitialized read problem
Program works fine (with random crashes) and Memory Validator reports Uninitialized read problem in pD3D = Direct3DCreate9. What could be the problem ? init3D.h class CD3DWindow { public: CD3DWindow(); ~CD3DWindow(); LPDIRECT3D9 pD3D; ...
Edit: Your stack trace is very, very strange- inside the USER32.dll? That's part of Windows. What I might suggest is that you're linking the multi-byte Direct3D against the Unicode D3D libraries, or something like that. You shouldn't be able to cause Windows functions to trigger an error.
6,903,992
6,904,094
Simultaneous Execution of Functions
I am creating an application which must execute a function that takes too long (lets call it slowfunc()), which is a problem, since my application is working with a live video feed. By running this function every frame, the frame rate is severely affected. Is there a way to run slowfunc() in the background without usi...
Run it in a thread and after the calculation is finished, make the thread sleep until another calculation is ready to be run. That way you are not hit with the initialization of the thread every time.
6,904,016
6,904,158
When using the builder pattern in C++, is it advisable for the setters to return a reference to the builder object?
I am thinking of using the builder pattern in C++ unit tests, to streamline the creation of input data for the code being tested. In Java the common idiom seems to be to have the setters of the builder class return the (reference to) the builder object itself, so that multiple setters can be chained in a single line. ...
Yes it's a common practice, it's called a "Fluent API". The canonical example: while ((std::cin >> std::setbase(16) >> i >> s).getline(s2)) { ... }
6,904,373
6,904,663
Is the C++ Standard Library replaceable?
Is the C++ standard library tied to the compiler or can a different implementation be provided? I wonder about this mostly because it seems that the relation between the typeid keyword and std::type_info hinders this. The typeid keywords depends on the existence of std::type_info, which I would consider to be a depende...
Large parts of the library are independent of the compiler, like containers and algorithms. Other parts are very much tied to a specific compiler, like you have found - type_info where the library rather documents what the compiler does rather than prescribes it. Other similar examples might be bad_exception, std::si...
6,904,804
6,905,660
Mitigating "type-validate then use" code duplication pattern
One of modules of the system deals with a JSON-based protocol that is used to transfer a wide variety of data. This results in almost a hundred of small sections of code that look like this: /* * Data package Foo reports Fooness level */ if(root.isMember("foo") && root["foo"].isInt()) { int foo = root["foo"...
You didn't list out the types of things like bar, so I'm just using Bar for that type. You can give yourself some helper methods, making use of status codes or exceptions, depending on how common you expect failures to be. bool get_string(std::string& result, const Bar& bar, const char* name) { if(bar.isMember(name) ...