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
4,544,440
4,545,827
How to design a client server architect
I like to know the server (TCP based) architecture to support large scale of clients(at least10K) to implement Fix server. My points are How we design it. How to listen on the open port? Use select or poll or any other function. How to process the response of the client? On large scale we cannot create the one thread f...
The architecture depends on what you want to do with the clients incoming data. My guess is that for every incoming message you would perform some computations and probably also return a response. In that case I would create 1 main listener thread that receives all the incoming messages (Actually, if your hardware has ...
4,544,740
4,544,772
C++ compiler template error information - tool to decode the error information
All, Question 1 while using templates, Compiler error information is known to be very cryptic (In the sense not readily readable by a newbee eyes) - though compiler nowadays tries best to put as much information as possible during coding problem. Is there a chance - that the error information is more better in some...
If your platform can't support clang for some reason try STLFilt to get sensible errors.
4,544,804
4,545,241
In what cases should I use memcpy over standard operators in C++?
When can I get better performance using memcpy or how do I benefit from using it? For example: float a[3]; float b[3]; is code: memcpy(a, b, 3*sizeof(float)); faster than this one? a[0] = b[0]; a[1] = b[1]; a[2] = b[2];
Efficiency should not be your concern. Write clean maintainable code. It bothers me that so many answers indicate that the memcpy() is inefficient. It is designed to be the most efficient way of copy blocks of memory (for C programs). So I wrote the following as a test: #include <algorithm> extern float a[3]; extern f...
4,544,897
4,544,947
ID3DX10Mesh::CloneMesh
I'm trying to copy mesh in DirectX10. I wrote this: HR(mesh->CloneMesh(mesh->GetFlags(),data.GetPosSemantic(),data.GetInputElementDesc(), data.GetDescCount(),&mMesh)); but when i try to render the mesh nothing appers on the screen. when i write mMesh = mesh; There are no problems with the rendering(unless w...
If you want to duplicate the mesh without any changes, you should use the second approach and call then mMesh->AddRef() to declare the data is owned by two pointers (better idea is to use some kind of smart pointers - COM or boost::shared_ptr adapted to COM-like objects). But the first case should work too - what is th...
4,545,047
4,545,077
C++,function overloading problem
I am having a trouble in this example.Whenever I send any arguments,it gives compiler error: prog.cpp: In function ‘int main()’: prog.cpp:11: error: call of overloaded ‘add(std::basic_istream<char, std::char_traits<char> >&, std::basic_istream<char, std::char_traits<char> >&)’ is ambiguous prog.cpp:4: note: candidates ...
cin >> x returns cin, not x. Try cin >> a >> b; add(a, b); Also syntax like cin >> a, b is invalid, use >> multiple times.
4,545,239
4,545,345
Problem in Breadth First Search
cin>>t; while (t--) { cin>>n; cin>>m; if (n==m) cout<<"0\n"; else { //Breadth First Search Tree: queue <gnode*> gqueue; bft_data bft=bft_data(); list<gnode>* gp; list<gnode>::iterator it; gp=_gfind(graph,n);// finds list containing gnode...
I haven't looked through your first code extract, but the second extract might explain the problem: the third argument to memset is a byte count, so you must multiply it by the size of the array element: memset(w,SIZE,SIZE * sizeof(int)); memset(c,0,SIZE * sizeof(int)); memset(pn,NULL,SIZE * sizeof (gnode*));
4,545,308
4,545,447
Visual Studio - sharing resource files
I have multiple projects that have some of the standard dialog boxes the same, and I would like to put these dialogs along with their resources in a separate location, and include these into all of my projects, so I don't have to make changes in all projects every time something is tweaked. What is the best practice to...
Compile them into a separate resource DLL, and then modify the code in each of your projects to access the resources from this DLL instead of from the EXE itself.
4,545,353
4,546,620
How to detect and isolate C++ Access Violation Error
While i was developing a C++ application, I was using a simple list<int> *somelist = new list<int>(); that contains data. I was trying to iterate this list using something like this: for (list<int>::iterator j=somelist->begin();j!=somelist->end();j++) { //do something with *j } When i was doing something with th...
With multi-threading your iterator can become invalidated if some other thread removes elements from the list. With a low-level programming such as C++, there is no way to detect this problem once it has happened. Your best bet is to "prevent this from happening." Use synchronization functions (e.g., WaitForSingleObjec...
4,545,475
4,568,009
how to hide windows 7 switch user button in vc++ CredentialProvider sample
I have provided a screenshot of my CredentialProvider window. In this window everything is fine now but i don't want to show Switch User button to the user. How i can do this. I am just editing Win-7 SDK sample for CredentialProvider (C++). Anyone can help me, or any link for code help. One more thing I want to ask i...
You cannot directly prevent the Switch User button from appearing; if the conditions are present that cause it to appear, then it's going to appear. What you can do however: prevent the conditions that cause it to appear. That button appears either when a tile is in the selected state and 1.) your credential provider ...
4,545,525
4,545,785
Pass char[N] param to thread
i have a variable declared as char myvariable[N] = "blablabla" and i need to pass it to a thread DWORD MyThread(LPVOID lpdwParam) i tried to cast inside the thread function the lpdwParam in char* but it doesn't work. How can i fix it? EDIT 1 Here the complete part of code char myvariable[16]; GetDlgItemTextA(hDlg, I...
If you're doing something like this: // ... char myvariable[N] = "blablabla"; HANDLE hThread=CreateThread(NULL, 0, MyThread, (LPVOID)myvariable, 0); // however you should use beginthread to avoid troubles with the CRT // ... DWORD MyThread(LPVOID lpdwParam) { char * mystring = (char *)lpdwParam; // ... re...
4,545,830
4,589,931
xmlrpc server in dll, sending signal to myself?
I'm writing some dll (on windows in MSVC++2008) which provides some functionality as xmlrpc server. To implement xmlrpc server I'm using xmlrpc-c library. I can start xmlrpc server in some diffrent ways. More intresting are: run method - This will run xmlrpc server forever so dll can't control until server is not term...
Signals (of the kind that makes an Xmlrpc-c library call abort early) don't exist in Windows. Best solution is to create new thread for server.
4,545,868
4,546,107
Detect duplicate definitions of a variable in shared library
It appears GCC linker doesn't care for one variable being defined in two files. I suspect this is the cause of trouble a 3rd party library is causing us. Take this: File a.cpp contains: int foo; //do things with it. File b.cpp contains: int foo; //do other things with it. File c.cpp contains: extern int foo; //...
It seems compiler option -fno-common forces all the variables to be initialized, so it triggers errors upon linking.
4,545,883
4,545,892
C++ Memory Pooling by Subclassing
So I was working on a way to memory pool c++ objects easily with minimal modification needed to the class that needs to be pooled. The memory pool itself is the standard variety you can find anywhere, but I've made this class: Poolable::Poolable(MemPool& lepool){ mempool = &lepool; } Poolable::~Poolable(){ ...
An alternative would be to make Poolable::operator new allocate memory from thepool so that you can use usual (non-placement) new statements. In your solution the user has to remember that those objects are to be allocated via some special technique, that's showing too much details and putting too much burden onto the ...
4,546,021
4,546,562
remove char from stringstream and append some data
In my code there is a loop that adds sth like that "number," to stringstream. When it ends, I need to extract ',' add '}' and add '{' if the loop is to repeated. I thought i can use ignore() to remove ',' but it didn't work. Do you know how I can do what I describe? example: douCoh << '{'; for(unsigned int i=0;i<dataSi...
You can extract the string (with the str() member), remove the last char with std::string::erase and then reset the new string as buffer to the std::ostringstream. However, a better solution would be to not insert the superfluous ',' in the first place, by doing something like that : std::ostringstream douCoh; const ch...
4,546,340
4,546,415
Simultaneous private and public inheritance in C++
Suppose a class Y publicly inherits a class X. Is it possible for a class Z to privately inherit Y while publicly inheriting X? To make this clearer, suppose X defines public methods x1 and x2. Y inherits X, overrides x1 and provides a method y. Does C++ allow for a third class Z to subclass Y in such a way that Y's im...
Yes, this is called virtual inheritance. struct X { virtual void x1(); void x2(); }; struct Y : virtual X { void x1(); // overrides void y(); }; struct Z : private Y, virtual X { }; People cannot do z.y() or z.x1() but they can do z.x2() and can convert a Z* to a X*. However once they do so, they can call...
4,546,491
4,546,693
How to cancel asynchronous read/write without closing the socket?
How to cancel asynchronous read/write without closing the socket? I use boost.asio. Thanks.
Use socket::cancel. Cancel all asynchronous operations associated with the socket.
4,546,507
4,546,553
.lib linking other .libs
Currently my visual studio is basically generating Engine.dll and Game.exe Engine.dll links to some other basic libraries like: d3dx9d.lib ComCtl32.lib WinMM.lib WSock32.lib etc. I also wanted to try to create an Engine.lib, but I get some really nice warnings now: Symbol x has been defined already. These libraries def...
Did you create a different namespace to avoid naming clashes? EDIT -- seems like there is some confusion as to what you're asking, because you are asking a couple of questions. To me, it sounds like you want to take a stab at implementing your own Engine class. However, you've got naming issues. I am treating this as...
4,546,583
4,546,622
Error C2888 migrating from VC9 to VC10
I am trying to compile solutions and projects on MSVC++ 10 that worked fine in MSVC++ 9, and I am having trouble with it, mostly getting the following message: error C2888: 'std::hash' : symbol cannot be defined within namespace 'tr1' on the following code: namespace std { namespace tr1 { template <> struct hash< Rube...
hash is in namespace std in VS2010, as it's part of C++0x's Standard library, not std::tr1. Just remove the tr1 section and the compiler should be fine. template<> class std::hash< Rubedo::eChannelFamily >> : public std::unary_function<const Rubedo::eChannelFamily, size_t> { public: size_t operator()(const Rube...
4,546,634
4,546,666
Intercept HTTP requests
I've some fishy application that makes HTTP requests to a website, i would like to intersect that request and send other data to the server. Is that possible in C#,java or C++? EDIT: The application isn't mine, i just know the endpoint that it sends http requests
Fiddler might provide the functionality you need. At the very least it may enable you to see what is being sent to the web site.
4,546,908
4,566,197
High Level OpenGL Library with PBO support
I want to do some image processing on the GPU and I'm looking for an appropriate library to use. The operations I want to do are: scaling, composition, color space transforms and translations. I have considered OpenCL and CUDA but I believe that OpenGL is more appropriate as most of the operations required are already ...
Qt can do it, but it is a rather vast collection of libraries if you just want one thing out of it...
4,547,073
4,547,317
C++ on Windows: Using DirectInput without a window?
Short version: How do I initialize and use DirectInput if I have no access to the HWND/HINSTANCE? Background information: I am currently using SFML for most parts of my program, amongst others for window creation. Works like a charm. But I'm not fully satisfied with SFML's input system (e.g. I want XInput for XBox 360 ...
Finding the window back isn't too hard, use EnumThreadWindows() and GetCurrentThreadId(). Note that DirectInput doesn't need a window handle anywhere. It just needs the instance handle in DirectInput8Create(). GetModuleHandle(NULL) is good for an SFML app.
4,547,147
4,547,177
global extern const clarification
Is declaring extern const or just extern the same thing in a header file? Also will both give external linkage? globals.cpp #include <string> extern const std::string foo = "bar"; globals.h #ifndef GLOBALS_H #define GLOBALS_H #include <iostream> extern const std::string foo; #endif /* GLOBALS_H */ OR globals.h #...
This one is correct, //globals.h extern const std::string foo; //Consistent Consistent!
4,547,163
4,547,871
C++ to C Wrapper using SWIG (for FLTK)
I need to generate wrapper to FLTK C++ classes to use it in pure C. I know, that SWIG can do that, and I know how to generate wrapper for C#, Python etc. But I do not know how to wrap C++ to C using SWIG. It's simple task, but I can't find the answer :) Please, help.
I don't think SWIG supports generation of C wrappers out of the box. You always need to specify a target language. In 2008, there was a GSoC project to write a C backend, but that was apparently never completed/incorporated into SWIG.
4,547,305
4,547,344
The limitations of the comma operator
I have read this question and I want to add to it that what are the things that can not be done using the comma operator. This has confused me a lot, as I can do this: int arr[3]; arr[0]=1,arr[1]=2,arr[2]=3; But when I do: int arr[3],arr[0]=1,arr[1]=2,arr[2]=3; It gives me a compiler error. I want to ask that what ...
One thing to realize is that not all uses of a comma in C are instances of the comma operator. Changing your second example to be a syntactically declaration: int a0=1,a1=2,a2=3; the commas are not operators, they're just syntax required to separate instances of declarators in a list. Also, the comma used in parameter...
4,547,542
4,548,166
How to turn on and off mfc gui by other class?
i need to make a class that have a pointer to mfc class and to turn on and off the gui and also to have the option to take data from the gui. thank you.
By "turn on and off the GUI" I will assume you mean hide or display the main window, since you haven't provided a good description of what you're looking for. You can use CWnd::ShowWindow with a parameter of SW_HIDE to turn the window off, and use SW_SHOW or SW_RESTORE to show it again. By "option to take data from the...
4,547,660
4,547,772
C++ static member variable and its initialization
For static member variables in C++ class - the initialization is done outside the class. I wonder why? Any logical reasoning/constraint for this? Or is it purely legacy implementation - which the standard does not want to correct? I think having initialization in the class is more "intuitive" and less confusing.It a...
Fundamentally this is because static members must be defined in exactly one translation unit, in order to not violate the One-Definition Rule. If the language were to allow something like: struct Gizmo { static string name = "Foo"; }; then name would be defined in each translation unit that #includes this header fi...
4,547,676
4,547,774
How fast can zlib be on a slow pc?
I have a 500Mhz CPU and 256MB RAM machine running 32bit Linux. I have a large number of files around 300KB in size. I need to compress them very fast. I have set up the compression level for zlib at Z_BEST_SPEED. Is there any other measure I could take? Is it possible to compress 25-30 files like this in a second on su...
You are essentially talking about a 10MB/sec speed. Even if you were to only copy the files from one place to another I would doubt that your slow hardware could do it. So, for compression I would vote No - it's not possible "to compress 25-30 files like this in a second on such a machine".
4,547,778
19,032,726
Is this a bug in boost::range_detail::demote_iterator_traversal_tag of boost::iterator_facade?
Following code: #include <boost/range/adaptor/transformed.hpp> #include <boost/range/join.hpp> struct foo { typedef int result_type; result_type operator ()(int x) { return x; } }; int main() { using boost::adaptors::transformed; int a[] = {1, 2, 3}; boost::join(a | transformed(foo()), a | transform...
In case any future Google users end up here like I did, yes it looks like this was a bug, because it is fixed in at least version 1.54 (probably sooner, I hit the bug using 1.44 and just downloaded the current version).
4,547,795
4,547,886
Inserting multiple rows in an Oracle database with OCCI
This is my first experience so OCCI so I beg your pardon if the answer is obvious. I have a Statement object, created the usual way: string sqlStatement = "INSERT INTO data_tab VALUES(:id, :name, :number, :when)"; m_stmt = m_conn->createStatement(sqlStatement); m_stmt->setMaxIterations(100); Then I need to loop over ...
You should invoke setMaxParamSize() prior to setting a variable length parameter: m_stmt->setMaxParamSize(2, 1000) // or whatever is the max length of your string.
4,547,917
4,550,155
SHGetFolderPath returns path with question marks in it
Our application calls ShGetFolderPath when it runs, to get the My Documents folder. This normally works great. However, for three users - Дмитрий, Jörg and Jörgen (see if you can spot the pattern!) - the call returns some very strange results. For example, for Дмитрий, the call returns: c:\Users\???????\Documents I as...
Go ahead and get the file path in Unicode. Then call GetShortPathNameW to convert to short pathname components. The output shouldn't contain any characters outside of the ASCII range even though it's a Unicode function. You can then truncate each Unicode character back to 8 bits to create a char string.
4,548,004
4,598,865
How to correctly and standardly compare floats?
Every time I start a new project and when I need to compare some float or double variables I write the code like this one: if (fabs(prev.min[i] - cur->min[i]) < 0.000001 && fabs(prev.max[i] - cur->max[i]) < 0.000001) { continue; } Then I want to get rid of these magic variables 0.000001(and 0.00000000001 f...
Thanks for your answers, they helped me a lot. I've read these materials:first and second The answer is to use my own function for relative comparison: bool areEqualRel(float a, float b, float epsilon) { return (fabs(a - b) <= epsilon * std::max(fabs(a), fabs(b))); } This is the most suitable solution for my needs...
4,548,145
4,548,425
Low level details of inheritance and polymorphism
This question is one of the big doubts that looms around my head and is also hard to describe it in terms of words . Some times it seems obvious and sometimes a tough one to crack.So the question goes like this:: class Base{ public: int a_number; Base(){} virtual void function1() {} virtual void ...
As a further illustration, here is a C version of your C++ program, showing vtables and all. #include <stdlib.h> #include <stdio.h> typedef struct Base Base; struct Base_vtable_layout{ void (*function1)(Base*); void (*function2)(Base*); }; struct Base{ struct Base_vtable_layout* vtable_ptr; int a_numb...
4,548,269
4,548,297
Does it make sense to use const in an interface or not?
I have a module that performs some calculations and during the calculations, communicates with other modules. Since the calculation module does not want to rely on the other modules, it exposes an interface like this (this is a very simplified version of course): class ICalculationManager { public: double ...
You make a function const when you are advertising to clients that calling the function will never change the externally visible state of the object. Your object only has one piece of state that can be retrieved, getValue. So, if getValue can cause the next getValue to return a different value then sure, leave it no...
4,548,395
4,548,421
How to retrieve the thread id from a boost::thread?
I want to be able to identify threads by a simple id when logging so that it is easy to trace the execution of a single thread. With windows using the API GetCurrentThreadId() can achieve what I want. In boost::thread there is a method get_id() but this doesn't represent an integral value like an integer. This objec...
Boost includes an operator<<(std::ostream&, const boost::thread::id&) overload that can be used to write a thread id to a stream (actually, the overload is a template and will work with any specialization of std::basic_ostream, not just std::ostream). The result of printing the id is likely platform-specific, since dif...
4,548,515
4,548,536
c++ normalizing data sizes across systems
I have a struct with three variables: two unsigned ints and an unsigned char. From my understanding, a c++ char is always 1 byte regardless of what operating system it is on. The same can't be said for other datatypes. I am looking for a way to normalize POD's so that when saved into a binary file, the resulting file i...
You can find fixed-width integer types (like std::int32_t and std::uint16_t) in <cstdint>. Your C++ Standard Library implementation may not include <cstdint> (it's not part of the current C++ standard; it's part of C++0x), in which case Boost has an implementation that should work on most platforms. Note that you will...
4,548,602
4,548,626
iPhone save game state
I'm implementing a save game feature to my game, so I'm looking for the best way to store the saved game. Since I'm using C++ everywhere it's possible, I can't use NSKeyedArchiver to store the state of the game. I am thinking in saving the state manually in a file, so I have a questions about that: In which subfolder o...
Write the file into the Documents directory (NSDocumentDirectory). Thats the path to save your stuff, you can alter its content in any way by eg. adding subfolders for your save games or whatever. DON'T save it inside the library folder!
4,548,629
4,548,690
Using stringstream instead of `sscanf` to parse a fixed-format string
I would like to use the facilities provided by stringstream to extract values from a fixed-format string as a type-safe alternative to sscanf. How can I do this? Consider the following specific use case. I have a std::string in the following fixed format: YYYYMMDDHHMMSSmmm Where: YYYY = 4 digits representing the year...
One not particularly efficient option would be to construct some temporary strings and use a lexical cast: std::string s("20101220110651184"); int year = lexical_cast<int>(s.substr(0, 4)); // etc. lexical_cast can be implemented in just a few lines of code; Herb Sutter presented the bare minimum in his article, "The S...
4,548,826
4,549,587
How does one write a stream insertion operator for the general case? (That is, for both `char` and `wchar_t` streams?)
I'm implementing a stream insertion operator for a class of mine. I'd like my class to work with both narrow and wide streams. I'm using a template to allow this kind of behavior -- and everything is independent of which stream type is actually used, with the exception of character literals. If it's a wide string, the ...
If you don't want the runtime overhead, I think that, although ugly, a macro can help you in this case. template <typename T> inline const T* select(const char* narrow, const wchar_t* wide); template <> inline const char* select<char>(const char* narrow, const wchar_t* /*wide*/) { return narrow; } template <> inl...
4,548,973
4,555,792
Resolve formatted table value in wix custom action
I've created certificate wix extension (extension of IisExtension). This includes a custom table, which is consumed by a custom action. A column is defined as follows: <columnDefinition name="Account" type="string" length="72" primaryKey="yes" modularize="property" category="formatted" description="..." /> This...
WcaGetRecordFormattedString is what you're looking for.
4,549,000
4,549,014
How to increase a maximum packet size for UDP?
I am usually sending packets that range from 3 to 15 KB but from time to time I need to send a large packet which is about 0.8-0.9 MB. In that case the UDP socket will stop because there is probably some limit on a single packet size. How can I increase this limit so I can send large packets?
The length field in the UDP packet header is only 16 bits in width; you can't have a single UDP packet larger than 65,535 bytes (that includes the header, too, so really the limit is 65,527 bytes; it's probably even lower still since IP has other restrictions).
4,549,004
4,550,266
CAtlRegExp expression issue w/ begin/end anchors
I have some code that uses the CAtlRegExp to perform some validation. In the particular case, a zip-code (5 or 5-4 format). In addition, I want the data to be exactly that, so I'm using anchors (^ and $). When I use the anchor-less expression the Match call succeeds. When I add the anchors, the Match call fails with th...
Edit: Completely changed my answer when I figured out the problem. The CAtlRegExp class does not support the repeat count in curly braces {}; it uses those for returning match objects. The 5 and 4 in your expression were literal characters that it had to match. It's just a coincidence that the string you were testing ...
4,549,151
4,549,167
C++ Double Address Operator? (&&)
I'm reading STL source code and I have no idea what && address operator is supposed to do. Here is a code example from stl_vector.h: vector& operator=(vector&& __x) // <-- Note double ampersands here { // NB: DR 675. this->clear(); this->swap(__x); return *this; } Does "Address of Address" make any se...
This is C++11 code. In C++11, the && token can be used to mean an "rvalue reference".
4,549,214
4,549,265
Shortest Program in c++
I came across this code recently that compiles, but runs with segmentation fault(g++). Here's the original link from topcoder topcoder profile #include <iostream> int main = ( std::cout << "Hello world!\n", 42 ); This also compiles int main=0; Can someone explain what's happening in this program. Using g++
This is all silly games. Both programs violate the requirement "a program shall contain a global function called main" (3.6.1p1). Those programs may fool some compilers because they define a symbol main, but that symbol is not a function at all! No wonder at least one of them crashes when the runtime tries to use th...
4,549,227
4,549,300
Shall I store a parent pointer in a tree/graph node?
I am developing a tree/graph like data structure. It should be more like a directed acyclic graph. One of the requirements is to find the path from root to a specific node, which means when user pick a node, the path from the root would be highlighted. So, the question is shall I store a parent pointer in each node? Or...
Generally, you store a pointer back to the parent only if you are going to be using algorithms that require it. Otherwise, it is unnecessary overhead both in terms of the memory used to store the pointer and the extra complexity of updating those pointers when you insert a node or rebalance/reorganize the tree. The ty...
4,549,257
4,549,268
Copy Constructor Doubt
Possible Duplicate: Why should the copy constructor accept its parameter by reference in C++? In wikipedia, it is mentioned that - The following are invalid copy constructors (Reason - copy_from_me is not passed as reference) : X (X copy_from_me); X (const X copy_from_me); because the call to those constructors w...
Both copy constructors use pass-by-value. When pass-by-value is used, a copy must be made of the argument. That copy is made by calling the copy constructor. To call the copy constructor, we need to pass by value. Which means we need to copy the argument, which means we need to call the copy constructor.....
4,549,422
4,549,438
How to split and join array in C++ for UDP?
I have a byte array like this: lzo_bytep out; // my byte array size_t uncompressedImageSize = 921600; out = (lzo_bytep) malloc((uncompressedImageSize + uncompressedImageSize / 16 + 64 + 3)); wrkmem = (lzo_voidp) malloc(LZO1X_1_MEM_COMPRESS); // Now the byte array has 802270 bytes r = lzo1x_1_compress(image...
The problem with doing this is that the UDP packets can arrive out or order, or be dropped. Use TCP for this; that's what it's for.
4,549,471
4,549,523
What C++(98/03) features are not-so-well supported by poor compilers?
Often I read of some software cutting out some C++ features in order to be compliant with poor/old/exotic C++ compilers. This one is just the last one I got into: Box2D isn't using namespaces because they need to support: poor C++ compilers where namespace support can be spotty A bigger example I can think of is Qt, ...
In my experience, people are just scared of new things and especially things that broke on them once, 20 decades ago. There's no valid reason against using namespaces in anything written during this century. If you're looking for things to toss out though, if you happened to be targeting windows not too long ago you h...
4,549,642
4,549,873
Anyone know of any plans to make ^ a shorthand for shared_ptr<T>?
For example: shared_ptr<const shared_ptr<const int> > pp; is fairly intimidating... whereas const int ^ const ^ pp; is instantly reminiscent of the raw pointer equivalent const int * const * pp;
Everyone missed the real reason :) The nice notation T^ suggests action like a real pointer, which suggests conversions would work the same way. This is not the case. Templates can't support conversions. For example consider T^ --> T const^ If you take ^ as *, this will work. However by default for a template: p<T> --...
4,549,838
4,549,870
IAT Hooking, QT library
I have a .dll injected into the address space of another process. The target app uses the QT library. I can insert a detour so that each time the QT function ?rowsInserted@QListView@@MAEXABVQModelIndex@@HH@Z is called my function is called instead and then the call passed on. However, how do I get access to the par...
It looks like the function is probably QListView::rowsInserted(const QModelIndex &, int, int). The parameters are listed in the function reference.
4,549,859
4,549,880
How to set QMainWindow title
How do I set the title of a QMainWindow? I tried googling and found setCaption(), but it appears it no longer works in Qt 4.
The method is setWindowTitle(): setWindowTitle(const QString &) http://doc.qt.io/qt-4.8/qwidget.html#windowTitle-prop
4,550,268
4,550,286
Sockets don't send all binary data
Actually I'm working on very simple FTP server. Now I have problem with sending file (RETR in FTP protocol). I'm using sockets and binary mode in my client. Files with text send perfectly, but problem is binary files (images etc.). Here's piece of my code: FILE *fin=fopen(fileloc,"rb"); if(fin != NULL){ fpos_t fil...
In your send call you are using strlen which might work fine for text data but not for binary data. When you read from the file you need to use a call like read which will tell you how many bytes were actually read so you can send that many bytes in the send call.
4,550,294
4,550,426
stdcall name mangling using extern c and dllexport vs module definitions (msvc++)
I was trying to export a simple test function for a dll to work with an application (fyi: mIRC) that specifies the calling convention as: int __stdcall test_func(HWND mWnd, HWND aWnd, char *data, char *parms, BOOL show, BOOL nopause) Now, to call this from the application, I'd be using test_func but I have noticed due...
dllexport/import are designed to be loaded back by themselves, not an old C library using GetProcAddress. The mangling you have seen is what all Microsoft compilers have done for a long time for __stdcall functions. Most likely, your target either expects a __cdecl function, not __stdcall, but if not, you will need to ...
4,550,458
4,550,653
OpenCV compare two images and get different pixels
For some reason the code bellow is not working. I have two 640*480 images which are very similar but not the same (at least few hundred/thousand pixels should be different). This is how I am comparing them and counting different pixels: unsigned char* row; unsigned char* row2; int count = 0; // this happens in a loop ...
It seems to me you aren't counting different pixels, not even pixels at all. You are counting how often a color channel of one pixel in the first image matches the channel of the corresponding pixel in the other image. You probably meant to do something along the lines of: ... //in the inner for loop if(row[x] != row2[...
4,550,487
4,550,545
boost::sandbox::odeint install
I would like to use the odeint module from the boost::sandbox but I am not sure how to integrate the sandbox code which I retrieved from svn into my boost install. I have boost installed to $BOOST_ROOT=/usr/local/boost_1_45_0. Is it proper to just merge contents of odeint into my boost path which would place the head...
I am not aware of any "proper" solution, but I can tell you that you should not meet any problems if you just copy boost/numeric/odeint.hpp and boost/numeric/odeint/*.hpp to that directory since no file will be overwritten (if something fails just remove them and you're done). For what its worth I did that for boost::p...
4,550,503
4,550,549
What happens when you use fwrite() with a class?
Suppose I have the following:class dataClass { public: int someData; float moreData; void setData(); }; dataClass data; What would happen if I called fwrite(&data, sizeof(data), 1, outputFilePointer);? Would the code act as if dataClass had no functions, or would I have to call fwrite() with each member?
In this very case, your class is POD, so it would work exactly as it would if it was a Plain Old C struct, i.e. it will dump the memory representation of data on disk (including the padding bytes that the compiler may insert). However, if virtual methods, virtual inheritance and other C++ stuff kicks in, you may start ...
4,550,655
4,552,903
Function to retrieve the size of an element
What I need is a function to retrieve the size of an element, be it a Java Applet window in a browser, text boxes in programs, applications window and so on. Now I don't know what this kind of function is called, but I uploaded an example from an application that had that functionality. <a href="http://img408.imageshac...
I found the solution! POINT p; HWND wnd; RECT rec; GetCursorPos(&p); wnd = WindowFromPoint(p); GetWindowRect(wnd, &rec); This will give you the coordinates for the box (extract from rec).
4,550,809
4,550,820
MS Visual C++ 2010 Error: On provision of default destructor
I am getting run-error on providing default destructor. However, if left to compiler to provide default destructor it is running safely. class foo { private: int m_size; int* m_array; public: foo( int a_size ):m_size( a_size ), m_array( new int(a_size) ){} ~foo() { delete [] m_array; ...
new int(a_size) dynamically allocates a single int with initial value a_size. I think you mean new int[a_size] which dynamically allocates an array of a_size ints. (You should also provide a copy constructor and copy assignment operator for your foo class as the default ones will not do the correct thing. Better would ...
4,550,854
4,551,381
How to convert photos to Polaroid-like programmatically?
How to convert modern day photos to the look and feel of those Polaroid photos ? References and/or sample codes are welcome. Thanks!
Convert the images to HSV (cv::cvtColor) then look at adjusting the hue/saturation values see http://en.wikipedia.org/wiki/HSL_and_HSV for a rather too technical article
4,550,914
4,550,973
Why can't a struct defined inside a function be used as functor to std::for_each?
The following code won't compile. The compiler complains about *no matching function for call to for_each*. Why is this so? #include <map> #include <algorithm> struct Element { void flip() {} }; void flip_all(std::map<Element*, Element*> input) { struct FlipFunctor { void operator() (std::pair<Ele...
std::for_each is a function template; one of the template parameters is the type of the function argument. You cannot use a local type as a template argument. It's just a restriction currently in the language. In the forthcoming revision of C++, C++0x, this restriction is removed, so you can use local types as templa...
4,551,101
4,552,146
LuaL_openlibs() and sandboxing scripts
I am embedding Lua (5.1) in a C/C++ application. I am using the LuaL_openlibs() function to load the base libs. However, this function loads some other libraries which I want to disable so that they are not available to my Lua scripts. Specifically, I want to disable the IO and OS modules. Is there a function I can cal...
I don't know how to disable modules, but you can still choose which ones to load instead of loading them all with luaL_openlibs. Section 7.3 of the Lua 5.1 manual says: The luaopen_* functions (to open libraries) cannot be called directly, like a regular C function. They must be called through Lua, like a Lua function...
4,551,278
4,551,307
Passing a class object as an argument in C++
Suppose I had a class named foo containing mostly data and class bar that's used to display the data. So if I have object instance of foo named foobar, how would I pass it into bar::display()? Something like void bar::display(foobar &test)?
Yes, almost. Or, if possible, use a const reference to signal that the method is not going to modify the object passed as an argument. class A; class B { // ... void some_method(const A& obj) { obj.do_something(); } // ... };
4,551,376
4,551,391
Importing 3ds Max OBJ using C++
I have created a an OBJ loader that can import .OBJ files that were exported from 3DS Max into my simple OpenGL viewer / app. At the heart of this was a Vector3.h written with the help of some tutorials. It worked great on a couple models I used, but the one I want to work with has something different that wasn't accou...
A face with four points is called a quad. Usually if you want to render it you should break it up into two triangles. So for example, you have this: ___ | | | | |___| You need to turn it into this: ___ |\ | | \ | |__\| Assuming the vertices go counter-clockwise (the default in OpenGL), starting from the upper ...
4,551,488
4,551,545
How to make Visual Studio 2010 recognize file extensions as C#/ASPX/C/C++ files?
There was a solution for VS 2005 here: http://www.dotnetmonster.com/Uwe/Forum.aspx/vs/3298/Make-Visual-C-recognize-file-extensions-as-C-files But doesn't find same registry for VS2008 and VS2010. So where can I find the solution update for this ? Thanks.
If what you're looking for is syntax highlighting for different extensions in the VS 2010 editor: Go to Tools -> Options -> TextEditor -> File Extensions and enter the extension.
4,551,698
4,553,907
Interpret a string as it refers to an in program variable. Geant4 units
So, I understand that this is not something built into the language (i.e. there is no eval() method in c++). I also understand that it is very difficult to associate the contents of a string input at runtime with a variable name from the program, since most of that info goes away. Nevertheless... I am trying to write a...
This is difficult to answer, partly because I've never used (or heard of before now) Geant4, and partly because it's not entirely clear what you're trying to do: are you making a C++ library for your colleagues to use directly? Or are you making some kind of tool that your colleagues can use without touching C++ themse...
4,551,867
4,561,118
Java: saving image as JPEG skew problem
I am trying to save an image to JPEG. The code below works fine when image width is a multiple of 4, but the image is skewed otherwise. It has something to do with padding. When I was debugging I was able to save the image as a bitmap correctly, by padding each row with 0s. However, this did not work out with the JPEG....
Thanks for your suggestions, but I have managed to work it out. To capture the image I was using WINGDIAPI HBITMAP WINAPI CreateDIBSection in C++, then OpenGL would draw to that bitmap. Unbeknown to be, there was padding added to the bitmap automatically the width was not a multiple of 4. Therefore Java was incorrectly...
4,551,898
4,551,922
Separating HTTP Response Body from Header in C++
I'm currently writing my own C++ HTTP class for a certain project. And I'm trying to find a way to separate the response body from the header, because that's the only part I need to return. Here's a sample of the raw http headers if you're not familiar with it: HTTP/1.1 200 OK Server: nginx/0.7.65 Date: Wed, 29 Dec 201...
HTTP headers are terminated by the sequence \r\n\r\n (a blank line). Just search for that, and return everything after. (It may not exist of course, e.g. if it was in response to a HEAD request.)
4,552,004
4,552,046
Why Does My Vector<PEVENTLOGRECORD> Mysteriously Get Cleared?
I am making a program that reads and stores data from Windows EventLog files (.evt) in C++. I am using the calls OpenBackupEventLog(ServerName, FileName) and ReadEventLog(...). Also using this: PEVENTLOGRECORD Anyway, without supplying all of the code, here is the basic idea: 1. I get a handle to the .evt file using ...
I'd guess that your vector (which I think should read as vector<PEVENTLOGRECORD>, not vector(PEVENTLOGRECORD)) contains pointers to the data rather than copies of the data. I think that whatever owns the actual data is releasing it when the ReadEventLog() indicates that there is no more data. One possible fix is that ...
4,552,080
4,552,230
creating two-dimensional array dynamically in continuous memory block
I was trying to create 2D array in a continuous memory block, but it is giving M continuous block, each of N size. int **arr = new int*[M]; for (int i = 0 ; i < M ; i++ ) { arr[i] = new int[N]; } How to create 2D array in a continuous memory block?
int *buffer=new int[M*N]; int **arr=new int*[M]; for(int i=0;i<M;++i) arr[i]=buffer+i*N; Actually it's not necessary to store arr pointers - they can be calculated when needed.
4,552,396
4,552,420
Is my use of C++ catch clause, families of exception classes, and destruction sane?
Once in a while, I notice some coding pattern that I've had for years and it makes me nervous. I don't have a specific problem, but I also don't remember enough about why I adopted that pattern, and some aspect of it seems to match some anti-pattern. This has recently happened to me WRT how some of my code uses excepti...
This is ok. It's actually good to catch exceptions by constant reference (and bad to catch pointers). Catching by value creates an unnecessary copy. The compiler is smart enough to handle the exception (and its destruction) properly -- just don't try to use the exception reference outside of your catch block ;-) In ...
4,552,537
4,552,647
Express highest floating point quantity that is less than 1
I was doing some rounding calculations and happened upon a question. How can I express the highest quantity less than 1 for a given floating point type? That is, how I write/represent value x such that x < 1, x + y >= 1 for any y > 0. In fractions this would be x = (q-1)/q where q is the precision of the type. For exam...
C99 defines nextafter() function. Use it like #include <math.h> double under_one = nextafter(1, 0);
4,552,582
4,554,715
casting derivedclassptrVector from baseclassptrVec, the best way?
I am getting base class pointer vector that needed to be passed to derived class pointer vector, please suggest best way to do the same. One way will be create a new derived class vector with the base class ptr vector size loop the incoming vector dynamic cast the base pointer and fill the derived vector. Please sugge...
If I understand the question right, you have the following situation class Base {}; class Derived: public Base {}; class Derived2: public Base {}; void foo(const vector<Derived*>&); void bar() { vector<Base*> baseVec; // Fill baseVec with pointers to Derived objects foo(baseVec); // Does not work } The probl...
4,553,162
4,555,577
C++ Boost ASIO: how to read/write with a timeout?
From reading other Stack Overflow entries and the boost::asio documentation, I've confirmed that there is no synchronous ASIO read/write calls that also provide an easy-to-use timeout as a parameter to the call. I'm in the middle of converting an old-school Linux socket application with select(2) calls that employs tim...
This has been brought up on the asio mailing lists, there's a ticket requesting the feature as well. To summarize, it is suggested to use asynchronous methods if you desire timeouts and cancellability. If you cannot convert to asynchronous methods, you might try the SO_RCVTIMEO and SO_SNDTIMEO socket options. They can...
4,553,223
4,553,305
Just how random is std::random_shuffle?
I'd like to generate a random number of reasonably arbitrary length in C++. By "reasonably arbitary" I mean limited by speed and memory of the host computer. Let's assume: I want to sample a decimal number (base 10) of length ceil(log10(MY_CUSTOM_RAND_MAX)) from 0 to 10^(ceil(log10(MY_CUSTOM_RAND_MAX))+1)-1 I have a v...
I'm slightly unclear as to the focus of this question, but I'll try to answer it from a few different angles: The quality of the standard library rand() function is typically poor. However, it is very easy to find replacement random number generators which are of a higher quality (you mentioned Boost.Random yourself, ...
4,553,396
4,553,441
Class for reading MP3 files
I am writing a game that is a bit depending on the soundtrack so I want to read mp3 file and use it's data (like the speed of music, beat and stuff). Is there any class (preferably) I could use or article that would cover everything about mp3 reading (from checking if it's an mp3 to actual decoding)? It's OK if I have ...
Yes, its complicated. MP3s are the typical lossy DCT compression scheme more or less. The process is similar to JPEG. Writing an mp3 decoder and encoder is a project in itself. Encode Quantize -> DCT Transform -> Entropy Encode -> Store Decode Entropy Decode -> IDCT -> Dequantize -> play I suggest FMOD its widely accep...
4,553,520
4,553,653
forward declaration of boost::thread variable
can someone please tell me can we forward declare a boost::thread variable. boost::thread t(thread); starts a thread, but I want to declare it somewhere and to start it somewhere else. Thanx in advance. When I use boost::thread t; t=boost::thread (thread); /usr/include/boost/noncopyable.hpp: In copy constructor ‘boo...
To my knowledge, the only way to do that is to use thread's move semantics: boost::thread t; // Will be initialized to `Not-a-Thread`. // Later... t = boost::thread(your_callable); // Now `your_callable()` runs inside a new thread that has been moved to `t`. EDIT: From the error messages you posted, it seems that yo...
4,553,735
4,553,796
GNU autotools: Debug/Release targets?
I've been looking for this for a while: I'm currently converting a medium-size program to autotools, coming from an Eclipse-based method (with makefiles) I'm always used to having a "debug" build, with all debug symbols and no optimizations, and a "release" build, without debug symbols and best optimizations. Now I'm t...
Add a clause to your configure.in or configure.ac file; AC_ARG_ENABLE(debug, AS_HELP_STRING([--enable-debug], [enable debugging, default: no]), [case "${enableval}" in yes) debug=true ;; no) debug=false ;; *) AC_MSG_ERROR([bad value ${enableval} for --enable-debu...
4,553,777
4,554,118
Detecting simulated keyboard/mouse input
Is there a way to detect simulated keyboard/mouse input on Windows. For example, a user types something on his keyboard vs sendKeys/PostMessage/On-screen keyboard. Is there a way that I can distinguish between the two? EDIT: Perhaps an example would help. I am making a game and want to distinguish between real input vs...
I might be wrong, but the on-screen keyboard (and other applications that simulate user input) most probably uses the SendInput API: SendInput operates at the bottom level of the input stack. It is just a backdoor into the same input mechanism that the keyboard and mouse drivers use to tell the window manager that the...
4,553,785
4,554,011
Where should I use iostream class?
As we know in C++ we have class iostream, which is inherited from istream(basic_istream) and ostream (basic_ostream). In every C++ book you can find, that with iostream class object you can read and write to the same stream. But I realy haven't see any explanation or example to understand why should I use such a stran...
You might want to read from and write to the same stream because the stream performs type conversions, like std::stringstream. You could also have iostream abstractions over data sources that permit both reading and writing- such as a socket or an in-memory buffer.
4,553,896
4,553,911
Conversion of char * to string
Does anyone have an idea how to convert char* to string. Actually, I have a function which returns value as char* and now i need to store/copy std::string. I have tried something like char *sResult = (char*)malloc(1024); std:string line; line= line+ sResult Thanks and regards, Sam
How about std::string line(szResult);
4,553,916
4,554,506
Uploading PNG File (HTTP POST) with C++ Winsock API
I'm trying to upload a PNG file through Winsock2 HTTP Post. Here's my request string: boundary = "-----rueldotme"; request += "POST " + uri + " HTTP/1.1\r\n"; request += "Host: " + hostname + "\r\n"; request += "User-Ag...
Not enough information to solve the problem, so I'll give a meta-answer instead: Use a packet sniffer (e.g., wireshark) to check exactly what data is actually being sent and received. This will let you verify that the request is as it should be, and that the "blank response" you're getting really is blank. One wild sta...
4,554,028
4,554,166
Smart pointers usage
I have a project and I want make smart pointers usage better. The main idea is to use them when returning new object from function. The question is what smart pointer to use? auto_ptr or shared_ptr from boost? As I know, auto_ptr is slower but it can fall back to the 'pure' pointer. And if I'll use smart pointer in pla...
What makes you think auto_ptr is slower than shared_ptr? Typically I would expect the reverse to be true, since shared_ptr needs to update the reference count. As for which you should use, different smart pointers imply different ownership semantics. Ownership implies the responsibility to delete the object when it is ...
4,554,031
4,554,077
When have you used C++ 'mutable' keyword?
When have you used C++ mutable keyword? and why? I don't think I have ever had to use that keyword. I understand it is used for things such as caching (or perhaps memorization) but in what class and condition have you ever needed to use it in?
Occasionally I use it to mark a mutex or other thread synchronisation primitive as being mutable so that accessors/query methods, which are typically marked const can still lock the mutex. It's also sometimes useful when you need to instrument your code for debugging or testing purposes, because instrumentation often n...
4,554,113
4,554,247
Finding out whether a DirectInput device supports XInput (with mingw/gcc)
I'm working on an input system, wrapping DirectInput and XInput. Currently XInput devices are enumerated twice, once as XInput and once as DirectInput (since they support both). How can I find out if a given DirectInput device also supports XInput? There is this MSDN page on the topic, but it requires wbemidl.h and wm...
wbemidl.h and all the related headers are available from mingw-w64 project, don't mind the 64it also supports 32bit. Here is an example that implements IsXInputDevice without including wmsstd.h
4,554,162
4,554,282
Is there any reason to use auto_ptr?
After reading Jossutis' explanation on auto_ptr from his STL book I've got a strong impression that whatever task I would try to use it in I'd 100% fail becuase of one of many auto_ptr's pitfalls. My question is: are there any real life tasks where auto_ptr is really usefull and does fit there well?
Clearly, auto_ptr looses against unique_ptr. Now, in a 'strict C++03 without boost' world, I use auto_ptr quite often, most notably : For 'factory member functions' which return a dynamically allocated instance of a given type : I like the fact that using std::auto_ptr in the return type explicits that the object must...
4,554,313
4,554,456
Doubt in Conditional inclusion
This is actually extracted from my module (Pre-processor in C) The conditional expression could contain any C operator except for the assignment operators,increment, and decrement operators. I am not sure if I am getting this statement or not since I tried using this and it worked.Also for other manipulation a probable...
You seem to misunderstand what the phrase conditional expression refers to. In this snippet #if defined TEST int a = 0; #endif The conditional expression is the part being tested by the #if, meaning it is the defined TEST part. The reason that assignment, increment and decrement are not allowed is because those oper...
4,554,466
4,554,728
Problem with C++ Boost installation (can't find file) in VC++ 2010
I freshly installed Boost 1.44 with the latest available installer from http://www.boostpro.com/download/. Then I created a VC++ unmanaged commandline project. I added the line #include <boost/regex.hpp> as stated in the Boost Getting Started tutorial, and I also put the Boost installation directory into the linking op...
The Boost library naming convention is listed on the Getting Started page. mt indicates multithreading is enabled g indicates debug versions of the CRT libraries were linked d indicates the version of the boost libraries themselves that you're linking to are debug versions s indicates that the CRT libraries have bee...
4,554,510
4,554,934
How to determine which compiler has been used to compile an executable?
From a compiled file, can I see which compiler has been used to generate the file?
There's also the good old 'strings' utility. Dumps all ascii-ish looking strings it finds in the binary. Different compilers embed different amounts of information in the binaries they produce, but many will actually include obviously identifying strings.
4,554,517
4,555,396
RichEdit Vertical Text Aligment
How can i align the text in a TRichEdit vertically centered. There is a property for aligning paragaph by horizontal but there isn't any property for vertical alignment. I use C++ builder.
TRichEdit is just a wrapper around MS RichEdit component, so you can get a handle and use WinAPI to work with it directly: http://msdn.microsoft.com/en-us/library/bb787873(VS.85).aspx
4,554,645
4,554,699
Send data over TCP/IP with sockets and serialize data
i have to send via TCP/IP with sockets a string formatted as CHARINT,INT where CHAR is a character and INT are numbers. Which is the best way to send them and receive them? And how could i split that string when I receive it to have again the two integers?
There are plenty of ways to do what you need, and the choice depends on how extensible you need to the solution to be. If all you need is two integers, then you can send them by putting them to array "int arr[2];" and use send(arr, 2*sizeof(int)) call to send the data. When receiving the data you do the opposite. Qui...
4,554,736
4,555,259
Hexadecimal to Hexatridecimal in c++
I am attempting to convert base 16 to base 36. I'm taking md5 hashes and making them have all 0-9a-z. I searched around and didn't find anything good. Any suggestions for converting hexadecimal to hexatridecimal in c++? Do you guys know any good libraries for doing it?
I assume the tricky part you're struggling with is the conversion to Rad36, not getting a integral value from a hex number represented as a string. So, here is a function which takes an unsigned __int64, converts it to Radix 36, and returns a string with the converted value. string rad36(unsigned __int64 v) { stri...
4,554,869
4,554,896
Smart pointer question
I'm rewriting my code with smart pointer. I have such situation: void Foo(SomeClass *p) { } boost::shared_ptr<SomeClass> p(new SomeClass); Now what to do: pass original pointer from wrapper (p.get()) or rewrite function argument and pass smart pointer directly like: void Foo(boost::shared_ptr<Foo> obj) { } I'm not su...
Unless Foo needs to take (shared) ownership of *p you should keep the signature the same and just pass p.get(). It's the simplest and most flexible option as well as requiring the least change to your existing code.
4,554,978
4,555,023
Derived classes and smart pointers
class Object { /* */ }; and a few derived: class Derived1 : public Object { /* */ }; class Derived2 : public Object { /* */ }; And I have a function which makes derived objects and returns pointer for Object; Object *make() { return new Derived1(); } So, this way I have to wrap returned object by smart pointer, b...
you can use: boost::shared_ptr<Object> make() { return boost::shared_ptr<Object>(new Derived1()); }
4,555,354
4,561,980
Using Mono SGen Garbage collector in C/C++ programs
Is it possible to use SGen garbage collector (from the mono runtime) in coventionnal C/C++ programs ? I think mono used also the Boehm-Demers-Weiser conservative garbage collector that can be used in C/C++ programs.
There are very few dependencies on the rest of the Mono code in SGen, so it should be easy to extract it out and adapt to other uses. The major difference from the Boehm collector is that it currently doesn't support a non-precise mode for heap objects, so you can't use it to replace malloc easily. It would work great,...
4,555,616
4,555,645
Is it safe to get an object in std::map by reference?
I have a map like this map<int,object> objmap; object& obj = objmap.find(num)->second; object& obj2 = objmap[num]; Whatever changes I make in the object have to be reflected on the map. Similar thing cant be done in a vector as it changes location of objects when it wants more space. Is it safe to do it in a std::map?...
So long as the object in question isn't removed from the map, then yes it is safe. Once inserted into a map objects don't move around even if other elements are added or removed. object& obj = objmap.find(num)->second; This is potentially dangerous unless you are sure that an element with key num actually exists in th...
4,555,654
4,644,321
DirectShow decoders dropping media time
In DirectShow, a media sample has two time-related properties: its time stamp and its media time. My application needs to seek to specific frames within a video and thus requires the media time. As it seems, however, most decoder filters do not pass on this information. I have a DirectShow graph that looks like this: [...
Not all decoders follow all the rules of DirectShow, so losing media times is one of the things you'll have to bear with. If you're only working with AVI files, just rely on accuracy of the splitter when using IMediaSeeking and use Stop() and Pause() of IMediaControl appropriately to ensure any cached frames are dismis...
4,555,961
4,556,025
How to use a class in DLL?
Can I put a class inside a DLL? The class i wrote is this: class SDLConsole { public: SDLConsole(); ~SDLConsole(){}; void getInfo(int,int); void initConsole(char*, char*, SDL_Surface*, int, int, int); void sendMsg(char*,int, SDL_Surface*); ...
If you use run time dynamic linking (uses LoadLibrary to load the dll) you cannot access the class directly, you need to declare a interface for your class and create a function that returns a instance of this class, like this: class ISDLConsole { public: virtual void getInfo(int,int) = 0; ...
4,555,989
4,556,386
Is there a faster lossy compression than JPEG?
Is there a compression algorithm that is faster than JPEG yet well supported? I know about jpeg2000 but from what I've heard it's not really that much faster. Edit: for compressing. Edit2: It should run on Linux 32 bit and ideally it should be in C or C++.
Jpeg encoding and decoding should be extremely fast. You'll have a hard time finding a faster algorithm. If it's slow, your problem is probably not the format but a bad implementation of the encoder. Try the encoder from libavcodec in the ffmpeg project.
4,556,142
4,556,163
Determining if a derived class overrides a method from a base class
class B { virtual int foo(); }; class D : public B { virtual int foo() { cout<<"D\n"; } }; int B::foo() { /* how do i tell if this->foo() is overridden by a subclass, or if it will */ /* simply recurse into B::foo()? */ this->foo(); } main() { D d; d.B::foo(); }
Answer: you can't. I'd expand if there was anything to expand upon.
4,556,417
4,556,443
Static local variables in methods a bad practice?
there is something that's bugging me. In a non-threaded program, is it better to have local static variables(inside methods) or static class members? In this example: class C{ public: C(){}; void foo(); }; void C::foo(){ static int bar = 0; bar++; printf("%d\n",bar); } Is it considered a bad practice if ba...
Neither is better. They serve very different use cases
4,556,496
4,556,749
Breakpoint not hit in a global static initialized class in a statically linked lib
I've experienced a weird behavior on VS2010 part. I've added this simple code to two .cpp files, and placed a breakpoint on the specified line of code namespace { class TestClass { public: TestClass() { printf(""); // ### BREAKPOINT_HERE } }; } TestClass a; The weird thing ...
I think the problem is not with the compiler, but with the linker. If it doesn't see any explicit accesses to a symbol in a module in a library, it will not link the module. Thus any static objects in that module will never exist. To realize why this is so, think back to a time before C++. The purpose of a library was ...