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 to shorten the learning curve? I have seen that function objects are commonly used so I would probably need to polish up on that. Additionally, are there any tutorials and 101 resources I can quickly look at to just get a feel and understanding on using boost. I realise there is a lot boost offers and I have to pick the right tools for the right job but any leads will help. Related How to learn boost (no longer valid; HTTP return status 404)
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 make your life much better. Plus, looking at how the boost libraries are coded will help you get better at c++ coding, especially templates. You mentioned what should you look up before trying boost. I agree that function objects are a great thing to research. Also, make sure to look up about template programming. A common problem to make sure you know is when to use the typename qualifier for dependent types. For the most part, however, the libraries are very well documented, with examples and reference materials.
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 constructor take zero parameters?
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 the generated list for repeats? Edit: Also I want it to be efficient in generating big numbers without the entire range. Edit: I see everyone suggesting shuffle algorithms. But if I want to generate large random number (1024 byte+) then that method would take alot more memory than if I just used a regular RNG and inserted into a Set until it was a specified length, right? Is there no better mathematical algorithm for this.
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 is, a 16-bit lfsr can produce a sequence 65535 long with no repeats. It's statistically random but of course eminently repeatable. Also, if it's done wrong, you can get some embarrassingly short sequences. If you look up the lfsr, you will find examples of how to construct them properly (which is to say, "maximal length").
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 buddy on twitter just tweeted that "is useful for transcription type things such as translation. Does not have to be Monkey's". I wish I had a clue.
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 names ("Xhjkxc" has low fitness; "Artekzo" has high fitness) Trying out a series of chess moves Guessing the combination to a safe, assuming you can tell how close you are to unlocking each tumbler Picking phone numbers that evaluate to words (e.g. "843-2378" has high fitness because it spells "THE-BEST")
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> { public: void operator()(const std::string& str) const { std::cout << str << std::endl; } }; int main(int argc, char** argv){ MyFct f; foo(f); return 0; } I'm getting the following error in line 6: no match for call to `(const std::unary_function<const std::string&, void>) (const std::string&)'
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 behave polymorphic. What you want is function object wrapper. boost::function comes to mind: void foo(boost::function<void(const std::string&)> const& fct) { const std::string str = "test"; fct(str); // no error anymore } Or make it a template template<typename FunctionObject> void foo(FunctionObject const& fct) { const std::string str = "test"; fct(str); // no error anymore } You can take it by value and then return the copy from foo if use it to apply it to some sequence. Which would allow the function object to update some state variables among its members. for_each is an example that does it like that. Generally, anyway, i would accept them by value because they are usually small and copying them allows greater flexibility. So i do template<typename FunctionObject> void foo(FunctionObject fct) { const std::string str = "test"; fct(str); // no error anymore } You will then be able to take a copy of fct and save it somewhere, and fct's operator() can be non-const and update some members (which is part of the whole point of operator()). Remember if you take a function object by const reference, you can't generally copy it, because the user could have passed a function. Copying it then will try to locally declare a function instead of a local function pointer. However, accepting by-value will accept a function pointer instead when a function was passed, which can safely be copied.
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 (remoteControl.buttonPressed(PLAY_BUTTON)) { fooBar.doSomethingFun(); } Also, I was thinking there may be a generic library I can use, which would with all remotes, or would I have to do some really low level coding?
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, eg. Myth TV
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 instructions may be more helpful than the script, depending on how well the script fits your needs. If your program is free or open source software, then you may wish instead to create a MacPorts portfile (documentation here), and allow your users to build your program using MacPorts; that is generally the preferred way to install portable free or open source software on Mac OS X. MacPorts has been known to run on Linux in the past, so it may be possible to develop and test your Portfile on Linux (though it will obviously need to be tested on a Mac).
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/PNG... So, if you know of a way of not using a library then great, if not then answers are still welcome!
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.ijg.org
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 whenever I come across a similar sub-tree (2,7,(5,6,11)) it would serialize to the same value 'x' and hence I can deduce that I've found a match. Here we assume that each node has properties that are unique. In the above example, it would be the numbers assigned to each node and hence they would always generate the same ids for similar sub-trees. I'm trying to do this in C++. Do algorithms already exist to perform such serialized tree matching?
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 Java items may continue to exist if a collection itself is garbage collected.
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? EDIT: How about your experience? Is it easy to use? Was it painful or rather joyful? Do you like 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 quite badly documented - there are not enough examples, and the hyperlinking is poor. OTOH, the information is all there if you care to dig for it. use of app-specific binary formats directly will be faster than storing same format as a BLOB in a database database corruption can mean the los of all your data rather than that in a single bad file OTOH, if your internal data fits in well with the relational model and if there is a a lot of it, I'd recommend SQLite - I use it myself for one of my projects. Regarding experience - I use it, it works well and is easy to integrate with existing code. If the documentation were easier to navigate I'd give it 5 stars - as it is I'd give it four.
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>(), std::allocator<std::pair<float const, float> >()); But when I display information about my unordered_map at the end of program: g++: unordered_map.size(): 15861612 unordered_map.load_factor: 10.0845 unordered_map.bucket_count: 1572869 unordered_map.max_size: 1572868 unordered_map.max_load_factor: 1 unordered_map.max_bucket_count: 1572869 vc++: unordered_map.size(): 13916119 unordered_map.load_factor: 8.8476 unordered_map.bucket_count: 1572869 unordered_map.max_size: 1572868 unordered_map.max_load_factor: 1 unordered_map.max_bucket_count: 1572869 How do I specify the minimum number of buckets ?
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 it to be the most buckets the map can ever have. I've never used the class, and I can't see anything in the draft C++0x spec to explain why the constructor is silently creating an object which doesn't do what you told it to. I also don't know what the motivation might be behind the value 1572869, other than that it's a largeish prime.
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, for example: I have a struct: typedef struct Foos{ int a; int b; } Foos; And the following definition of a const struct of type Foos static const Foos foo = { .a = 1, .b = 2, }; GCCE has no problem with this one and ARMV5 goes "expected an expression" error on the ".a = 1, .b = 2,". From what I googled regarding this I reckon that this method should be legal in C but illegal in C++, if that's the case then what are the possibilities for declaring const structs in C++ ? If that's not the case then any other help will be appreciated. Thanks in advance :)
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 he could not be convinced that this open source toolchain is similarly powerful to his MSVC-environment. A VST-Plugin is a shared library for audio processing. We use the Tobybear Minihost as our testing application for it and it works just fine. However, we are not able to debug it. We can set breakpoints, but Eclipse does not recognize them when the Minihost opens the Plugin. Do you know how to debug a shared library using GDB/Eclipse on Windows?
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 could be popped of? And how do you recognise a situation you should use dynamic memory allocation?
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 lifetime. The memory allocated on the stack will only be around while that method is executing. Once the method is finished the memory will be automatically reclaimed.
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 = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lres == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); Put these wrapper functions at the top of your code: LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast<LPBYTE>(&nResult), &dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; }
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 abstract class". Class Definiton (AudioEndpointVolumeNotifierImpl.h): class AudioEndpointVolumeNotifierImpl : public IAudioSessionEvents { private: LONG _cRef; public: AudioEndpointVolumeNotifierImpl() : _cRef(1){} ~AudioEndpointVolumeNotifierImpl(){} HRESULT STDMETHODCALLTYPE OnSimpleVolumeChanged(float NewVolume, BOOL NewMute,LPCGUID EventContext); HRESULT STDMETHODCALLTYPE OnChannelVolumeChanged(DWORD ChannelCount, float NewChannelVolumeArray[], DWORD ChangedChannel, LPCGUID EventContext){return S_OK;} HRESULT STDMETHODCALLTYPE OnDisplayNameChanged(LPCWSTR NewDisplayName, LPCGUID EventContext){return S_OK;} HRESULT STDMETHODCALLTYPE OnGroupingParamChanged(LPCGUID NewGroupingParam, LPCGUID EventContext){return S_OK;} HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPWCHAR NewIconPath, LPCGUID EventContext){return S_OK;} HRESULT STDMETHODCALLTYPE OnSessionDisconnected(AudioSessionDisconnectReason DisconnectReason){return S_OK;} HRESULT STDMETHODCALLTYPE OnStateChanged(AudioSessionState NewState){ return S_OK; } ULONG STDMETHODCALLTYPE AddRef() { return InterlockedIncrement(&_cRef); } ULONG STDMETHODCALLTYPE Release() { ULONG ulRef = InterlockedDecrement(&_cRef); if (0 == ulRef) { delete this; } return ulRef; } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, VOID **ppvInterface) { if (IID_IUnknown == riid) { AddRef(); *ppvInterface = (IUnknown*)this; } else if (__uuidof(IAudioSessionEvents) == riid) { AddRef(); *ppvInterface = (IAudioSessionEvents*)this; } else { *ppvInterface = NULL; return E_NOINTERFACE; } return S_OK; } }; Corresponding .cpp: HRESULT STDMETHODCALLTYPE AudioEndpointVolumeNotifierImpl::OnSimpleVolumeChanged(float NewVolume, BOOL NewMute, LPCGUID EventContext) { PostStatusChange(NewVolume); return S_OK; } Fails in an IClassFactory instance on the following code: ... AudioEndpointVolumeNotifierImpl* pObject = new AudioEndpointVolumeNotifierImpl(); if (pObject == NULL) { return E_OUTOFMEMORY ; } ... A good portion of this code IS lifted from some tutorials (the IUnknown stuff in particular). I'm not expecting this code to work just yet, but I can't see why it doesn't compile. Thanks.
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, and that the method actually takes an LPCWSTR (which makes more sense given the context anyway), that would explain your error. I would try changing your declaration to HRESULT STDMETHODCALLTYPE OnIconPathChanged(LPCWSTR NewIconPath, LPCGUID EventContext){return S_OK;}
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 idioms as they have already done in the std::vector, albeit with more book-keeping the list class. On a related note, why not have the capacity function in list? You can argue that such a function would pay memory allocation cost up-front and eliminate the overhead later on as you push_back objects. At least it will make the interfaces of two STL sequence containers slightly more consistent.
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 a thing; there's no particular requirement to make all functions consistent across all STL containers, especially when they make little sense for others. You can accomplish the same effect using a custom allocator. As Manuel suggested, look at boost.
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 as the C++ code does. So far: --->C++ DLL source<--- Note the exported functions are in the end of the code C# code(definition) [DllImport("TestDLL.dll", EntryPoint = "Initkey" ,ExactSpelling = true , CallingConvention = CallingConvention.Cdecl)] public static unsafe extern void Initkey(byte[] key); [DllImport("TestDLL.dll", EntryPoint = "encode", ExactSpelling = true, CallingConvention = CallingConvention.Cdecl)] public static unsafe extern void encode(UInt32 *stream); C# code(function calling) -Initialize blowfish key UInt32[] keyarray = new UInt32[2]; //some code Extern.Initkey(Misc.ConvertFromUInt32Array(keyarray)); // // //Helper function used to convert a UInt32 array into Byte array. public static byte[] ConvertFromUInt32Array(UInt32[] array) { List<byte> results = new List<byte>(); foreach (UInt32 value in array) { byte[] converted = BitConverter.GetBytes(value); results.AddRange(converted); } return results.ToArray(); } -Encode the data. UInt32[] keyarray2 = new UInt32[2]; //some code unsafe { fixed (UInt32* LPBYTE = keyarray2) { Extern.encode(LPBYTE); } } After keyarray2 is overwritten by the Encode function, I check the values in the C++ code by decrypting them to make sure everything is alright. Well, It's not alright.That's my problem, That's why I am asking you for your help. The values are different when I decrypt them,but If I encrypt them and decrypt them in the C++ source, they are equal.The C++ code is absolutely the same,except that there's no DLL since the code is in C++. Could that be, because of the Initialize function.I had read a couple of months ago that arrays in C++ are passed as Pointers.I don't believe it,but even so - could that be the problem? I can't find a clue. I have wasted my life with that blowfish in C#. At least that solution should work, but it doesn't - Why?
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 gives me the following g++ error: /usr/include/c++/4.3/bits/stl_map.h:419: error: no matching function for call to ‘MyClass()’ This compiles fine if I add a default constructor; I am certain it's not caused by incorrect syntax.
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 default constructor you can use insert/find functions. Following example works fine: myMap.insert( std::map< int, MyClass >::value_type ( 1, MyClass(1) ) ); myMap.find( 1 )->second;
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 issues could I be looking at if I ran this code? I'd do this investigating myself however I'm away from my dev machine for a week. EDIT: Hold on a second, I've been thinking a bit more. As has been observed in the comments, the intent of this code was to have a parameter left on the stack when all is said and done (caller puts two params on the stack, callee -- expecting only one param -- pops only one off). However, since my cast doesn't make mention of the calling convention, am I casting away stdcall, at least from the view of the caller? int function(int) will still pop a param off the stack, but does the caller revert to thinking the function is __cdecl (the default) because of the cast? (i.e. three total params popped?) EDIT2: The answer to that second question, as confirmed by Rob, is yes. I would have to restate __stdcall if I wanted to leave a param on the stack: (*(__stdcall int(*)(char*,char*))function)("thought", "experiment");
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 then pop off two pointers (having previously pushed on two pointers), so your stack is being corrupted by 4 bytes. Both calling conventions use the same return mechanism, and have the same register rules (eax, ecx and edx are not preserved). See wikipedia for more details. Depending on the stack frame layout and alignment this mismatch could cause a number of effects. If you are lucky then you get away with it. If not you might mess up the return address of your main function, causing the program to crash when it branches to who-knows-where. If the compiler has injected some kind of stack guard to catch corruption then it will likely detect this and abort the program.
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 VS2008
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 returns 0. Remarks The _kbhit function checks the console for a recent keystroke. If the function returns a nonzero value, a keystroke is waiting in the buffer. The program can then call _getch or _getche to get the keystroke.
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 default behavior.
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 loads it is: //only gets called on vista bool LoadQueryFullProcessImageName() { HMODULE hDLL = LoadLibrary("kernel32.dll"); if (!hDLL) return(0); //Now use pointer to get access to functions defined in DLL fpQueryFullProcessImageName = (LPQueryFullProcessImageName)GetProcAddress(hDLL, "QueryFullProcessImageNameA"); //ANSI version if (!fpQueryFullProcessImageName) return false; return true; } the typedef is typedef WINBASEAPI BOOL (*LPQueryFullProcessImageName)( __in HANDLE hProcess, __in DWORD dwFlags, __out_ecount_part(*lpdwSize, *lpdwSize) LPSTR lpExeName, __inout PDWORD lpdwSize ); Unfortunately, I get a run time error on Vista when the function pointer is dereferenced: Run-Time Check Failure #0 - The value of ESP was not properly saved across a function call. This is usually a result of calling a function declared with one calling convention with a function pointer declared with a different calling convention. The typedef is straight from the .h file so I can't understand why it's messing up. Any help? I've tried tons of variants but no luck.
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 dependency is of no interest to you, but you still need __stdcall for proper call invokation.
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> res) { CSingleLock lock(m_pMutex); lock.Lock(); m_Res = res; lock.Unlock(); } shared_ptr<CResource> GetResource() { CSingleLock lock(m_pMutex); lock.Lock(); shared_ptr<CResource> res = m_Res; lock.Unlock(); return res ; } private: shared_ptr<CResource> m_Res; } CResourceBase base; //---------------------------------------------- Thread A: while (true) { ...... shared_ptr<CResource> nowResource = base.GetResource(); nowResource.doSomeThing(); ... } Thread B: shared_ptr<CResource> nowResource; base.SetResource(nowResource); ...
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: shared_ptr<CResource> nowResource; base.SetResource(nowResource); ... thread B still has access to the nowResource. If thread A gets the resource ptr, both thread can use object at the same time without any synchronization! This would be of course race condition.
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 from.
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 for string and so on) I try to push it all into one vector. I tried std::vector<Argument* > vec; std::vector<Argument<typename T>* > vec; std::vector<Argument<>* > vec; but nothing of this seems to work. Is there a way to do this? Thanks in advance.
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 removed from the vector. Option 2 (my personal favorite) : use Boost.Variant to make a typedef of all possible argument types and use that typedef as the argument type in std::vector typedef boost::variant<ArgumentType1, ArgumentType2, ArgumentType3> ArgumentType; std::vector<ArgumentType> vec;
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 run cscript adplus.vbs -crash However, it appears that you can't use adplus for apps that crash on startup (http://support.microsoft.com/kb/q286350/ says that "Do not use ADPlus in the following situations: If you must troubleshoot a program or process that quits unexpectedly during startup"). The same article says "use User Mode Process Dump", but I failed to install it successfully. Any idea of how to get a dump of a process that crashes on startup on Win32?
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 file that you can debug.
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() { std::cout << "TestA: " << Foo().Bar() << std::endl; } module_b.cpp: #include <iostream> struct Foo { const char * Bar() { return "MODULE_B"; } }; void TestB() { std::cout << "TestB: " << Foo().Bar() << std::endl; } main.cpp: void TestA(); void TestB(); int main() { TestA(); TestB(); } And the output is: TestA: MODULE_A TestB: MODULE_A
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 a header does. The violation comes because your definitions are different ( the other one contains the string "MODULE_A") but there is no way for the linker (which just looks at class/function names) to detect this.
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 without validation there are chances of Access Violation. This triggered me to look into exception handling in constructor's initializers list. I found in one of the article that try can be used inside initializer list. I wrote small test program to test this concept: //Test class stores the unique ID and returns the same with API getTestID class Test { public: Test(int nID):m_nID(nID){ } int getTestID() const { return m_nID; } private: int m_nID; }; class Test2 { public: Test2(Test* pTest) try :m_pTest(pTest), m_nDuplicateID(pTest->getTestID()) { } catch (...) { cout<<"exception cought "<< endl; } void printDupID() { cout<<"Duplicate ID" << m_nDuplicateID << endl; } private: Test* m_pTest; int m_nDuplicateID; }; int main(int argc, char* argv[]) { Test* pTest = new Test(10); Test2 aTest2(pTest); aTest2.printDupID(); delete pTest; return 0; } This code is not getting compiled in VC6.0. Do I need to make any changes to make it compile in VC 6.0? Also, in one of the article I found that using try in constructor's initializer list does not strictly confirms to C++ standards. In that case, how do we handle the exceptions in constructor's initializers list (standard way of handling )? Thanks.
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 time - take a look at this http://www.gotw.ca/gotw/066.htm and other articles on Herb Sutter's GotW site.
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 my application I have an image buffer (1 MB large) which I want to send to another process. So now I inquire a pointer to the image and then copy the whole image buffer into the mapfile. But I wonder if this is really necessary. Isn't it possible to just copy an actual pointer in the shared memory which points to the image buffer data? I tried a bit but didn't succeed.
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++ 4.3.2, Blitz 0.9). Here's the code: #include <blitz/blitz.h> #include <blitz/array.h> #include <blitz/matrix.h> #include <blitz/matexpr.h> #include <blitz/tinymat.h> #include <blitz/tinymatexpr.h> #include <blitz/tinyvec.h> #include <blitz/tinyvec-et.h> #include <blitz/vector.h> #include <blitz/vector-et.h> typedef blitz::TinyVector<double,3> v3; typedef blitz::TinyMatrix<double,3,3> m33; int main(int,char**) { const m33 a; const m33 b; m33 c;c=blitz::product(a,b); // Compiles OK //const m33 d=blitz::product(a,b); // Fails to compile. return 0; } I do like to be const-ed to the hilt, so it'd be nice to know if there's a way of getting it to work (experience with Blitz++ so far suggests it might just be a matter of picking the right includes...).
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-const matrix that you would pass as a const reference as the parameter of a function. Now, just for fun, the truth is you could copy template operator=() code and make a new template constructor inside blitz/tinymat.h out of it, but i wouldn't ! If you really want to, here's how : // Turn the following code... template<typename T_expr> TinyMatrix<T_numtype, N_rows, N_columns>& operator=(_bz_tinyMatExpr<T_expr> expr) { // USEFUL CODE return *this; } // ...into this : template<typename T_expr> TinyMatrix(_bz_tinyMatExpr<T_expr> expr) { // USEFUL CODE } and your code compiles (and probably works).
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 called twice. #include <iostream> class MyClass { public: ~MyClass() { std::cout << "destructor of MyClass" << std::endl; } }; MyClass getMyClass() { MyClass obj = MyClass(); return obj; // dtor call for obj here? } int main() { MyClass myobj = getMyClass(); return 0; // Another dtor call for myobj. } But "destructor of MyClass" is getting printed only once. Is my assumption wrong or is there something else going on here?
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 copying it back. Modern compilers do this routinely whenever possible (there are some situations where this isn't easy since there are several return paths in the function that return different instances).
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 how to do this wiould be greatly appreciated. Pretty rubbish at c++ and I cant debug easily as its in a dll. Much appreciated Tony
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 issue at all. Using LGPL, you have many other options, including GTK, QT (as of 4.5), FLTK, etc. Of these, QT is probably my personal favorite.
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) Each word will be a key with it's following word as it's value. so "over" => "the". Some keys can have multiple values. For example, "the" => "dog" || "wall" || "cat" || "house". The value is randomly chosen from those for that key. When the program runs it picks a word at random and makes a sentence. So it could be something like: "the cat fell off the dog". I tried implementing a map (map myMap;) but this allows only one value per key (I think). Hope I explained this right.
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. to get around that you could also store a vector in a regular map and add your strings to the vector.
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 I'm new to C++ , as is the other developer, I wonder if it might not make sense go ahead and specify to this level. Thoughts? edit: Wow - completely against, unanimous. I was thinking about, for example, the whole business about specifying const vs. non-const, passing references, handling default constructor and assigns, and so forth. I do believe it's been quite helpful to spec this out to this level of detail so far. I definitely have gotten a clearer idea of how the system will work. Maybe if I just do a few methods, as an example, before diving into the code?
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 with the location to my COM DLL. I also have some other code in a seperate COM DLL that I support that uses the older, now deprecated CComModule.RegisterServer(TRUE) call. This code creates a win64 subkey under the 0 key for a 64-bit DLL and a win32 subkey under the 0 key for a 32-bit DLL. I am using the correct bit version of regsvr32 to do the registration in all cases (matching the regsvr32 bitness to DLL bitness). Why does LoadTypeLibEx and _AtlComModule.RegisterServer both not create the win64 key for a 64-bit dll containing my TypeLib while the older CComModule.RegisterServer creates the correct keys?
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 they are not compatible. Thus, it would seem that the behavior I'm seeing isn't really because of the registration methods I'm using, but because of the underlying type libraries.
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 the element nearest to 1.6, instead of -1 (or some other flag value) indicating that the value 1.6 wasn't found.
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 days HeapWalker was very helpful and you could even select a BITMAP handle and view it's graphic contents. I'm trying to remember how to read a .MAP file and add up the various sections but there is very little documentation and I'm not sure how accurate this technique is. Anybody have any advice?
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 windbg from Microsoft. As long as you build your files with a pdb, it will will be able to resolve symbols in your application. You can then take a few snap shots of the memory to look for leaks. You can also do a complete dump of all allocations to see where memory is being allocated and how much is being allocated.
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) { //populate bitMap from a string buffer }
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); } If you want the raw data, use the iterator constructor: void populateBitSet (std::string &buffer, boost::dynamic_bitset<unsigned char> & bitMap) { bitMap = boost::dynamic_bitset<unsigned char> (buffer.begin(), buffer.end()); } These do end up allocating the needed memory twice, so you might be better off with a stack allocation and a swap. Or you just can wait until C++0x and let the move semantics do their thing. // Unecessary in C++0x void populateBitSet (std::string &buffer, boost::dynamic_bitset<unsigned char> & bitMap) { boost::dynamic_bitset<unsigned char> localBitmap(buffer.begin(), buffer.end()); bitMap.swap(localBitmap); } Edit: To clarify why the first versions allocate twice as much memory: Take a look at another way to write the first version: typedef boost::dynamic_bitset<unsigned char> bits; // just to shorten the examples. void populateBitSet (std::string &buffer, bits &bitMap) { const bits &temp = bits(buffer); // 1. initialize temporary bitMap = temp; // 2. Copy over data from temp to bitMap } If you put these two lines together, as in the first example, you still get a temporary constructed on the stack, followed by an assignment. In 1. boost needs to allocate enough memory for the entire set of bits. In 2, boost needs to allocate again enough memory to hold that same set of bit and then copy the values over. It's possible that bitMap already has enough memory, so it may not always need to reallocate, but it's also possible that it will free its backing memory and reallocate from scratch anyway. Most containers that fit the stl mold also have a swap function that you can use in place of assignment when you intend to throw away one side of the swap. These are usually O(1) and non-throwing as they often just involve swapping some pointers. See this GotW for another reason why these are useful. In C++0X, you'll be able to use assignment, and still get the advantages of swap. Since you can overload on r-values (like the temporary), the container know that when you assign a temporary, it knows that it can cannibalize the temp and basically do a swap. The Visual Studio Team Blog has covered rvalues and move semantics quite well here.
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 calculation directly affects how much the CPU is in use.
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 it doenst paint my stuff. Also tried this: #define MyDefinedMsg (WM_APP+1) //...// case WM_CREATE: //...// SetWindowLongPtr(hWnd,GWLP_USERDATA,ptr); PostMessage(hWnd,MyDefinedMsg,0,0); break; case MyDefinedMsg: InvalidateRect(hWnd,NULL,TRUE); break; but did not work. Thanks in advance
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 correctly interpreting the string literals that I feed it. Here's my code: 130 insertexpr : "INSERT" expr '(' expr ')' 131 132 { 133 $$ = new QLInsert( $2, $4 ); 134 } 135 ; And my input, following the "Query: " prompt: Query: INSERT abc(5); input:1.0-5: syntax error, unexpected string, expecting end of file or end of line or INSERT or ';' Now, if I remove the "INSERT" string literal from my parser.yy code on line 130, the program runs just fine. In fact, after storing the input data (namely, "abc" and the integer 5), it's returned right back to me correctly. At first, I thought this was an issue with character encodings. Bison code needs to be compiled and run using the same encodings, which should not be an issue seeing as I am compiling and running from the same terminal. My system details: Ubuntu 8.10 (Linux 2.6.24-16-generic) flex 2.5.34 bison 2.3 gcc 4.2.4 If you need any more info or code from, let me know!
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&, const T& > in constructor. Ofcourse I'm understend that when STL was designed boost does not exists, but designers could be create something similar on boost::function. I belive it has some deep reasons. EDITED Sorry for dummy question, map have same posibility :) My question doesn't have sense after your answers.
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 compiler values a multi-character character constant a character at a time, shifting the previous value left by the number of bits per target character, and then or-ing in the bit-pattern of the new character truncated to the width of a target character. The final bit-pattern is given type int, and is therefore signed, regardless of whether single characters are signed or not (a slight change from versions 3.1 and earlier of GCC). If there are more characters in the constant than would fit in the target int the compiler issues a warning, and the excess leading characters are ignored. For example, 'ab' for a target with an 8-bit char would be interpreted as (int) ((unsigned char) 'a' * 256 + (unsigned char) 'b')', and '\234a' as (int) ((unsigned char) '\234' * 256 + (unsigned char) 'a')'.
"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-character character constant or warning: character constant too long for its type are generated in this case."
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 20 digits for a unsigned long long. Does anyone have a better solution?
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 idea?
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", how many of them are there?
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; i++) { std::clock_t startTime = std::clock(); // a very fast function in the middle cout << "Time: " << setprecision(9) << (clock() - startTime + 0.00)/CLOCKS_PER_SEC << endl; } return 0; } Related Questions: How to overcome clock()'s low resolution High Resolution Timer with C++ and linux Equivalent of Windows’ QueryPerformanceCounter on OSX
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 operations double diffclock(clock_t clock1, clock_t clock2) { double diffticks = clock1 - clock2; double diffms = (diffticks) / (CLOCKS_PER_SEC / NUMBER); return diffms; } int main() { // start a timer here clock_t begin = clock(); // execute your functions several times (at least 10'000) for (int i = 0; i < NUMBER; i++) { // a very fast function in the middle func() } // stop timer here clock_t end = clock(); // display results here cout << "Execution time: " << diffclock(end, begin) << " ms." << endl; return 0; } Note: std::clock() lacks sufficient precision for profiling. Reference.
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 - - 1126 - 00:00:00 - - 1128 - 00:00:00 - - 1129 - 00:00:09 - - 1130 - 00:00:00 - - 1131 - 00:00:09 - 1122 - pts/1 00:00:00 snstatusdemuxd - 1122 - 00:00:00 - - 1127 - 00:00:00 - - 1132 - 00:00:00 - - 1133 - 00:00:00 - And then in the filesystem I can see the threads: root@10.67.100.2:~# ls /proc/1120/task/ 1120 1125 1126 1128 1129 1130 1131 So is there some way I can get the SPID from my application so I can somehow identify what my SPID is in each running thread? Thanks! /Mike Edit: I should add that the PID returned from getpid() is the same in each thread. When I add this code to my threads: // Log thread information to syslog syslog(LOG_NOTICE, "ibnhwsuperv: gettid()= %ld, pthread_self()=%ld", (long int)syscall(224), pthread_self()); I get this result: Jan 1 01:24:13 10 ibnhwsupervd[1303]: ibnhwsuperv: gettid()= -1, pthread_self()=839027488 Neither of which look like the SPID given by ps or in the proc filesystem. Also, note that gettid does not return the SPID.
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. Does it apply to my situation here?
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 auto_ptr will be used. This has the weird behaviour of tranferring ownership of the thing being copied to the copy and, so the thing being copied's pointer is now null. It is possible, though unlikely, that you actually want this behaviour, in which case an auto_ptr is safe. Assuming you do not, you should either: add a copy constructor to manage the copying Note this is not enough - see the follow-up question mentioned above for more info. or: use a smarter, possibly reference counted pointer, such as one of the boost smart pointers
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 is not what I want. Any ideas, or do I have to code it separately for each platform? €: I want to create a sub directory, and store files into it. (You may punish me if this is a bad idea)
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 problem I encountered was that it becomes hard to maintain after a while. What I meant by utilizing sqlite is that I will map my entire in-memory data structure into a sqlite database, and let the sqlite do the diff and revision for me. Speed should not be a issue if I create a in-memory database. That was the idea and I was wondering if that could work.
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 access to an object's private members, it can get them, no matter what you try to do to prevent it.
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 how to use REST channels. Which library should I use to do so?
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 library and link it to your app with GCJ. The best reference is the GCJ Documentation. There is also a Linux Journal contains the article Embedded Java with GCJ that you can read. You can also study applications that use gcj.
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: is it safe to call methods of temporary variables? is it standard compliant?
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_ptr<node> parent) { parent_ = parent; } void add_child(shared_ptr<node> child) { children_.push_back(child); child->set_parent(shared_from_this()); } void frob() { do_frob(); if (parent_) parent_->frob(); } private : void do_frob(); shared_ptr<node> parent_; vector< shared_ptr<node> > children_; }; In this example, you have a tree of nodes, each of which holds a pointer to its parent. The frob() member function, for whatever reason, ripples upwards through the tree. (This is not entirely outlandish; some GUI frameworks work this way). The problem is that, if you lose reference to the topmost node, then the topmost node still holds strong references to its children, and all its children also hold a strong reference to their parents. This means that there are circular references keeping all the instances from cleaning themselves up, while there is no way of actually reaching the tree from the code, this memory leaks. class node : public enable_shared_from_this<node> { public : void set_parent(shared_ptr<node> parent) { parent_ = parent; } void add_child(shared_ptr<node> child) { children_.push_back(child); child->set_parent(shared_from_this()); } void frob() { do_frob(); shared_ptr<node> parent = parent_.lock(); // Note: parent_.lock() if (parent) parent->frob(); } private : void do_frob(); weak_ptr<node> parent_; // Note: now a weak_ptr<> vector< shared_ptr<node> > children_; }; Here, the parent node has been replaced by a weak pointer. It no longer has a say in the lifetime of the node to which it refers. Thus, if the topmost node goes out of scope as in the previous example, then while it holds strong references to its children, its children don't hold strong references to their parents. Thus there are no strong references to the object, and it cleans itself up. In turn, this causes the children to lose their one strong reference, which causes them to clean up, and so on. In short, this wont leak. And just by strategically replacing a shared_ptr<> with a weak_ptr<>. Note: The above applies equally to std::shared_ptr<> and std::weak_ptr<> as it does to boost::shared_ptr<> and boost::weak_ptr<>.
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+(const Test& rhs){ return Test(i + rhs.i); } void non_const_function(){ i *= i; } }; int main(){ //code below gives errors, builtin types don't allow evil code //int i = 5+5 = 8; //int& iRef = 5+5; //int* iPtr = &(5+5); //5 = 10; Test x = Test(5) + Test(5) = 8;//assign to a temporary Test& xRef = Test(5) + Test(5);//reference to a temporary Test* xPtr = &(Test(5) + Test(5));//address of a temporary Test(5) = Test(10);//assign to a temporary Test(8).non_const_function();//call a non-const function return 0; } xRef and xPtr are both working pointers, with the expected values. Of course I wouldn't write such code in a real project, but I'm still interested how / why this works. The only info I found on google about this was that "if you create a reference to a temporary, the temporaries lifetime is linked to the lifetime of the reference" Note : -not all compilers are that forgiving, e.g. Metrowerks ARM (does it use GCC ?) only allows const reference to temporaries. EDIT : -increasing the warning to W4 in VC++ 2008 showed lots of errors - good to know. EDIT 2: Thank you all for the help. I'm back to work, fixing 100's of warnings. CONCLUSION : use highest warning from start (I even found a REAL bug thanks to /G4)
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 GCC doesn't allow a non-const reference to a temporary. Test* xPtr = &(Test(5) + Test(5));//address of a temporary In addition, GCC warns about taking the address of a temporary, for obvious reasons. Test(5) = Test(10);//assign to a temporary Again, this is just assignment, which, as I explained above, is no big deal. Test(8).non_const_function();//call a non-const function Temporary objects aren't constant. There's nothing stopping them from calling non-const functions.
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 this name is not best one for this function.
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 considered best practice?
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); int getX() const; int operator + (const B& b); }; class B { private: int x; public: B(int x); int getX() const; int operator + (const A& A); }; A::A(int x) : x(x) {} int A::getX() const { return x; } // Method 1 int A::operator + (const B& b) { return getX() + b.getX(); } B::B(int x) : x(x) {} int B::getX() const { return x; } // Method 1 int B::operator + (const A& a) { return getX() + a.getX(); } // Method 2 int operator + (const A& a, const B& b) { return a.getX() + b.getX(); } int operator + (const B& b, const A& a) { return a.getX() + b.getX(); } #include <iostream> using namespace std; int main() { A a(2); B b(2); cout << a + b << endl; return 0; }; If I would like to have symmetry among the two types, which method is the best approach in the above code. Are there any possible dangers in choosing one method over the other? Does this vary with the return type? Please explain! Thank you!
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 { // ... }; class FailsToDerive : public Sealed { // Cannot be instantiated }; I found this example on this site somewhere but I can't find it... (here) I know there are other ways of doing this but just now I'm curious if you actually can do something like this.
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 elaborated-type-specifier introduces it into the declaration the same way a simple-type-specifier introduces its type-name. If the identifier resolves to a typedef-name or a template type-parameter, the elaborated-type-specifier is ill-formed. [Note: this implies that, within a class template with a template type-parameter T, the declaration friend class T; is ill-formed. ] I recognize the code above as a pattern to seal (disallow the extension of) a class. There is another solution, that does not really block the extension but that will flag unadvertidly extending from the class. As seen in ADOBE Source Library: namespace adobe { namespace implementation { template <class T> class final { protected: final() {} }; }} #define ADOBE_FINAL( X ) private virtual adobe::implementation::final<T> with the usage: class Sealed : ADOBE_FINAL( Sealed ) {//... }; While it allows extension if you really force it: class SealBreaker : public Sealed, ADOBE_FINAL( Sealed ) { public: SealBreaker() : adobe::implementation::final<Sealed>(), Sealed() {} }; It will restrict users from mistakenly do it. EDIT: The upcoming C++11 standard does allow you to befriend a type argument with a slightly different syntax: template <typename T> class A { // friend class T; // still incorrect: elaborate type specifier friend T; // correct: simple specifier, note lack of "class" };
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) and you can provide a const version of operator[] too. If you're concerned about padding (and don't want to add the appropriate platform specific bits to force the struct to be unpadded) then you can use: struct Vec2 { float x; float y; float& operator[](int i) { assert(i>=0); assert(i<2); return (i==0)?x:y; } const float& operator[](int i) const { assert(i>=0); assert(i<2); return (i==0)?x:y; } };
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 any packet information like it did under the release build. I've tried to mirror the build configurations to match exactly but its still happening. Any suggestions would be greatly appreciated.
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 issues. This has bit me more than once.. :) This is assuming you are not expecting to see anything using stuff like OutputDebugString() as Mehrdad suggested... Also, make sure your packets are UNDER 1024 bytes in size, or you will NOT get them. Took me a while to figure this one out back when XP came out, and I couldn't figure out why my code worked on 2000, but not XP... Even though send (sendto) would return success, it never actually SENT the packet.. Anyways, I've dealt with UDP a lot on Win32, so if you give me some example code I should be able to help more... But anyways, check that ALL your variables are initialized to some sort of default value on both the sender and the receiver, (which is just good practice), and then re-build it and try again. Also, check your packet size with a sizeof() before it sends, and if it's greater than 1024 bytes, don't bother... It's also a good idea to check size of the received packet, and if it's not exactly the size you expect, then drop the packet. This holds MORE true for broadcasts, but still applies. Let me know if any of this helped, I posted a LOT of UDP code on another question here a little while back, and that code works, you might want to refer to it.
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){ optional = new std::vector<int>(); // fill vector with data } // process vector } Or have two functions with an overloaded name, one of which leaves out the argument: void foo(int i) { std::vector<int> vec; // fill vec with data foo(i, vec); } void foo(int i, const std::vector<int>& optional) { // process vector } Are there reasons to prefer one solution over the other? I slightly prefer the second one because I can make the vector a const reference, since it is, when provided, only read, not written. Also, the interface looks cleaner (isn't NULL just a hack?). And the performance difference resulting from the indirect function call is probably optimized away. Yet, I often see the first solution in code. Are there compelling reasons to prefer it, apart from programmer laziness?
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. With the second approach (overloaded methods), each method has a clear purpose. Each method is well-structured and cohesive. Some additional notes: If there's code which needs to be duplicated into both methods, this can be extracted out into a separate method and each overloaded method could call this external method. I would go a step further and name each method differently to indicate the differences between the methods. This will make the code more self-documenting.
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. It just uses the iterators you provide to move elements around. The faster those iterators work in terms of accessing and assigning an element, the faster the std::sort would work.
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 are indeed passing an array pointer, int main() { int* arr = new int[5]; deleteForMe(arr); return 0; } My question is, in this case where the pointer is an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not arr is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether arr was dynamically created. Yet, if I do the following instead, int main() { int* num = new int(1); deleteForMe(num); return 0; } The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with strlen and a non-\0-terminated string -- it will keep going until it hits 0). So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world someone is remembering.)
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. It may do this by over-allocating enough to store the array size. For more details, see the C++ Super FAQ.
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 manifest to resources... Microsoft (R) Windows (R) Resource Compiler Version 6.1.6723.1 Copyright (C) Microsoft Corporation. All rights reserved. Linking... LINK : fatal error LNK1104: cannot open file 'libboost_system-vc90-mt-gd-1_38.lib' // GoogleAuthenticate.h #pragma once #include <boost/asio.hpp> class GoogleAuthenticate { public: GoogleAuthenticate(void); virtual ~GoogleAuthenticate(void); }; // GoogleAuthenticate.cpp #include "StdAfx.h" #include "GoogleAuthenticate.h" GoogleAuthenticate::GoogleAuthenticate(void) { } GoogleAuthenticate::~GoogleAuthenticate(void) { } // websave.cpp #include "stdafx.h" #include <iostream> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { cout << "hello" << endl; return 0; } I checked the boost/boost-1.38/lib folder and the libboost_system-vc90-mt-gd-1_38.lib is present there. Also added the path in "Additional Include Directories" in Configuration Properties of the project. Is there anything that is being missed here ?
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 Encrypt function with same parameters. C++ Blowfish.Encrypt((LPBYTE)responce + 2,(LPBYTE)responce + 2, 4); C# Blowfish.Encrypt(responce, 2, responce, 2, responce.Length - 2); However,In C++ I get the data encrypted,but not in C#. Line 45,47 and 49 in C# NET Blowfish are the problematic lines,after the calculation at line 45 - the result becomes 0. line 47 becomes 2 + 0 = 2 and line 49 2 is not less than 2,so there's no loop. There's some padding in C++ blowfish,but I get lost when I try to understand it. My problem is that in C#, the padding must be exactly the same as in C++,so I get a valid answer.I can't use random padding and then remove the useless bytes after decryption,because the server I send the encrypted array is not mine. Could you point me to what padding is used in the C++ blowfish and how it should be implemented in C# NET. //Note I need not send this packet multiple times,only one time. Thanks in advance!
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 to spec, if it ignores your undersized data. The C++ code seems to be padding with null bytes, the comment says: // pad end of data with null bytes to complete encryption It would be helpful to see the C++ function GetOutputLength(), to see how it handles undersized inputs. I guess it rounds upwards, but it would be nice to verify.
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 additional instruction could slow down the delete performance. Could it be because of const pointers. Then again standard could have done something for this special case I guess. Does anyone know exact reasons for not allowing this?
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 be an lvalue.
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 similar, but not quite the same) Edit: ICU seems to be the right answer, but it's a bit overkill for my needs. I ended up doing string-replace for the known few extended chars that were used.
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 array ), then get the reversed order of the phrase that the user entered. Here is my code: #include "stdafx.h" #include <iostream> #include <String> #include <cstring> using namespace std; using namespace System; #pragma hdrstop char* getCharArray(string); string reversePhrase( int, char* ); void main(void) { string sPhrase = ""; int sSize = 0; string sReversed = ""; char* cPhrase = NULL; cout << "Welcome to the You Type It & We'll Reverse it! [Version 1.0] " << endl; cout << "This program will reverse your phrase, and count how many characters are in it!" << endl; cout << "To begin just enter a phrase." << endl; cout << "Enter a phrase: "; getline( cin, sPhrase); sSize = sPhrase.length(); cout << endl; cPhrase = getCharArray(sPhrase); sReversed = reversePhrase( sSize, cPhrase ); cout << sReversed; system("pause"); } string reversePhrase(int size , char* cPhrase) { string sReversed = ""; int place = size; for ( int i = 0; i < size ; i ++ ) { sReversed.append(1, cPhrase[place]); cout << "Current string: " << sReversed << endl; cout << "Current character: " << cPhrase[place] << endl; place--; } return sReversed; } char* getCharArray(string sPhrase) { int size = 1; size = sPhrase.length(); char* cArray = NULL; cArray = new char[size]; for (int i = 0 ; i < size ; i++) { cArray[size] = sPhrase.at(i); } return cArray; } When I type in "ownage" into the program, this is what I get returned: It is almost like my Character Array is getting garbage collected before it can use all of the characters. This is probably an easy fix but, I just don't see how I can get around this one.
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 } } cArray[size]=0; // NOTE return cArray; } Note that the assignment in the loop now uses the index variable. Also, you need to allocate one extra char in the array to set the null terminator for the string and then you need to set it at the end. You'll also need to think about deallocating the array at some point
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" as a macro parameter, since it is a "reserved command". Two questions about that: How is this possible? I cannot imagine that there is such a mistake in the linux header files... Did I do something wrong before? I tried an #undef and but this won't help. How do I fix this error? It cannot be true that I have to change the linux header files, can it? Thanks for help.
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 (for instance a macro to find out the name of the current function). Assuming the macros in question are really fake inlined functions, it would be possible to write your own .c file full of nothing but functions calling these macros, compile it, and refer to those functions via an extern "C" header. You would get the same behavior, but slightly worse performance (which is unlikely to be a problem). If the macros actually have to be macros, then your best bet is to hand edit them to be C++ compliant.
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, so this question is an attempt to clear the issue up. Consider the following code: #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 defined by intent auto_ptr <Z> p; }; int main() { vector <A> av; Z z; A a(z); av.push_back( a ); av.push_back( A(z) ); av.clear(); } Please examine the above & in your reply indicate where undefined behaviour in the meaning of the C++ Standard could occur for this particular class used in this particular way. I am not interested whether the class is useful, well-behaved, sortable, or how it performs under exceptions. Please also note that this is not a question about the validity of creating a vector of auto_ptrs - I am well aware of the issues regarding that. Thanks all for your inputs on what in retrospect is probably a rather silly question. I guess I focussed too much on the copy ctor & forgot about assignment. The lucky winner of my acceptance points (and points mean prizes!) is litb for a typically exhaustive explanation (sorry earwicker)
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 defined by intent auto_ptr <Z> p; }; int main() { vector <A> av; ... } I will examine the lines up to the one where you instantiate the vector with your type A. The Standard has to say In 23.1/3: The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types. In 23.1/4 (emphasis mine): In Table 64, T is the type used to instantiate the container, t is a value of T, and u is a value of (possibly const) T. +-----------+---------------+---------------------+ |expression |return type |postcondition | +-----------+---------------+---------------------+ |t = u |T& |t is equivalent to u | +-----------+---------------+---------------------+ Table 64 In 12.8/10: If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. The implicitly-declared copy assignment operator for a class X will have the form X& X::operator=(const X&) if each direct base class B of X has a copy assignment operator whose parameter is of type const B&, const volatile B& or B, and for all the nonstatic data members of X that are of a class type M (or array thereof), each such class type has a copy assignment operator whose parameter is of type const M&, const volatile M& or M. Otherwise, the implicitly declared copy assignment operator will have the form X& X::operator=(X&) (Note the last and second last sentence) In 17.4.3.6/1 and /2: In certain cases (replacement functions, handler functions, operations on types used to instantiate standard library template components), the C++ Standard Library depends on components supplied by a C++ program. If these components do not meet their requirements, the Standard places no requirements on the implementation. In particular, the effects are undefined in the following cases: for types used as template arguments when instantiating a template component, if the operations on the type do not implement the semantics of the applicable Requirements subclause (20.1.5, 23.1, 24.1, 26.1). Operations on such types can report a failure by throwing an exception unless otherwise specified. Now, if you look at the specification of auto_ptr you will note it has a copy-assignment operator that takes a non-const auto_ptr. Thus, the implicitly declared copy assignment operator of your class will also take a non-const type as its parameter. If you read the above places carefully, you will see how it says that instantiating a vector with your type as written is undefined behavior.
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 • Display any record in the file • Change any record in the file Is there anything I should know of before I start this that could make this much more easy & efficient... Like for example, should I try and use XML or what that be too hard to work with via C++? I've never really understood the most efficient way of doing this. Like would I search through the file and look for things in brackets or something? EDIT The datasize shouldn't be too large. It is for homework I guess you could say. I want to write the struct's contents into a file's route, how would I go about doing that?
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 also acceptable, and has many reusable implementations available, but it will start loosing performance once you go into thousands of records. The same goes for JSON. And one might still debat which one is simpler - JSON or XML. Another possibility is to create a struct and write its contents directly to the file. Will get tricky though if the record size is not constant. And, if the record format changes, the file will need to be rebuilt. Otherwise this solution could be one of the best performance-wise - if implemented carefully.
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 here's my question: do you know any present-day compiler that implements by default one's complement or sign-magnitude representation? Can we change default representation with some compiler flag? What is the simplest way to determine which representation is used? And what about C++ standard?
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 the IP protocol suite use one's complement, so perhaps dedicated "network accelerator"-type CPU:s implement it.
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 (vain) attempt to just declare the functions and let the implementation come true only on the .c. This is an abridged description of my code: common.h #include <stdio.h> module1.h #include "common.h" #ifndef MODULE1_H_ #define MODULE1_H_ int init(int option); int open(char* db, char* username, char* password); int get(int handler, int date[2], int time[2], int* data, int& rowsize, int& numrows); int put(int handler, int* data, int& datasize, int& numrows); int close(int handler); int finalize(); #endif /* MODULE1_H_ */ module2.h #include "common.h" #ifndef MODULE2_H_ #define MODULE2_H_ int get1(int handler, int date, int time, int *data, int& datasize, int& rowsize); int put1(int handler, int* data, int datasize); #endif /*MODULE2_H_*/ module1.cpp #include "module1.h" int init(int option) { ... } int finalize() { ... } int get(int handler, int date[2], int time[2], int* data, int& rowsize, int& numrows) { .... } ... module2.cpp #include "module1.h" #include "module2.h" int get1(int handler, int date, int time, int* data, int rowsize) { int daterange[2]={date,date}; int timerange[2]={time,time}; int rsize, numrows, result; result=get(handler, daterange,timerange, data, rsize, numrows); rowsize=rsize; if(numrows!=1) printf("Uh oh...\n"); return result; } ... Compilation & linkage: g++ -o module1.o -c module1.cpp g++ -o module2.o -c module2.cpp g++ -fPIC -shared -o library.so module1.o module2.o As I said, it compiles OK. The problem is during linkage, where the linker "sees" that there are two implemented functions from module1.h: one from the inclusion of module1.h in module1.cpp; and the other from the inclusion of module1.h together with module2.h in module2.cpp. I know the functions are supposed to be declared, but I'm obviously doing a faux-pas. Could someone please point out where it is? Thank you in advance.
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 been using it with success up until now, but I was "blinded" by the errors; that include's documentation states that care should be taken when using it in C++ context (not in C) but this is the first instance where that warning actually produces effects. Thank you once more for your help.
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 underlined?
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 = new MyThread(args...); t.start(); Must be the same in your case.
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, geometry feature or light etc. In particular geometry features can either be a single piece of geometry of a collection of sub features, which is indicated by the presence of a separate structure. Being a linked list it is a flat structure but the order implies hierarchy. Also, each entry has an attribute structure which is able to be propagated down the list. A separate function allows this list to be traversed and a provided function pointer to be executed on traversal of the list. Each function used in this way must take proper care to maintain the attribute structure as it is propagated down the list and this is a frequent cause of rendering bugs (usually things not realising they should be redrawn because they are part of a group of entries, for example) While some aspects of OO design jump right out at me I am interested to hear: how i would best implement being able to pass a function pointer down a list (or vector - are STL vectors ok for lists like this?) whether i would be right to implement windows and geometry features as related (or even the same) classes how to best design a class that can have a collection of itself any suggestions regarding attribute transferral between objects (e.g color, scale). the desired behaviour is that modifying a feature will alter the attributes of that feature and any sub-features it contains, and modifying a sub-feature will only modify that feature. I realize this is a long and broad question, so appreciate your thoughts on any of the above queries. thanks!
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, saying error C2143: syntax error : missing ';' before 'type' If the code is changed to be like below it will pass compilation: int foo(int x) { int y; assert(x != 0); y = 2 * x; return y; } If I change the source file name from .c to be .cpp, the compilation will also pass as well. I suspect there's an option somewhere to turn off the strictness of the compiler, but I haven't found it. Can anyone help on this? Thanks in advance. I am using cl.exe that is shipped with Visual Studio 2008 SP1. Added: Thank you all for answering! It seems I have to live in C89 with Microsoft's cl.exe.
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 promising for enabling C99. You may have to live with C89 (which ain't so bad) or find a better C compiler (which would be better).
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 through whole file. How would I do this? The reason is because the number of lines to be processed is very large (~ 10^7). And those that start with 34 are only around 1-10% of it. I am aware that I can grep the lines and output it into another file, but this is too tedious and creates more disk space consumption. This code illustrates my failed attempt using "continue": #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; int main () { string line; ifstream myfile ("mydata.txt"); vector<vector<string> > dataTable; if (myfile.is_open()) { while (! myfile.eof() ) { stringstream ss(line); int FirstCol; string SecondCol; if (FirstCol != 34) { continue; } // This will skip those other than 34 // but will still iterate through all the file // until the end. // Some processing to FirstCol and SecondCol ss >> FirstCol >> SecondCol; cout << FirstCol << "\t << SecondCol << endl; } myfile.close(); } else cout << "Unable to open file"; return 0; }
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 34 qux 62 foo1 62 qux 78 qux ...this code will do what you want: #include "stdafx.h" #include <iostream> #include <vector> #include <fstream> #include <sstream> using namespace std; int main () { string line; ifstream myfile ("mydata.txt"); vector<vector<string> > dataTable; if (myfile.is_open()) { bool found34 = false; while ( myfile ) { stringstream ss(line); int FirstCol; string SecondCol; // This will skip those other than 34 // but will still iterate through all the file // until the end. // Some processing to FirstCol and SecondCol myfile >> FirstCol >> SecondCol; cout << FirstCol << "\t" << SecondCol << endl; switch( FirstCol ) { case 34 : found34 = true; cout << "Processing a 34"; continue; // keep looping default : if( found34 ) { // we found all the 34's and now we're on to the next value, so we're done cout << "We're done."; break; } else { // we haven't found the first 34 yet, so keep scanning until we do cout << "Keep on looking for a 34..."; continue; } } } myfile.close(); } else cout << "Unable to open file"; return 0; }
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; // <- Visual C++ complains } }; The error message is "error C2440: 'initializing' : cannot convert from 'overloaded-function' to 'MemberFunctionType'" This works if f is not overloaded, but not in the example above. Any suggestion? EDIT Beware, the code above did not reflect my real-world problem, which was that I had forgotten a "const" - this is what the accepted answer points out. I'll leave the question as it is, though, because I think the problem could happen to others.
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! MemberFunctionType pointer = &C::f; } }; Clarification: The original question didn't contain that const. I did a wild guess in the comments whether he possibly has f being a const member function in the real code (because at a yet earlier iteration, it turned out yet another thing was missing/different to the real-world code :p). He actually had it being a const member function, and told me i should post this as an answer.
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 "asdf", and ss.c with the value of an expression of the form int(), that is, 0. ]
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 with no warnings using g++, should this code compile or at least give some warnings? It turns out that the built-in C++ compiler on 64 bit solaris gave me a linker error, which is how I noticed that there was an issue. What is the rule on matching arguments in this case? Is it up to compilers?
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(int x); void g(const int x); void f(const int x)//this is allowed { } void g(const int x) { } Anyone calling f won't care that you are going to treat it as const because it is your own copy of the variable. With int * const x, it is the same, it is your copy of the pointer. Whether you can point to something else doesn't matter to the caller. If you ommitted the first const though in const int * const, then that would make a difference because it matters to the caller if you change the data it is pointing to. Reference: The C++ Standard, 8.3.5 para 3: "Any cv-qualifier modifying a parameter type is deleted ... Such cv-qualifiers affect only the definition of the parameter with the body of the function; they do not affect the function type"
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)); NotificationFilter.dbcc_size = sizeof(DEV_BROADCAST_DEVICEINTERFACE); NotificationFilter.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE; NotificationFilter.dbcc_classguid = hidGuid; HDEVNOTIFY deviceNotify = RegisterDeviceNotification(StatusHandle, &NotificationFilter, DEVICE_NOTIFY_SERVICE_HANDLE); A notification is then received via the SERVICE_CONTROL_DEVICEEVENT event. (Remember, this is a Service so no WM_DEVICECHANGE). I thought I could just specify the DEV_BROADCAST_DEVICEINTERFACE flag in the RegisterDeviceNotification() call so it would override dbcc_classguid and get all devices, but it turns out that that flag is not supported on Windows 2000, which is a dealbreaker for me. Also, I'm guessing that that would return more than just USB devices. How should I modify this to get all USB devices, not just USB HID? Should it be as simple as just giving a different GUID? Is there even a GUID for all USB?
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_DEVICEINTERFACE; NotificationFilter.dbcc_reserved = 0; NotificationFilter.dbcc_classguid = GUID_DEVINTERFACE_USB_DEVICE; HDEVNOTIFY hDevNotify = RegisterDeviceNotification(hwnd, &NotificationFilter, DEVICE_NOTIFY_SERVICE_HANDLE);
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"); } }; int main(void) { A a(1, 2); int p=10; A a1(5, 6); B b(3, 4); int q=11; B b2(7, 8); a.p(); b.p(); int * x=(int*)&a; printf("%d %d %d %d\n", x[0], x[1], x[2], x[3]); x=(int*)&b; printf("%d %d %d %d\n", x[0], x[1], x[2], x[3]); }
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: template<class C, typename Rtype, typename Ptype1, Rtype (C::*FuncPtr)(Ptype1)> void RegisterFunc(const char* const scriptname) { objtemplate->Set( v8::String::New(scriptname), v8::FunctionTemplate::New( V8ScriptClass<C>::RelayCallback<C, Rtype, Ptype1, FuncPtr> )); }; template<typename Rtype, typename Ptype1, Rtype (*FuncPtr)(Ptype1 param1)> static v8::Handle<v8::Value> RelayCallback(const v8::Arguments& args) { std::cerr<<__FUNCTION__<<std::endl; v8::HandleScope handle_scope; return handle_scope.Close(toJSType( ((FuncPtr)(toCType(args[0]))) )); }; Looks to me like the typedef and the actual function signature are identical. edit: forgot one declaration: class EXPORT FunctionTemplate : public Template { public: /** Creates a function template.*/ static Local<FunctionTemplate> New( InvocationCallback callback = 0, Handle<Value> data = Handle<Value>(), Handle<Signature> signature = Handle<Signature>());
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.