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
693,390
693,418
how do i get started using boost
I hear a lot about boost here and I am beginning to think it could help a lot with my software development. More so in concurrency and memory management in my particular case as we have had a lot of bugs in this area. What are the key language features I need to polish up on to effectively benefit from using boost and...
Boost has an unimaginable number of libraries. Easy ones to get started on are noncopyable array circular_buffer foreach operators (one of my personal favorites) smart_ptr date_time More advanced ones include lambda bind iostreams serialization threads Getting used to boost takes time, but I assure you it will ma...
693,652
693,657
What is the meaning of having void in the constructor definition?
Given the following code: #pragma once class B { public: B(void) { } ~B(void) { } }; I know I can also write this: #pragma once class B { public: B() { } ~B() { } }; What is the purpose of having void in the first example? Is it some type of practice that states ...
The two are same, at least in C++. In C, providing an empty pair of parentheses typically means an unspecified parameter list (as opposed to an empty parameter list). C++ does not have this problem. How can a correct answer get downvoted so many times? Yet another SO bug?
693,880
694,303
Create Random Number Sequence with No Repeats
Duplicate: Unique random numbers in O(1)? I want an pseudo random number generator that can generate numbers with no repeats in a random order. For example: random(10) might return 5, 9, 1, 4, 2, 8, 3, 7, 6, 10 Is there a better way to do it other than making the range of numbers and shuffling them about, or checking...
You may be interested in a linear feedback shift register. We used to build these out of hardware, but I've also done them in software. It uses a shift register with some of the bits xor'ed and fed back to the input, and if you pick just the right "taps" you can get a sequence that's as long as the register size. That...
693,889
693,894
What's the "Hello World!" of genetic algorithms good for?
I found this very cool C++ sample , literally the "Hello World!" of genetic algorithms. I so decided to re-code the whole thing in C# and this is the result. Now I am asking myself: is there any practical application along the lines of generating a target string starting from a population of random strings? EDIT: my bu...
Is there any practical application along the lines of generating a target string starting from a population of random strings? Sure. Imagine any scenario in which you know how to evaluate the fitness of a particular string, and in which the choices are discrete and constrained in some way: Picking pronounceable name...
693,910
693,933
Passing a function object: Error
What's wrong with the following little program that passes a function object? #include <iostream> #include <functional> void foo(const std::unary_function<const std::string&, void>& fct) { const std::string str = "test"; fct(str); // error } class MyFct : public std::unary_function<const std::string&, void> { pub...
A common mistake. unary_function and binary_function are just two structs that add typedefs argument_type result_type and respectively first_argument_type second_argument_type result_type Not more. They are for convenience of creators of function object types, so they don't have to do those themselves. But they don't...
693,922
693,937
How can I use a remote control to interact with a Linux C or C++ application?
I'd like to capture the input from a TV remote control and detect which buttons are pressed in my application. The operating system is Linux (Windows answers won't be much use to me, but may be to others). I'm using C++ but C code would work for me also. I'd like to use the code in a fashion similar to this: if (remote...
First off you are going to need some hardware to detect the IR emissions, for example a USB-UIRT On Linux, the USB-UIRT is support by LIRC which deals with the low level end of things for you. There are a number of open source packages that work with this to provide control, so you can look at their code for examples, ...
693,952
693,976
How to Compile for OS X in Linux or Windows?
I would like to port my C/C++ apps to OS X. I don't have a Mac, but I have Linux and Windows. Is there any tool for this?
There appears to be some scripts that have been written to help get you set up cross compiling for the Mac; I can't say how good they are, or how applicable to your project. In the documentation, they refer to these instructions for cross-compiling for 10.4, and these ones for cross compiling for 10.5; those instructio...
694,080
694,085
How do I read JPEG and PNG pixels in C++ on Linux?
I'm doing some image processing, and I'd like to individually read each pixel value in a JPEG and PNG images. In my deployment scenario, it would be awkward for me to use a 3rd party library (as I have restricted access on the target computer), but I'm assuming that there's no standard C or C++ library for reading JPEG...
There is no standard library in the C-standard to read the file-formats. However, most programs, especially on the linux platform use the same library to decode the image-formats: For jpeg it's libjpeg, for png it's libpng. The chances that the libs are already installed is very high. http://www.libpng.org http://www...
694,132
694,245
Tree matching using serialization of tree and unique id generation for each subtree
Binary tree http://img9.imageshack.us/img9/9981/binarytree.jpg What would be the best way to serialize a given binary tree and inturn evaluate a unique id for each serialized binary tree? For example, I need to serialize the sub-tree (2,7,(5,6,11)) and generate a unique id 'x' representing that sub-tree so that wheneve...
Do you want to to be able match any arbitrary part of the tree or a subtree running upto some leaf node(s)? IIUC, you are looking at suffix matching. You can also look at Compact Directed Acyclic Word Graph for ideas.
694,387
694,393
OOP Terminology: "Container" & "Collection"
Is the C++ term "Container" simply synonymous with the Java term "Collection" ?
Yes. Though, if I may speculate here, C++ term container better emphasizes ownership of contained items, as opposed to Java's collection, where there is no explicit memory ownership (due to garbage collection). Items in a C++ container are destroyed when a container is destroyed (hence items are contained or owned), in...
694,517
694,520
Sqlite as a replacement for fopen()?
On an official sqlite3 web page there is written that I should think about sqlite as a replacement of fopen() function. What do you think about it? Is it always good solution to replece application internal data storage with sqlite? What are the pluses and the minuses of such solution? Do you have some experience in it...
It depends. There are some contra-indications: for configuration files, use of plain text or XML is much easier to debug or to alter than using a relational database, even one as lightweight as SQLite. tree structures are easier to describe using (for example) XML than by using relational tables the SQLite API is quit...
694,572
694,649
Specify the minimum number of buckets when constructing a boost::unordered_map
I am trying to use boost::unordered_map to cache some values. I try to specify minimum number of buckets in the constructor: #include <boost/unordered_map.hpp> typedef boost::unordered_map<float, float> Mycache; Mycache cache((std::size_t)25165843, boost::hash<float>(), std::equal_to<float>(...
boost::unordered_map::max_bucket_count() returns the implementation-dependent limit on the bucket count of an unordered_map. You appear to have exceeded this limit with your constructor parameter. Note that while MSDN defines this to be the max buckets "currently" permitted (whatever that means), the C++0x spec defines...
694,706
694,710
defining static const structs
This question is related to Symbian OS yet I think that C/C++ veteran can help me too. I'm compiling an open source library to Symbian OS. Using a GCCE compiler it compiles with no errors (after some tinkering :) ). I changed compiler to ARMV5 and now I have multiple errors with the definitions of static const structs,...
static const struct Foos foo = { 1, 2 }; Compiles with both g++ and gcc. You could ofcourse, as onebyone points out, define a constructor: typedef struct Foos { int a; int b; Foos(int a, int b) : a(a), b(b) {} }; Which you would initalize like so: static const struct Foos foo(1, 2);
694,733
694,748
Executing command prompt's functionality using Win32
What Windows API functions are available to execute command prompt's functionality? For example, I like to execute dir command and want to show the output in GUI without using cmd.exe in Windows.
You can start cmd /c dir S:\ome\Path from your process and grab the output. Otherwise it's not possible. But if you're not interested in particular formatting details of dir then you're probably better off just enumerating files/directories and display them.
694,744
694,940
How to debug a shared library using eclipse/gdb on Windows?
At my university we are currently developing a VST-Plugin on Windows using open source tools. My professor is pretty fond of Microsoft Visual Studio and rather sceptic towards open source tools such as Eclipse, GCC, Subclipse etc. However, until now I was able to solve all of his problems and it would be a shame if h...
These appear to be a bug/limitation of GDB on windows http://synthedit.audioholik.com/index.php?name=Content&pid=8 http://dev.eclipse.org/newslists/news.eclipse.tools.cdt/msg17618.html The workaround is force a breakpoint in your code.
694,807
694,819
C++ Dynamic memory allocation
I'm just learning about dynamic memory allocation, but there is one thing i'd like to be explained. One use for dynamic allocation is for dynamic sized arrays, and thats clear to me. Another use is for normal objects. What is a situation one should use it? Is it because normally objects are pushed on the stack, and cou...
Another issue for dynamic memory is lifetime. Dynamic memory (new, malloc, etc ...) lives on the heap. It will stay alive until it is explicitly deleted by a piece of code through the appropriate memory function. This is very useful for long lived objects. Non dynamic memory, or the stack, has a very definite lifeti...
694,884
694,904
Checking if Registry Value exists Visual C++ 2005
Im trying to code a Visual C++ 2005 routine that checks the registry for certain keys/values. I have no trouble in writing code using c# but I need it in C++. Anybody know how to do this using c++ in vs2005. Many thanks Tony
Here is some pseudo-code to retrieve the following: If a registry key exists What the default value is for that registry key What a string value is What a DWORD value is Example code: Include the library dependency: Advapi32.lib Put the following in your main or where you want to read the values: HKEY hKey; LONG lRes...
695,346
695,365
Beginning C++ problem; cannot instantiate abstract class (C2259 in VS)
I'm attempting to create a concrete instance of the IAudioEvents COM interface (available in Vista and later). This is my first foray into COM programming, so I'm probably just doing something stupid here. Anyway, the following code fails to compile with "C2259: 'AudioEndpointVolumeNotifierImpl' : cannot instantiate ...
Oddly, although OnIconPathChanged is described as taking an LPWCHAR parameter here: http://msdn.microsoft.com/en-us/library/dd370939(VS.85).aspx It is shown taking an LPCWSTR in the example here: http://msdn.microsoft.com/en-us/library/dd370797(VS.85).aspx One of these is probably wrong; if we assume it is the former, ...
695,372
695,411
C++ standard list and default-constructible types
Why is that the single parameter constructor of std::list<T> requires T to be a default-constructible type? I mean the following code does not compile. struct Foo { // does not have default constructor. Foo (int i) {} } int main(void) { std::list<Foo> l(10); } It seems possible to use the construct and destroy i...
std::list doesn't have a capacity function because it makes no sense; it never has to resize like a vector does. It's capacity is only limited by the available memory, which is not easily determined. From what you asked for, I think you actually want reserve(). That's a one-off for vector because it (badly) needs such ...
695,419
695,599
Problem in calling a C++ dll function from C#
This is my 3rd thread concerning a blowfish problem in C#.Despite the fact I cannot have blowfish implemented in my application, I decided to use it as an external C++ dll. Please note I've tried Blowfish.NET and any other, the problem is that I'm translating code from C++ to C# and the C# code must do exactly the same...
To add to what jachymko has said, also check the documentation for BitConverter - you need to be sure you are passing the key and data in the byte order you intended. Note - from your previous thread, I successfully encrypted data using the modified Blowfish.NET encryptor and got it to match the result of your C++ code...
695,645
695,663
Why does the C++ map type argument require an empty constructor when using []?
See also C++ standard list and default-constructible types Not a major issue, just annoying as I don't want my class to ever be instantiated without the particular arguments. #include <map> struct MyClass { MyClass(int t); }; int main() { std::map<int, MyClass> myMap; myMap[14] = MyClass(42); } This ...
This issue comes with operator[]. Quote from SGI documentation: data_type& operator[](const key_type& k) - Returns a reference to the object that is associated with a particular key. If the map does not already contain such an object, operator[] inserts the default object data_type(). If you don't have de...
695,734
695,783
Thought experiment with __stdcall and corrupted stack (C++)
My mind was wandering today on the topic of function pointers, and I came up with the following scenario in my head: __stdcall int function (int) { return 0; } int main() { (*(int(*)(char*,char*))function)("thought", "experiment"); return 0; } AFAIK this code would corrupt the stack, so what types of issu...
You are calling the function as if it is _cdecl which means the caller pushes the arguments and cleans up the stack. The receiving function is _stdcall which implies the callee cleans up the stack. The callee is expecting a single argument so will pop 4 bytes off the stack. When the function returns the caller will th...
695,754
695,756
C++ STL map::erase a non-existing key
Regarding the C++ STL map, erasing by key:- size_type map::erase ( const key_type& x ); Is it legal to erase a non-existing key? i.e. is the snippet below ok? map<char,int> mymap; mymap['c']=30; mymap.erase('c'); mymap.erase('c'); mymap.erase('D'); Cheers
Yes, in fact, std::map::erase() returns a size_type which indicates the number of keys erased. Thus it returns 0 for nothing erased and 1 for something erased for a map.
695,960
695,973
c++ exit loop based on keyboard input
Is it possible to exit a C++ loop based on keyboard input without actually having to input something each iteration? For instance while(checkkeyboardinput != 'q') { do work } I feel that this is very easy, but google isn't helping me, and I can't remember how to do this. Thanks for the help. EDIT: I'm using...
Try _kbhit(). As far as I know it checks if there is any keyboard input waiting in the buffer. http://msdn.microsoft.com/en-us/library/58w7c94c%28VS.80%29.aspx _kbhit Checks the console for keyboard input. int _kbhit( void ); Return Value _kbhit returns a nonzero value if a key has been pressed. Otherwise, it retur...
696,117
696,146
What happens when you close a c++ console application
I guess the question says it all, but, what happens if someone closes a c++ console app? As in, clicks the "x" in the top corner. Does it instantly close? Does it throw some sort of exception? Is it undefined behavior?
Closing a c++ console app with the "x" in the top corner throws an CTRL_CLOSE_EVENT which you could catch and process if you set a control handler using the SetConsoleCtrlHandler function. In there you could override the close functionality and perform whatever you wished to do, and then optionally still perform the de...
696,306
696,365
Run-Time Check Failure #0 loading QueryFullProcessImageName from kernel32.dll
I have an application that needs to run both on WinXP and Vista64. My program requires QueryFullProcessImageName() to work on Vista but not on XP. I try to load QueryFullProcessImageName() (instead of linking statically) via the kernel32.dll so that the same executable can run on both WinXP and Vista. The code that loa...
You should change the typedef to typedef BOOL (WINAPI *LPQueryFullProcessImageName)( HANDLE hProcess, DWORD dwFlags, LPSTR lpExeName, PDWORD lpdwSize ); WINBASEAPI is used for declaring static dependencies and it doesn't specify the __stdcall calling convention. You use GetProcAddress() and so the static dependen...
696,308
696,413
Is boost shared_ptr<XX> thread-safe?
Is the following code thread safe when using boost shared_ptr. Thanks! class CResource { xxxxxx } class CResourceBase { CResourceBase() { m_pMutex = new CMutex; } ~CResourceBase() { ASSERT(m_pMutex != NULL); delete m_pMutex; m_pMutex = NULL; } private: CMutex *m_pMutex; public: void SetResource(shared_ptr<CResource>...
There is no race possibility in you example (it' correctly locked). However, you should be very careful with shared_ptr in multithread code. Please, keep in mind that there is possibility that you have access do the same object through different shared_ptrs from different threads. For example, after: Thread B: shar...
696,320
696,328
Overloading C++ STL methods
How can I overload the STL implementation for methods like find, erase and insert to take varying parameters? I tried to look up the overloading of STL methods but couldn't find any help.
You can't overload the methods of a class without editing the code of that class. Write your own free functions that act as helpers; they would take the relevant container class as the first parameter. You can inherit from a class and add methods that way, but the std container classes are not designed to be inherited ...
696,399
696,405
How to put different template types into one vector
I'd like to construct a message with unknown length or number of arguments. I took a simple template like template <typename T> class Argument { public: int size; int type; T data; }; and with some overloaded addMessage (int value) { Argument<int> *a = new Argument<int>; vec.push_back(a); } (same...
Option 1 : make sure that all different types of arguments derive from a base class and use pointers to that class. Note that this option is risky in terms of memory management. You might want to make it safer by using boost::shared_ptr instead of pointers. Otherwise, you must manually clean up when an item is being re...
696,580
696,616
Getting a dump of a process that crashes on startup
On a customer machine (WinXP SP2) to which I have no access, I have a Win32 EXE (unmanaged C++) that crashes on startup. I guess the best way to troubleshoot this is to obtain a (mini-)dump and analyze it later with windbg or similar. Now, I would normally tell the customer to install Debugging Tools for Windows and ru...
You can install WinDBG on the client machine and then use "Image File Execution Options" and set WinDBG to open once that the process has started. Then run the crashing process and WinDBG will open up immediately. press g (Go) and wait for the process to crash then type ".dump /mfh dumpFileName.dmp". Now you have dump ...
696,952
696,964
Bitmask to Array Index
Is there a simple way to convert a bitmask in to an array index? ie. If i've got an enum a = 0x01, b = 0x02, c = 0x04, d = 0x08, e = 0x10, etc and I want to store releated data in an array, is there a simple way such that i can convert a to 0, b to 1, c to 2. etc? Many thanks
r = ln base 2 and programmatically, unsigned int v=yourEnumValue; unsigned r = 0; while (v >>= 1) { r++; } r is your answer
696,985
696,991
several definitions of the same class
Playing around with MSVC++ 2005, I noticed that if the same class is defined several times, the program still happily links, even at the highest warning level. I find it surprising, how comes this is not an error? module_a.cpp: #include <iostream> struct Foo { const char * Bar() { return "MODULE_A"; } }; void TestA()...
It is an error - the code breaks the C++ One Definition Rule. If you do that, the standard says you get undefined behaviour. The code links, because if you had: struct Foo { const char * Bar() { return "MODULE_B"; } }; in both modules there would NOT be a ODR violation - after all, this is basically what #including ...
697,026
697,046
exception handling in constructor’s initializer list
In my project I found a piece of code in which a method was getting called in constructor's initializer list. Test2(Test* pTest):m_pTest(pTest), m_nDuplicateID(pTest->getTestID()) { } I observed that there is a chance that the users of Test2 might pass NULL to the constructor. Since the pointer is used withou...
Firstly, if you dereference the NULL pointer standard C++ does not guarantee that that an exception will be thrown, so your code is useless for this case. Secondly, if an exception were thrown, what would your exception handler do? Thirdly, constructor/function exception blocks are widely considered to be awaste of t...
697,664
697,684
Using shared memory under Windows. How to pass different data
I currently try to implement some interprocess communication using the Windows CreateFileMapping mechanism. I know that I need to create a file mapping object with CreateFileMapping first and then create a pointer to the actual data with MapViewOfFile. The example then puts data into the mapfile by using CopyMemory. In...
Different processes have different address spaces. If you pass a valid pointer in one process to another process, it will probably point to random data in the second process. So you will have to copy all the data.
697,711
698,344
Why doesn't this Blitz++ code compile?
I'm a blitz++ newbie. So far, so good, but I'm a bit mystified why the commented out line in the code below fails to compile with error: conversion from ‘blitz::_bz_tinyMatExpr<blitz::_bz_tinyMatrixMatrixProduct<double, double, 3, 3, 3, 3, 1, 3, 1> >’ to non-scalar type ‘const m33’ requested I'm on Debian/Lenny (g++...
I have had a look at the source code of Blitz++. As surprising as it may seem, there is no template constructor for TinyMatrix, but there is a template = operator. That means that you cannot do what you are trying to do. So I'd suggest forgetting about your matrix being const. Or find another way like creating a non-co...
697,868
697,871
Why is the destructor not called for the returned object from the function?
I was thinking that when a function returns an object on the stack to the calling function, the calling function gets a copy of the original object but the original object's destructor is called as soon as the stack unwinds. But in the following program, the destructor is getting called only once. I expected it to be c...
This is a special case where the compiler is allowed to optimize out the copy: this is called named return value optimization (NRVO). Basically, the compiler allocates memory for the return object on the call site and lets the function fill in that memory directly instead of creating the object at the called site and c...
698,011
698,042
String Compare not working in Visual C++ 2005
If get a gring from the registry and it correctly displays when I place it in a message box. ::MessageBoxW(0, (LPCWSTR)achValue, _T("Found"), MB_YESNO); The value is stored in archValue which is a DWORD. What I want to do is compare it to the following string "2.0.7045.0" but strcmp fails to work for me. Any ideas on h...
You need to use the wide char version of strcmp: wcscmp.
698,043
698,067
looking for free c++ cross platform GUI framework
im looking for cross platform GUI for free for commercial project ( that means i can't give the code ) no GPL and i guess no LGPL what else its leaving me ? wxWidgets ? Thanks
If you want to avoid LGPL, wxWidgets is probably the most feature-complete option. It uses a derivitive of LGPL which is more flexible on the distribution. However, LGPL is fine for use with commercial works. The only restriction is that you need to link dynamically with the UI library, which is typically not an issu...
698,312
698,356
Relation between word length, character size, integer size and byte
What is the relation between word length, character size, integer size, and byte in C++?
The standard requires that certain types have minimum sizes (short is at least 16 bits, int is at least 16 bits, etc), and that some groups of type are ordered (sizeof(int) >= sizeof(short) >= sizeof(char)).
698,345
698,593
I need to have a key with multiple values. What datastructure would you recommend?
I have an string array filled with words from a sentence. words[0] = "the" words[1] = "dog" words[2] = "jumped" words[3] = "over" words[4] = "the" words[5] = "wall." words[6] = "the" words[7] = "cat" words[8] = "fell" words[9] = "off" words[10] = "the" words[10] = "house." etc. (Stupid example, but it works for this) ...
you can use a multimap from the STL and use the call pair<iterator, iterator> equal_range(const key_type& k) to get a range of iterators that match your key personally i find this slightly clunky due to having to deal with iterator ranges rather than just getting an object back that represents all values for that key....
698,415
698,436
How specific to get on design document?
I'm creating a design document for a security subsystem, to be written in C++. I've created a class diagram and sequence diagrams for the major use cases. I've also specified the public attributes, associations and methods for each of the classes. But, I haven't drilled the method definitions down to the C++ level yet....
Since you're new, it probably makes sense not to drill down. Reason: You're still figuring out the language and how things are best structured. That means you'll make mistakes initially and you'll want to correct them without constantly updating the documentation.
698,472
714,030
What's the difference between calling CComModule.RegisterServer, _AtlComModule.RegisterServer, and LoadTypeLibEx for TypeLib registration?
In my DllRegisterServer method of my COM dll, I previously had code that called LoadTypeLibEx(module, REGKIND_REGISTER, &pTypeLib) to register my COM classes and their corresponding TypeLib's. My COM DLL is a 64-bit. I've noticed that on my 64-bit Vista system, under HKCR:\\TypeLib\{myguid}\1.0\0 I find a win32 subkey ...
It appears that perhaps the behavior I'm seeing regarding win32/win64 subkeys reflects the fact that some type libraries can be used in 64-bit and 32-bit programs because there they contain no bit-constrained (read: pointer) parameters. Other type libraries, meanwhile, need different entries for win32 and win64 because...
698,520
698,544
Search for nearest value in an array of doubles in C++?
I have a sorted array of double values in C++. Is there an STL function that will return the index of the nearest value in the array to a given double value? For example, given the following array double myarray[5] = { 1.0, 1.2, 1.4. 1.5, 1.9 }; the function call search(myarray, 1.6); should return 3, the index of t...
maybe std::lower_bound std::upper_bound will help you.
698,655
698,735
How can I categorize the memory usage of a NON-.NET application/DLL?
I have a 32-bit Visual Studio 8.0 C++ Windows DLL (non-.NET) that appears to be taking up more memory than I would expect. I want to determine exactly where the memory is going, not just a single figure of the total memory used (not interested in Task Manager or Resource Monitor's memory usage values). Back in 16-bit ...
If you need to find the size of various sections of the DLL you can use dumpbin.exe. It is a command line tool for inspecting DLLs and executables. Be sure to run vcvars32.bat before trying to run it. To look at the actual memory consumption of your DLL, I would suggest starting with umdh.exe. It ships as part of wi...
698,859
698,887
Setting boost dynamic_bitset from a string
Dynamic bitset I have a use case where i need to populate boost::dynamic_bitset<unsigned char> , from a std::string buffer. Can you suggest as to how to go about this. So I need to come up with a function void populateBitSet (std::string &buffer, boost::dynamic_bitset<unsigned char> & bitMap) { //p...
If you have binary data like this: string buffer = "0101001111011"; You want to initialize it like this (turns out there's a constructor that handles this case): void populateBitSet (std::string &buffer, boost::dynamic_bitset<unsigned char> & bitMap) { bitMap = boost::dynamic_bitset<unsigned char> (buffer)...
698,921
699,484
monitor cpu usage per thread on windows mobile device
Is is possible to measure CPU per thread on a windows mobile (or CE 5) device programmatically (c++)? If not, is their a utility that will monitor the CPU usage of a process?
CPU usage cannot be directly measured because, unlike an x86, the ARM processor doesn't have a register for it. You can calculate it using the Toolhelp APIs to get a list of processes and their child threads and then use GetThreadTimes to figure out how much time each thread is using. Keep in mind that doing this calc...
698,967
699,019
InvalidateRect in WM_CREATE does not work
I want to invalidate the window when it's created. How can I do that? calling InvalidateRect during WM_CREATE doesn't work. The thing is I call SetWindowLongPtr in WM_CREATE and set GWLP_USERDATA. WM_PAINT looks for some pointer in USER_DATA but the first time I receive WM_PAINT the data isn't apparently still there so...
Your window is already invalid when it is created PostMessage puts a message in the queue so is likely to arrive after the regular creation messages (WM_CREATE/WM_SIZE/WM_PAINT etc). If your painting is failing due to GWLP_USERDATA being NULL then something else is happening...
699,054
699,083
Bison does not appear to recognize C string literals appropriately
My problem is that I am trying to run a problem that I coded using a flex-bison scanner-parser. What my program is supposed to do is take user input (in my case, queries for a database system I'm designing), lex and parse, and then execute the corresponding actions. What actually happens is that my parser code is not c...
This is a classic error, if you use flex to lex your input into tokens, you must not refer to the literal strings in the parser as literal strings, but rather use tokens for them. For details, see this similar question
699,250
699,269
std::map design: why map accept comparator as template parameter
Map type from STL have next type: std::map< Key, Data, Compare, Alloc > As one of template parameters we could pass Compare predicate, why map accept this predicate as template parameter and not as object in constructor? It could has more flexible interface with something like boost::function< bool, const T&, cons...
Map DOES have such a constructor. From section 23.3.1 of the C++ Standard: explicit map(const Compare& comp = Compare(), const Allocator& = Allocator());
699,301
699,324
Is int x = 'fooo' a compiler extension?
I have seen and used C++ code like the following: int myFourcc = 'ABCD'; It works in recent versions of GCC, not sure how recent. Is this feature in the standard? What is it called? I have had trouble searching the web for it... EDIT: I found this info as well, for future observers: from gcc documentation The compile...
"Note that according to the C standard there is no limit on the length of a character constant, but the value of a character constant that contains more than one character is implementation-defined. Recent versions of GCC provide support multi-byte character constants, and instead of an error the warnings multiple-char...
699,603
699,604
change volume win32 c++
How would I go about changing the sound volume in c++ win32? Also how would I mute/unmute it? Thanks for the help!
Two options: There's an answer to that question here on SO (changing the master volume from C++, which also includes SetMute, etc.) Have you considered showing the Volume controls and letting the user? If so, I can post some code for that. (You basically just shell out to the volume control applet.
699,781
699,807
C++ binary constant/literal
I'm using a well known template to allow binary constants template< unsigned long long N > struct binary { enum { value = (N % 10) + 2 * binary< N / 10 > :: value } ; }; template<> struct binary< 0 > { enum { value = 0 } ; }; So you can do something like binary<101011011>::value. Unfortunately this has a limit of...
Does this work if you have a leading zero on your binary value? A leading zero makes the constant octal rather than decimal. Which leads to a way to squeeze a couple more digits out of this solution - always start your binary constant with a zero! Then replace the 10's in your template with 8's.
700,188
700,339
A Large Number of sp_counted_impl_p Objects
I just performed Allocation Profiling about how many objects of each type are in my application. I am using boost::shared_ptr extensively. I found a large number of sp_counted_impl_p objects allocated, each occupying 16 bytes. How many of sp_counted_impl_p objects can be expect per shared_ptr? Does someone have an ide...
For what I can see in the implementation, just one per shared_ptr. However, note that there are more objects used by boost internally, that may use this counted class directly or shared_ptr itself. Also, if you use the boost.serialization framework, it is also based on this class/mechanism. Anyway, by "a large number",...
700,392
700,397
High Resolution Timing Part of Your Code
I want to measure the speed of a function within a loop. But why my way of doing it always print "0" instead of high-res timing with 9 digits decimal precision (i.e. in nano/micro seconds)? What's the correct way to do it? #include <iomanip> #include <iostream> #include <time.h> int main() { for (int i = 0; i <100; ...
Move your time calculation functions outside for () { .. } statement then devide total execution time by the number of operations in your testing loop. #include <iostream> #include <ctime> #define NUMBER 10000 // the number of operations // get the difference between start and end time and devide by // the number of o...
700,426
700,462
How to get the SPID in linux 2.6 from C++
I have a question: Is there some way to the SPID in linux 2.6 from a C++ application? When I do a "ps -amT" I can see the threads in the process: root@10.67.100.2:~# ps -amT PID SPID TTY TIME CMD 1120 - pts/1 00:00:20 sncmdd - 1120 - 00:00:00 - - 1125 - 00:00:00 - - 112...
How about gettid()? Edit: If your libc doesn't have the gettid() function, you should run it like this: #include <sys/syscall.h> syscall(SYS_gettid); ... or see example on this manual page.
700,570
700,659
How can I write a program which can test throughput of disk?
How can I write a program which can test throughput of disk in Windows systems using c++? What's the mainly steps and APIs that I can use to programming?
One open-source benchmark is bonnie, which mostly uses the standard C API. You'll need to change some of the timing functions to suit Windows.
700,588
700,614
Is it safe to store objects of a class which has an std::auto_ptr as its member variable in std::vector?
I can't use shared_ptr in my project, no boost :( So, I'm having a class roughly similar to the one below: class MyClass { private: std::auto_ptr<MyOtherClass> obj; }; Now, I want to store the instances of above class in std::vector. Is it safe? I've read here that it's wrong to use std::auto_ptr with STL containers...
I've posted a question as a follow-up to this answer, see Class containing auto_ptr stored in vector. Assming your class does not have a user-defined copy constructor, then no, it is probably (see below) not safe. When your class is copied (as will happen when it is added to a vector) the copy constructor of the ...
700,731
702,007
Qt4.4 how to get the user settings path
linux: $HOME/.config windows: %APPDATA% mac os: $HOME/.config It can be set using http://qt-project.org/doc/qt-4.8/qsettings.html#setPath, but it seems as I am not able to retrieve it. http://qt-project.org/doc/qt-4.8/qlibraryinfo.html#location QLibraryInfo::LibrariesPath returns the system wide settings dir, which i...
This might not answer your question directly: if you want to store per-user persistent data, shouldn't you use QDesktopServices::storageLocation(QDesktopServices::DataLocation) instead?
700,863
703,324
How to utilize sqlite for undo/redo features?
I'm writing a desktop application to do vector drawing in C++, and considering using sqlite to back my undo/redo feature. Has anybody used sqlite for undo/redo features? How does it work out for you? Clarification: I was aware of the stack approach, I have even implemented one application with that approach. The probl...
It makes sense to use SQLite to back undo/redo when an SQLite database is the application's data file format. See the SQLite website for an explanation of how to do this with SQLite triggers.
701,040
701,091
Is it OK to return a const reference to a private member?
I need to implement read-only access to a private member container. If I return a constant reference is it possible to const_cast it and obtain a full access to the member? What's the technique to be used? Thanks.
Returning a const & is a sensible thing to do in many circumstances, particularly if the object being returned is large or cannot be copied. Regarding the const_cast, remember the "private" access specifier in C++ is there as an aid to the programmer - it is not intended to be a security measure. If someone wants acces...
701,180
701,210
Is there an un-buffered I/O in Windows system?
I want to find low-level C/C++ APIs, equivalent with "write" in linux systems, that don't have a buffer. Is there one? The buffered I/O such as fread, fwrite are not what I wanted.
Look at CreateFile with the FILE_FLAG_NO_BUFFERING option
701,277
937,089
I am using a comet server and I want it to interact with C++
I am using persevere for an application I am writing that controls remote hardwere. Persevere is written in Java and doesn't supply an alternative API. I am using a web-based GUI as the control panel. So far, so good. I can get and set data using REST channels like dojo does but the problem is that I don't really know ...
If you use gcc as your toolchain you can embed a JVM with GCJ to run persevere inside your application. GCJ makes it easy to call C++ from Java with it's CNI interface (much easier than JNI). I used that method to use Java scripting inside our C++ application. You can even compile the persevere jar into a native librar...
701,313
701,324
Is it safe to call temporary object's methods?
I have a function which shall return a char*. Since I have to concatenate some strings, I wrote the following line: std::string other_text; // ... func(("text" + other_text).c_str()); I know that I could avoid the question naming the string I want to use. I just want to take the chance to make a more general question:...
It is safe to call methods of temporary variables, but not safe to return a char* of a temporary variable for later use. This char* points to a buffer that will be freed soon. Once it is freed you will have a pointer to an invalid region in memory. Instead please return an std::string object.
701,456
701,711
What are potential dangers when using boost::shared_ptr?
What are some ways you can shoot yourself in the foot when using boost::shared_ptr? In other words, what pitfalls do I have to avoid when I use boost::shared_ptr?
Cyclic references: a shared_ptr<> to something that has a shared_ptr<> to the original object. You can use weak_ptr<> to break this cycle, of course. I add the following as an example of what I am talking about in the comments. class node : public enable_shared_from_this<node> { public : void set_parent(shared_pt...
701,699
701,768
Assigning to temporary (like 5 = 10 but for user-defined types)
after doing some test-code for this link : Is it safe to call temporary object's methods? I found a rather strange feature of the c++ language, which I'm not sure how it works : struct Test{ int i; Test(int ii):i(ii){} Test& operator=(int ii){ i = ii; return *this; } Test operator+(c...
Let's go line by line: Test x = Test(5) + Test(5) = 8;//assign to a temporary There's no big deal here. Temporaries are still just normal objects, and thus the assignment operator works on them just as it would on anything else. Test& xRef = Test(5) + Test(5);//reference to a temporary Like Metroworks, my GC...
702,003
702,031
(*this)[i] after overloading [] operator?
I overloaded the [] operator in my class. Is there a nicer way to call this function from within my class other than (*this)[i]?
Add function at(size_t i) and use this function. EDIT: If you actively using stl avoid semantic inconsistence: in std::vector operator[] does not check if index is valid, but at(..) check and could throw std::out_of_range exception. I think in project with more stl similar behavior will expected from your class. Maybe ...
702,185
702,191
Initializing in constructors, best practice?
I've been programming in C++ a while and I've used both methods: class Stuff { public: Stuff( int nr ) : n( nr ) { } private: int n; } Or class Stuff { public: Stuff( int nr ) { n = nr; } private: int n; } Note: This is not the same as this, similar but not the same. What is conside...
Initializer lists are preferred. See FAQ 10.6
702,253
702,527
How to call a method inde an Xlam from C++ Unmanaged XLL file
I have an Xlam addin with some methods, I'd like to call these methods from a C++ Unmanaged Xll file, is there a way to do this?
Can you use the Excel12v function?
702,647
702,674
C++ Symmetric Binary Operators with Different Types
I am learning C++ and I was wondering if I could gain some insight into the preferred way of creating binary operators that work on instances of two different types. Here is an example that I've made to illustrate my concerns: class A; class B; class A { private: int x; public: A(int x); ...
The best way is to define (outside of either class) int operator+ (const A& a, const B& b), and make it a friend function of both classes if needed. In addition, define int operator+(const B& b, const A& a) {return a + b;} To make it symmetric.
702,650
702,701
Making a template parameter a friend?
Example: template<class T> class Base { public: Base(); friend class T; }; Now this doesn't work... Is there a way of doing this? I'm actually trying to make a general class sealer like this: class ClassSealer { private: friend class Sealed; ClassSealer() {} }; class Sealed : private virtual ClassSealer ...
It is explicitly disallowed in the standard, even if some versions of VisualStudio do allow it. C++ Standard 7.1.5.3 Elaborated type specifiers, paragraph 2 3.4.4 describes how name lookup proceeds for the identifier in an elaborated-type-specifier. If the identifier resolves to a class-name or enum-name, the...
702,658
3,801,999
C++ union array and vars?
There's no way to do something like this, in C++ is there? union { { Scalar x, y; } Scalar v[2]; }; Where x == v[0] and y == v[1]?
I've used something like this before. I'm not sure its 100% OK by the standard, but it seems to be OK with any compilers I've needed to use it on. struct Vec2 { float x; float y; float& operator[](int i) { return *(&x+i); } }; You can add bounds checking etc to operator[] if you want ( you probably should want) ...
703,432
703,547
debug vs release build in Visual studio c++ 2008 win32 runtime issue
I have a simple udp listener written in c++ using win32 when I compile and run the program under debug mode it works perfectly, and I'm clearly able to see the information from the packets that I'm receiving. When I run this same code as a release build it compiles fine and seems to run fine, but its not printing out a...
This is more likely an issue of not initializing variables to some initial value, so in debug they have some sort of value, but in release, most things are initialized zero (NULL). So, some condition/branch may be taking place, that you do not expect... Without your source code for example, it's REALLY hard to spot i...
703,453
703,468
Optional function parameters: Use default arguments (NULL) or overload the function?
I have a function that processes a given vector, but may also create such a vector itself if it is not given. I see two design choices for such a case, where a function parameter is optional: Make it a pointer and make it NULL by default: void foo(int i, std::vector<int>* optional = NULL) { if(optional == NULL){ ...
I would definitely favour the 2nd approach of overloaded methods. The first approach (optional parameters) blurs the definition of the method as it no longer has a single well-defined purpose. This in turn increases the complexity of the code, making it more difficult for someone not familiar with it to understand it....
703,503
703,518
Which STL container is best for std::sort? (Does it even matter?)
The title speaks for itself .... Does choice of container affects the speed of the default std::sort algorithm somehow or not? For example, if I use list, does the sorting algorithm just switch the node pointers or does it switch the whole data in the nodes?
I don't think std::sort works on lists as it requires a random access iterator which is not provided by a list<>. Note that list<> provides a sort method but it's completely separate from std::sort. The choice of container does matter. STL's std::sort relies on iterators to abstract away the way a container stores data...
703,561
707,321
Speeding up virtual function calls in gcc
Profiling my C++ code with gprof, I discovered that a significant portion of my time is spent calling one virtual method over and over. The method itself is short and could probably be inlined if it wasn't virtual. What are some ways I could speed this up short of rewriting it all to not be virtual?
It's sometimes instructive to consider how you'd write the code in good old 'C' if you didn't have C++'s syntactic sugar available. Sometimes the answer isn't using an indirect call. See this answer for an example.
703,691
703,706
How does delete[] know it's an array?
Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed, void deleteForMe(int* pointer) { delete[] pointer; } The pointer could be all sorts of different things, and so performing an unconditional delete[] on it is undefined. However, let's assume that we ...
The compiler doesn't know it's an array, it's trusting the programmer. Deleting a pointer to a single int with delete [] would result in undefined behavior. Your second main() example is unsafe, even if it doesn't immediately crash. The compiler does have to keep track of how many objects need to be deleted somehow. ...
704,286
706,935
Looking for cross platform Packet Capture Library
beside wincap , is there any recommended cross platform Packet Capture Library to use with c/c++ ? Thanks
You can use the "pcap" interface. Unix like system implement this interface with libpcap and Winpcap on windows. http://en.wikipedia.org/wiki/Pcap
704,294
705,780
Linker Error while building application using Boost Asio in Visual Studio C++ 2008 Express
I just started writing a small application in C++ using Visual Studio C++ 2008 Express. I installed the Boost Library using the Windows installer. While compiling the program I get the following error : Compiling... stdafx.cpp Compiling... websave.cpp GoogleAuthenticate.cpp Generating Code... Compiling ma...
Forgot to add this : In Configuration Properties > Linker > Additional Library Directories, enter the path to the Boost binaries, e.g. C:\Program Files\boost\boost_1_38_0\lib. Should have RTFM. http://www.boost.org/doc/libs/1_36_0/more/getting_started/windows.html#link-from-within-the-visual-studio-ide Fixed.
704,402
704,413
C++ blowfish works with fewer letters,but C# blowfish doesn't
a C++ blowfish supports encrypting a block with less than < 8 letters,while .NET doesn't.Why? -->C# NET Blowfish<-- -->C++ Blowfish<-- In both C++ and C# applications,I encrypt the following array byte response[6] = { 0x00, 0x80, 0x01, 0x61, 0x05, 0x06 }; In both C++ and C# applications,I call the...
The code you pastebinned (not recommended for SO by the way, as your paste will be removed if noone reads it in a while, thereby leaving this question broken) says in its header comment: /// Note that the number of bytes must be adjusted to the block size of the algorithm. (lines 3 and 4). So it seems to be behaving t...
704,430
704,755
What`s wrong with qt 4.5.0 integration with Visual Studio 2008?
I downloaded and installed qt evaluation for vs2008 and expect it to be integrated with VS, but it is not. It is trial 30 days commercial license. What`s wrong with it or may be I got it wrong?
The Visual Studio integration is a separate download: http://www.qtsoftware.com/downloads/visual-studio-add-in
704,466
704,568
Why doesn't delete set the pointer to NULL?
I always wondered why automatic setting of the pointer to NULL after delete is not part of the standard. If this gets taken care of then many of the crashes due to an invalid pointer would not occur. But having said that I can think of couple of reasons why the standard would have restricted this: Performance: An add...
Stroustrup himself answers. An excerpt: C++ explicitly allows an implementation of delete to zero out an lvalue operand, and I had hoped that implementations would do that, but that idea doesn't seem to have become popular with implementers. But the main issue he raises is that delete's argument need not b...
704,527
704,784
How to do Latin1-UTF8 encoding change in C++ (maybe with Boost)?
My source base is mostly using UTF8, but some older library has Windows Latin1 encoded strings hardcoded within it. I was hoping Boost would have a clear conversion feature, but I did not find such. Do I really need to hand-code such a commonplace solution? Looking for a portable solution, running on Linux. (This Q is...
International Components for Unicode (ICU) does have the solutions you are looking for. Boost can be compiled with support for ICU, e.g. for Boost regular expressions, but precompiled versions of Boost usually don't include it.
704,602
704,626
I am trying to return a Character Array but, I'm only getting the first letter returned
I'm working on a small little thing here for school. After hours of researching, and a ton of errors and logic reworking I've almost completed my little program here. I'm trying to take user input, store it into the string, get a character array from the string ( dont ask why, I just have to put this into a character a...
Try rewriting getCharArray like this char* getCharArray(string sPhrase) { int size = 1; size = sPhrase.length(); char* cArray = NULL; cArray = new char[size+1]; // NOTE for (int i = 0 ; i < size ; i++) { cArray[i] = sPhrase.at(i); // NOTE } ...
704,614
715,702
compile error: cpumask.h: "and" may not appear in macro parameter list
I'm trying to move a project from an old linux platform to a kubunutu 9.04. Now I get this error when compiling with gcc 4.3.3: /usr/src/linux-headers-2.6.28-11-generic/include/linux/cpumask.h:600:37: error: "and" may not appear in macro parameter list If I understand the message right, it is not allowed to use "and" ...
I believe the problem is that and is a keyword in C++ but not C (they use &&). The kernel guys sometimes macros as an alternative to inline functions. Sometimes, however, they need macros because what they want to do has to be done in the scope of the calling function, and defining a function to do that won't work (fo...
704,738
704,745
Create class diagram from c++ source?
Is there any free tools available for generating class diagram from c++ source files and if possible for mfc source files too.
We use doxygen with graphviz support
704,780
705,611
Class containing auto_ptr stored in vector
In an answer to Is it safe to store objects of a class which has an std::auto_ptr as its member variable in std::vector? I stated that a class that contained an auto_ptr could be stored in a vector provided the class had a user-defined copy constructor. There were several comment suggesting that this was not the case,...
Trying to put the list of places together that makes the example undefined behavior. #include <memory> #include <vector> using namespace std; struct Z {}; struct A { A( Z z ) : p( new Z(z) ) {} A( const A & a ) : p( a.p.get() ? new Z( *a.p.get()) : 0 ) {} // no assigment op or dtor d...
704,892
704,963
What is the best way I should go about creating a program to store information into a file, edit the information in that file, and add new information
I'm about to start on a little project i'm trying to do where I create a C++ program to store inventory data into a file ( I guess a .txt will do ) • Item Description • Quantity on Hand • Wholesale Cost • Retail Cost • Date Added to Inventory I need to be able to: • Add new records to the file • Displ...
There are many approaches. Is this for homework or for real use? If it's for homework, there are probably some restrictions on what you may use. Otherwise I suggest some embedded DBMS like SQLite. There are others too, but this will be the most powerful solution, and will also have the easiest implementation. XML is al...
704,908
704,926
Compilers and negative numbers representations
Recently I was confused by this question. Maybe because I didn't read language specifications (it's my fault, I know). C99 standard doesn't say which negative numbers representation should be used by compiler. I always thought that the only right way to store negative numbers is two's complement (in most cases). So her...
I think it's not so much a question of what representation the compiler uses, but rather what representation the underlying machine uses. The compiler would be very stupid to pick a representation not supported by the target machine, since that would introduce loads of overhead for no benefit. Some checksum fields in t...
704,995
705,258
C++ multiple declaration of function error when linking
I seem to be forgetting my C++ ... I'm trying to declare some functions in C in separate sources, and including the appropriate .h when necessary. It compiles OK; but the problem is during linking, where the linker complains about functions already being defined. I even tried defining the functions as extern, in a (vai...
Thank you all for your replies and comments. I figured out the problem (it turned out to be a very stupid thing) and am close to solving it (hopefully). It turns out it comes from another include file (cfortran.h) which implements a layer for using C function calls in Fortran (and vice-versa). It's very useful and I've...
704,998
709,572
How to underline individual items in a CListCtrl
We want some items in a CListView to appear like hypertext links. I can make everything underlined by setting the lfUnderline flag in LOGFONT, and creating a font from this, before calling SetFont - but this applies to the whole CListView. Does anyone know how to make individual items in a CListView to appear underline...
You can do this by using the custom-draw notifications and modifying the font on the particular item you want within the custom-draw handler. See this link for details.
705,037
705,051
How to pass parameters to a Thread object?
I'm working with a C++ class-library that provides a Thread base-class where the user has to implement a run() method. Is there a recommended way on how to pass parameters to that run() method? Right now I prefer to pass them via the constructor (as pointers).
I'm not sure about C++, but that's how you would do it in Java. You'd have a class that extends Thread (or implements Runnable) and a constructor with the parameters you'd like to pass. Then, when you create the new thread, you have to pass in the arguments, and then start the thread, something like this: Thread t = ne...
705,459
705,486
OO design - propagating attributes
I'm an experienced C programmer dipping my toes in OO design (specifically C++). I have a particular piece of code I hate and would like to clean up using C++. The code implements a display tree for use in a 3d graphics app. It is a linked list of entries which have a type field specifying whether the entry is a window...
1) Use boost::function and stl algorithms like for_each count_if 2) Divide model from the view. It will be ok. 3) GoF design pattern Composite 4) To implement reaction on changes take a look at GoF design pattern Observer
705,502
705,516
Why does Microsoft's C compiler want the variables at the beginning of the function?
I am currently writing a C (not C++). It seems the Microsoft's C compiler requires all variables to be declared on top of the function. For example, the following code will not pass compilation: int foo(int x) { assert(x != 0); int y = 2 * x; return y; } The compiler reports an error at the third line, say...
It looks like it's using C89 standard, which requires that all variables be declared before any code. You may initialize them with literals, etc., but not mix code and variables. There should be a compiler flag to enable C99 somewhere, which will get you the behavior you're used to. EDIT: quick Googling does not look p...
705,609
705,738
How can I properly parse my file? (Using break/continue)
I have the following data that looks like this for example: 34 foo 34 bar 34 qux 62 foo1 62 qux 78 qux These are sorted based on the first column. What I want to do is to process lines that starts with 34, but I also want the file iteration to quit after it finds no more 34s, without having have to scan t...
Based on the assumption that the file is sorted by FirstCol, use a state variable that indicates whether or not you have found the first one. Once you have found the first one, as soon as you find a column that is != 34, you can break out of the loop. For example, suppose your data is now: 15 boo 32 not 34 foo 34 bar ...
705,854
705,976
How to get the address of an overloaded member function?
I'm trying to get a pointer to a specific version of an overloaded member function. Here's the example: class C { bool f(int) { ... } bool f(double) { ... } bool example() { // I want to get the "double" version. typedef bool (C::*MemberFunctionType)(double); MemberFunctionType pointer = &C::f; /...
Well, i'll answer what i put as comment already so it can be accepted. Problem is with constness: class C { bool f(int) { ... } bool f(double) const { ... } bool example() { // I want to get the "double" version. typedef bool (C::*MemberFunctionType)(double) const; // const required! MemberFunction...
706,030
706,082
Are uninitialized struct members always set to zero?
Consider a C struct: struct T { int x; int y; }; When this is partially initialized as in struct T t = {42}; is t.y guaranteed to be 0 or is this an implementation decision of the compiler?
item 8.5.1.7 of standard draft: -7- If there are fewer initializers in the list than there are members in the aggregate, then each member not explicitly initialized shall be default-initialized (dcl.init). [Example: struct S { int a; char* b; int c; }; S ss = { 1, "asdf" }; initializes ss.a with 1, ss.b with ...
706,059
706,071
Mismatch between constructor definition and declaration
I had the following C++ code, where the argument to my constructor in the declaration had different constness than the definition of the constructor. //testClass.hpp class testClass { public: testClass(const int *x); }; //testClass.cpp testClass::testClass(const int * const x) {} I was able to compile this wit...
In cases like this, the const specifier is allowed to be ommitted from the declaration because it doesn't change anything for the caller. It matters only to the context of the implementation details. So that's why it is on the definition but not the declaration. Example: //Both f and g have the same signature void f...
706,352
983,473
Use RegisterDeviceNotification() for ALL USB devices
I currently have some code that sets up notifications of connected USB HID devices within a Windows Service (written in C++). The code is as follows: GUID hidGuid; HidD_GetHidGuid(&hidGuid); DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); N...
Used GUID_DEVINTERFACE_USB_DEVICE (in "usbiodef.h") to watch for all USB devices. DEV_BROADCAST_DEVICEINTERFACE NotificationFilter; ZeroMemory(&NotificationFilter, sizeof(NotificationFilter)); NotificationFilter.dbcc_size = sizeof(NotificationFilter); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTER...
706,861
707,838
Where does Intel C++ Compiler store the vptr ( pointer to virtual function table ) in an Object?
Where does Intel C++ Compiler store the vptr ( pointer to virtual function table ) in an Object ? I believe MSVC puts it at the beginning of the object, gcc at the end. What is it for icpc ( Intel C++ Compiler )?
For Intel C++ compiler, for Linux, I found it to be the beginning of the object. Code: #include <cstdio> class A { int a, b; public: A(int a1, int b1): a(a1), b(b1) {} virtual void p(void) { printf("A\n"); } }; class B: public A { public: B(int a1, int b1): A(a1, b1) {} void p(void){ printf("B\n"); } }; i...
706,908
707,204
Can't convert function pointer argument
The error I'm getting: error C2664: 'v8::FunctionTemplate::New' : cannot convert parameter 1 from 'v8::Handle<T> (__cdecl *)(const v8::Arguments &)' to 'v8::InvocationCallback' Relevant definitions: typedef Handle<Value> (*InvocationCallback)(const Arguments& args); template<class C> class V8ScriptClass { public: ...
I found the error. the RelayCallback template takes a static function pointer as argument, and I tried to instantiate it with a member function pointer. I just had to change it to a member function pointer template argument.