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
3,493,415
3,493,440
Is there a way to prohibit the use of a class by value in c style variable arguments list?
Accidential use of classes inside of c style typeless variable arguments list is a common error source. Example: class MyString { public: char *pChars; int Length; MyString(char *pChars) { this->pChars = pChars; Length = strlen(pChars); } }; int main() { MyString s1("Bla1...
Decent compilers (like gcc) check whether printf arguments match format specifiers in format string. Just do not forget to add -Wformat or -Wall command line option. http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
3,493,796
3,493,838
Global variable destructors not called, where to start?
I'm faced with the problem that my applications global variable destructors are not called. This seems to occur only if my application successfully connects to an oracle database (using OCI). I put some breakpoints in the CRT and it seems that DllMain (or __DllMainCRTStartup) is not called with DLL_PROCESS_DETACH, thus...
The most common situation I encounter where this occurs is a program crash. In certain circumstances crashes can happen silently from an end user perspective. I would attach a debugger to the program, set it to break on all native exceptions and run the scenario.
3,493,933
11,841,016
Can't write TIFF files using Libtiff on Mac
TIFFWriteScanline works on Windows and Linux but fails on Mac Updated question: I use libtiff3.9.4 for reading and writing TIFF files in c++ on mac 10.6.4. My project is written to be portable and runs without any issues on both Windows 32-bit og Ubuntu 64-bit. But on the mac the Libtiff function TIFFWriteScanline alwa...
I moved this question to the LibTiff mailing list a long time ago, but i forgot to give the answer here, so here it is: I inserted printf and modified some TiffError messages in the Libtiff code, and it turned out that these changes did not show anywhere when my program failed. After searching for at few hours i found ...
3,494,026
3,495,680
Good practice for choosing an algorithm randomly with c++
Setting: A pseudo-random pattern has to be generated. There are several ways / or algorithms availible to create different content. All algorithms will generate a list of chars (but could be anything else)... the important part is, that all of them return the same type of values, and need the same type of input argumen...
Thank you for all your great input. I decided to go with function pointers, mainly because I didn't know them before and they seem to be very powerfull and it was a good chance to get to know them, but also because it saves me lot of lines of code. If I'd be using Ruby / Java / C# I'd have decided for the suggested Str...
3,494,137
3,494,480
Why in this call to AfxWinInit I get a warning C6309?
while doing some static code analysis I've found a weird one. On a call like this one: if(!AfxWinInit(moduleHandle,NULL,::GetCommandLine(),0) I get the warning C6309 at the second parameter (C6309: argument 2 is null: it does not adhere to function specification of AfxWinInit) Docs say that for Win32 applications the ...
friend BOOL AFXAPI AfxWinInit(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_z_ LPTSTR lpCmdLine, _In_ int nCmdShow); That looks wrong to me, the 2nd argument should have been annotated as _In_opt_. From the SAL Annotations documentation: Optional Option Describes if the buffer itself is ...
3,494,340
3,494,371
Dealing with large amounts of data in c++
I have an application that sometimes will utilize a large amount of data. The user has the option to load in a number of files which are used in a graphical display. If the user selects more data than the OS can handle, the application crashes pretty hard. On my test system, that number is about the 2 gigs of physic...
There is the STXXL library which offers STL like containers for large Datasets. http://stxxl.sourceforge.net/ Change "large" into "huge". It is designed and optimized for multicore processing of data sets that fit on terabyte-disks only. This might suffice for your problem, or the implementation could be a good star...
3,494,520
3,494,645
Camera rotation (OpenGL)
I am having trouble with a camera class I am trying to use in my program. When I change the camera_target of the gluLookAt call, my whole terrain is rotating instead of just the camera rotating like it should. Here is some code from my render method: camera->Place(); ofSetColor(255, 255, 255, 255); //draw axis l...
From the POV of the terrain, yes, the camera is rotating. But, since your view is from the POV of the camera, when you rotate the camera, it appears that the terrain is rotating. This is the behavior that gluLookAt() is intended to produce. If there is something else that you expected, you will need to rotate only t...
3,494,889
3,495,041
C++ How to replace a function but still use the original function in it?
I want to modify the glBindTexture() function to keep track of the previously binded texture ID's. At the moment i just created new function for it, but then i realised that if i use other codes that use glBindTexture: then my whole system might go down to toilet. So how do i do it? Edit: Now when i thought it, checkin...
One possibility is to use a macro to replace existing calls to glBindTexture: #define glBindTexture(target, texture) myGlBindTexture(target, texture) Then in you code, where you want to ensure against using the macro, you surround the name with parentheses: (glBindTexture)(someTarget, someTexture); A function-like ma...
3,495,139
3,495,507
Calling a virtual base class's overloaded constructor
Is there a (practical) way to by-pass the normal (virtual) constructor calling order? Example: class A { const int i; public: A() : i(0) { cout << "calling A()" << endl; } A(int p) : i(p) { cout << "calling A(int)" << endl; } }; class B : public virtual A { public: B(int i) ...
Unfortunately, you will always have to call the virtual base classes constructor from the most derived class. This is because you are saying that the virtual base is shared between all classes that derive from it for the instance of the object. Since a constructor may only be called once for a given instaniation of an ...
3,495,337
3,495,448
What key was pressed? Keyboard hooks
I'm using low level hooks, but I can't determine what key was pressed. Values are the same for every single key. Is here something I'm doing wrong? Hook method void hook() { /** this part is probably not important since I use global WH_KEYBOARD_LL, is that right? */ HWND hwnd = FindWindow(NULL, "Vertices.exe")...
KBDLLHOOKSTRUCT *kbdStruct = (KBDLLHOOKSTRUCT*)lParam; :)
3,495,339
3,543,854
Writing a simple ActiveX control for IE that has one method
I'm learning how to write a scriptable ActiveX control. My goal is to have a tiny control that can check to see if something is installed on the system. What I've done so far is: Create a MFC ActiveX control project in VS2008 Add some 'safe for scripting' bits that I found here. Extend the IDL to provide my "IsInstall...
You almost certainly have the wrong prototype for a scriptable function. OLE Automation for scripting languages tends to rely on returning a HRESULT then using an out parameter for the actual return code. So change it to [id(1)] HRESULT IsInstalled(VARIANT_BOOL* p); Also TRUE != VARIANT_TRUE, you must return VARIANT_TR...
3,495,428
3,495,499
Boost::tribool: odd behaviour, or bug?
I'm exploring boost::tribool and was surprised by the following behaviour. { using namespace boost; boost::tribool t(indeterminate); assert(t==indeterminate); // This assertion fails! } However, if I do this, the assert passes. assert(indeterminate(t)); No compiler warnings or errors in either case. Anyone have a...
I think the answer is in the documentation: the result of comparing two indeterminate values is indeterminate (not true) - we don't know what the values are, so we can't tell that they are equal; the indeterminate function can be used to test if a tribool is in an indeterminate state.
3,495,449
3,495,469
C++ "Variable not declared in this scope" - again
I guess this is a really simple question and, probably, one that has been answered several times over. However, I really do suck at C++ and have searched to no avail for a solution. I would really appreciate the help. Basically: #ifndef ANIMAL_H #define ANIMAL_H class Animal { public: void execute(); void setNam...
void setName( char* _name ) { name = _name; } should be void Animal::setName( char* _name ) { this->name = _name; } You need to have Animal:: if you use the this parameter. Without Animal:: it thinks you are just creating a new global function called setName
3,495,539
3,495,621
Help with understanding this algorithm
I would like to implement the Ramer–Douglas–Peucker_algorithm in C++. The pseudo code looks like this: function DouglasPeucker(PointList[], epsilon) //Find the point with the maximum distance dmax = 0 index = 0 for i = 2 to (length(PointList) - 1) d = OrthogonalDistance(PointList[i], Line(PointList[1], PointList[...
The OrthogonalDistance is shown in this picture: So it's the distance from your point and the point on the line which is the projection of that point on the line. The distance from a point to a line is usally something like this: (source: fauser.edu) where x0 and y0 are the coordinates of the external point and a, b,...
3,495,548
3,495,622
Adding locks to the class by composition
I'm writing thread-safe class in C++. All of its public methods use locks (non-recursive spin locks). Private methods are lock-free. So, everything should be OK: user calls public method, it locks object and then does the work through private methods. But I got dead lock when a public method calls another public method...
I'm not sure why recursive mutexes would be considered bad, see this question for a discussion of them. Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex) But I don't think that's necessarily your problem because Win32 critical sections support multiple entries from the same thread without blocking. From the doc: Wh...
3,495,612
3,496,451
How to obtain stacktrace when tracking memory leaks?
I've written a memory tracking system in c++ using Detours to patch the various memory allocation functions. When I receive a call to malloc in addition to the malloc I also store the stacktrace (so I can pin point the leak). The only reliable way to obtain an accurate stacktrace is to use StackWalk64 (I tried RtlCaptu...
Could you use a thread-local flag in your malloc implementation to prevent the recursive calls to StackWalk64?
3,495,850
3,495,881
Can a std::vector be ='d to another std::vector?
Say I have the following: std::vector<int> myints; and then I have a function that returns an int vector: std::vector<int> GiveNumbers() { std::vector<int> numbers; for(int i = 0; i < 50; ++i) { numbers.push_back(i); } return numbers; } could I then do: myints = GiveNumbers(); would doing this safely make it so...
Yes. This is safe. You will be copying the results from your GiveNumbers() function into myints. It may not be the most efficient way to do it, but it is safe and correct. For small vectors, the efficiency differences will not be that great.
3,495,927
3,495,951
Does this pseudocode assume a zero based index?
I'm not sure if when they write 1 if this is the first or second element in the array: function DouglasPeucker(PointList[], epsilon) //Find the point with the maximum distance dmax = 0 index = 0 for i = 2 to (length(PointList) - 1) d = OrthogonalDistance(PointList[i], Line(PointList[1], PointList[end])) if d >...
At a guess, it looks like index 1 is the first element in the array (otherwise the first element is never being indexed anywhere). The best way to tell for sure is probably to try it though :)
3,496,308
3,498,229
How to create a direct3d texture of a web page rendered by MSHTML in C++?
I have integrated a web page inside my native C++ Application through MSHTML (Microsoft Rendering engine of IE). What I want to do now is to generate a LPDIRECT3DTEXTURE9 (Direct3d texture) of the displayed web page. Is it possible ? Do you know how to ? Thanks in advance for all your answers.
Do you need to capture the 'visible' portion of a rendered webpage, or the entire webpage, regardless of length/width? If its the latter, Rob Manderson wrote a good article on achieving this with the IHTMLElementRender interface. His article can be found here: http://www.codeproject.com/KB/IP/htmlimagecapture.aspx If y...
3,496,412
3,497,116
Embeddable Cross-Platform Web Browser?
I'm wondering if there is a Web Browser that I can embed in my Applications and that is cross-Platform (Windows, OS X, Linux)? I'm undecided about the programming language, but I guess I'll have to go the C++ route (in which case I'd likely choose Qt as a GUI Framework) unless something for .net/mono or Java exists? Do...
As @Andrey noted in his comment WebKit is itself embeddable. If you use Qt then you can easily embed it into your application using QtWebKit.
3,496,561
3,496,674
Polymorphism and checking if an object has a certain member method
I'm developing a GUI library with a friend and we faced the problem of how to determine whether a certain element should be clickable or not (Or movable, or etc.). We decided to just check if a function exists for a specific object, all gui elements are stored in a vector with pointers to the base class. So for example...
You could just have a virtual IsClickable() method in your base class: class Widget { public: virtual bool IsClickable(void) { return false; } }; class ClickableWidget : public Widget { public: virtual bool IsClickable(void) { return true; } } class SometimesClickableWidget : public Widget { public: virtual...
3,496,678
3,496,827
gslice definition in C++
I have some misunderstanding about the gslice function. Definition from MSDN states: gslice defines a subset of a valarray that consists of multiple slices of the valarray that each start at the same specified element. The ability to use arrays to define multiple slices is the only difference between gslice and slice...
See this description from cplusplus.com. It includes a diagram as to what the function is actually doing.
3,496,754
3,496,910
VC++ says "no overloaded function takes 7 arguments" I say YES IT DOES!
In my PDBComponent class's header file, I just created a new constructor for a grand total of two constructors: class PDBComponent { public: PDBComponent(string name,double min_current,double nom_current, double max_current, EPSCommands* command_ptr, double delay); PDBComponent(...
So, you get an error when the 6-parameter constructor is being compiled when you've commented it out in the header - but is that the same source file that contains the calls to the constructor? Is it possible that a different header is being used for that compilation somehow (maybe precompiled header weirdness is invo...
3,496,901
3,503,480
How to handle IHttpSecurity::OnSecurityProblem having a IWebBrowser2 object
I can't seem to understand how i give my implementation of the IHttpSecurity::OnSecurityProblem to my IWebBrowser2 object. I know that i need to implement a class something like this: class CServiceProvider : public IServiceProvider { public: CServiceProvider(); ~CServiceProvider(); // IUnknown ULONG STDMETHO...
I already figure out how this is done. Using MFC we only need to implement CCustomOccManager that implements the COccManager in witch the implementation of CreateSite function returns an implementation of our COleControlSite (example CCustomControlSite). In this class you will need to override at least the QueryService...
3,496,982
3,497,021
How can I print a list of elements separated by commas?
I know how to do this in other languages, but not in C++, which I am forced to use here. I have a set of strings (keywords) that I'm printing to out as a list, and the strings need a comma between them, but not a trailing comma. In Java, for instance, I would use a StringBuilder and just delete the comma off the end af...
Use an infix_iterator: // infix_iterator.h // // Lifted from Jerry Coffin's 's prefix_ostream_iterator #if !defined(INFIX_ITERATOR_H_) #define INFIX_ITERATOR_H_ #include <ostream> #include <iterator> template <class T, class charT=char, class traits=std::char_traits<charT> > class infix_o...
3,497,022
3,497,072
Reverse a c-type string
Here is my code: void reverseStr(char *str) { if (str == NULL) return; int i=0, j=strlen(str) -1; while(i<j) { char temp = str[j]; //i think this is the cause of the problem str[j] = str[i]; str[i] = temp; i++; j--; } } So here is where it is called: int...
Str pointes to a fixed string. You are modifying it in place. In other words, you trying to change the text literal. Try this: char *str = strdup("Forest Gump"); reverseStr(str); cout << str; free(str);
3,497,310
3,497,421
Substring search interview question
char* func( char* a, const char* b ) { while( *a ) { char *s = a, *t = b; while( (*s++ == *t++) && *s && *t ); if( *t == 0 ) return a; a++; } return 0; } The above code was written to search for the first instance of string "b" inside of string "a." I...
If a points to "cat" and b points to "ab", func will return a pointer to "at" (the wrong value) instead of 0 (the intended value) because the pointer t is incremented even though the comparison (*s++ == *t++) fails. For completeness' sake and in order to answer the second question, I'd offer one solution (surely among ...
3,497,329
3,497,363
Likeliness of Named RVO?
I have a function that looks like this: // Fetch 1 MB of data void GetData(std::vector<char> & outData); The 1MB is exaggerated, but I just want to make the point that it's preferable to avoid unnecessary copies. If I add this overload: std::vector<char> GetData() { std::vector<char> result; GetData(result); ...
With most reasonably recent compilers (e.g., VS 2005 or newer, gcc 3.4 or newer), it's essentially certain. I only say "most" because I haven't tested every compiler in existence. Every new compiler I've looked at in probably the last 5 years or so has included it.
3,497,569
3,497,584
Is There Any Way to Use C++ Ifstream to Read in Every Tenth Row?
I have a file with thousands of lines, each one representing a point of a line. The number of chars on each line is variable. Im plotting these lines, but i only want to plot every tenth line. I know i could just do something like: for (int k = 0; k < 9; k++) { File.getline(buf, 1024); } but i was wondering if the...
In general, no. Unless your lines are fixed length or otherwise have some hints in them as to where the next lines are, you have no choice but to scan the file for newlines and throw away intervening characters.
3,497,655
3,505,377
QWizardPages to keep their own minimum sizes
I'm working with Qt (version 4.6 on Windows XP 32-bit and compiling in Qt Creator 2.0.0) and trying to get a QWizard to work out. First Problem: I have three QWizardPages in my QWizard so far. Each page has a QVBoxLayout applied as it's layout. My first page has very small content (just a three line QLabel) but for som...
To fix this problem, I created a child class of QWizard and created a private slot like this: void ChildClass::fitContents(int id) { adjustSize(); // this automagically resizes the window to fit the contents } And made it had it called every time the page was changed, like so: connect(this, SIGNAL(currentIdChanged...
3,497,694
3,504,845
Simplifying a cubic bezier path?
I'm trying to achieve something close to what Adobe Illustrator does with the brush tool. It correctly analyzes and simplifies the path, including its bezier handles. I implemented the Ramer–Douglas–Peucker_algorithm however, it wound up not really being what I needed. It works very well for line segments, but doesn't ...
You probably want to explore least squares fitting for Bezier curves. Here's one thread and a pdf that may be helpful.. I did this sort of thing several years ago, and found one of Gerald Farin's books helpful, but I can't remember which one.
3,497,734
3,497,909
Pointer of a 2D array in C++?
I am writing a function to rotate a NxN matrix by 90 degree. Here is my function // "matrix" is an n by n matrix void rotateMatrix(int ** matrix, int n) { for(int layer=0; layer < n; layer++) { int first = layer, last = n - layer -1; for(int i=0; i<n; i++) { int temp = matr...
Are the dimensions of the matrix known at compile time? If so: template <size_t n> void rotateMatrix(int (&matrix)[n][n]) { ... }
3,497,803
3,497,886
Privacy of member variables within the methods of other member variables
Do the methods of a member variable have access to other private member variables within the same class? I have in mind a functor member variable. Can a pointer to a private member variable be dereferenced and assigned to, outside of the class? What about in the method of another member variable? Maybe something like...
Whenever you are calling the method of a member variable, unless its type is the class being defined, you won't have access to private member variables. If you give access (somehow) to a pointer to a member variable, without precising that it is "const", yes, it can be dereferenced and assigned to. The same assertion i...
3,497,861
3,498,322
Creating threads that copy the arguments passed to them
I'm currently using boost::thread, because it very conveniently allows me to pass an arbitrary number of arguments to the thread and copies them along the way, so I don't have to worry about them being deleted before the thread launches. Is there any other library that allows this, or a way to simulate it using pthread...
I don't remember the details of Boost.Thread, but the general idea is something like this: class thread_function_base { public: virtual ~thread_function_base(void) {} virtual void run(void) = 0; }; template <typename Func> class thread_function_0 : public thread_function_base { public: thread_function_0(co...
3,498,014
3,498,114
calling c code from c++
how does a call from c++ to c work internally??
It is a heavy duty implementation detail. But most C++ compilers I know don't try to do anything special to differentiate a C function from a non-instance C++ function. Just the plain olden cdecl calling convention for both. Kinda important because the CRT implementation, with functions like printf(), are just as usa...
3,498,096
3,498,139
C++ virtual function not found
I have a class designed to do import/export of data in one of a few different formats. Each format should have exactly the same interface, so I'm implementing it as a base class with a bunch of virtual methods and a derived class for each specific format: #ifndef _IMPORTEXPORT_H_ #define _IMPORTEXPORT_H_ #include "std...
By the time this dtor gets called: exportfile::~exportfile() { assert(this->hFile != 0); this->endSection(); fclose(this->hFile); this->hFile = 0; } the compiler has 'unwound' the vtable so it will resolve to the exportfile::endSection() function - it will not call the derived version. You'll need t...
3,498,240
3,498,485
Problem with CreateDC and wglMakeCurrent
PIXELFORMATDESCRIPTOR pfd = { /* otherwise fine for a window with 32-bit color */ }; HDC hDC = CreateDC(TEXT("Display"),NULL,NULL,NULL); // always OK int ipf = ChoosePixelFormat(hDC,&pfd); // always OK SetPixelFormat(hDC,ipf,&pfd); // always OK HGLRC hRC = wglCreateContext(hDC); // always OK wglMakeCurrent(hDC,h...
I've got a dormant brain cell from reading Petzold 15 years ago that just sprang back to life. The DC from CreateDC() is restricted. Good for getting info about the display device, measurement, that sort of stuff. Not good to use as a regular painting DC. You almost certainly need GetDC().
3,498,246
3,498,295
Banning MAC address from accessing certain port - C++
I want to stop someone with a certain MAC address from accessing a certain port on my server, I'm using this as a sort of hardware ban for a private server a friend of mine runs. I am looking to do this in C++, and would like to know what I would need to research in order to do it. The server runs Windows. Also, how w...
Filtering on MAC addresses is only useful if the server and client are on the same LAN. The server will see the MAC address of the nearest upstream router, not the client's MAC address.
3,498,430
3,498,546
Using the ndisprot example driver (in the WDK) with C++
I have compiled succesfully the ndisprot example ndis driver that came with the Windows Driver Kit, but I don't know how to use it from C++ to send or receive packets. Could someone instruct me on how?
Review the .html file for details. The prottest sample app that exercise the driver is available in the src\network\ndis\ndisprot\60\test directory. Shows you how to use the Read/WriteFile and DeviceIoControl functions.
3,498,444
3,498,473
C++ static const access through a NULL pointer
class Foo { public: static const int kType = 42; }; void Func() { Foo *bar = NULL; int x = bar->kType; putc(x, stderr); } Is this defined behavior? I read through the C++ standard but couldn't find anything about accessing a static const value like this... I've examined the assembly produced by GCC 4.2, Clang++, ...
You can use a pointer (or other expression) to access a static member; however, doing so through a NULL pointer unfortunately is officially undefined behavior. From 9.4/2 "Static members": A static member s of class X may be referred to using the qualified-id expression X::s; it is not necessary to use the class...
3,498,730
3,498,750
Is C++ an Object Oriented language?
I have always heard that C++ is not Object Oriented but rather "C with Classes". So, when I mentioned to an interviewer that C++ was not really object oriented, he asked me why I didn't consider it an OO language. I haven't done any C++ since University, and I didn't have much of an answer. Is C++ Object Oriented or ...
C++ is usually considered a "multi-paradigm" language. That is, you can use it for object-oriented, procedural, and even functional programming. Those who would deny that C++ is OO generally have beef with the fact that the primitive types are not objects themselves. By this standard, Java would also not be considere...
3,498,850
3,498,874
Error Performing Pointer Arithmetic on void * in MSVC
Error 1 error C2036: 'const void *' : unknown size file.cpp 111 I don't follow. GCC never complains about void * pointer arithmetic, even on -ansi -pedantic -Wall. What's the problem? Here's the code- struct MyStruct { const void *buf; // Pointer to buffer const void *bufpos; // Pointer...
You can't do pointer math on a void * pointer. Cast oData->bufpos and oData->anotherConstVoidPtr to something the compiler knows how to deal with. Since you seem to be looking for sizes, which are presumably in bytes, casting to char * should work: if (((char *)oData->bufpos + someSize_t) ...
3,499,101
3,507,906
When do we need a .template construct
I made the following program #include <iostream> #include <typeinfo> template<class T> struct Class { template<class U> void display(){ std::cout<<typeid(U).name()<<std::endl; return ; } }; template<class T,class U> void func(Class<T>k) { k.display<U>(); } int main() { Class<i...
The < symbol means both "less than" and "begin template arguments." To distinguish between these two meanings, the parser must know whether the preceding identifier names a template or not. For example consider the code template< class T > void f( T &x ) { x->variable < T::constant < 3 >; } Either T::variable or T...
3,499,295
3,501,527
How do I check if a table exists in sqlite3 c++ API?
I'm opening a database file and potentially creating it if it doesn't exist. But for some reason, this doesn't create the table. Any ideas? const char* sql = "CREATE TABLE IF NOT EXISTS blocks(id text primary_key,length numeric)"; sqlite3_stmt *stmt; rc = sqlite3_prepare_v2(db_, create_table_sql, -1, &stmt, NULL); rc...
Variation on another given answer: select count(type) from sqlite_master where type='table' and name='TABLE_NAME_TO_CHECK'; Will return 0 if table does not exist, 1 if it does.
3,499,325
3,501,106
What's a portable value for UINT_MIN?
In limits.h, there are #defines for INT_MAX and INT_MIN (and SHRT_* and LONG_* and so on), but only UINT_MAX. Should I define UINT_MIN myself? Is 0 (positive zero) a portable value?
If you want to be "typesafe" you could use 0U, so if you use it in an expression you will have the correct promotions to unsigned.
3,499,353
3,499,378
C++ calling child virtual member from parent virtual member
I create a parent class that calls it's own virtual member. But this virtual member is overridden by child class. class Parent { public: void doSomething() { doVirtual(); } protected: virtual void doVirtual() {} }; class Child : public Parent { protected: virtual void doVirtual() {} }; Parent ...
If the functions don't do anything (or do exactly the same thing) how do you know that when you run the executable directly it calls the parent method? Have the 2 functions actually do something different - the compiler might be 'coalescing' the functions if they're identical (though I'd expect that to be less likely ...
3,499,446
3,499,464
C++ iterating through files and directories
I'm working on a C++ program that will automatically backup my work to my FTP server. So far I am able to upload a single file, by specifying a file name using this CString strFilePath = szFile ; int iPos = strFilePath.ReverseFind('\\'); CString strFileName = strFilePath.Right((strFilePath.GetLe...
Since you are using MFC, you can use the CFileFind class. Example code is given in MSDN. Alternatively, you can use boost.filesystem for the same.
3,499,529
3,499,536
c++ redefine variable as constant
I have a struct: struct s { UINT_PTR B_ID; }; s d; d.B_ID=0x1; That works fine, but I want d.B_ID to be constant. I tried to use (const) but it didn't work. So after I put a value to d.B_ID, then I want make it a constant. Any ideas? EDIT ok i don't want the whole struct a constant. when i set timer and use th...
Variable modifiers are fixed at compile time for each variable. You may have to explain the context of what you are trying to do, but perhaps this will suit your needs? struct s { int* const B_ID; }; int main (void) { int n = 5; s d = {&n}; int* value = d.B_ID; // ok // d.B_ID = &n; // error return 0; } ...
3,499,565
3,499,598
Member templates ,Statemement From ISO C++ Standard?
can any one explain this? "Overload resolution and partial ordering are used to select the best conversion function among multiple template conversion functions and or non-template conversion functions." Please explain with a program..... the statement is from ISO C++ Standard 14.5.2 section ,point 8
struct S{ template<class T> operator T(){return T();} operator int(){return 0;} }; int main(){ S s; int xi = s; // both template and non template are viable. Overload res chooses non tmpl char xc = s; // both template and non template are viable. Overload res chooses tmpl } Edit: After first commen...
3,499,899
3,500,005
c++ structures and constructures
ok so i nee help with this constructures struct balls { balls() { SetTimer(hWnd, balls.BALL_ID, 1, null); } int Ex; int Ey; UINT_PTR BALL_ID; }; well when i set the timer im having trouble with balls.BALL_ID. the compiler thinks that balls is structure like balls...
BALL_ID is a member of the balls struct so when you want to use it within a member function you don't need to prefix it with the name of an instance. So just initialize BALL_ID then use it: struct balls { balls( UINT_PTR id ) : BALL_ID( id ), Ex( 0 ), Ey( 0 ) { SetTimer(hWnd, BALL_ID, ...
3,499,927
3,499,947
Postfix-expression evaluation
I am trying to write a program for evaluating postfix-expression code: #include <iostream> #include <cstring> #include <stack> #include <ostream> using namespace std; int main(int argc,char *argv[]){ char *a=argv[1]; int n=strlen(a); stack<int>s; for (int i=0;i<n;i++) { if (a[i]=='+') ...
The pop function justs pops but does not return anything. You should use the top to get the top value and then call pop So s.push(s.pop() * s.pop()); should be changed to: int temp1 = s.top(); s.pop(); int temp2 = s.top(); s.pop(); s.push(temp1 * temp2);
3,500,232
3,500,259
Declare an object in C++ w/o creating it?
Is this possible? For example if i write Car myCar; Then the constructor taking no arguments of Car is called. It results in an error if there is only a constructor taking arguments. In Java I can easily declare an object and create it later using the exact same statement as above.
No, this is not possible. You could come up with some dirty hacks based on placement new which may get you close, but I doubt you are interested in them. Why do you want to do that? Perhaps there is some clean way how to achieve that in a C++ style. If you only want to create a variable which will point to some object ...
3,500,301
3,500,341
Can gcc/g++ tell me when it ignores my register?
When compiling C/C++ codes using gcc/g++, if it ignores my register, can it tell me? For example, in this code int main() { register int j; int k; for(k = 0; k < 1000; k++) for(j = 0; j < 32000; j++) ; return 0; } j will be used as register, but in this code int main() { registe...
You can fairly assume that GCC ignores the register keyword except perhaps at -O0. However, it shouldn't make a difference one way or another, and if you are in such depth, you should already be reading the assembly code. Here is an informative thread on this topic: http://gcc.gnu.org/ml/gcc/2010-05/msg00098.html . Ba...
3,500,336
3,500,377
Polymorphic QSharedPointer
I'm trying to use QSharedPointer in my polymorphic stucture, but I couldn't find right syntax to convert pointer of base class to pointer of derived class. struct Switch : State { int a; }; QSharedPointer <State> myState=QSharedPointer <State>(new Switch); QSharedPointer <Switch> mySwitchTest= ??? myState; What s...
Use qSharedPointerCast(): QSharedPointer <Switch> mySwitchTest= qSharedPointerCast<Switch>(myState); Or call staticCast() on the smart pointer: QSharedPointer <Switch> mySwitchTest= myState.staticCast<Switch>(); Both versions are basically equivalent to doing static_cast on raw pointers.
3,500,380
3,500,463
c++ structs and const
ok well i have structure struct balls { balls(UINT_PTR const &val) : BALL_ID(val){} int Ex; int Ey; const UINT_PTR BALL_ID; }; balls ball1(0x1); and i have a switch statement switch(wParam) { case ball1.BALL_ID: if(ball1.Ex<300) { bal...
The case labels must be integral constant expressions -- they must be evaluable during translation (i.e. at compile). In this case, BALL_ID cannot be evaluated at compile-time. Different ball objects are allowed to have different BALL_ID values, hence the compiler cannot possibly evaluate it during translation. Futher,...
3,500,503
3,532,624
Check COM Interface still alive?
In COM how does one verify that a pointer to a COM object still has a valid object on the other end? I have an issue where this following bit of code attempts to check if the m_pServer pointer is still alive, however when that application exposing that interface is killed this bit of code crashes the application. Can ...
What you're trying to do here is simply not possible. Because m_pServer lives in another process you're really asking the following question Is Process XXX still running? This is simply not an answerable question in the world of windows (or linux / unix). You can never reliably answer the question because the mom...
3,501,181
3,501,321
File synchronization library
I'm looking into C/C++ libraries (Win/Linux) that allow me to synchronize information over network. I want to run multiple instances of my program (on different PC's), and want to synchronize files locally instead of accessing files remotely over the network at a single location. If all instances are to maintain DB con...
I think the design space for such a thing is pretty huge, but it reminded me of a kinda cool library I saw the other day, VAST. The idea is that it's a spatially-represented distributed publish/subscribe model. Maybe it is adaptable to your purpose. Another thing that is probably immediately useful if you are most in...
3,501,195
3,505,532
Fastest OLEDB read from ORACLE
What would be the fastest way of retrieving data from the Oracle DB via OLEDB? It should be portable (have to work on Postgres and MS SQL), only one column is transfered (ID from some large table). Current performance is 100k rows/sec. Am I expecting too much if I want it to go faster? Clarification: datatable has 23M...
What the heck, I'll take a chance. Edit: As far as connectivity, I HEARTILTY recommend: Oracle Objects for OLE, OO4O for short. It's made by Oracle for Oracle, not by MS. It uses high-performance native drivers, NOT ODBC for a performance boost. I've personally used this myself on several occasions and it is fast. I wa...
3,501,353
4,932,281
Creating groups of CMake options
I am using CMake to manage a build of a collection of projects on Linux, not a single project but the principle is the same. Each project has its own collection of options, for example DEVEL switches and custom code to be included. These are added in the standard CMake way: OPTION(NAME "Helpstring" VALUE) I am looking...
Both commenters are correct here: the cmake-gui program (the Qt-based gui) groups options together based on leading prefix up to the first underscore character. The ccmake program (the ncurses-based "gui") does not have the same grouping capability yet.
3,501,698
3,503,791
Is C++ and .NET used together in Domains like Banking , Health Care and Telecom
This may seem relevant but it has some significance for me,may be few others like me. I just want to know ,How Important is it to Learn C++ , COM and ATL while you are a .NET programmer? I love programming with .NET and C# .Visual Studio just has it's own charm of intellisence ,Color Coding and other pretty features , ...
I learnt plain old C 25 years ago and C++ 13 years ago and used each daily (until something better came along). Since I started working with C# and .Net about 6-7 years ago I have had to use my previous C++ skills exactly once... (and I Googled the specific answer on that occasion anyway!). Unless you intend to specia...
3,501,890
3,502,010
Factory method anti-if implementation
I'm applying the Factory design pattern in my C++ project, and below you can see how I am doing it. I try to improve my code by following the "anti-if" campaign, thus want to remove the if statements that I am having. Any idea how can I do it? typedef std::map<std::string, Chip*> ChipList; Chip* ChipFactory::createChi...
You are right, you should use a map from key to creation-function. In your case it would be typedef Chip* tCreationFunc(); std::map<std::string, tCreationFunc*> microcontrollers; for each new chip-drived class ChipXXX add a static function: static Chip* CreateInstance() { return new ChipXXX(); } and also register...
3,501,912
3,501,931
Why are default arguments trailing ones?
Why are default arguments in C++ trailing ones?
if you had void func(int a = 0, int b);, how would you specify to use the default parameter in calling this function?
3,502,013
3,502,097
What is the very last place where you can execute logic in a Windows executable?
In my application, I want to execute logic at the very last moment. The later, the better. The reason for this is that I keep track of certain elements in my application (data structures, resources, ...), and at the end of the application, a routine looks at these elements and reports if they were not correctly closed...
Use /ENTRYPOINT. In your custom entry point, call the CRT entry point and then your final logic.
3,502,280
3,522,186
How to add/subtract to value rather than just be that value
Using the Openframeworks library in C++, I have the radius of a glow (max_distance) that is determined by the stretch of the mouse dragging across the screen (mouseDragX). It works fine. But rather than every time I resize it (by dragging the mouse), I want it not to start at 0 and follow the mouse drag directly. max_d...
If I understand correctly, you want todo something like this. // Every time the mouse *stops* moving, (say on mouse-up // message) save previous max_distance int base = max_distance; // when mouse moves max_distance = base + mouseDragX/2;
3,502,530
3,503,738
Using Visual Studio project properties effectively for multiple projects and configurations
I have always used Visual Studios built in GUI support for configuring my projects, often using property sheets so that several projects will use a common set. One of my main gripes with this is managing multiple projects, configurations and platforms. If you just do everything with the main GUI (right click the projec...
I just found out somthing I didnt think was possible (it is not exposed by the GUI) that helps make property sheet far more useful. The "Condition" attribute of many of the tags in the project property files and it can be used in the .props files as well! I just put together the following as a test and it worked great ...
3,502,680
3,502,694
Does c++0x tuple use the new variadic templates or Boost's macro-fied tuple implementation?
I read it was based on Boost's version, but I wasn't quite sure what that meant when it came down to implementation. I know Boost does their own variadic template, but I would assume c++0x would use its own variadic templates for the new tuple.
The tuple in the C++0x draft standard uses C++0x variadic templates. It is declared as (§20.4.1): template <class... Types> class tuple; Note, however, that the TR1 language extensions also include tuple, which does not use variadic templates, since there was no such thing when TR1 was written. In TR1, tuple is decl...
3,502,684
3,503,802
Determine windows DPI settings programmatically?
we've got a problem with one of our non dpi aware MFC applications. If you change the system setting to high dpi (e.g. 120 or 144 dpi), the application icon on the taskbar looks screwed up. Unfortunately, we have to register our own WNDCLASS for the mainframe, and in the WNDCLASS.hIcon member you have to set an icon. T...
You will have to add a manifest to your program (or edit the existing one) to turn DPI Virtualization off. It should look like this: <assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3" > <asmv3:application> <asmv3:windowsSettings xmlns="http://s...
3,502,687
3,502,787
What is a reference in C?
I have just started C++ and have come across references and have not understood completely. References , as i read is an alternative name for an object.Why use that instead of directly accessing the object as any operation on references is directly reflected on the object ...? Why and when are they used ? Is ist like...
Why use that instead of directly accessing the object as any operation on references is directly reflected on the object ...? C++ passes parameters by value, meaning if you have a function such as: void foo(MyObject o) { ... } By default C++ will make a copy of a MyObject, not directly use the object being pas...
3,503,008
3,503,176
Is concurrently overwriting a variable with the same value safe?
I have the following situation (caused by a defect in the code): There's a shared variable of primitive type (let it be int) that is initialized during program startup from strictly one thread to value N (let it be 0). Then (strictly after the variable is initialized) during the program runtime various threads are star...
It's incredibly unlikely but not impossible according to the standard. There's nothing stating what the underlying representation of an integer is, not does the standard specify how the values are loaded. I can envisage, however weird, an implementation where the underlying bit pattern for 0 is 10101010 and the archite...
3,503,072
3,503,377
Should an abstract class' destructor be pure virtual?
I think virtual alone is generally sufficient. Is there another reason to make it pure virtual than to force derived classes to implement their own destructor? I mean if you allocate something in your class' constructor you should impement your own destructor - if your class is derived or not. Doesn't count as answer a...
If you want your class abstract and it has no pure virtual functions - leave it to the destructor. Actually, I don't think there's more. All the pure virtual destructor does, is make the whole class abstract. You have to provide the implementation for the pure virtual destructor as well as for a non-pure virtual ...
3,503,263
3,503,294
What is the best way to sync computer time with an internet time server?
I need to get the current time from one of internet time server in my desktop application. I suppose I need something like a request string and a regular expression to get time from any site that user wants (may be with several predefined sites). Or may be there are some free libraries exist? Thanks.
This is what the Network Time Protocol was built for. But it's probably something best left to your operating system, lest you end up with duelling applications using different, not-quite-synchronised servers. See the headings in the link above for UNIX and Windows implementations.
3,503,573
3,503,600
What is the purpose of "typename" in C++
Possible Duplicate: Officially, what is typename for? When I use template <typename TMap> typename TMap::referent_type * func(TMap & map, typename TMap::key_type key) { ... } what is the purpose of the two "typename"'s on the second line? It seems to trigger a compile-time warning (VS2008: C4346) but it's only a "...
The typename keyword just tells the compiler that whatever identifier follows is a valid type. This is important in templates because the compiler may not yet have the definitions of the types used in the templates, but you still want to be able to use part of that type's definition (e.g., like key_type above). If yo...
3,503,874
3,504,330
Symbols files and debugging
Assume i have a custom service written in VC++ 6.0 and i have shipped it as part of a particular release. Unfortunately i did not take the pdb while building the binary. At a later point of time my customer reported a crash and i had to get the pdb to identify the crash cause. Will a pdb that i take now be enough to id...
You'll need to make sure you compiled with exactly the same compiler version (patches could change code generation and addresses), set of compiler/linker options, the same library versions as well as the same source to make sure the addresses match. If you're able to do that then you should be able to take a pdb genera...
3,503,934
3,504,854
How do I detect memory access violation and/or memory race conditions?
I have a target platform reporting when memory is read from or written to as well as when locks(think mutex for example) are taken/freed. It reports the program counter, data address and read/write flag. I am writing a program to use this information on a separate host machine where the reports are received so it does ...
It is probably too late to talk you out of this, but this does not work. Threading races are caused by subtle timing issues between threads. You can never diagnose timing related problems with logging. Heisenbergian, just logging alters the timing of a thread. Especially the kind you are contemplating. Infamously,...
3,504,142
3,533,516
Cloning rapidxml::xml_document
How do I get a complete copy of a RapidXML xml_document? There is a clone_node function; how to use to to create a complete copy of an existing document?
I'm sure there's a cleaner, tree-based approach, but I solved it with the following, where str is the xml output from another doc: xml_document<> doc; doc.parse<0>(doc.allocate_string(str));
3,504,156
3,504,245
How to insert xml into Mysql?
this questions looks really easy but I'm a noob in C++ and MySQL so it still doesn't work. Here is the deal: I have a string (_bstr_t) that contains the xml and I want to store it in a longblolb column in MySql. Ways I tried that failed: write my xml on a local file and use mysql command LOAD_FILE, this worked local...
As far as I know it's really easy as microsoft provides ::char* for that. If you have your string in a _bstr_t object, just do mysql_real_escape_string(your_object::char*), that should do the trick. If that fails, you can also use strcncpy. You could do that like this: char xml[200]; _bstr_t the_xml_you_loaded; strcnc...
3,504,189
3,504,276
Help with this issue
My application allows rotating points around a center based on the mouse position. I'm basically rotating points around another point like this: void CGlEngineFunctions::RotateAroundPointRad( const POINTFLOAT &center, const POINTFLOAT &in, POINTFLOAT &out, float angle ) { //x' = cos(theta)*x - sin(theta)*y //y' = sin...
If you subtract the old rotation from the new one, you'll get a value you should be able to use to rotate the already-modified points. Note that this requires storing the old rotation, and the coordinates will get less and less accurate the more you translate them around. It's close enough for government work, though...
3,504,215
3,504,226
What does the colon mean in a constructor?
Possible Duplicates: C++ weird constructor syntax Variables After the Colon in a Constructor What does a colon ( : ) following a C++ constructor name do? For the C++ function below: cross(vector<int> &L_, vector<bool> &backref_, vector< vector<int> > &res_) : L(L_), c(L.size(), 0), res(res_), backref(backref_)...
This is a way to initialize class member fields before the c'tor of the class is actually called. Suppose you have: class A { private: B b; public: A() { //Using b here means that B has to have default c'tor //and default c'tor of B being called } } So now by writting: c...
3,504,238
3,504,536
New to C++, help me get started
Im a Java programmer, with a little C knowledge who wants to get started with with C++ can someone recommend a good tutorial? also any help with: projects to learn with recommended reading what IDE ? I currently use NetBeans general C++ advice
Depends on your target platform, I use Visual Studio as an IDE. The general rule of C++ as opposed to Java is that it contains a hell of a lot more freedom than Java, especially as regards to templates vs generics, the stack vs the heap, and the enforcement (or lack thereof) of object orientation and it's principles. ...
3,504,504
3,504,527
Find out what version of Boost was used to compile an executable/DLL
Is there any way to use "strings" or some otehr command to decide what version of Boost was used to compile a particular executable or .so? All I have is the executable/.so itself.
Boost is mostly a header-only library, with extensive use of templates (which all compiles down to probably some optimized binary). Given only the executable binary, you're most likely not be able to deduce the Boost version used. Probably the only way you'll know what Boost version is used by looking at the executable...
3,504,642
3,505,243
generate a truth table given an input?
Is there a smart algorithm that takes a number of probabilities and generates the corresponding truth table inside a multi-dimensional array or container Ex : n = 3 N : [0 0 0 0 0 1 0 1 0 ... 1 1 1] I can do it with for loops and Ifs , but I know my way will be slow and time consuming . So , I ...
If we're allowed to fill the table with all zeroes to start, it should be possible to then perform exactly 2^n - 1 fills to set the 1 bits we desire. This may not be faster than writing a manual loop though, it's totally unprofiled. EDIT: The line std::vector<std::vector<int> > output(n, std::vector<int>(1 << n)); decl...
3,504,868
3,564,578
Extract XML embedded in another XML using PugiXML
Is there an easy way in PugiXML to unescape and load an XML embedded in another XML.
Here it is xml_parse_result pr = doc.load_buffer_inplace( (void * )response.c_str(), response.size() ); if (pr.status!=status_ok) return pr; xml_node resultXml = doc.child("soap:Envelope"); resultXml = resultXml.child("soap:Body"); resultXml = resultXml.child( (webmethodName + "Response").c_str() ); resultXml = re...
3,504,961
3,504,970
Porting VC 6.0 Application to VS 2003 VC++ application
I have an application which is written in VC++ using VC 6.0 version. Now i open the project in VS2003. Does my project now have any link or relation with .Net framework as i am not using the .Net framework. Will the VC 7 compiler bring about a relationship with . Net.
No, there is no requirement to use .NET with VS 2003 (or VS 2008 or VS 2010). You can bring your VC 6.0 project over to VS 2003 and it will still be a native project.
3,505,176
3,505,205
How can I scan another process memory to find what follows a specific string?
I want to scan the entire heap of a currently running native application through another process. For example, I want to know what follows all the instances of the ASCII sequence "test" in this process memory (in this case I would scan for "test" and keep reading after it). I tried to google for more information but di...
Try VirtualQueryEx. If you're finding that you're accessing a lot of memory in the other process, consider using CreateRemoveThread (sample code). This will allow you to inject your own DLL into the other process and run code there directly. Once you're running code in the other process, you'll be able to access memory...
3,505,336
3,511,752
Find current users active directory group C++
How would I go about querying what active directory group the currently logged in user belongs to? I am assuming it will be through LDAP but I havnt been able to find much on how to get this particular information. I have put together some code but im not quite sure what I need to do next // Open the access token a...
In your particular case I think you can do without any LDAP calls. Here's a suggestion: use GetCurrentProcessId and OpenProcess to get a handle to the current process call OpenProcessToken on that handle to open the access token associated with the current process call GetTokenInformation on that access token, with a ...
3,505,343
3,505,403
Can I call `delete` on a vector of pointers in C++ via for_each <algorithm>?
Suppose I have a std::vector<Obj *> objs (for performance reasons I have pointers not actual Objs). I populate it with obj.push_back(new Obj(...)); repeatedly. After I am done, I have to delete the pushed-back elements. One way is to do this: for (std::vector<Obj *>::iterator it = objs.begin(); it != objs.end(); ++it) ...
Your problem is that delete is not a function, but rather a keyword and as such you can't take it's address. In C++0x, there will be a std::default_delete class (used by std::unique_ptr), which you could use, or - as everyone's saying - writing one yourself would be trivial (the standard one also raises a compile error...
3,505,347
3,505,391
Converting a byte swapping/shifting code snippet from C++ to .NET
I have a short code snippet in C++ and I need to have the same functionality in C#: typedef enum {eD=0x0, eV=0x1, eVO=0x2, eVC=0x3} eIM; #define htonl(x) ( ( ( ( x ) & 0x000000ff ) << 24 ) | \ ( ( ( x ) & 0x0000ff00 ) << 8 ) | \ ( ( ( x ) & 0x00ff0000 ) >> 8 ) | \ ...
enum eIM { eD = 0, eV, eVO, eVC } int value = System.Net.IPAddress.HostToNetworkOrder((int)eIM.eV);
3,505,352
3,505,422
portable way to create a timestamp in c/c++
I need to generate time-stamp in this format yyyymmdd. Basically I want to create a filename with current date extension. (for example: log.20100817)
strftime #include <stdio.h> #include <stdlib.h> #include <time.h> int main() { char date[9]; time_t t = time(0); struct tm *tm; tm = gmtime(&t); strftime(date, sizeof(date), "%Y%m%d", tm); printf("log.%s\n", date); return EXIT_SUCCESS; }
3,505,525
3,505,646
Question about STDIN STDOUT STDERR
I'm designing a MIPS simulator in c++ and my simplified OS must be able to run stat() occasionally (when a program being executed on my simulator requires an input or an output or something.) The problem is, I need to be able to assert STDIN, STDOUT, and STDERR as parameters to stat "stat("stdin",buff)" where buff is...
On a POSIX system, you can use fileno() to convert from a FILE* (e.g. stdin, stdout, stderr) to an integer file descriptor. That file descriptor can be sent to fstat().
3,505,639
3,505,948
How to setup visual studio for cross platform c++ development
After some time mainly .net development, i need to work in c++ in a cross platform manner. I don't want to give up visual studio, so my hope was that it is possible to use visual studio and the windows target as a testbuild, and then every once in a while through means of a vm test the code on linux or mac. Does anyone...
First of all, select a non-managed C++ project (to avoid the .net stuff). After that, turn up the warning level (/W3 should do), and be very careful what you do/write. IMHO, GCC is better at keeping you straight with the standard (-Wall -Wextra -pedantic -std=c++11), but you specify MSVC. As Noah said, you'll need bui...
3,505,668
3,505,961
How to compute a point on a line in CGAL
Given a 3D line in CGAL, how do I compute a point on that line that is some known distance from an endpoint?
If you have two points P0 and P1, you can make a vector V = P1 - P0. Given distance D from P0, you can get the resulting point R = P0 + (D ÷ ||V||) ⋅ V. (Linearly interpolate between the lines, changing D into a percentage by dividing by the full length of the line.) I don't know CGAL (and the documentation kind of su...
3,505,674
3,524,693
Comparing SIFT features stored in a mysql database
I'm currently extending an image library used to categorize images and i want to find duplicate images, transformed images, and images that contain or are contained in other images. I have tested the SIFT implementation from OpenCV and it works very well but would be rather slow for multiple images. Too speed it up I t...
So I basically did something very similar to this a few years ago. The algorithm you want to look into was proposed a few years ago by David Nister, the paper is: "Scalable Recognition with a Vocabulary Tree". They pretty much have an exact solution to your problem that can scale to millions of images. Here is a link...
3,505,686
3,505,798
However convert a memory to a byte array?
Now I have a database, which one field type is an array of byte. Now I have a piece of memory, or an object. How to convert this piece of memory or even an object to a byte array and so that I can store the byte array to the database. Suppose the object is Foo foo The memory is buf (actually, don't know how...
There are two methods. One is simple but has serious limitations. You can write the memory image of the Foo object. The drawback is that if you ever change the compiler or the structure of Foo then all your data may no longer loadable (because the image no longer matches the object). To do this simply use &Foo as the ...
3,505,713
3,505,738
C++ template compilation error: expected primary-expression before ‘>’ token
This code compiles and works as expected (it throws at runtime, but never mind): #include <iostream> #include <boost/property_tree/ptree.hpp> void foo(boost::property_tree::ptree &pt) { std::cout << pt.get<std::string>("path"); // <--- } int main() { boost::property_tree::ptree pt; foo(pt); return 0;...
You need to do: std::cout << pt.template get<std::string>("path"); Use template in the same situation as typename, except for template members instead of types. (That is, since pt::get is a template member dependent on a template parameter, you need to tell the compiler it's a template.)
3,505,790
3,505,816
Empty while loop not checking condition
In a multithreaded C++ program, I have the equivalent of this running in one thread: while(obj->member) { } // waiting for obj->member to be set to false in another thread and in another thread, obj->member is set to false. Even when it's set to false, however, the loop doesn't break. If I change it to this: while(obj...
Try making member volatile. This will force it to be fetched from memory each time it is used, rather than from a CPU register (which is how the compiler might optimise it.)
3,505,830
3,505,879
Why does calling free () on a pointer allocated with 'new' cause heap corruption?
Does it actually work on some compilers/machines but on others it causes heap corruptions and crashes? Does anyone have any insight into what going on under the covers?
C++ wants to call a destructor on the object when you use delete, but passing it to free doesn't allow this to happen. If the object contained other objects then those objects' destructors would not be called either. If the object had pointers in it then those wouldn't get freed. Additionally C++'s new and delete cou...
3,505,872
3,505,953
Retrieve xml from MySQL
I'm a noob at C++ and MySQL and I only want to retreive a xml file stored as a longblob in MySQL. I did a SELECT query to get the content and after I store this content in a xml file with std::ofstream. With this i get: <?xml version="1.0" encoding="UTF-16"?> <AnObject noNamespaceSchemaLocation... instead of this: <?...
You question is similar to this question: SQL Server - Storing linebreaks in XML data type And the highest ranked answer says you need to use a VARCHAR (or a TEXT) data type. However, this question discusses the best practices of storing XML in a database, and it recommends storing XML outside the database. (And if ...
3,506,000
3,507,247
Disambiguating argument-less function calls in variadic class hierarchies
I am trying to provide users of a class (MyGizmo below) that derives from a variadic hierarchy (ObjGetter below) with a simple, uncluttered way to unambiguously call a member function that takes no arguments (check() below). I can make this work with functions that take arguments (like tune() below) but I have not foun...
You need a member function template check<Type> with some kind of structure to delegate up the inheritance chain if the type does not match the head of the variadic list. This is a classic problem for SFINAE. template< class Obj2 > typename std::enable_if< std::is_same< Obj, Obj2 >::value, Obj * >::type check() c...
3,506,026
3,506,459
Clone abstract base class (without meddling with derived)
I'm experiencing a challenging problem, which has not been solvable - hopefully until now. I'm developing my own framework and therefore trying to offer the user flexibility with all the code complexity under the hood. First of all I have an abstract base class which users can implement, obviously simplified: class ISt...
If I understand the problem correctly, you shouldn't insert new T -s into the map, but rather objects that create new T-s. struct ICreateTransit { virtual ~ICreateTransit() {} virtual IStateTransite* create() const = 0; }; template <class T> struct CreateTransit: public ICreateTransit { virtual IStateTran...
3,506,113
3,506,389
c++ high memory and cpu
ok well i have a simple game that uses really high of memory and cpu. cpu goes over 44% and memory goes over 5000. here is my code Code how to fix this? EDIT memory: 5000 bytes. cpu: 44% on i5 the program get slower by the time it runs.
The best way to tackle something like this is to comment-out big chunks of code until you stop seeing runaway CPU/memory, and then gradually uncomment those chunks until you identify the problem. After a quick scan of the code, I do wonder why you are starting eleven timers to update your game objects. It would be bett...