question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
1,222,418
1,222,941
When exactly is the postfix increment operator evaluated in a complex expression?
Say I have an expression like this short v = ( ( p[ i++ ] & 0xFF ) << 4 | ( p[ i ] & 0xF0000000 ) >> 28; with p being a pointer to a dynamically allocated array of 32 bit integers. When exactly will i be incremented? I noticed that the above code delivers a different value for v than the following code: short v = ( p[...
The problem is order of evaluation: The C++ standard does not define the order of evaluation of sub expressions. This is done so that the compiler can be as aggressive as possible in optimizations. Lets break it down: a1 a2 v = ( ( p[ i++ ] & 0xFF ) << 4 | ( p[ i ] & 0xF0000000 ) >> 28...
1,222,608
1,356,502
ATL Security update broke compatibility for DLLs depending on the older version
The recent ATL security update updated the C++ runtimes to version 8.0.50727.4053. Unfortunately, this update broke one of our DLLs that dynamically links to the runtime, as we only have 8.0.50727.762 available to us on the target machine (we don't even use ATL). Is there a way we can get Visual Studio to dynamically ...
Another solution is forcing VS to link against the old versions of the WinSxS DLLs as explained in this article.
1,222,626
1,222,936
What should I do to develop a well structed C++ program?
Right now, I want to develop a C++ program. And the UI design is the difficult issue. my question is: 1. is there any good practice for developing a well structed c++ program ? 2. is there any good practice for developing UI in c++? 3. I usually heard of Activex in C++, can it use to encapsulate a UI, and is good for...
I try to give some answers to your questions: 1) Good Program Structure This really depends on what matters most - cost of development, ease of deployment/update, maintainability, target machine requirements. It is hard to give you a good answer because the topic is so large. I suggest this as a good place to start rea...
1,222,632
1,223,499
MVC with Qt widget that uses a QAbstractTableModel subclass
I'm doing some refactoring. I'm implementing a Model-View-Controller pattern. The view is a Qt widget. Originally, the Qt widget created a new instance of a QAbstractTableModel subclass on the heap. Lets call it FooTableModel. e.g Widget::Widget(QWidget* parent) : QWidget(parent) m_model(new FooTableModel(...
Generally you want to avoid passing the view to the model. If your MVC model is a QObject and the FooTableModel instance is a child of it then you don't need to worry about the cleanup becasue Qt will do it for you. Ideally, if you are using Qt the FooTableModel would be THE model, or whatever had the instance of it w...
1,222,806
1,223,938
some questions about MFC development?
How do you develop UI in MFC? do you use any free libray, or usually develop from scratch? There are always so many DLL files in a C++ developed software, what are them used for ? What's the difference between MFC ActiveX Control and MFC DLL ?
Visual Studio 2008 enhances MFC by adding the 'Feature Pack'. This allows you to create MS Office 2007 style GUIs (amongst others), complete with a Ribbon Bar. http://msdn.microsoft.com/en-us/library/bb982354.aspx I cut my C++ teeth using MFC, but I'd recommend you look at Qt instead - it's a much more modern framewor...
1,222,914
1,301,884
QGraphicsView and QGraphicsItem: don´t scale item when scaling the view rect
I am using Qt´s QGraphicsView - and QGraphicsItem-subclasses. is there a way to not scale the graphical representation of the item in the view when the view rectangle is changed, e.g. when zooming in. The default behavior is that my items scale in relation to my view rectangle. I would like to visualize 2d points which...
Set the QGraphicItem's flag QGraphicsItem::ItemIgnoresTransformations to true does not work for you?
1,222,926
1,226,955
boost::asio, asynchronous read error
For some reason this results in an access violation, however not having any detailed documentation/help on this I'm not sure where I'm doing it wrong. Since going by what I've seen on the boost site this should be correct, and print the contents of each asio::write call from the client to a new line. The client seems...
You should change this code snippet: void startRead() { std::cout << "Connection::startRead()" << std::endl; socket.async_read_some(boost::asio::buffer(readBuffer), boost::bind(&Connection::handleRead,this,_1,_2)); } to: void startRead() { std::cout << "Connec...
1,223,172
1,223,202
What is this piece of c++ code doing?
I don't know how and why this piece of code works: // postorder dfs Iterator< Index<String<char> >, TopDown<ParentLink<Postorder> > >::Type myIterator(myIndex); while (goDown(myIterator)); for (; !atEnd(myIterator); goNext(myIterator)) // do something with myIterator ( Traverse Through (Suffix)-tree ) It's an ex...
You've run into the fun parts of C++ - using language constructs in syntactically valid but difficult-for-human-parsing techniques. while (goDown(myIterator)); This will "goDown(myIterator)" until it returns false. Then it will continue onto the for loop. It's looping over nothing - but that's okay, because the func...
1,223,297
1,223,522
Library plans for C++0x?
Lately I've been getting very excited about the support for lambdas in VC2010. I'm slowly starting to grasp the full potential this feature has in transforming C++ into something alot better. But then I realized that this potential greatly depends on main stream support of lambdas in day to day libraries like boost and...
Lambdas already fit very well into existing libraries - anywhere that a function accepts a function object of a type given by a template parameter. This is one of the great things about them - they're a classic example of a language feature that codifies existing practice in a nifty syntax. Obviously the boost lambda l...
1,223,616
1,223,642
How to implement a queued map?
The problem: I want to be able to FIFO queue outgoing messages. For update/deletion reasons, I also want to be able to access every message in the queue based upon an object ID. I've currently implemented a solution where data is pushed into a deque, and an iterator to that data is kept. The iterator, keyed by an objec...
Why not make the deque a deque of IDs and the map a map from ID to object. Then when you access an ID in the deque, you look up the ID in the map. If the IDs are globally unique, you only need one map to service all the deques.
1,223,690
1,223,697
PInvoke error when marshalling struct with a string in it
I have a C++ struct struct UnmanagedStruct { char* s; // Other members }; and a C# struct struct ManagedStruct { [MarshalAs(UnmanagedType.LPStr)] string s; // Other members } the C++ library exposes extern "C" UnmanagedStruct __declspec(dllexport) foo( char* input ); And it is imported like [DllImport...
For this type of scenario, do not use a String directly. Instead switch the type to be an IntPtr value and use Marshal.PtrToStringAuto/Ansi/Uni as appropriate. In this case, since your native code uses char*, PtrToStringAnsi is the best choice. struct ManagedStruct { IntPtr s; public string sAsString { get { retu...
1,223,962
1,224,132
Container with two indexes (or a compound index)
I have a class like this class MyClass { int Identifier; int Context; int Data; } and I plan to store it in a STL container like vector<MyClass> myVector; but I will need to access it either by the extenal Index (using myVector[index]); and the combination of Identifier and Context which in this case I ...
Boost::Multi-Index has this exact functionality if you can afford the boost dependency (header only). You would use a random_access index for the array-like index, and either hashed_unique, hashed_non_unique, ordered_unique, or ordered_non_unique (depending on your desired traits) with a functor that compares Identifie...
1,223,999
1,224,056
C++ Map can't insert with pair
Why can't I insert as shown below? #include <map> struct something { } some_object; typedef std::map<std::string, something*> list; typedef std::pair<std::string, something*> pair; int main() { list l; pair p("abc", &some_object); // working fine!!! l.insert(p); // 17 errors return 0; } Visual stu...
You need to #include <string>
1,224,306
1,224,357
Template Metaprogramming - I still don't get it :(
I have a problem... I don't understand template metaprogramming. The problem is, that I’ve read a lot about it, but it still doesn’t make much sense to me. Fact nr.1: Template Metaprogramming is faster template <int N> struct Factorial { enum { value = N * Factorial<N - 1>::value }; }; template <> struct Factori...
Just as factorial is not a realistic example of recursion in non-functional languages, neither is it a realistic example of template metaprogramming. It's just the standard example people reach for when they want to show you recursion. In writing templates for realistic purposes, such as in everyday libraries, often th...
1,224,361
1,224,501
Determine static initialization order after compilation?
In C++, I know that the compiler can choose to initialize static objects in any order that it chooses (subject to a few constraints), and that in general you cannot choose or determine the static initialization order. However, once a program has been compiled, the compiler has to have made a decision about what order t...
Matthew Wilson provides a way to answer this question in this section (Safari Books Online subscription required) of Imperfect C++. (Good book, by the way.) To summarize, he creates a CUTrace.h header that creates a static instance of a class that prints the filename of the including source file (using the nonstandar...
1,224,464
1,224,474
C/C++ Packing and Compression
I'm working on a commercial project that requires a couple of files to be bundled (packed) into an archive and then compressed. Right now we have zlib in our utility library, but it doesn't look like zlib has the functionality to compress multiple files into one archive. Does anyone know of free libraries I'd be able t...
Perhaps libtar? Also under a BSD license.
1,225,177
1,226,393
Initializing member variables
I've started to pick up this pattern: template<typename T> struct DefaultInitialize { DefaultInitialize():m_value(T()){} // ... conversions, assignments, etc .... }; So that when I have classes with primitive members, I can set them to be initialized to 0 on construction: struct Class { ... DefaultInitialize...
This is a valid pattern? It's a known "valid" pattern, i would say. Boost has a class template called value_initialized that does exactly that, too. I am using the right terminology? Well, your template can be optimized to have fewer requirements on the type parameter. As of now, your type T requires a copy constru...
1,225,411
1,225,429
Boost's Linear Algebra Solution for y=Ax
Does boost have one? Where A, y and x is a matrix (sparse and can be very large) and vectors respectively. Either y or x can be unknown. I can't seem to find it here: http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/index.htm
Linear solvers are generally part of the LAPACK library which is a higher level extension of the BLAS library. If you are on Linux, the Intel MKL has some good solvers, optimized both for dense and sparse matrices. If you are on windows, MKL has a one month trial for free... and to be honest I haven't tried any of the ...
1,225,589
1,225,599
Most Compact Way to Count Number of Lines in a File in C++
What's the most compact way to compute the number of lines of a file? I need this information to create/initialize a matrix data structure. Later I have to go through the file again and store the information inside a matrix. Update: Based on Dave Gamble's. But why this doesn't compile? Note that the file could be very ...
FILE *f=fopen(filename,"rb"); int c=0,b;while ((b=fgetc(f))!=EOF) c+=(b==10)?1:0;fseek(f,0,SEEK_SET); Answer in c. That kind of compact?
1,225,695
1,225,726
C++ STL map typedef errors
I'm having a really nasty problem with some code that I've written. I found someone else that had the same problem on stackoverflow and I tried the solutions but none worked for me. I typedef several common STL types that I'm using and none of the others have any problem except when I try to typedef a map. I get a "so...
You are getting this problem because the compiler doesn't know what a map is. It doesn't know because the map header hasn't been included yet. Your header uses the STL templates: string, vector, map, & pair. However, it doesn't define them, or have any reference to where they are defined. The reason your test file barf...
1,225,741
1,240,024
Performance impact of -fno-strict-aliasing
Is there any study or set of benchmarks showing the performance degradation due to specifying -fno-strict-aliasing in GCC (or equivalent in other compilers)?
It will vary a lot from compiler to compiler, as different compilers implement it with different levels of aggression. GCC is fairly aggressive about it: enabling strict aliasing will cause it to think that pointers that are "obviously" equivalent to a human (as in, foo *a; bar *b = (bar *) a;) cannot alias, which all...
1,225,769
1,225,787
Is setting parent for a window from different process correct?
I have two applications having two different top level windows: App1 -- Window1 App2 -- Window2 Now, I am creating a Dialog Dlg1 in App1 and I want to set window2(App2) as a parent window. ( That is because I want my Dlg1 to come on top of Window2 ). I created the dialog by setting Window2 as parent. It worked. But is...
This is more or less supported and it does work with some restrictions. You will need to be careful that the two processes are running as the same user, and that you have no security or elevation issues that would prevent the two processes communicating. Secondly, you may run into issues if the window in question has s...
1,225,828
1,225,838
FireFox Com Function
For IE microsoft provides COM to access it programatically. Is there any function to access Firefox from our Program
Mozilla Active X Control has largely compatible interface. (IWebBrowser/IWebBrowser2/...) Of course Native XPCOM interfaces are a possibility for C++ programs.
1,225,958
1,225,996
What is the correct way to handle timezones in datetimes input from a string in Qt
I'm using Qt to parse an XML file which contains timestamps in UTC. Within the program, of course, I'd like them to change to local time. In the XML file, the timestamps look like this: "2009-07-30T00:32:00Z". Unfortunately, when using the QDateTime::fromString() method, these timestamps are interpreted as being in the...
Do it like this: QDateTime timestamp = QDateTime::fromString(thestring); timestamp.setTimeSpec(Qt::UTC); // mark the timestamp as UTC (but don't convert it) timestamp = timestamp.toLocalTime() // convert to local time
1,226,044
1,226,639
Do you know tool building tree of include files in project\file?
Say, I'd like to have a tool (or script?) taking project (or .h file) and building searchable tree of "includes" included into it (of included into of included into and so so on). Is there exist something like this? Should I write this by myself [of course I am :), but may be somebody had it already written or may be h...
Not entirely sure this is what you're after, but you can easily get a list of includes by generating the post-CPP-processed file from the base c file, and grepping out the file/line number comments, e.g., using gcc gcc -E main.c {usual flags} | grep '#' | cut -d' ' -f3 | sort | uniq where main.c is your base c file.
1,226,634
1,226,957
How to use base class's constructors and assignment operator in C++?
I have a class B with a set of constructors and an assignment operator. Here it is: class B { public: B(); B(const string& s); B(const B& b) { (*this) = b; } B& operator=(const B & b); private: virtual void foo(); // and other private member variables and functions }; I want to create an inheriting clas...
You can explicitly call constructors and assignment operators: class Base { //... public: Base(const Base&) { /*...*/ } Base& operator=(const Base&) { /*...*/ } }; class Derived : public Base { int additional_; public: Derived(const Derived& d) : Base(d) // dispatch to base copy constructor ...
1,226,652
1,226,678
Thread-local singletons
I would like to create a singleton class that is instantiated once in each thread where it is used. I would like to store the instance pointers in TLS slots. I have come up with the following solution but I am not sure whether there are any special considerations with multithreaded access to the singelton factory when ...
Since your objects are thread-local, why do you need locking to protect them at all? Each threads that calls getInstance() will be independent of any other thread, so why not just check that the singleton exists and create it if needed? The locking would only be needed if multiple threads tried to access the same singl...
1,226,876
1,227,524
How can I open a help file (chm or so) from my GUI developed in VC++ 2008?
I'm trying to add some help to my GUI developed in VC++ 2008. I want to compile a chm file, or a hlp file that can be accessed from my menu. Anyone can give me any idea about how to do this? Thanks a lot
Under HKLM\Software\Microsoft\Windows\HTMLHelp , create an entry named help.chm value C:\path to\help file.chm Then to open the chm at a particular topic call HtmlHelp(m_hWnd, "Help.chm", HH_DISPLAY_TOPIC, NULL);
1,227,020
1,227,269
What is function __tcf_0? (Seen when using gprof and g++)
We use g++ 4.2.4 and I'm trying to track down some performance problems in my code. I'm running gprof to generate the profile, and I'm getting the following "strangeness" in that the most expensive function is __tcf_0: Each sample counts as 0.01 seconds. % cumulative self self total tim...
__tcf_0 seems indeed to be a function which calls destructor of static objects and which is registered for each static objects, to be called at exit (taking for granted what is said on this page) Now, the result of your gprof is quite strange, since the function which takes most of the time only takes 0.04 seconds, whi...
1,227,379
1,227,422
When would you use an std::auto_ptr instead of boost::shared_ptr?
We've pretty much moved over to using boost::shared_ptr in all of our code, however we still have some isolated cases where we use std::auto_ptr, including singleton classes: template < typename TYPE > class SharedSingleton { public: static TYPE& Instance() { if (_ptrInstance.get() == NULL) ...
auto_ptr and shared_ptr solve entirely different problems. One does not replace the other. auto_ptr is a thin wrapper around pointers to implement RAII semantics, so that resources are always released, even when facing exceptions. auto_ptr does not perform any reference counting or the like at all, it does not make mul...
1,227,506
1,227,714
Unix Makefile in Windows Visual Studio 2008
I've done a decent search, but can't seem to find a way to get Visual Studio 2008 to use a unix Makefile, or even to create some MSVC compatible equivalent from the Makefile. Does anyone have ideas or similar issues? Note: I already know the benefits/drawbacks of using Makefiles or not, and I don't want to hear your op...
You can also use cccl with make for windows. cccl is a wrapper around Microsoft Visual C++'s cl.exe and link.exe. It converts Unix compiler parameters into parameters understood by cl and link.
1,227,653
1,227,918
Linking against library in release and .exe in debug crashes in Visual studio
I'm using Visual C++ 2008 SP1. I have an app that is compiled in debug mode, but links against a library in release mode. I'm getting a crash at the start-up of the application. To make the problem smaller, I created a simple solution with 2 projects: lib_release (generates a .lib, in release mode) exec_using_lib_rele...
You don't have to use the same runtimes for release and debug modules (but it helps), as long as you follow very specific rules: never mix and ,match accessing the memory allocated using each runtime. To put this more simply, if you have a routine in a dll that allocates some memory and returns it to the caller, the ca...
1,227,842
1,227,846
(C++ and gcc) error: expected constructor, destructor, or type conversion before 'inline'
I have a header file with some inline template methods. I added a class declaration to it (just a couple of static methods...it's more of a namespace than a class), and I started getting this compilation error, in a file that uses that new class. There are several other files that include the same .h file that still c...
It means that you put the "inline" keyword in the wrong place. It needs to go before the method's return type, e.g. template <typename T> inline GLfloat NormalizeHorizontally(T x) Simple as that. The reason that you got this message on one compilation unit and not others may be because it is a templated function tha...
1,228,025
1,228,110
pthread_key_t and pthread_once_t?
Starting with pthreads, I cannot understand what is the business with pthread_key_t and pthread_once_t? Would someone explain in simple terms with examples, if possible? thanks
No, it can't be explained in layman terms. Laymen cannot successfully program with pthreads in C++. It takes a specialist known as a "computer programmer" :-) pthread_once_t is a little bit of storage which pthread_once must access in order to ensure that it does what it says on the tin. Each once control will allow an...
1,228,161
1,228,199
Why use prefixes on member variables in C++ classes
A lot of C++ code uses syntactical conventions for marking up member variables. Common examples include m_memberName for public members (where public members are used at all) _memberName for private members or all members Others try to enforce using this->member whenever a member variable is used. In my experience, m...
You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example: _Foo _L are all reserved words while _foo _l are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found th...
1,228,170
1,280,286
How does Visual Build (kinook) build c++ projects?
The bld file has the sln file specified, but what does it call to build it? MSDev? MSBuild? other? I want to add some command line params, but I am not sure which executable it calls for unmanaged C++ solutions.
It depends. For Visual Studio 2002/2003, it always calls devenv.com. For Visual Studio 2005 and up, it calls msbuild.exe by default, or devenv or vcbuild if specified in the Override field on the Options tab. ... the action will automatically locate the correct devenv.com or msbuild.exe compiler, based on the vers...
1,228,362
1,228,392
Boost::Asio read/write operations
What is the difference between calling boost::asio::ip::tcp::socket's read_some/write_some member functions and calling the boost::asio::read/boost::asio::write free functions? More specifically: Is there any benefit to using one over the other? Why are both included in the library?
read_some and write_some may return as soon as even a single byte has been transferred. As such you need to loop if you want to make sure you get all of the data - but this may be what you want. The free functions are wrappers around read_some and write_some, and have different termination conditions depending on the o...
1,228,402
1,228,898
How does one include TR1?
Different compilers seem to have different ideas about TR1. G++ only seems to accept includes of the type: #include <tr1/unordered_map> #include <tr1/memory> ... While Microsofts compiler only accept: #include <unordered_map> #include <memory> ... As for as I understand TR1, the Microsoft way is the correct one. Is t...
Install boost on your machine. Add the following directory to your search path. <Boost Install Directory>/boost/tr1/tr1 see here boost tr1 for details Now when you include <memory> you get the tr1 version of memory that has std::tr1::shared_ptr and then it includes the platform specific version of <memory> to get all t...
1,228,545
1,234,191
What configuration file format allows the inclusions of otherfiles and the inheritance of settings?
I'm writing a Multiplayer C++ based game. I need a flexible file format to store information about the game charactors. The game charactors will often not share the same attributes, or use a basew For example: A format that would allow me to do something like this: #include "standardsettings.config" //include other f...
After alot of searching i've found a pretty good solution using Lua Lua I found out was originally designed as a configuration file language, but then evolved into a complete programming language. Example util.lua -- helper function needed for inheritance function inherit(t) -- return a deep copy (incudes a...
1,228,777
1,228,882
Visual Studio 2008, Runtime Libraries usage advice
I would like some information on the runtime libraries for Visual Studio 2008. Most specifically when should I consider the DLL versions and when should I consider the Static versions. The Visual Studio documentation delineates the technical differences in terms of DLL dependencies and linked libraries. But I'm left wo...
Larry Osterman feels that you should always use the multi-threaded DLL for application programming. To summarize: Your app will be smaller Your app will load faster Your app will support multiple threads without changing the library dependency Your app can be split into multiple DLLs more easily (since there will only...
1,229,050
1,229,100
How to pass bool from c# through c++ com interface in idl
I know I'm missing something simple, I have next to no experience with these com things. I would like to do this within an interface in an idl [id(5), helpstring("Returns true if the object is in a valid state.")] HRESULT IsValid([out, retval] boolean bValid); However this gives : [out] paramter is not a pointer. Ok, ...
Try: HRESULT IsValid([out, retval] VARIANT_BOOL *bValid); In order to work as an output, it has to be a pointer to the value; this is how it will be written to on the C++ side: *bValue = VARIANT_TRUE; I don't know if you can write the type as boolean - I've only ever seen VARIANT_BOOL being used. On the C# side, it w...
1,229,241
1,229,277
How do I force a program to appear to run out of memory?
I have a C/C++ program that might be hanging when it runs out of memory. We discovered this by running many copies at the same time. I want to debug the program without completely destroying performance on the development machine. Is there a way to limit the memory available so that a new or malloc will return a NUL...
Try turning the question on its head and asking how to limit the amount of memory an OS will allow your process to use. Try looking into http://ss64.com/bash/ulimit.html Try say: ulimit -v Here is another link that's a little old but gives a little more back ground: http://www.network-theory.co.uk/docs/gccintro/gcc...
1,229,429
1,229,530
Using SQL statements to query in-memory objects
Suppose I have a collection of C++ objects in memory and would like to query them using an SQL statement. I’m willing to implement some type of interface to expose the objects’ properties like columns of a database row. Is there a library available to accomplish this? In essence, I’m trying to accomplish something li...
C++ objects are not the same thing as SQL tables. If you want to use SQL syntax to query the objects, you will first need to map/persist them into a table structure (ORM, object-relational-mapping). There are a number of fine ORM solutions out there besides Linq. Once you have your objects represented in SQL tables, y...
1,229,430
1,229,542
How do I prevent my 'unused' global variables being compiled out?
I'm using static initialisation to ease the process of registering some classes with a factory in C++. Unfortunately, I think the compiler is optimising out the 'unused' objects which are meant to do the useful work in their constructors. Is there any way to tell the compiler not to optimise out a global variable? clas...
The compiler is not allowed to optimiza away global objects. Even if they are never used. Somthing else is happening in your code. Now if you built a static library with your global object and that global object is not referenced from the executable it will not be pulled into the executable by the linker.
1,229,433
1,229,448
Manual invocation of constructor?
Suppose I am allocating an arbitrary block of memory. Part of this block is atomic data (ints, bytes, etc.) and some of this block of data I want to be occupied by objects. Can I turn any arbitrary piece of memory into an object through a constructor call, such as data->MyObject () and subsequently destroying the obj...
What you are looking for is called placement new.
1,229,441
1,229,459
Simultaneous C++ development on Linux and Windows
We have a handful of developers working on a non-commercial (read: just for fun) cross-platform C++ project. We've already identified all the cross-platform libraries we'll need. However, some of our developers prefer to use Microsoft Visual C++ 2008, others prefer to code in Emacs on GNU/Linux. We're wondering if it ...
Use CMake to manage your build files. This will let you setup a single repository, with one set of text files in it. Each dev can then run the appropriate cmake scripts to build the correct build environment for their system (Visual Studio 2008/2005/GNU C++ build scripts/etc). There are many advantages here: Each dev...
1,229,728
1,229,746
Serialize a structure in C# to C++ and vice versa
Is there an easy way to serialize a C# structure and then deserialize it from c++. I know that we can serialize csharp structure to xml data, but I would have to implement xml deserializer in c++. what kind of serializer in C# would be the easiest one to deserialize from c++? I wanted two applications (one C++ and anot...
Try Google Protocol Buffers. There are a bunch of .NET implementations of it.
1,229,786
1,229,965
Using Boost.Thread headers with MSVC Language Extensions disabled
I just discovered that when Language Extensions are disabled in MSVC, you get this error if you try to include boost/thread/thread.hpp: fatal error C1189: #error : "Threading support unavaliable: it has been explicitly disabled with BOOST_DISABLE_THREADS" It seems that when Boost detects that language extensions are...
I don't see any simple way to turn off the behavior. You could wrap the block with your own #ifdef starting at boost\config\suffix.hpp(214): #ifndef TEMP_HACK_DONT_DISABLE_WIN32_THREADS // XXX TODO FIXME #if defined(BOOST_DISABLE_WIN32) && defined(_WIN32) \ && !defined(BOOST_DISABLE_THREADS) && !defined(BOOST_HAS_P...
1,230,006
1,230,021
C++ Overriding Methods
I can't figure out what is up with this. I have a Scene class that has a vector of Entities and allows you to add and get Entities from the scene: class Scene { private: // -- PRIVATE DATA ------ vector<Entity> entityList; public: // -- STRUCTORS --------- Scene(); // -- ...
I think that you need to post your calling code, but the essentially problem is this. You have a concrete class Polygon deriving from another concrete class Entity. Your addEntity and getEntity functions take and return an Entity by value so if you try to pass in or retrieve an Entity, you will copy only the Entity par...
1,230,065
1,234,024
Speedup Matlab to C++ Conversion
I have some Matlab image processing code which runs pretty slowly and I'm prepared to convert it over to C/C++. I don't really know much about how matlab works and how code is executed but I'm just interested to hear what kind of speedups I might expect. Clearly there are many variables that will affect this but I'm ...
It mostly depends on the tightness of your loops in Matlab. If you are simply calling a series of built-in Matlab image processing functions, you will most likely not be able to improve performance (most likely you will hurt it). If you are looping over image pixels or doing some kind of block processing, you may see...
1,230,222
1,230,530
Selected Rows in QTableView, copy to QClipboard
I have a SQLite-Database and I did it into a QSqlTableModel. To show the Database, I put that Model into a QTableView. Now I want to create a Method where the selected Rows (or the whole Line) will be copied into the QClipboard. After that I want to insert it into my OpenOffice.Calc-Document. But I have no Idea what to...
To actually capture the selection you use the item view's selection model to get a list of indices. Given that you have a QTableView * called view you get the selection this way: QAbstractItemModel * model = view->model(); QItemSelectionModel * selection = view->selectionModel(); QModelIndexList indexes = selection->s...
1,230,260
1,230,319
MFC CEdit Ctrl Question
I have a CEdit control that I want to be able to take time input from. Now I want this input to come in the form hh:mm:ss. Currently I am using a separate CEdit control for hour, mins, & secs. I know I could require the user enter in colons to separate hours, mins, secs, but this I believe will get confusing for my u...
Reformatting the text is simple enough, although I would wait until a lost focus message rather than insert colons while the user is typing, it gets confusing especially if they need to edit or delete a character. You can implement tab stops within the field by getting VK_TAB but I'm not sure I would do this - users ar...
1,230,423
1,230,558
C++ : handle resources if constructors may throw exceptions (Reference to FAQ 17.4]
Thanks for all the response. I reformatted my question to understand the state of the member pointer after the containg class constructor throws an exception Again my example class :) class Foo { public: Foo() { int error = 0; p = new Fred; throw error; // Force throw , trying to unders...
There is a similar question here that covers what your asking. In this case, if the call to new fails, then the memory for the pointer is guaranteed to be freed. If the call succeeds, and the constructor throws after that, you will have a memory leak. The destructor of the class will not be called, because the object w...
1,230,450
1,234,159
error: syntax error before '@' token (why?)
I include the amalgamation sqlite code in my iPhone project, and remove the reference to the iPhone sqlite framework. My main target compile fine. I have a second target for unit testing with the google framework. When compile I get: error: syntax error before '@' token I don't understand why. I have set both project...
I finally figure out the problem. I copy this from the iPhone target to the Testing target: GCC_DYNAMIC_NO_PIC = NO GCC_OPTIMIZATION_LEVEL = 0 GCC_PRECOMPILE_PREFIX_HEADER = YES GCC_PREFIX_HEADER = JhonSell_Prefix.pch GCC_PREPROCESSOR_DEFINITIONS = DEBUG But why before I have not issues? I truly not understand.
1,230,598
1,230,614
Non-destructible read from a stream
Is is possible to try to read from a stream but do not change the stream itself (and return bool whether it was a success)? template <typename T> bool SilentRead (stringstream& s, T& value) { stringstream tmp = s; tmp >> value; return tmp; } This doesn't work because stringstream doesn't have public copy c...
StringStream, refering to this allows you to use tellg and seekg to get / set position. So you could: 1. Get current position 2. Read 3. Set current position to one, that you have just read.
1,230,677
1,230,684
How does the compiler determine which member functions mutate?
A comment to one of my posts interested me: Me too. I also give accessors/mutators the same name. I was wondering about this, because I have always used setBar(int bar) instead of a mutator named the same thing. I want to know: can the compiler determine based on a const identifier what mutates at runtime, or can it ...
The first thing the compiler looks at is the number and type of parameters you're passing to the function. This resolves the overload on bar before it even needs to look at const-ness. If you fail to mark bar() as const, the compiler will inform you of this the first time you attempt to call bar() on a const instance o...
1,230,915
1,230,979
Static Pointer to Dynamically allocated array
So the question is relatively straight forward, I have several semi-large lookup tables ~500kb a piece. Now these exact same tables are used by several class instantiations (maybe lots), with this in mind I don't want to store the same tables in each class. So I can either dump the entire tables onto the stack as 'stat...
Static members will never be allocated on the stack. When you declare them (which of course, you do explicitly), they're assigned space somewhere (a data segment?). If it makes sense that the lookup tables are members of the class, then make them static members! When a class is instanced on the stack, the static member...
1,231,178
3,803,333
Load an PEM encoded X.509 certificate into Windows CryptoAPI
I need to load a PEM encoded X.509 certificate into a Windows Crypto API context to use with C++. They are the ones that have -----BEGIN RSA XXX KEY----- and -----END RSA XXX KEY-----. I found examples for Python and .NET but they use specific functions I can't relate to the plain Windows Crypto API. I understand how ...
KJKHyperion said in his answer: I discovered the "magic" sequence of calls to import a RSA public key in PEM format. Here you go: decode the key into a binary blob with CryptStringToBinary; pass CRYPT_STRING_BASE64HEADER in dwFlags decode the binary key blob into a CERT_PUBLIC_KEY_INFO with CryptDecodeObjectEx; pass ...
1,231,433
1,231,475
Strange backtrace - where is the error?
I'm developing an image processing application in C++. I've seen a lot of compiler errors and backtraces, but this one is new to me. #0 0xb80c5430 in __kernel_vsyscall () #1 0xb7d1b6d0 in raise () from /lib/tls/i686/cmov/libc.so.6 #2 0xb7d1d098 in abort () from /lib/tls/i686/cmov/libc.so.6 #3 0xb7d5924d in ?? () f...
Perhaps a previously allocated chunk of memory has a buffer overflow that is corrupting the heap?
1,231,685
1,231,693
How do I display more decimals in the output console?
I want to output the value of a double in it's full precision. However, when using the cout function, it only displays the first 6 digits even though there is around 15-16 digits of precision. How do I get my program to display the entire value, including the magnitude (power) component?
Use the setprecision() manipulator: http://www.cplusplus.com/reference/iostream/manipulators/setprecision/ You can also force scientific notation with the scientific manipulator: http://www.cplusplus.com/reference/iostream/manipulators/scientific/ cout << scientific << setprecision(15) << my_number << endl;
1,231,788
1,231,794
How do I initialize a const std::pair?
Let's say that I've got a : #include <utility> using namespace std; typedef pair<int, int> my_pair; how do I initialize a const my_pair ?
Use its constructor: const my_pair p( 1, 2 );
1,231,899
1,231,918
Check if a char* buffer contains UTF8 characters?
In the absence of a BOM is there a quick and dirty way in which I can check if a char* buffer contains UTF8 characters?
Not reliably. See Raymond Chen's series of posts on the subject. The problem is that UTF-8 without a BOM is all too often indistinguishable from equally valid ANSI encoding. I think most solutions (like the win32 API IsTextUnicode) use various heuristics to give a best guess to the format of the text.
1,231,942
1,232,035
Learning C++ without an IDE
I've recently started to learn C++ and am completely confused with the choices of IDEs and compilers out there. I am competent with interpreted languages and like the simplicity of using any IDE or text editor and then running the interpreter from the command line. Everything works as I expect, regardless of the IDE us...
Firstly, are there any books or websites that teach C++ from this approach? (IDE-less) Yes, definitely. Stroustrup's book has already been mentioned. For learning C++ I'd also recommend two other books: If you like thorough explanations and don't shy away from 1000 pages, look at Lippman et al. If you rather like a s...
1,231,991
1,286,591
Unlock a thread from another process, in c++
I'm programming an interprocess communication module (Process A and Process B). Is there any way the communication thread in B can run (be unlock) as soon as process A finishes a specific action, I mean without B doing any polling nor B waiting too much after A finishes its action? Which are the concepts/models/design ...
This is quite hard job: For Unix OSes you can use: pthread condition and mutex with setpshared argument. Note: it is supported well under Linux 2.6, Solaris, but it does not supported FreeBSD and Cygwin (don't know about Mac OS X) For Unixes you may also use named semaphores, but I don't know the support level of them...
1,232,006
1,232,068
Initializing aggregate unions
I've got a union : union my_union { short int Int16; float Float; }; I'd like to create : const my_union u1 = ???; const my_union u2 = ???; and initialize their values to be of different types respectively : u1 -> int16 u2 -> float How do I do that ? If the above is not possible, are there any workarounds?
union can have any number of constructors - this will work for any datatypes without constructor, so your example is well if exclude string (or make pointer to string) #include <string> using namespace std; union my_union { my_union(short i16): Int16(i16){} my_union(float f): Float(f){} my...
1,232,081
1,346,381
Heap randomization in Windows
Windows 7 has Heap randomization and Stack randomization features. How could I manage it? How they are affects performance of my application? Where I could find more information on how it works? I'm using Visual Studio 2008 for developing C++ programs. I can't find any compiler's options for that features.
Ok, Heap randomization and Stack randomization are Windows features, but have to be explicitly enabled for each process at link time. Mark Russinovich described how it is work in his 5-th Windows Internals book. Stack randomization consists of first selecting one of 32 possible stack locations separated by either 64 K...
1,232,176
1,232,195
How do I put two increment statements in a C++ 'for' loop?
I would like to increment two variables in a for-loop condition instead of one. So something like: for (int i = 0; i != 5; ++i and ++j) do_something(i, j); What is the syntax for this?
A common idiom is to use the comma operator which evaluates both operands, and returns the second operand. Thus: for(int i = 0; i != 5; ++i,++j) do_something(i,j); But is it really a comma operator? Now having wrote that, a commenter suggested it was actually some special syntactic sugar in the for statement, and...
1,232,262
1,232,272
Memory leak in C,C++; forgot to do free,delete
We allocate memory in C using malloc and in C++ using new. I know that memory allocated must be freed or given back to OS using free in C and delete in C++. If I forgot to use free/delete after allocating memory, it means there will be memory leak. Now, my question is, is this memory leak only during the time period of...
It's per-process. Once your process exits, the allocated memory is returned to the OS for use by other processes (new or existing). To answer your edited question, there's only a finite amount of memory in your machine. So if you have a memory leak, then the major problem is that the memory isn't available for other pr...
1,232,329
1,232,343
How to take output from .NET executable and convey to MFC application?
I have a dialog based MFC application through which I have to call a .NET executable. My question are: How will the MFC application know that the .NET executable is closed? if suppose a .Net executable process some information and want to convey the output to the MFC application, how can this be achieved. Please help...
The MFC application can just wait for the .NET process to exit in the normal way - either using a wait handle or by polling it. As for collecting output - the simplest mechanisms is likely to be for the .NET executable to write to a file, and then the MFC app can read it afterwards. It's crude but very easy to implemen...
1,232,505
1,232,515
Register a C# COM component?
I have developed a C# com component which I am using from managed c++. On my dev machine when everything works fine. However when I distribute the files, I received an error that the component has not been registered. When I try a regsvr32 on the dll it gives me an error (C# dlls cannot be registered). How do I properl...
You use regasm with /codebase (and it needs to be ComVisible [but as Patrick McDonald correctly poinhts out, you've already got past that as it works locally])
1,232,791
1,232,923
How can I make a file selector with a combobox in VC++ 2008?
I have this dialog: ID__BATERIA __FAX DIALOGEX 0, 0, 235, 86 STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU CAPTION "Nueva batería de fax" FONT 8, "MS Shell Dlg", 400, 0, 0x1 BEGIN DEFPUSHBUTTON "OK",IDOK,120,65,50,14 PUSHBUTTON "Cancel",IDCANCEL,175,65,50,14 LTEXT ...
From http://msdn.microsoft.com/en-us/library/bb775808.aspx "This notification message occurs only for a combo box with the CBS_SIMPLE style. In a combo box with the CBS_DROPDOWN or CBS_DROPDOWNLIST style, a double-click cannot occur because a single click closes the list box."
1,232,951
1,233,018
Are there good Patterns/Idioms for Data Translation/Transformation?
I'm sorry for the generic title of this question but I wish I was able to articulate it less generically. :-} I'd like to write a piece of software (in this case, using C++) which translates a stream of input tokens into a stream of output tokens. There are just five input tokens (lets call them 0, 1, 2, 3, 4) and each...
You could define a graph, where each node contains an input token and an associated output. The links of each node describe the possible next tokens. Thus, a path in the graph describe a possible transformation rule. To transform the data, start from the node corresponding to the first input token, and try to navigate ...
1,232,964
1,232,986
Reading data from file into array of structs C++
I have a sample txt file and want to read the contents of the file into an array of structs. My persons.txt file contains 5 arbitrary nos one on each line. 7 6 4 3 2 My program looks like this: #include <iostream> #include <fstream> using namespace std; struct PersonId { typedef PersonId* ptr; PersonId(); ...
istream& operator >> (istream& is, PersonId &p) { is >> p.fId; return is; } (Reading the member fId of p, not the entire structure) And the the while in main, read the structure, not a value: instead of indata >> is; put indata >> p[i];
1,233,040
1,233,351
Why should I setup a plugin interface in c++ instead of c
As a result of my previous questions I asked myself: Is it usefull at all to setup a C++ interface for a plugin system? The following points are speaking against it: No common ABI between different compilers and their versions, no common layout of the objects in memory No direct class export. You have to export factor...
Although this is more about the "how" than the "why", you may be interested in the (not yet)Boost.Extension library, as well as the author's blog on the topic. For the "why" part, my 2 (Canadian) cents: It depends on the audience (the plugin writers) and on the richness of the interface between your application and its...
1,233,042
1,233,174
How can I separate headers, classes and main functions in C++?
Please help me in separating the classes, headers and main() in the following program. I tried my best but there is problem. #include "stdafx.h" #include<iostream> #include<string> using namespace std; class player { public: string name; string type; void getdata() { cout<<"Enter the name of th...
If you want to separate your classes you should use create two files; .h & .cpp. In the header file you place your definitions and declarations, and in the CPP file you implement your methods. Player.h #ifndef __PLAYER_H_ #define __PLAYER_H_ #include <string> class Player { public: Player(); ~Player(); /...
1,233,381
1,233,460
linking and using a C++ library with an Objective-C application
I'm writing a graphical application using Objective-C for the front end and C++ for the graphics processing and network communication. I read around on Apple's site looking for a way to link either a .dylib or .so with my C++ code in it to my Xcode project, but nothing seemed to work. I was able to get the project to r...
You're going to hit one obstacle in the form of what's called "name mangling". C++ stores function names in a way not compatible with Obj-C. Objective-C doesn't implement classes in the same way as C++, so it's not going to like it. One way around this is to implement a set of simple C functions which call the C++ func...
1,233,400
1,233,577
How to circumvent Symbian naming conventions?
I'm about to write a C++ library that is to be used by a Windows application as well as on Symbian. Linux is not a current requirement but should generally be possible, too. For this reason I would like to use the STL/Boost naming conventions instead of Symbian's, which I think, are hard to get used to. This seems to a...
Coding conventions are not strict. They are there to make understanding code easier for us humans. If you're writing a multi-platform library, feel free to use whatever convention you are comfortable with. Of course, your library probably needs to interface with the underlying operating system in some ways. With the he...
1,233,435
1,233,827
Detect compiler with #ifdef
I'm trying to build a small code that works across multiple platforms and compilers. I use assertions, most of which can be turned off, but when compiling with PGI's pgicpp using -mp for OpenMP support, it automatically uses the --no_exceptions option: everywhere in my code with a "throw" statement generates a fatal co...
Take a look at the Pre-defined C/C++ Compiler Macros project on Sourceforge. PGI's compiler has a __PGI macro. Also, take a look at libnuwen's compiler.hh header for a decent way to 'normalize' compiler versioning macros.
1,233,501
1,237,981
read from file to array of structs within structs in C++
I have asked this question previously here and a similar question was closed. SO based on a comment from another user, I have reframed my question: In the first post, I was trying to read tha data from a file into an array with a struct.By using indata << p[i] and is >> p.fId, I was able to read values from data file i...
OK, first some grumbling :-) You say what you want. You wrote how you try. Great. I guess result is not what you expected. But you didn't tell us what is the result you get and why you are disappointed with it. As I look at your code, it shouldn't compile. The problem is here: istream& PersonData::read(std::istream& is...
1,233,612
1,233,677
Comparing 2 graphs created by Boost Graph Library
This may be a rather novice or even wrong question so please be forgiving. Is there a way to compare 2 graphs created using the Boost Graph Library => with 1 graph created in memory and the 2nd loaded from an archive (i.e. 2nd was serialized out previously)? I don't see an operator== provided in BGL's documentation, bu...
Boost.Graph can do this but not with the == operator: http://www.boost.org/doc/libs/1_39_0/libs/graph/doc/isomorphism.html It is a hard problem so it will take long for large graphs.
1,233,963
1,234,050
How Operating System callbacks work
Follow up question to: This question As described in the linked question, we have an API that uses an event look that polls select() to handle user defined callbacks. I have a class using this like such: class example{ public: example(){ Timer* theTimer1 = Timer::Event::create(timeInterval,&example::Fun...
The real answer would depend on the implementation of Timer, but if you're getting callbacks run from the same thread, it's most likely using signals or posix timers. Either way, select() isn't involved at all. With signals and posix timers, there is very little you can do safely from the signal handler. Only certain s...
1,234,031
1,234,062
How do i forward declare a class that has been typedef'd?
I have a string class that, unsurprisingly, uses a different implementation depending on whether or not UNICODE is enabled. #ifdef UNICODE typedef StringUTF16 StringT; #else typedef StringUTF8 StringT; #endif This works nicely but I currently have a problem where I need to forward declare the StringT typedef. How can...
Follow the example set by the iosfwd standard header. Write a header file that contains this, and call it StringTFwd.h class StringUTF16; class StringUTF8; #ifdef UNICODE typedef StringUTF16 StringT; #else typedef StringUTF8 StringT; #endif At least this is reusable and doesn't ugly up the headers that refer to it.
1,234,107
1,234,134
why >?= and <?= don't work in VC++?
why >?= and <?= don't work in VC++? but they work fine in gcc/g++ like: a>?=b; are they right usages?
Because those are the old GC++-specific extensions for minimum and maximum. From 6. Extensions to the C++ Language: The GNU compiler provides these extensions to the C++ language (and you can also use most of the C language extensions in your C++ programs). If you want to write code that checks whether these features ...
1,234,303
1,234,338
How can I get an HDC object from a CDC object?
I have an object, dc, of type CDC and I'd like to get an HDC object. I read the MSDN documentation here, but don't really understand it. Can someone provide me with a brief example/explanation on how to do this?
CDC class has operator HDC() defined which allows the compiler to convert a CDC object to HDC implicitly. Hence if you have CDC* and a function which takes HDC then you just dereference the pointer and send it to the function.
1,234,582
1,234,618
Purpose of Trigraph sequences in C++?
According to C++'03 Standard 2.3/1: Before any other processing takes place, each occurrence of one of the following sequences of three characters (“trigraph sequences”) is replaced by the single character indicated in Table 1. ---------------------------------------------------------------------------- | trigraph | ...
This question (about the closely related digraphs) has the answer. It boils down to the fact that the ISO 646 character set doesn't have all the characters of the C syntax, so there are some systems with keyboards and displays that can't deal with the characters (though I imagine that these are quite rare nowadays). In...
1,234,750
1,238,315
C++ Socket Server - Unable to saturate CPU
I've developed a mini HTTP server in C++, using boost::asio, and now I'm load testing it with multiple clients and I've been unable to get close to saturating the CPU. I'm testing on a Amazon EC2 instance, and getting about 50% usage of one cpu, 20% of another, and the remaining two are idle (according to htop). Detai...
boost::asio is not as thread-friendly as you would hope - there is a big lock around the epoll code in boost/asio/detail/epoll_reactor.hpp which means that only one thread can call into the kernel's epoll syscall at a time. And for very small requests this makes all the difference (meaning you will only see roughly sin...
1,234,760
1,234,794
Is it a bad idea to use pointers as loop incrementers instead of the usual "int i"?
An example of this would be: char str[] = "Hello"; int strLength = strlen(str); for ( char * pc = str; pc < str + strLength; pc++) { *pc += 2; } Edit: Accounted for write-protected memory issue.
My one issue is that you'd have a lot of fun if you leave out the * in *pc in the for loop. Whoops? More generally, it is slightly harder to tell the difference between reassigning the pointer and modifying the value. However, (though I don't have it handy), Stroustroup himself endorses(see edit) pointer iteration in t...
1,234,988
1,236,098
How to get a Win32 Thread to wait on a work queue and a socket?
I need a client networking thread to be able to respond both to new messages to be transmitted, and the receipt of new data on the network. I wish to avoid this thread performing a polling loop, but rather to process only as needed. The scenario is as follows: A client application needs to communicate to a server via a...
An alternative to I/O Completion Ports for sockets is using WSAEventSelect to associate an event with the socket. Then as others have said, you just need to use another event (or some sort of waitable handle) to signal when an item has been added to your input queue, and use WaitForMultipleObjects to wait for either ki...
1,235,165
1,235,208
C++ cross-platform dynamic libraries for Linux and Windows
I am wanting to write some cross-platform library code. I am creating a library both static and dynamic with most of the development done in Linux, I have got the static and shared library generated in Linux but now wanted to generate a Windows version of a static and dynamic library in the form of .lib and .dll using ...
In general, there are two issues you need to be concerned with: The requirement that, on Windows, your DLL explicitly exports symbols that should be visible to the outside world (via __declspec(dllexport), and Being able to maintain the build system (ideally, not having to maintain a separate makefile and Microsoft Vi...
1,235,286
1,235,294
why does pointer to array fails to return as **
I don't understand why the following fails: #include<string> class Foo { public: std::string** GetStr(){return str;} private: std::string * str[10]; }; Thanks
First, you tag this as C++ and C. Which is it? C does not have a string class. If it is C++, please remove the C tag, it is misleading (they are not the same language!). Edit: I misunderstood what you are trying to do. Your method should compile. You just have to remember to dereference the returned str to get the stri...
1,235,299
1,235,353
C++ multiple processes?
I've got a project that consists of two processes and I need to pass some data between them in a fast and efficent manner. I'm aware that I could use sockets to do this using TCP, even though both processes will always exist on the same computer, however this does not seem to be a very efficient solution. I see lots of...
For IPC, Windows supports named pipes just like Linux does, except that the pipe names follow a different format, owing to the difference in path formats between the two operating systems. This is something that you could overcome with simple preprocessor defines. Both operating systems also support non-blocking IO on ...
1,235,371
1,235,674
Fastest base conversion method?
Right now I'm working on a project which requires an integer to be converted to a base 62 string many times a second. The faster this conversion is completed, the better. The problem is that I'm having a hard time getting my own base conversion methods to be fast and reliable. If I use strings, it's generally reliable ...
Probably what you want is some version of itoa. Here is a link that shows various versions of itoa with performance tests: http://www.strudel.org.uk/itoa/ In general, I know of two ways to do this. One way it to perform successive divisions to strip off one digit at a time. Another way is to precompute conversions i...
1,235,425
1,235,515
coclass in .idl import interface defined elsewhere?
I have an IDL file that defines a few interfaces followed by a coclass. Can I make this class import interfaces that are not defined in this class?
Yes. You need to use the import directive to load the .idl for the external interfaces, or use importlib to load the type library. Something like this: import "otherlibrary.idl"; library MyLibrary { coclass MyClass { interface OtherInterface; }; }; Or this: library MyLibrary { importlib "otherlibrary.tlb"...
1,235,447
1,235,471
std::getline and eol vs eof
I've got a program that is tailing a growing file. I'm trying to avoid grabbing a partial line from the file (e.g. reading before the line is completely written by the other process.) I know it's happening in my code, so I'm trying to catch it specifically. Is there a sane way to do this? Here's what I'm trying: if (g...
This will never be true: if (getline (stream, logbuffer)) { if (stream.eof()) { /// will never get here If getline() worked, the stream cannot be in an eof state. The eof() and related state tests only work on the results of a previous read operation such as getline()- they do not predict what the next ...
1,235,798
1,235,956
How do I use CharNext in the Windows API properly?
I have a multi-byte string containing a mixture of japanese and latin characters. I'm trying to copy parts of this string to a separate memory location. Since it's a multi-byte string, some of the characters uses one byte and other characters uses two. When copying parts of the string, I must not copy "half" japanese c...
Here is a really good explanation of what is going on here at the Sorting it All Out blog: Is CharNextExA broken?. In short, CharNext is not designed to work with UTF8 strings.
1,236,117
1,236,131
attached process error VS C++ .NET
When I go to Debug -> Start I get the error: "Unable to attach to machine 'mypc' Do you want to continue anyway? YES/NO I did not attach a proces and am not sure why it is coming up. (Also, when I hit YES to the error, it does not run.) How do I remove all attachments on the debugger?
It's probably a problem with your project configuration settings. Right click on the project in Solution Explorer and click Properties. Go to the Debugging Tab. Make sure that you're debugging on your machine. In the "Remote Settings" option your connection should be Local. You also want to make sure the option to ...
1,236,161
1,236,262
Why does the original CString get overwritten when passing a copy to the DrawText function with the DT_MODIFYSTRING option?
I've already found a workaround to this problem, but was just wondering if anyone knew what was actually happening to cause the problem I was seeing. My guess is that it has something to do with mutability of strings, but I thought the CString object accounted for that in the copy constructor. The following code cause...
First, note that CString can be used as a raw string pointer in two ways: operator LPCSTR - gives a pointer which should never be modified. GetBuffer - gives a pointer to memory specifically for the purpose of modifying the string. Now, DrawText is declared to accept a LPCSTR. So when you pass a CString object direct...
1,236,485
1,236,492
How to access elements of a C++ map from a pointer?
Simple question but difficult to formulate for a search engine: if I make a pointer to a map object, how do I access and set its elements? The following code does not work. map<string, int> *myFruit; myFruit["apple"] = 1; myFruit["pear"] = 2;
You can do this: (*myFruit)["apple"] = 1; or myFruit->operator[]("apple") = 1; or map<string, int> &tFruit = *myFruit; tFruit["apple"] = 1; or (C++ 11) myFruit->at("apple") = 1;
1,236,550
1,236,559
Incorrect floating point math?
Here is a problem that has had me completely baffled for the past few hours... I have an equation hard coded in my program: double s2; s2 = -(0*13)/84+6/42-0/84+24/12+(6*13)/42; Every time i run the program, the computer spits out 3 as the answer, however doing the math by hand, i get 4. Even further, after inputting...
You're not actually doing floating point math there, you're doing integer math, which will floor the results of divisions. In C++, 5/4 = 1, not 1.25 - because 5 and 4 are both integers, so the result will be an integer, and thus the fractional part of the result is thrown away. On the other hand, 5.0/4.0 will equal app...
1,236,670
1,237,091
How to make OpenGL apps in 64-bit Windows?
My project compiles, link and run in xp32 then I tried to cross compile it to x64 and I came across a lot of questions: There's no native x64 instalable OpenGL SDK so I link against what? I saw someone saying that x64 apps use 32bits opengl dll. I tryied to run my compiled 64-bits app in a xp64 with drivers to my vide...
The 64-bit OpenGL import library is included in the Windows SDK and gets installed to %ProgramFiles%\Microsoft SDKs\Windows\<version>\Lib\x64\OpenGL32.lib. The corresponding DLL is named opengl32.dll and is located in %SystemRoot%\system32. The 32-bit version is also named opengl32.dll and is located in %SystemRoot%\sy...