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,193,693
1,194,670
Behaviour of static variables in dynamically linked libraries (C/C++)
As discussed here, a static variable is stored in the .BSS or .DATA segment. Where is this memory stored if the static variable is inside a function that's in a dynamically linked library ? Does storage for this variable get allocated in the .BSS or .DATA segment of the linking process at the time of linkage ?
The static variable is going to end up in the .BSS or .DATA section of the DLL file. The executable that links to the DLL probably won't even know it exists. When the EXE loads the DLL, the system sets up the DLL's data sections for it, and then calls the DllMain(). That's when the DLLs statics come into existence and ...
1,193,748
1,193,769
How to create a BMP file from raw byte[] in Java
I have a C++ application which communicates with a camera and fetches raw image-data. I then have a Byte[] in C++, which i want to send to Java with JNI. However, i need to convert the raw Byte[] to an real file format(.bmp was my first choice). I can easily do this if i write it from C++ to an file on the hard-drive,...
It's just two lines in Java 1.5: BufferedImage image = ImageIO.read( new ByteArrayInputStream( byteArray ) ); ImageIO.write(image, "BMP", new File("filename.bmp")); Java (on Windows) knows how to export jpg, png and bmp as far as i know.
1,193,756
1,202,685
Right side Explorer context menu (IID_IContextMenu?)
One of my applications has a Windows Explorer like file list control. When the user right clicks on a file I can successfully show the Explorer context menu (with some extra options of my own). However if the user right clicks on the list control itself (no items selected), then I'm unable to show the 'correct' context...
Call IShellFolder::CreateViewObject() to get the IContextMenu for a folder itself. IShellFolder::GetUIObjectOf() is meant for retrieving interfaces for individual items inside of a folder, not for a folder itself. This is stated in MSDN's documentation: IShellFolder::CreateViewObject Method This method is also used ...
1,194,090
1,194,101
nested struct with array
Please, help me to create a nested struct with an array. How do I fix this code? class CMain { public: CMain(); ~CMain(); private: struct { CCheckSum() : BufferSize(500) {memset(Buffer, 0, BufferSize);} const int BufferSize; char Buffer[Buffer...
Static arrays need to know their length at compile time, or you need to dynamically allocate memory: struct CCheckSum { CCheckSum() : BufferSize(500), Buffer(new char[BufferSize]) { memset(Buffer, 0, BufferSize); } ~CCheckSum() { delete[] Buffer; } // Note the use of delete[]! cons...
1,194,371
1,197,117
Which one to use when static_cast and reinterpret_cast have the same effect?
Possible Duplicate: Should I use static_cast or reinterpret_cast when casting a void* to whatever Often, especially in Win32 programming it is required to cast from one opaque type to another. For example: HFONT font = cast_here<HFONT>( ::GetStockObject( SYSTEM_FONT ) ); Both static_cast and reinterpret_cast are a...
Everybody has noted that reinterpret_cast<> is more dangerous than static_cast<>. This is because reinterpret_cast<> ignores all type information and just assigns a new type without any real processing, as a result the processing done is implementation defined (though usually the bit patterns of the pointers are the sa...
1,194,453
1,194,715
Fetching rows in a MySQL database table using MySQL C API and C++
I'm confused when trying to fetch table rows in mysql using C++ with MySQL C API. I can do it easily in PHP, just because C++ is a strongly-typed language so that we also need to take care of the dirty process.. This is how I done it in PHP $data = array(); $i = 0; $query = mysql_query("SELECT * FROM `my_table`"); whil...
In the MySQL C API, mysql_fetch_row returns a MYSQL_ROW object, which is essentially an array of values in the current row. So, your code should be something like: mysql_query(sqlhnd, "SELECT * FROM `my_table`"); MYSQL_RES *confres = mysql_store_result(sqlhnd); int totalrows = mysql_num_rows(confres); int numfields = m...
1,194,479
1,194,685
Write your own memory manager
I'd like to write my own memory manager. The target language is C++ and the goal of the memory manager is mainly to help debugging. It should detect double frees, memory overwrite and so on. And of course - I'd like to learn about memory management. Can someone give me a hint so resources where I can learn how to write...
I think this is a very interesting project that you might learn a lot from. Here's a little bit of reading material on the subject of memory management. It goes over some of the basics of memory management, leads into a simple malloc implementation, then touches on a couple more advanced topics. Inside memory managemen...
1,194,709
1,194,795
Refactoring C++ in Eclipse CDT
I've installed the Galileo release (Eclipse 3.5/CDT 5.1) in hopes of utilizing the better refactoring support mentioned in What is the state of C++ refactor support in Eclipse? However I do not see all the mentioned refactoring options listed. I don't see any plug-ins related to refactoring on http://download.eclip...
You should install CDT 6.0. However, my guess is that the options mentioned in the question you linked are not yet ready for mainline. My CDT offers Rename, Extract Variable/Constant/Function, Hide Method. From those, I only use Rename regularly, the others do not yet seem finished. One of the problems with such tools ...
1,194,842
1,196,195
Is it safe to serialize a raw boost::variant?
boost::variant claims that it is a value type. Does this mean that it's safe to simply write out the raw representation of a boost::variant and load it back later, as long as it only contains POD types? Assume that it will be reloaded by code compiled by the same compiler, and same version of boost, on the same archite...
Regarding serialisation: It should work, yes. But why don't you use boost::variant's visitation mechanism to write out the actual type contained in the variant? struct variant_serializer : boost::static_visitor<void> { template <typename T> typename boost::enable_if< boost::is_pod<T>, void>::type operator()...
1,194,941
1,195,074
Does SQL Server Compact Edition depend on the .net framework?
My company is looking at using SQL Server Compact Edition 3.5 as a datastore for a few programs that have been developed over the last several years. Most of these programs are were written in C++ and are installed on some older machines with Windows 2000, XP, or Vista installed. Does SQL Server Compact Edition 3.5 dep...
SQL Server Compact Edition does not depend on the .NET framework and can be deployed and used with a purely unmanaged, C++ client using the OLEDB provider. Most of the management and development tools do however rely on the .NET framework and most development is probably done using the ADO.NET provider, which does re...
1,195,206
1,195,221
Is there a Java equivalent or methodology for the typedef keyword in C++?
Coming from a C and C++ background, I found judicious use of typedef to be incredibly helpful. Do you know of a way to achieve similar functionality in Java, whether that be a Java mechanism, pattern, or some other effective way you have used?
Java has primitive types, objects and arrays and that's it. No typedefs.
1,195,572
1,195,611
compiling "standard" C++ in visual studio (non .net)
(This is a probably a very beginner question and I may be missing something obvious) I've just moved from my mac back to windows, and I'm trying to get set up with C++. I have visual studio 2008 C++: how do I compile "normal" non .net/clr C++? I want a command line application, and the only project that seemed fit was ...
Select General->Empty project project type.
1,195,656
1,195,679
Integer storage - Hexadecimal/Octal
I understand that integers are stored in binary notation, but I was wondering how this affects the reading of them - for example: Assuming cin.unsetf(ios::dec); cin.unsetf(ios::hex); and cin.unsetf(ios::oct); the user inputs 0x43 0123 65 which are stored as integers. Now assume that the program wants to recognize th...
Integers (and all other data) are not stored using "binary notation", they are stored as binary numbers. And no, there is no way for integers to retain their input format (which is what you are actually asking).
1,195,675
1,195,690
convert a char* to std::string
I need to use an std::string to store data retrieved by fgets(). To do this I need to convert the char* return value from fgets() into an std::string to store in an array. How can this be done?
std::string has a constructor for this: const char *s = "Hello, World!"; std::string str(s); Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.
1,195,979
1,196,011
How to interpret numbers correctly (hex, oct, dec)
I'm trying to write a program that takes input of - hexadecimals, octals, and decimals -, stores them in integer variables, and outputs them along with their conversion to decimal form. For example: User inputs: 0x43, 0123, 65 Program outputs: 0x43 hexadecimal converts to 67 decimal 0123 octal converts to 83 decimal 65...
Take a look at the strtol function. char * args[3] = {"0x43", "0123", "65"}; for (int i = 0; i < 3; ++i) { long int value = strtol(args[i], NULL, 0); printf("%s converts to %d decimal\n", args[i], value); } Outputs: 0x43 converts to 67 decimal 0123 converts to 83 decimal 65 converts to 65 decimal
1,196,000
1,196,054
How to keep items sorted based on dynamic attribute?
I'm using an STL std::multiset<> as a sorted list of pointers. The sort order is determined by a property of the items being pointed to, something along the lines of this simplified example: struct A { int x; }; bool CompareAPointers(const A* lhs, const A* rhs) { return lhs->x < rhs->x; } std::multiset<A*, Compare...
Boost Multi-Index supports sorting anything you want and supports changing the fields the list gets oderdered by, although you can't just type a1.x=1 anymore, instead, you have to use MultiIndex::replace(). I can't think of a faster/more natural way of doing this, as deleting and reinserting the element would've to be ...
1,196,039
1,196,130
How to use MS SOAP toolkit?
I know that the Microsoft SOAP toolkit has been deprecated for a while now (.NET has all this stuff built in) but I was wondering in anyone has a quick bit of info on setting up a simple app that uses it. I was referred to http://www.devarticles.com/c/a/Cplusplus/Building-A-SOAP-Client-With-Visual-C-plus/ but the serv...
Don't do it. It's 5 years deprecated, and it was 2 years out of date when it became deprecated. Don't. Assuming you are running on Windows (since you mentioned the MS SOAP Toolkit), use the imminently-arriving WWSAPI instead. Also see this post: http://blogs.msdn.com/vcblog/archive/2009/03/31/interested-in-using-we...
1,196,540
1,199,192
Assigning result of function which returns a Foo to a const Foo&
I've got a function which returns an object of type Foo: Foo getFoo(); I know the following will compile and will work, but why would I ever do it? const Foo& myFoo = getFoo(); To me, the following is much more readable, and doesn't force me to remember that C++ allows me to assign an r-value to a const reference: co...
Contrary to popular opinion, there is no guarantee that assigning the result of a function returning an object by value to a const reference will result in fewer copies than assigning it to the object itself. When you assign an rvalue to a const reference, the compiler may bind the reference in one of two ways. It may ...
1,196,808
1,196,895
How to detect "Use MFC" in preprocessor
For a static Win32 library, how can I detect that any of the "Use MFC" options is set? i.e. #ifdef ---BuildingForMFC--- .... #else ... #endif
I have always checked for the symbol _MFC_VER being defined. This is the version number of MFC being used 0x0700 = 7.0 It is in the "Predefined Macros" in MSDN
1,197,106
1,197,129
static constructors in C++? I need to initialize private static objects
I want to have a class with a private static data member (a vector that contains all the characters a-z). In java or C#, I can just make a "static constructor" that will run before I make any instances of the class, and sets up the static data members of the class. It only gets run once (as the variables are read only ...
To get the equivalent of a static constructor, you need to write a separate ordinary class to hold the static data and then make a static instance of that ordinary class. class StaticStuff { std::vector<char> letters_; public: StaticStuff() { for (char c = 'a'; c <= 'z'; c++) lette...
1,197,111
1,197,136
Bit setting and code readability
I have an Arduino application (well actually a library) that has a number of status flags in it - and originally I simply declared them as ints (well uint8_t so 8 bit unsigned chars in this case). But I could have combined them all into one integer and used bitmask operations to set and test the status. An example of t...
Check out Raymond Chen's excellent take on this issue. In summary, you need to do some detailed calculation to find out whether the latter case is actually more efficient, depending on how many objects there are vs. how many callsites actually set these states. As far as readability, it looks like you're doing this wi...
1,197,148
1,197,182
How do I use the registry?
In the simplest possible terms (I'm an occasional programmer who lacks up-to-date detailed programming knowledge) can someone explain the simplest way to make use of the registry in codegear C++ (2007). I have a line of code in an old (OLD!) program I wrote which is causing a significant delay in startup... DLB->Direct...
Use the TRegistry class... (include registry.hpp) //Untested, but something like... TRegistry *reg = new TRegistry; reg->RootKey = HKEY_CURRENT_USER; // Or whatever root you want to use reg->OpenKey("theKey",true); reg->ReadString("theParam",defaultValue); reg->CloseKey(); Note, opening and reading a ini file is usual...
1,197,340
1,197,490
Is it possible to write an impure template in C++?
Is it possible to write an impure template in C++? That is, a template that will sometimes give a different resulting type or int for the same template parameters. For example, is it possible to write a template Foo<T> where Foo<int>::type is sometimes char and at other times float? Or a template Foo<T> where Foo<doubl...
It's not possible. If you have a template that behaves that way, it violates the ODR and / or other rules, such as that a specialization should be declared before it would be instantiated. So you can't just put a specialization that would somehow change a typedef member to make it resolve to a different type for all fo...
1,197,357
1,197,374
What happens when you compare two objects?
If I wrote an operator == for class Foo (in C++), what happens, exactly? Does it compare each data member against each other? class Foo { private: int bar; public: bool operator==(const Foo other&) { return *this == other; //what? //is this the same as bar == bar? } }
The above code will call itself recursively until you get a stack overflow (snicker) and the program crashes. The method itself (the one you wrote) is the equality operator, which is then called again explicitly within the body. The idea behind overriding the equality operator (operator==) is that you can decide for yo...
1,197,566
1,197,590
Is it ever not safe to throw an exception in a constructor?
I know that it's not safe to throw exceptions from destructors, but is it ever unsafe to throw exceptions from constructors? e.g. what happens for objects that are declared globally? A quick test with gcc and I get an abort, is that always guaranteed? What solution would you use to cater for that situation? Are the...
Throwing exceptions from a constructor is a good thing. When something fails in a constructor, you have two options: Maintain a "zombie" state, where the class exists but does nothing, or Throw an exception. And maintaining zombie classes can be quite a hassle, when the real answer should have been, "this failed, now...
1,197,858
1,197,881
Binary file I/O issues
Edit: I'm trying to convert a text file into bytes. I'm not sure if the code is turning it into bytes or not. Here is the link to the header so you can see the as_bytes function. link #include "std_lib_facilities.h" int main() { cout << "Enter input file name.\n"; string file; cin >> file; ifstream in(...
The reason your first method didn't change the file is because all files are stored in the same way. The only "difference" between text files and binary files is that text files contain only bytes that can be shown as ASCII characters, while binary files* have a much more random variety and order of bytes. So you are...
1,198,044
1,198,075
Function pointer as template argument?
Is it possible to pass a function pointer as a template argument without using a typedef? template<class PF> class STC { PF old; PF& ptr; public: STC(PF pf, PF& p) : old(*p), ptr(p) { p = pf; } ~STC() { ptr = old; } }; void foo() {} void foo2() {} int main() { ...
Yes: STC<void (*)()> s(foo2, fp); // like this It's the same as taking the typedef declaration and removing the typedef keyword and the name.
1,198,055
1,198,077
Best way to use a C++ Interface
I have an interface class similar to: class IInterface { public: virtual ~IInterface() {} virtual methodA() = 0; virtual methodB() = 0; }; I then implement the interface: class AImplementation : public IInterface { // etc... implementation here } When I use the interface in an application is it be...
One of the most common reasons for using an interface is so that you can "program against an abstraction" rather then a concrete implementation. The biggest benefit of this is that it allows changing of parts of your code while minimising the change on the remaining code. Therefore although we don't know the full bac...
1,198,110
1,198,157
Is there an equivelant to 'AssemblyInfo.cs' in a Win32 DLL project?
I already looked at this topic, but I need the answer flipped around. How would I set the assembly information attributes* in a Win32 DLL?
Okay, I figured it out with a little more looking. Right click the Visual Studio Project, and select Add -> Resource.. Select 'Version', then click 'New...' Visual Studio will generate the files for you, and you can simply edit the information.
1,198,117
1,198,179
Getting commands from string input
I have a program which gets commands as a string. Each character in the string represents a command. An example of command is given below OBIPC O - Open a file B - Make the text in Bold I - Make the text in italics P - Print the text C - Close the file My program has to parse this string and do respective job. Each co...
Yep. That's exactly how I'd do it, except using Runnable::run() instead of IExececutable::Execute().
1,198,159
1,198,167
Many small files or one big file? (Or, Overhead of opening and closing file handles) (C++)
I have created an application that does the following: Make some calculations, write calculated data to a file - repeat for 500,000 times (over all, write 500,000 files one after the other) - repeat 2 more times (over all, 1.5 mil files were written). Read data from a file, make some intense calculations with the data...
Opening a file handle isn't probable to be the bottleneck; actual disk IO is. If you can parallelize disk access (by e.g. using multiple disks, faster disks, a RAM disk, ...) you may benefit way more. Also, be sure to have IO not block the application: read from disk, and process while waiting for IO. E.g. with a re...
1,198,215
1,210,219
MFC: child dialog behavior
I'm trying to make my child dialog box to be created as a member of the main application class as follows: class ParentWindow : public CWinApp { public: // Other MFC and user-implemented classes before this line MiscSettings activeMiscSettings; public: ParentWindow(); ~ParentWindow(); // Overrides ...
I have ended up deciding to create a struct containing the settings to be configured in the child dialog in the parent dialog class, passing in the pointer to the struct when calling a constructor, and have the child dialog's OK button handler modify the struct's contents as it is a pointer. I think this is as clean as...
1,198,260
1,201,902
How can you iterate over the elements of an std::tuple?
How can I iterate over a tuple (using C++11)? I tried the following: for(int i=0; i<std::tuple_size<T...>::value; ++i) std::get<i>(my_tuple).do_sth(); but this doesn't work: Error 1: sorry, unimplemented: cannot expand ‘Listener ...’ into a fixed-length argument list. Error 2: i cannot appear in a constant expre...
Boost.Fusion is a possibility: Untested example: struct DoSomething { template<typename T> void operator()(T& t) const { t.do_sth(); } }; tuple<....> t = ...; boost::fusion::for_each(t, DoSomething());
1,198,573
1,200,320
C API for getting CPU load in linux
In linux, is there a built-in C library function for getting the CPU load of the machine? Presumably I could write my own function for opening and parsing a file in /proc, but it seems like there ought to be a better way. Doesn't need to be portable Must not require any libraries beyond a base RHEL4 installation.
If you really want a c interface use getloadavg(), which also works in unixes without /proc. It has a man page with all the details.
1,198,577
1,198,584
std::auto_ptr, delete[] and leaks
Why this code does not cause memory leaks? int iterCount = 1000; int sizeBig = 100000; for (int i = 0; i < iterCount; i++) { std::auto_ptr<char> buffer(new char[sizeBig]); } WinXP sp2, Compiler : BCB.05.03
Because you're (un)lucky. auto_ptr calls delete, not delete []. This is undefined behavior. Try doing something like this and see if you get as lucky: struct Foo { char *bar; Foo(void) : bar(new char[100]) { } ~Foo(void) { delete [] bar; } } int iterCount = 1000; int sizeBig = 100000; for (int i = 0; i < i...
1,198,717
1,198,734
creating zip file from a folder - in c++
I want to create a program that , when executed, will compress a selected folder. Can it be done?
If you don't want to use boost, there's also zlib, along with minizip, which is a wrapper around zlib for managing zip files.
1,198,893
1,198,946
Access to global data in a dll from an exported dll function
I am creating a C++ Win32 dll with some global data. There is a std::map defined globally and there are exported functions in the dll that write data into the map (after acquiring a write lock, ofcourse). My problem is, when I call the write function from inside the dll DllMain, it works without any problems. But when ...
Looks like the constructor of std::map did not run yet when your code was called. Lifetime of global non-PODs in a Win32 DLL is pretty tricky, and I'm not certain as to how MinGW specifically handles it. But it may be that the way you're compiling the DLL, you've set your own function (DllMain?) as an entry point, and ...
1,198,918
1,198,955
How linker resolves the symbol in assembly code
I wanted to know how linker resolves the printf symbol in the following assembly code. #include<stdio.h> void main() { printf("Hello "); } .file "test.c" .def ___main; .scl 2; .type 32; .endef .section .rdata,"dr" LC0: .ascii "Hello \0" .text .globl _main .def _main; ....
Assuming ELF file format, the assembler will generate an undefined symbol reference in the object file. This'll look like this: Symbol table '.symtab' contains 11 entries: Num: Value Size Type Bind Vis Ndx Name 0: 00000000 0 NOTYPE LOCAL DEFAULT UND 1: 00000000 0 FILE LOCAL DE...
1,199,018
1,199,057
Is it possible to make both a managed and unmanaged versions of the same C++ assembly?
We use a software from another company for one of our products. A developer from that company is kinda 'old' and works in C (no offence). We work in .Net 3.5 (C#). He asked me if it is possible, with the same source code (presumably in C, maybe C++), to create an assembly that he could compile both a managed and unmana...
In order to compile to managed assembly the code needs to be written using Managed C++ Extensions. Please note that C is not an OO language so you cannot compile to a managed assembly. The primary reason for doing this is if you have an existing code base written in C++ that you want to use directly in .NET application...
1,199,336
1,199,649
cancellation handler won't run if pthread_exit called from C source instead of C++ source
I'm linking a C++ source with a C source and a C++ source. I create a thread with pthread, a cancellation point and then I call pthread_exit either through the C or the C++ source file. If the pthread_exit call comes from the C source, the cancellation handler does not fire! What may be the reason for this? b.cc: #incl...
Inspired by Ch. Vu-Brugier I took a look at pthread.h and found out that I have to add #undef __EXCEPTIONS before including pthread.h. This is a satisfactory workaround for my current needs.
1,199,513
1,199,526
Restart a process [exe] in Windows
I have a C++ exe; under a particular scenario I need to stop the exe and start it up again. This has to be done from within the same exe and not from outside. What is the best way to achieve this? My guess is to start a new instance of the process and then kill the running process. But is there any straight forward API...
No, there's no such built-in method. You really have to detect the path to the executable (GetCurrentModule(), then GetModuleFileName()), run the new process (CreateProcess()), then exit the current process (ExitProcess()).
1,199,764
1,199,795
How to check if a SQL query is valid for writing with ADO?
My app has an advanced feature that accepts SQL queries written by the user. The feature should include a "Validate" button to check if the query is valid. The most simple way I found to do this using ADO is just trying to run the query and catch possible exceptions. But how can I also check if the query enables to add...
Transactions, anyone? begin transaction // Query being validated goes here rollback transaction
1,199,920
1,199,960
How to Find CPU Utilization of a Single Thread within a Process
I am looking a Tool on How to Find CPU Utilization of a Single Thread within a Process in VC++. It would be great full if any one could provide me a tool. Also it could be better if you guys provide how to do programmatically. Thank you in Advance.
Perhaps using GetThreadTimes would help ? To elaborate if the thread belongs to another executable, that would be something (not tested) in the lines of: // Returns true if thread times could be queried and its results are usable, // false otherwise. Error handling is minimal, considering throwing detailed // exception...
1,200,021
1,200,058
Small question about precompiled headers
Looking at an open source code base i came across this code: #include "StableHeaders.h" #include "polygon.h" #include "exception.h" #include "vector.h" ... Now the StableHeaders.h is a precompiled header which is included by a 'control' cpp to force it's generation. The three includes that appear after the precompiled...
Compilers that don't support precompiled headers would just include StableHeaders.h and reparse it every time (rather than using the precompiled file). It won't cause any problems neither does it fix any problems for certain compilers as you asked. I think its just a minor 'mistake' that probably happened over time d...
1,200,026
1,200,213
Error on dlopen: St9bad_alloc
I have some c++ code I'm using for testing in which the first line is a call to dlopen in an attempt to load my shared object. Upon hitting this line I get the following error: Terminate called after throwing an instance of std::bad_alloc: what() : St9bad_alloc I've upped the memory (free -m now reports that I hav...
Take a look at the C++ dlopen mini HOWTO, hope that helps.
1,200,188
1,200,218
How to convert std::string to LPCSTR?
How can I convert a std::string to LPCSTR? Also, how can I convert a std::string to LPWSTR? I am totally confused with these LPCSTR LPSTR LPWSTR and LPCWSTR. Are LPWSTR and LPCWSTR the same?
str.c_str() gives you a const char *, which is an LPCSTR (Long Pointer to Constant STRing) -- means that it's a pointer to a 0 terminated string of characters. W means wide string (composed of wchar_t instead of char).
1,200,475
1,200,594
overload operator<< within a class in c++
I have a class that uses a struct, and I want to overload the << operator for that struct, but only within the class: typedef struct my_struct_t { int a; char c; } my_struct; class My_Class { public: My_Class(); friend ostream& operator<< (ostream& os, my_struct m); } I can only compile when I declare t...
How do I overload the << operator for my_struct ONLY within the class? Define it as static std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //... or namespace { std::ostream & operator<<( std::ostream & o, const my_struct & s ) { //... } in the .cpp file in which you implement MyClass. EDIT:...
1,200,727
1,200,836
Cross-platform drawing library
I've been looking for a good cross-platform 2D drawing library that can be called from C++ and can be used to draw some fairly simple geometry; lines, rectangles, circles, and text (horizontal and vertical) for some charts, and save the output to PNG. I think a commercial package would be preferable over open source be...
Try Anti-Grain Geometry. From the description: Anti-Grain Geometry (AGG) is an Open Source, free of charge graphic library, written in industrially standard C++. The terms and conditions of use AGG are described on The License page. AGG doesn't depend on any graphic API or technology. Basically, you can think of AGG a...
1,201,051
1,204,926
floating point precision
I have a program written in C# and some parts are writing in native C/C++. I use doubles to calculate some values and sometimes the result is wrong because of too small precision. After some investigation i figured out that someone is setting the floating-point precision to 24-bits. My code works fine, when i reset the...
This is caused by the default Direct3D device initialisation. You can tell Direct3D not to mess with the FPU precision by passing the D3DCREATE_FPU_PRESERVE flag to CreateDevice. There is also a managed code equivalent to this flag (CreateFlags.FpuPreserve) if you need it. More information can be found at Direct3D and ...
1,201,179
1,211,242
How to identify top-level X11 windows using xlib?
I'm trying to get a list of all top level desktop windows in an X11 session. Basically, I want to get a list of all windows that are shown in the window managers application-switching UI (commonly opened when the user presses ALT+TAB). I've never done any X11 programming before, but so far I've managed to enumerate thr...
I have a solution! Well, sort of. If your window manager uses the extended window manager hints (EWMH), you can query the root window using the "_NET_CLIENT_LIST" atom. This returna list of client windows the window manager is managing. For more information, see here. However, there are some issues with this. For a st...
1,201,198
1,201,282
Syntax error compiling header containing "char[]"
I am trying to build a Visual C++ 2008 DLL using SDL_Mixer 1.2: http://www.libsdl.org/projects/SDL_mixer/ This is supposedly from a build made for Visual C++, but when I include SDL_mixer.h I get error C2143: "syntax error : missing ';' before '['". The problem line is: const char[] MIX_EFFECTSMAXSPEED = "MIX_EFFECTSMA...
My bad. Although the answers here are correct regarding C construct, the actual problem was that I had included a "D" language file instead of the C version.
1,201,261
1,202,176
What is the Fastest Method for High Performance Sequential File I/O in C++?
Assuming the following for... Output: The file is opened... Data is 'streamed' to disk. The data in memory is in a large contiguous buffer. It is written to disk in its raw form directly from that buffer. The size of the buffer is configurable, but fixed for the duration of the stream. Buffers are written to the file, ...
Are there generally accepted guidelines for achieving the fastest possible sequential file I/O in C++? Rule 0: Measure. Use all available profiling tools and get to know them. It's almost a commandment in programming that if you didn't measure it you don't know how fast it is, and for I/O this is even more true. M...
1,201,295
1,201,323
private non-const and public const member function - coexisting in peace?
I am trying to create a class with two methods with the same name, used to access a private member. One method is public and const qualified, the other is private and non-const (used by a friend class to modify the member by way of return-by-reference). Unfortunately, I am receiving compiling errors (using g++ 4.3): W...
Overload resolution happens before access checking, so when you call the a method on a non-const A, the non-const member is chosen as a better match. The compiler then fails due to the access check. There is no way to "make this work", my recommendation would be to rename the private function. Is there any need to have...
1,201,388
1,202,550
Create thumbnails in C++
Wondering if anyone knows how to create thumbnails in C++ from NITF 2.1 images
Using the package below you should be able to read a NITF image and then generate your own smaller version to save as a thumbnail. NITRO is a full-fledged, extensible library solution for reading and writing National Imagery Transmission Format (NITF) files, a U.S. Department of Defense standard format. It is written ...
1,201,537
1,201,573
How to enclose the path stored in a variable in quotes?
Let us have a path C:\Program Files\TestFolder this path i got programatically and stored in a varible dirpath(for example) Now i have concatinated string dirpath=getInstallationpath()+"\\ test.dll /codebase /tlb"; then dirpath is become C:\Program Files\TestFolder\test.dll /codebase /tlb But my problem is i have m...
I can see two issues with that line. First of all, you need to escape the backslash preceding test.dll. Secondly, wrapping the path in quotation marks requires that you also escape the quotation marks. After these changes, it should look like this: dirpath="\""+getInstallationPath()+"\\test.dll\" /codebase /tlb " Ed...
1,201,560
1,201,664
Is it possible to implement a recursive Algorithm with an Iterator?
I have given a tree like this: http://www.seqan.de/dddoc/html/streePreorder.png http://www.seqan.de/dddoc/html/streePreorder.png i can acces each node with the next operator. // postorder dfs Iterator< Index<String<char> >, BottomUp<> >::Type myIterator(myIndex); for (; !atEnd(myIterator); goNext(myIterator)) // d...
If your iterator only supports forward (and possibly backward) traversal, but not following links on the tree or fast random access, you will have a very hard time adapting a tree algorithm to it. However, in the end any answer will depend on the interface presented by your custom iterators, which you have not provided...
1,201,593
1,201,840
Where is C not a subset of C++?
I read in a lot of books that C is a subset of C++. Some books say that C is a subset of C++, except for the little details. What are some cases when code will compile in C, but not C++?
If you compare C89 with C++ then here are a couple of things No tentative definitions in C++ int n; int n; // ill-formed: n already defined int[] and int[N] not compatible (no compatible types in C++) int a[1]; int (*ap)[] = &a; // ill-formed: a does not have type int[] No K&R function definition style int b(a) int a...
1,201,875
1,201,940
When doing a parallel search, when will memory bandwidth become the limiting factor?
I have some large files (from several gigabytes to hundreds of gigabytes) that I'm searching and trying to find every occurrence of a given string. I've been looking into making this operate in parallel and have some questions. How should I be doing this? I can't copy the entire file into memory since its too big. Wil...
With this new revised version of the question, the answer is "almost immediately". Hard disks aren't very good at reading from two places on the disk at the same time. :) If you had multiple hard drives and split your file across them, you could probably take advantage of some threading. To be fair, though, I would say...
1,201,959
1,202,052
How do I reference one VC++ project from another in the same project?
I am new to Visual Studio. Need your help with the following. Visual Studio 2005, VC++ 1 solution has 2 projects. Lets call the solution as 'solution' Project 1 is named 'p1' and project 2 is called 'p2' Do I need to export functions and classes from 'p1' so that I can use them by importing in 'p2'? What if I simply in...
If I remember correctly (haven't used C++ for a while), there were two different kinds of C++ libraries - a static library (a .lib file) and a dynamic library (a .dll file). In the case of a static library you had to configure p2 so that it links to p1.lib (in project properties); add p1 to dependancies of p2, so that ...
1,202,003
1,202,038
How do I see if another process is running on windows?
I have a VC++ console app and I need to check to see if another process is running. I don't have the window title, all I have is the executable name. How do I get the process handle / PID for it? Can I enumerate the processes running with this .exe ?
You can use EnumProcesses to enumerate the processes on a system. You'll need to use OpenProcess to get a process handle, then QueryFullProcessImageName to get the processes executable.
1,202,283
1,206,928
Native C/Managed C++ Debugging
I have a native C Dll that calls 'LoadLibrary' to load another Dll that has the /clr flag turned on. I then use 'GetProcAddress' to get a function and call it on dynamically loaded dll. I would like to step into the dynamic library in the debugger, but the symbols never load. Any idea? And I should have said I'm usi...
This is from VS2008, but if I remember correctly VS2005 was similar. In the native project's properties, under "Configuration Properties->Debugging" there is a "Debugger Type" which is set to "Auto" by default. You'll need to change it to "Mixed", because VS isn't smart enough to realize you need managed debugging
1,202,365
1,202,392
Ways to speed up build time? (C#/Unmanaged C++)
A legacy app I am working on currenty takes ~2hours to build. The project has about 170 projects with 150 or so being unmanaged C++ and the other 30 C#.Net 2.0. What are some suggestions on ways to improve build times for something like this?
Focus on the C++ projects - they are almost guaranteed to be the largest time drains for building. Some tips on getting the C++ build times down: Make sure that you're only including headers that you need in the C++ projects! Use forward declarations whenever possible in headers instead of including other headers Use ...
1,202,446
1,202,464
Is there any free program for making diagrams of file dependencies extracted from header files?
Looking for something similar to Modelmaker that was for Delphi. Showing dependecies of modules. Any help is appreciated. Doxygen has been great so far. If someone know if it's possible to achieve what I want with Doxygen, then please let me know :)
is this what you are looking for?
1,202,653
1,203,011
Check for environment variable in another process?
In Windows, is there a way to check for the existence of an environment variable for another process? Just need to check existence, not necessarily get value. I need to do this from code.
If you know the virtual address at which the environment is stored, you can use OpenProcess and ReadProcessMemory to read the environment out of the other process. However, to find the virtual address, you'll need to poke around in the Thread Information Block of one of the process' threads. To get that, you'll need t...
1,202,714
1,202,830
Hypothetical, formerly-C++0x concepts questions
(Preamble: I am a late follower to the C++0x game and the recent controversy regarding the removal of concepts from the C++0x standard has motivated me to learn more about them. While I understand that all of my questions are completely hypothetical -- insofar as concepts won't be valid C++ code for some time to come, ...
I've used the most recent C++0x draft, N2914 (which still has concepts wording in it) as a reference for the following answer. 1) Concepts are like interfaces in that. If your type supports a concept, it should also support all "base" concepts. Wikipedia statement you quote makes sense from the point of view of a type'...
1,202,883
1,202,906
Detecting string argument in a loop
The program takes a string using getline, and then passes that string to a function where it stores the string into substrings separated by whitespace. I did that just by reading characters with a loop. However, now I'm trying to pass a second string argument that separates the strings into substrings if the loop encou...
Look at std::string::find_first_of. This allows you to easily ask a std::string object for the position of the next of any characters in another string object. For example: string foo = "This is foo"; cout << foo.find_first_of("aeiou"); // outputs 2, the index of the 'i' in 'This' cout << foo.find_first_of("aeiou", 3);...
1,203,451
1,203,504
How to write an application for the system tray in Linux
How do I write my application so it'll live in the system tray on Linux? In fact, just like CheckGmail. As with CheckGmail, I'd also like some sort of popup box to appear when I hover the tray icon. Is there an API, class or something for doing this? All I'm able to find seems to be for Windows. If I have to be languag...
The Qt framework contains a QSystemTrayIcon class. This means that you can write an application in C++ or Python (or any other language with Qt bindings, including C#, Ada, Pascal, Perl, PHP and Ruby) and run your application on Windows, Linux, Mac or any other supported Qt operating system. I should add that Qt applic...
1,203,765
1,203,772
How to dump the symbols in a .a file
Can you please tell me how can I dump all the symbols in a .a file on MacOS X? I am getting a linking error while compiling my c++ problem on MacOS X. I would like to find out if the sybmols exists on the .a file that I am linking with. Thank you.
man nm Nm displays the name list (symbol table) of each object file in the argument list. If an argument is an archive, a listing for each object file in the archive will be produced. File can be of the form libx.a(x.o), in which case only symbols from that member of the object file are listed. ......
1,204,118
1,204,160
Can I include iostream header file into custom namespace?
namespace A { #include <iostream> }; int main(){ A::std::cout << "\nSample"; return 0; }
Short answer: No. Long answer: Well, not really. You can fake it, though. You can declare it outside and use using statements inside the namespace, like this: #include <iostream> namespace A { using std::cout; }; int main(){ A::cout << "\nSample"; system("PAUSE"); return 0; } You cannot localize a library, bec...
1,204,313
1,204,337
Counting occurrences in a vector
This program reads strings of numbers from a txt file, converts them to integers, stores them in a vector, and then tries to output them in an organized fashion like so.... If txt file says: 7 5 5 7 3 117 5 The program outputs: 3 5 3 7 2 117 so if the number occurs more than once it outputs how many times that ha...
How about using a map, where the key is the number you're tracking and the value is the number of occurrences? If you must use a vector, you've already got it sorted. So just keep track of the number you previously saw. If it is the same as the current number, increment the counter. Every time the number changes: print...
1,204,452
1,204,554
Passing D3DFMT_UNKNOWN into IDirect3DDevice9::CreateTexture()
I'm kind of wondering about this, if you create a texture in memory in DirectX with the CreateTexture function: HRESULT CreateTexture( UINT Width, UINT Height, UINT Levels, DWORD Usage, D3DFORMAT Format, D3DPOOL Pool, IDirect3DTexture9** ppTexture, HANDLE* pSharedHandle ); ...and pass in D3DFMT_UNKNOWN...
I just tried it out and it does not fail, mostly When Usage is set to D3DUSAGE_RENDERTARGET or D3DUSAGE_DYNAMIC, it consistently came out as D3DFMT_A8R8G8B8, no matter what I did to the back buffer format or other settings. I don't know if that has to do with my graphics card or not. My guess is that specifying unknown...
1,204,553
1,204,576
Are there any good libraries for solving cubic splines in C++?
I'm looking for a good C++ library to give me functions to solve for large cubic splines (on the order of 1000 points) anyone know one?
Try the Cubic B-Spline library: https://github.com/NCAR/bspline and ALGLIB: http://www.alglib.net/interpolation/spline3.php
1,204,693
1,204,806
Is C++0x collapsing under the weight of new features and the standardization process?
From Dr. Dobbs: Concepts were to have been the central new feature in C++0x Even after cutting "concepts," the next C++ standard may be delayed. Sadly, there will be no C++0x (unless you count the minor corrections in C++03). We must wait for C++1x, and hope that 'x' will be a low digit. There is hope be...
Stroustrup was one of the voters to remove Concepts finally. I don't see C++ collapsing, instead I see that the C++ committee is doing its job. Half-baked features are not the solution for a robust language like C++. A look at what is going to be in C++0x tells you the opposite of what you are saying. Finally, I don't ...
1,204,697
1,204,739
Reading a UTF-8 Unicode file through non-unicode code
I have to read a text file which is Unicode with UTF-8 encoding and have to write this data to another text file. The file has tab-separated data in lines. My reading code is C++ code without unicode support. What I am doing is reading the file line-by-line in a string/char* and putting that string as-is to the destin...
UTF-8 uses 1 byte for all ASCII characters, which have the same code values as in the standard ASCII encoding, and up to 4 bytes for other characters. The upper bits of each byte are reserved as control bits. For code points using more then 1 byte, the control bits are set. Thus there shall not be 0 character in your ...
1,204,935
1,225,070
Problem with IDropTarget when using with a VCL Form
I have a VCL gui developed in Codegear. I have created a DropTarget for the mainform and the DropTarget object implements the IDropTarget interface which allows me to drag and drop files from explorer. Now because I only want some of the child components to be drop targets (not the whole form), I only have the DragEnte...
Sounds like you are ignoring that IDropTarget has a DragOver() method that you need to use in addition to DragEnter(). If DragEnter() does not begin with coordinates that you allow, then you have to return S_OK with the pdwEffect parameter set to DROPEFFECT_NONE, and then let DragOver() continue doing its own coordina...
1,204,975
1,204,984
Does the compiler decide when to inline my functions (in C++)?
I understand you can use the inline keyword or just put a method in a class declaration ala short ctor or a getter method, but does the compiler make the final decision on when to inline my methods? For instance: inline void Foo::vLongBar() { //several function calls and lines of code } Will the compiler ignore my ...
Whether or not a fiunction is inlined is, at the end of the day, entirely up to the compiler. Typically, the more complex a function is in terms of flow, the less likely the compiler is to inline it. and some functions, such as recursive ones, simply cannot be inlined. The major reason for not inlining a function is t...
1,204,983
1,204,992
is it possible to store output of system call in windows?
E.G.: I want to store output of system("dir");
You can either use redirection to a file (system( "dir > file" )), read that file and delete it or go the unnamed pipes way as in Unix - call CreatePipe() to create a pipe and attach it as the input/output stream in PROCESS_INFORMATION structure and pass that structure into CreateProcess().
1,205,419
1,206,241
Writing a QNetworkReply to a file
I'm downloading a file using QNetworkAccessManager::get but unlike QHttp::get there's no built-in way to directly write the response to a different QIODevice. The easiest way would be to do something like this: QIODevice* device; QNetworkReply* reply = manager.get(url); connect(reply, SIGNAL(readyRead()), this, SLOT(n...
That looks correct. I would use the lower-level forms of read() and write(), not the QByteArray ones, which do not properly support error handling, but other than that, it looks fine. Are you having problems with it?
1,205,516
1,205,542
MS VC++ 6 : Why return !false rather than true?
Looking at some code I noticed that another dev had changed every instance of true to !false. Why would you do that? thx
There is no good reason to write !false instead of true. Bad reasons could include obfuscation (making the code harder to read), personal preferences, badly considered global search-and-replace, and shenanigans converting boolean values to integers. It's possible that some confusion has been caused by the TRUE and FALS...
1,205,753
1,209,811
which embedded web server to use for my app GUI
I'm writing an application in c++ and I was thinking to use an embedded simple web server that will be my gui, so i could set up my application port on localhost. What such web server would you recommend to use in c++/c? Thanks
If you are using boost then rolling your own in boost:asio is simple. I assume by embedded you mean a built in webserver not that you are running on some tiny embedded hardware. If you want something simpler look at mongoose - also see https://stackoverflow.com/questions/738273/open-source-c-c-embedded-web-server
1,206,540
1,354,689
WebBrowser control: Detect navigation failure
I am hosting a webbrowser control, that usually loads an external documents, then makes some modifications using HTML DOM. We also embed custom application links using a fake protocol, such as "Close This" that are caught and handled in BeforeNavigate2. When the link tarket is misspelled (say, "spp:CloseWindow"), Befor...
Internet Explorer and Windows have an extensible list of available protocols implemented in UrlMon.dll, I believe. See here for a bit about IE architecture. The reason you cannot detect the bad protocol in BeforeNavigate is that the protocol is unknown, so no real navigation is happening. The browser decides to show ...
1,206,690
1,207,161
how to print the unicode characters in hexadecimal codes in c++
I am reading the string of data from the oracle database that may or may not contain the Unicode characters into a c++ program.Is there any way for checking the string extracted from the database contains an Unicode characters(UTF-8).if any Unicode characters are present they should be converted into hexadecimal forma...
There are two aspects to this question. Distinguish UTF-8-encoded characters from ordinary ASCII characters. UTF-8 encodes any code point higher than 127 as a series of two or more bytes. Values at 127 and lower remain untouched. The resultant bytes from the encoding are also higher than 127, so it is sufficient to ch...
1,206,829
1,206,845
How to read code without any struggle
I am a new to professional development. I mean I have only 5 months of professional development experience. Before that I have studied it by myself or at university. So I was looking over questions and found here a question about code quality. And I got a question related to it myself. How do I increase my code underst...
There is only way I've found to get better at reading other peoples code and that is read other peoples code, when you find a method or language construct you don't understand look it up and play with it until you understand what is going on. Hungarian notation is terrible, very few people use it today, it's more of an...
1,206,854
1,206,896
Returning multiple auto_ptrs from a function
I have a function that allocates two variables on the heap and returns them to the caller. Something like this: void Create1(Obj** obj1, Obj** obj2) { *obj1 = new Obj; *obj2 = new Obj; } Usually, in similar cases, when I have a function with one variable I use the "source" trick with auto_ptr: auto_ptr<Obj> Cr...
You can assign to a std::auto_ptr by calling its reset method: void f( std::auto_ptr<Obj>& pObj1, std::auto_ptr<Obj>& pObj2 ) { pObj1.reset( new Obj ); pObj2.reset( new Obj ); } The reset call will properly delete whatever the auto_ptr was pointing to before.
1,206,871
1,207,224
C++ MVC Model - How should it be implemented?
I'm a little confused as to how the model should 'work' in my basic C++ implementation, or rather how the data from say the database backend should be encapsulated/worked with. My thoughts at the moment are for a model with for example a static findById() method, which would return an instance of that same model, which...
So, I think you are asking what kind of interface would be appropriate to "translate" between a relational database and an object oriented application, particularly in the context of an MVC application written in C++. A common approach is called object-relational mapping, or ORM. I'm only familiar with how Ruby on Rai...
1,206,879
1,206,912
How to map a resource file in Qt?
Is it possible to map a resource file in Qt? For example: QFile file(resource_name); file.open(QIODevice::ReadOnly); uchar* ptr = file.map(0, file.size()); When I try this, ptr == 0, indicating an error. It works fine if I try to map a regular file. I am running Qt on linux, which supports QFile::Map.
Yes, it is possible. There is one thing to keep in mind though. By default the qt resource compiler rcc compresses the resources. The file.size() call will return the actual, un-compressed size of the original file. However, the embedded resource is compressed and is most likely a different size. The file.map(0, ...
1,207,106
1,208,083
Calling base class definition of virtual member function with function pointer
I want to call the base class implementation of a virtual function using a member function pointer. class Base { public: virtual void func() { cout << "base" << endl; } }; class Derived: public Base { public: void func() { cout << "derived" << endl; } void callFunc() { void (Base::*fp)() = &Ba...
When you call a virtual method via a reference or a pointer you will always activate the virtual call mechanism that finds the most derived type. Your best bet is to add an alternative function that is not virtual.
1,207,265
1,207,310
In qt 4.5, is it possible to have resources in a statically linked plugin?
I have a custom QT plugin module that has embedded resources. I want to statically link this plugin with an application: LIBS += -lstatic_plugin_with_resources In the application I am using the Q_IMPORT_PLUGIN() macro, which allows the application to use the plugin; however the plugin can not access its embedded reso...
It is possible. In the application you need to explicitly initialize the resources that are contained in the static plugin. This is accomplished by calling the Q_INIT_RESOURCE(resource_base_name), where resource_base_name is the base name of the .qrc file that specifies the resources. This should probably be called ...
1,207,456
1,207,484
Am I crazy to recreate a tiny garbage collection system inside my functions?
I have some (C++) functions each containing several calls creating similar arrays of the same basic type on the heap. At various points in these functions, I may need to throw an exception. Keeping track of which arrays have been deleted is a pain, and quite error prone, so I was thinking about just adding the array po...
You don't have to rely on garbage collection. You have std::auto_ptr that provides pointer like syntax and wraps a dynamically allocated object. When destroyed, it automatically destroys the object it points to. You could implement something similar for arrays.
1,207,478
1,207,517
Does it make sense to implement iterators for containers which has no obvious end - e.g. trees?
I`m writing binary search tree template for two reasons - learning C++ and learning most common algorithms and data structures. So, here is the question - as long as I want to implement iterators, it seems to me that there is no strict definition for where tree ends. What are your suggestions? How do I do this?
For trees, there are standards for traversing the tree, i.e. enumerating the nodes: Preorder traversal, inorder traversal, and postorder traversal. Rather than describe all these here, I'll redirect you to http://en.wikipedia.org/wiki/Tree_traversal. The concepts are mostly applied to binary trees, but you can extend t...
1,207,762
1,207,851
What is c printf %f default precision?
I'm curious: If you do a printf("%f", number); what is the precision of the statement? I.e. How many decimal places will show up? Is this compiler dependent?
The ANSI C standard, in section 7.19.6.1, says this about the f format specifier: If the precision is missing, 6 digits are given
1,207,906
1,207,933
Why is it illegal/immoral to reseat a reference?
Possible Duplicate: Why are references not reseatable in C++ I am trying to more or less swap two reference variables (as practice, I could have swapped the actual variables). I tried doing this by making a temporary variable and making one of the references equal the other, but this got shot down by the compiler. H...
Because there is no syntax to do it: int x = 0; int y = 1; int & r = x; Now if I say: r = y; I assign the value of y to x. If I wanted to reseat I would need some special syntax: r @= y; // maybe? As the main reason for using references is as parameters and return types of functions, where this is not an issue, i...
1,208,028
1,208,062
Significance of a .inl file in C++
What are the advantages of having declarations in a .inl file? When would I need to use the same?
.inl files are never mandatory and have no special significance to the compiler. It's just a way of structuring your code that provides a hint to the humans that might read it. I use .inl files in two cases: For definitions of inline functions. For definitions of function templates. In both cases, I put the declarat...
1,208,153
1,208,207
C# generics compared to C++ templates
Possible Duplicate: What are the differences between Generics in C# and Java… and Templates in C++? What are the differences between C# generics compared to C++ templates? I understand that they do not solve exactly the same problem, so what are the pros and cons of both?
You can consider C++ templates to be an interpreted, functional programming language disguised as a generics system. If this doesn't scare you, it should :) C# generics are very restricted; you can parameterize a class on a type or types, and use those types in methods. So, to take an example from MSDN, you could do: p...
1,208,540
1,208,690
How can I get a printers device context?
I'm on Windows and trying to print an Enhanced Metafile (EMF) using PlayEnhMetaFile(). I'm currently displaying it using a device context for a window on the screen, but now I want to send it to a printer. How can I get a device context for the printer and pass it into this function properly?
The easiest way is to use construct the device context from PRINTDLG.hDevMode and PRINTDLG.hDevNames after calling PrintDlg if using win32 API, or calling CPrintDialog::GetPrinterDC if you're using MFC. If using MFC: CPrintDialog dlgPrint(FALSE, PD_USEDEVMODECOPIES); HDC hPrinterDC = dlgPrint.GetPrinterDC(); or win32 ...
1,208,644
1,208,667
How can I get the size of a memory block allocated using malloc()?
Possible Duplicates: How can I get the size of an array from a pointer in C? Is there any way to determine the size of a C++ array programmatically? And if not, why? I get a pointer to a chunk of allocated memory out of a C style function. Now, it would be really interesting for debugging purposes to know how big th...
It's not standard but if your library has a msize() function that will give you the size. A common solution is to wrap malloc with your own function that logs each request along with the size and resulting memory range, in the release build you can switch back to the 'real' malloc.
1,208,766
1,208,858
quicksort in C++ is slow
I have 9 values in the form of a matrix and need to compute the median from these values as part of a simulation process. I use quicksort in C++ (i.e qsort()) which results in the process running slow (as this process iterates several times). Is there a better sorting algorithm that I could use?
Sorting to get a median is very inefficient. You could use STL nth_element instead: #include <algorithm> // Assuming you keep the elements in a vector v of size len std::nth_element( v.begin(), v.begin()+len/2, v.end() ); median = v[len/2]; //... or, if the elements are in a simple array v[len], then std::nth_elem...
1,208,853
1,208,869
How to call C++ static method
Is it possible to return an object from a static method in C++ like there is in Java? I am doing this: class MyMath { public: static MyObject calcSomething(void); private: }; And I want to do this: int main() { MyObject o = MyMath.calcSomething(); // error happens here } There are only static meth...
Use :: instead of . MyObject o = MyMath::calcSomething(); When you are calling the method without the object of the class you should use :: notation. You may also call static method via class objects or pointers to them, in this case you should use usual . or -> notation: MyObject obj; MyObject* p = new MyObject(); My...
1,208,961
1,209,000
Can an object instance null out the "this" pointer to itself safely?
Class A { public: NullIt() { this = NULL; } Foo() { NullIt(); } } A * a = new A; a->Foo(); assert(a); //should assert here Is there a way to achieve this effect, memory leaks aside?
No. The object knows nothing about the external references to it (in this case, "a"), so it can't change them. If you want the caller to forget your object, then you can do this: class MyClass { void Release(MyClass **ppObject) { assert(*pObject == this); // Ensure the pointer passed in points at us ...
1,208,963
1,208,976
Looking for a bitwise operator
I have a list of objects of the same class. The order of the list is not important. What i want to do, is to (using bitwise operations) determine whether i should set some field with an incremental value or not. But the trick is that i want need this operation to return false (must not set field) only for the first ele...
I think you need a counter