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
6,013,786
6,013,821
Template inheritance inner class access problem
I can't believe gcc won't accept the following code... Please tell me if accessing an inner class from a base template is really not possible or am i missing something? template <class T> class BaseClass { public: struct MyStruct { T *data; }; }; template <class T> class ChildClass : public BaseCla...
The problem is that MyStruct is a dependent name, so you have to tell the compiler to defer name lookup until the template is instantiated by qualifying it with the base class name: typename BaseClass<T>::MyStruct ms1; For more information, I'd read the Parashift C++ FAQ entry, "Why am I getting errors when my templat...
6,013,969
6,013,988
Erasing vector element crashing the program
Why the follwoing code is failing ? typedef vector<SOCKET /*socket*/> UIConnection; UIConnection::iterator itrUICon; for ( itrUICon = m_ListUIConnection.begin();itrUICon != m_ListUIConnection.end();itrUICon++) { if (*itrUICon == nSock) { itrUICon = m_ListUIConnection.erase(itrUICon); ...
Probably because you are erasing the last item in the vector and then incrementing itrUICon in the increment part of the for statement when it is already equal to .end(). Prefer using the erase()/std::remove() idiom or at least move the increment out of the for statement and only perform it if you didn't preform an era...
6,013,987
6,014,119
How to send a HBITMAP over a socket using WIN32 and C++?
I have created an application where I am required to send the cropped part of an image over a Socket. I have cropped the image using StretchBlt(), I am also able to display and save the cropped image to a bitmap file. Next, I want to send this cropepd image over a Socket connection. The connection between socket is est...
You can't pass an HBITMAP (which is a HANDLE, a reference pointer in memory) to another machine. You can use the GetBitmapBits Function to transform the HBITMAP into a byte array and send this byte array using send(). On the other side, you'll have to create another compatible bitmap, and use SetBitmapBits Function aft...
6,014,016
6,018,558
what option do i have to execute or communication with native process from Chrome browser using npapi
I would like to write a Chrome plugin that will communicate with my native C++ process, to invoke it and capture its return output. What options do I have in the Chrome browser using npapi? im using firebreath for npapi so mybe something with boost?
NPAPI doesn't restrict you; it's just native C++ code. That means you can use any IPC mechanism that you would used for any two processes. There won't end up being anything NPAPI-specific about what you end up with. (Given that, you might want to ask a new version of this question without mentioning Chrome or NPAPI, si...
6,014,036
6,014,492
generate unique hash keys of url
i want to generate unique hash keys of an url. atm im using boost hash std::size_t seed = 0; boost::hash_combine(seed, host); boost::hash_combine(seed, path); boost::hash_combine(seed, query); boost::hash_combine(seed, fragment); but the hash keys are very often duplicate... :( http://www.finanzen.de/geldan...
I don't think there's an error in that code. The hash values are different with this dummy example: #include <boost/functional/hash.hpp> #include <cstdio> int main() { size_t seed = 0; std::string s1("www.finanzen.de"); std::string s2("geldanlage-boerse.html"); std::string s3("geldanlage-china.html"); ...
6,014,107
6,014,170
Have a static lib, is there a simple way to know it is for 32 bit or 64 bit?
Is there any tool that can directly test if a library is made for 32 or 64 bit?
You can use dumpbin utility with /headers option It returns whether the library was built for 32 or 64 bit architecture. Check DUMPBIN Reference for details. Example usage: c:\>dumpbin libXYZ.lib /headers
6,014,147
6,014,330
Finding elements within distance k from a matrix
Given a n*n matrix and a value k, how do we find all the neighbors for each element? for example: in a 4*4 matrix, with k=2 say matrix is : [ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] where these values are the indexes of the location, the neighbors for 1 are 1,2,3,5,6,9 . The values 3,6 and 9 come only beca...
This should do the trick for k=1. Make minor changes to make it work for all k int width = 4; int height = 4; int k = 1; int value = 2; bool hasRight = (value % width != 0); bool hasLeft = (value % width != 1); bool hasTop = (value > 4); bool hasBottom = (value < (height * width - width)); cout << value; // Always i...
6,014,152
6,017,181
Path to a USB Device in Windows
I would be using a USB hub to connect multiple devices. I want to fix a specific USB device to a particular slot. Then check if it is done properly. The way I am planning to achieve this is to get the complete USB path like PCIROOT(0)#PCI(1D00)#USBROOT(0)#USB(1)#USB(2)#USB(3)#USB(3) I can get this particular string i...
You can build this path by using the SetupAPI. The device manager is built with this. You start with CM_Locate_DevNode and enumerate children with CM_Get_Child.
6,014,199
6,017,297
streaming loads and non USWC memory
I just read this rather interesting article, Copying Accelerated Video Decode Frame Buffers. Where they explain how to do copying from USWC memory as fast as possible using streaming loads. My question is why this technique would not also speed up normal copies, from non USWC memory? A streaming load would read an enti...
From http://software.intel.com/en-us/articles/increasing-memory-throughput-with-intel-streaming-simd-extensions-4-intel-sse4-streaming-load/ "The streaming load instruction is intended to accelerate data transfers from the USWC memory type. For other memory types such as cacheable (WB) or Uncacheable (UC), the instruct...
6,014,201
6,065,776
Pass a block to a C++ method from objective C
I have a C++ helper class that I use with objective-C. I would like to pass the c++ class a block from a view controller (a callback) so that when it is executed I am on the main thread and can update the UI. I currently have a similar system working with function pointers and performSelector when the function is calle...
So is it just that you're not entirely familiar with the block syntax? If so, here's a quick example that should hopefully make sense if you're already familiar with function pointers (the syntax is more or less the same, but with the use of an ^ for declaring one [creating a closure is, of course, different]). You pr...
6,014,228
6,014,256
Is it possible that application can lose I/O connection to a file?
I have a C application. Which creates a connection to file at startup and it continuously runs for many days. I am only connecting one time . and not reconnecting it in code. Only checking if if(NULL == file) Is there can be case that my application lose I/O connection of that file handler ? if yes. Is there a way ...
Yes it's possible. For example if the file is on another machine or on a removable storage. Then you can physically disconnect/unplug the device and the subsequent operations on the handle will fail. As others mentioned in the comments, you can simulate it in a test case by creating a RAM disk and either unmounting it ...
6,014,252
6,034,955
How do I make sure that the (luabind) lua state is good after an error has occurred?
When lua code causes an exception, luabind will leave an error message on the stack for me to collect. I am wondering how to guarantee that the lua stack will be in a sensible state after I have handled the exception: The examples I've found tells me to use luabind::from_stack(e.state(), -1). Won't this leave the erro...
It will leave the error message on the stack. Whether you should pop it depends entirely on what you are doing with the stack next. If you don't need the message anymore (since you saved it somewhere else) then pop it. If you are going to use it further down the catch chain, then leave it. The point is, you use the Lu...
6,014,349
6,014,398
ODR violation when name-lookup finds a different declaration
I've been thinking of the following. Consider two files: A.cpp: template<class T> void g(T) {} inline void f() { g(1); } B.cpp: template<class T> void g(T) {} void g(int) {} inline void f() { g(1); } Without void g(int) {} this program is 100% valid. With void g(int) {}, g(1) resolves to the template version in A.c...
Yes, it does. In the exception for inline functions it's specified that not only shall the definitions of the inline function consist of exactly the same token sequence but that all the corresponding identifiers in the function definition which name entities outside of the function definition must refer to the same ent...
6,014,594
6,014,775
How to do look ups on the CFDictionary
Possible Duplicate: How to retrieve the values for the particular key from CFMutableDictionary In C++: typedef struct { unsigned short wId; bool bPersists; unsigned short uPeriod; bool bStop; }stTimer; unsigned short wId; stTimer pEvent; CTypedPtrMap<CMapWordToPtr,WORD,stTimer*>m_cIdMap; if(m_cI...
You would use an NSDictionary and box the keys with NSNumber (assuming you have created a class to represent your stTimer struct. [myDictionary setObject: myStTimer forKey: [NSNumber numberWithUnsignedInt: [myStTimer wId]]]; StTimer* mySTTimer = [myDictionary objectForKey: [NSNumber numberWithUnsignedInt: anId]]; I d...
6,014,644
6,021,645
Routine when starting boost::asio::io_service
I want to create an http client using boost asio. To have a structured and optimized I have looked into the examples of boost asio to have some idea of what a good implementation should look like. Mostly, I have followed the structure of HTTP Server, so I have a connection manager that holds a set of pointers to each...
I have tried, as HTTP Server 2 example, to set up a thread pool of io_services and assigning work to them so that they will not return until stopped. When using asynchronous programming, I strongly suggest using the following designs in order: single io_service with a single thread pool of threads invoking a...
6,014,717
6,014,776
... with constructor not allowed in union problem
I desperately need to find a solution for the following problem: namespace test { template <int param = 0> struct Flags { int _flags; Flags() { _flags = 0; } Flags(int flags) { _flags = flags; } void init() { ...
As @Als said, union cannot define non-POD as member data, there is one alternative. You can still define a pointer to the non-POD as member data of the union. So this is allowed: union { struct { Flags<4096> *pf; //pointer to non-POD }p1; struct { Flags<16384> *pff; //pointer to non-POD }...
6,014,815
6,014,981
Good approaches to enforce building with increased warning level for new C++ code
I've inherited a large C++ codebase for several Windows applications that successfully is in use by many customers. The codebase is large, >1mill LOC. The codebase has a history of 15+ years. The codebase is in some areas dominated by C programming style and/or not very modern C++ style, e.g. not using Standard C++ co...
I would even go as far as going to warning level 4 (/W4). Since you're using Visual Studio, it's quite easy to suppress bothersome warnings like signed vs unsigned comparision: #pragma warning(disable:NNNN) Where NNNN is the number of your warning. Now put all those disabled warnings in a header file (say, "tedious_w...
6,014,927
6,014,960
I'm trying to declare a constant string in my C++ class, but I get an "Invalid in-class assignment", and I don't understand why
here's the code: #include <string> class Config { public: static const std::string asdf = "hello world!"; } I can't diagnose why this won't work
Only integral types can be initialized in the class (presuming they're declared as static const). So do this: //Config.h class Config { public: static const std::string asdf; //declaration static const int demo_integral = 100; //initialization is allowed! } //Config.cpp const std::string Config::asdf = "hell...
6,015,080
6,016,700
C/C++: Is this undefined behavior? (2D arrays)
Is it undefined behavior if I go through the elements of a 2D array in the following manner? int v[5][5], i; for (i = 0; i < 5*5; ++i) { v[i] = i; } Then again, does it even compile? (I can't try it right now, I'm not at home.) If it doesn't, then imagine I somehow acquired a pointer to the first element and usi...
Accessing elements of a multidimensional array from a pointer to the first element is Undefined Behavior (UB) for the elements that are not part of the first array. Given T array[n], array[i] is a straight trip to UB-land for all i >= n. Even when T is U[m]. Even if it's through a pointer. It's true there are strong re...
6,015,137
6,017,492
using firebreath created npapi for chrome can i call the plugin methods from the extensions and not from html loaded page
I've built a simple NPAPI plugin, and registered it with Chrome. This all works; javascript in the browser is able to interact with plugin. But i need to be able to call methods of my plugin from Chrome extensions. Can it be done?
Yes, you can. Extensions are implemented in JS and HTML, so you can embed and call a plugin from an extension just as you would from a web page.
6,015,227
6,015,274
Create an xml from an object
Possible Duplicate: c++ linux library for creating an xml and reading from an xml (serialize/ deserialize) HI, I am working in Ubuntu. I would like to create an xml from am object I have this: Class me { std::tring name; int age; }; main() me *p = new me(); p->age=12; p->name="dina"; How can I create an ...
You should look at TinyXml; it allows a Document Object Model (DOM) to be constructed with your object attributes and then saved to file.
6,015,293
6,015,658
convert ExceptionDescribe to string
I need to get the output of ExceptionDescribe() in JNI as string so I can write it afterwards in a file instead of writing it directly on command line. Is there any way or idea how to do that? Thanks in Advance, Sami
You have apparently use the ExceptionOccured() method. jthrowable exc; exc = (*env)->ExceptionOccurred(env);
6,015,340
6,016,001
stitching aerial images
I am trying to stitch 2 aerial images together with very little overlap, probably <500 px of overlap. These images have 3600x2100 resolution. I am using the OpenCV library to complete this task. Here is my approach: 1. Find feature points and match points between the two images. 2. Find homography between two images 3....
In the results that you have posted, I can see that you have at least one keypoint mismatch. If you use findHomography(src, dst, 0), it will mess up your homography. You should use findHomography(src, dst, CV_RANSAC) instead. You can also try to use warpAffine instead of warpPerspective. Edit: In the results that you p...
6,015,453
6,015,589
VTABLE for abstract classes C++
Possible Duplicate: Does an abstact classes have a VTABLE? Does a vtable gets created for an abstract class that have pure virtual functions and virtual functions ? class Abstarct { public: virtual void f() = 0; virtual void g() {} }; Thanks.
I just saw that none of the answers in the other topic clearly answers it. The answer is: Yes and No. Since the vtable and vptr is implementation-defined concept and is not mandated by the C++ Standard, so compilers are free to choose any approach as long as it does dynamic dispatching of the virtual functions (pure o...
6,015,607
6,028,676
Multiplatform crash reporting?
What would be the best way to implement crash reporting in a cross-platform app in c++ (windows, mac, linux)? Looked into google breakpad, but spent a few weeks trying to make socorro (UI) work to no avail. edit: @Nim to clear up, I want to send a stack-trace to my server when some exception occurs.
When we went crossplatform (from being previously Windows-only), we spent a lot of time researching the possible tools for exactly this. Google Breakpad really is the best crossplatform solution out there. Your problem is Socorro, which is huge, obfuscated, and confusing. I can suggest two routes: Drop the current ve...
6,015,769
6,015,850
how to use addr2line in commandline
how to use addr2line? i have a program that gives the backtrace of last 10 addresses that it visited before crash. but if i use these address to addr2line like addr2line -e test [address] it just gives me ??:0 is there a special way to compile to use addr2line like we use ggdb to use gdb?
You need to have some debugging information compiled in to your executable. e.g. $ gcc t.c # debug information not requested $ gdb ./a.out ... (gdb) break main Breakpoint 1 at 0x400588 (gdb) q $ addr2line -e a.out 0x400588 ??:0 # no information returned $ gcc -g t....
6,015,789
6,016,831
Unwillingly calling QueryInterface via RPC
In my application, I create an object A, that creates an object B, both via CreateInstance. Both objects should live in the same process. Now I see that object B, when asked for a certain interface, is returning E_NOINTERFACE, although I defined it in the COM_MAP: class B: { // .... BEGIN_COM_MAP(B) COM_INTERF...
From you description it was definitely marshalling kicking in. Marshalling is done by tunnelling calls through RPC so it looks rather weird, but that's how it is done on Windows. The consumer thread likely called CoInitializeEx() with COINIT_APARTMENTTHREADED. Since the object to create was marked as Free it couldn't h...
6,015,837
6,015,919
unresolved externals Error in C++ Project
I wrote my project using a simple editor and I compile them by using Microsoft vc++ compiler through command line interface, I am getting the following error: /out:Main.exe Main.obj Main.obj : error LNK2019: unresolved external symbol "public: void __thiscall Ac count::debit(int)" (?debit@Account@@QAEXH@Z) refere...
Apparently you have forgotten to include the Account.obj in your command line arguments: /out:Main.exe Main.obj Account.obj
6,016,094
6,016,225
Unable to write in registry when windows UAC is set to always notify
I have a C++ application, In which we write settings to the registry (Under HKEY_CURRENT_USER & HKEY_LOCAL_MACHINE for my application).When windows User Access Control is set to Always Notify, RegCreateKeyEx method returns access denied and it does not write to HKEY_LOCAL_MACHINE but it writes successfully in HKEY_CURR...
If you do take the path to only allow the application to be run as admin, you can set the manifest in Visual Studio in: Project >> Properties >> Configuration Properties >> Linker >> Manifest File >> UAC Execution Level. Ideally you would find some way that does not require modifying HKEY_LOCAL_MACHINE
6,016,156
6,016,273
Accessing Memory of other applications C++
I am thinking about a problem I have been having for some time now.. I would like to write a C/C++ program (under windows first) that can access(read/change values) the memory(stack, heap, everything) of other running programs. (Not like shared memory but any memory the computer has..) Without having to start the appli...
As @sharptooth said, this requires support from the OS. Different OS does it differently. Since you are on Windows, there are a few steps you could follow: Call OpenProcess, or CreateProcess to access, or launch a new process. In this call, you must request PROCESS_VM_READ access. Call ReadProcessMemory to read a chun...
6,016,327
6,016,572
How to define dynamic constructor in C++?
It allocates memory to the objects while creating to sane memory space. but how to define the dynamic constructor. plz explain with an example. Thanks.
There is no dynamic constructor in C++. This is how to define a constructor for class A: class A { public: // Constructor A() { /* constructor code*/ } }; This is how to allocate memory and construct the object: A *a = new A();
6,016,378
6,016,400
exception error in program
int maxNum(int *n) { int Maximum = n[0]; for(int i = 1; i <= 8; i++) { if( Maximum < n[i] ) Maximum = abs(n[i]); } return Maximum; } void DibHomoginityDetect(CDib& dib) { register int i,j,x[8]; int w = dib.GetWidth(); int h= dib.GetHeight(); CDib cpy =dib; ...
Kind of hard to tell from the code, but I guess your for-loop should really be: for(int i = 0; i < 8; i++) Arrays in C++ are indexed from zero, not one.
6,016,811
6,017,872
functions as template argument, plus variadic template argument
I'm writing a generalized function wrapper, that can wrap any function into a lua-style call, which has the form int lua_function( lua_State *L) And I wish the wrapper function is generated on-the-fly, so I'm thinking of passing the function as a template argument. This is trivial if you know the number (e.g, 2) of arg...
Things like std::function and std::result_of use the following technique to do what you want regarding variadic templates: template<typename Signature> struct wrapper; // no base template template<typename Ret, typename... Args> struct wrapper<Ret(Args...)> { // instantiated for any function type }; You could exp...
6,016,987
6,017,028
Tracking down which dependency contains SSE instructions
One of our customers needs a build of our program without SSE as he's on quite old hardware. My problem is that even if I modify our project settings across the board to unset SSE for all libraries & binaries it would seem there's still a dependency somewhere which is compiled with SSE instructions on, causing the appl...
Disassemble all involved binaries, then do a search for SSE instruction mnemonics in the disassemblies.
6,017,162
6,017,245
iTunes COM interface - Cannot add song to library
I'm trying to add a simple .mp3 file to the iTunes library but my program keeps crashing when I call AddFile(). However, when I call get_Tracks() it returns a valid pointer, so I suppose the pointer to IITLibraryPlaylist is valid. What am I doing wrong? IiTunes* p_iTunes; IITLibraryPlaylist* p_Library; IITOperationStat...
The problem is you pass WCHAR* instead of properly allocated BSTR and that leads to undefined behavior. You should first allocate a BSTR using SysAllocString() (don't forget to release the string later) or better yet use a wrapper class like ATL::CComBSTR or _bstr_t for managing BSTR lifetime.
6,017,325
20,800,719
who to make variables during run-time (in c++ )
I want to let the user of my program define variables , then makes mathematical operation on them like "define a:integer , b:double" then "print a*b" I found that I can use "boost any" but I need the type of the variable be dynamically recognized because want to use variable(objects) of classes .... so I want to us...
The best way to do it is using Polymorphism in C++
6,017,365
6,017,978
Object outside camera OpenGL
I'm using a Perspective View with gluPerspective and gluLookAt and I have the x,y world coordinates of an object. How can I determine if the object is outside the viewable area? Note that the camera is always moving around.
First thing first: OpenGL doesn't have a camera. It just transforms vertices around. And gluLookAt just applies a transformation on the objects that's inverse to a movement of a thought camera. The solution had already been given in the first comment by Robert Massaioli: In OpenGL a perspective transformation is descri...
6,017,399
6,017,455
is there cross platform library to call/create process in c++
Is there any cross platform library to create process's (using createProcess win32 api in windows for example). for linux/windows/mac?
Boost.Process will do that as will PoCo (Processes namespace, in Foundation) None of these are intrusive libraries, and none of these imply UI frameworks. Both will support static linkage without major size overhead.
6,017,672
6,018,045
tinyXml how to add an element
I have the following: TiXmlDocument doc; TiXmlDeclaration * decl = new TiXmlDeclaration( "1.0", "utf-8", ""); doc.LinkEndChild( decl ); TiXmlElement * root = new TiXmlElement( "Value" ); TiXmlElement * element = new TiXmlElement( "number" ); root->LinkEndChild( element); TiXmlText * text = new TiXmlText( "5" ); ...
If you want to append a node containing an integer value, this integer has first be transformed to a string. You can do this with a variety of functions, but I prefer snprintf (others might differ :) ) Consider the following example: int five = 5; char buf[256]; snprintf(buf, sizeof(buf), "%d", five); // transforms the...
6,017,764
6,019,148
C++ to Java Code Conversion doubts
I am Converting some code from c++ to Java. Having the following doubts- C++ - static char **gprs; In Java - private static String[] gprs; OR private static Byte[] gprs; C++ - static char *mask; In Java - private static byte mask; (Correct?) C++ - memset((char *)&rm,'\0',sizeof(DRMK)); // Here DRMK is a struct. rm is...
C++ - static char **gprs; Depends on the use of gprs, but I would say (from looking at the rest of the code) that byte is more suitable. A byte array that is. C++ - static char *mask; I would use a byte rather than a char given the "mask" name. C++ - memset((char *)&rm,'\0',sizeof(DRMK)); As stated in other answers...
6,017,797
6,018,881
(iphone) weird EXC_BAD_ACCESS , at A::A() in backtrace but code points to B::B()
In Xcode 4, I'm having this weird EXC_BAD_ACCESS. where backtrace shows 0 A::A() (in Debug navigator) code is pointing at B::B() (in Editor view, A and B class doesn't share class hierarchy) Both A & B are c++ struct. I've tried cleaning the project. (I suspect some object files didn't get cleaned up. eager to know...
turned out it was compiler being llvm-gcc reverting back to gcc solved the problem.
6,018,012
6,018,143
Can I assign a member data pointer to a derived type?
This is probably best shown with example code. The following fails to compile with g++: struct Base { }; struct Derived : public Base { }; struct Container { Derived data_; }; int main(void) { Base Container::*ptr = &Container::data_; } I get the following error: invalid conversion from 'Derived Container::...
This is not a compiler bug, you can't do that. (But you can assign a Base::* to a Derived::*). I don't see any good reason for the limitation (excepted that to handle the case of multiple inheritance, that would complicate even more the representation of a member pointer).
6,018,213
6,019,040
OpenAL: alcOpenDevice() slow, can it be speed up?
Is it normal to take up to 2 seconds to run this function? It takes about 0.5 to 2.5 seconds, rarely more than 1 second though, usually around 0.6 to 0.9 seconds. Just wondering, if i could speed this up somehow, perhaps remembering the device name from the first run or something?
These methods are usually slow since they're probably handling the initialization of the device, etc. My guess is that this method is slow mostly because of the operating system. The usual workarounds these types of methods is doing them asynchronously (in a background thread) and displaying a "Loading" text/image. You...
6,018,254
6,018,276
Initialize a vector with a dynamic length
Can you please tell me how to change the size of the buf vector into a dynamic length? long five = 555; char buf[256]; snprintf(buf, sizeof(buf), "%d", five); THX! How to change my code with std::vector<std::string>buf; in order to work correctly? I have error: vector is not a member of std; buf was not declared ...
In C++, you can't. You will have to allocate it dynamically somehow, or better still use a dynamic data structure like a std::vector.
6,018,346
6,018,394
Generic bridge between C++ and PHP
We have a web application (quite a heavy-weight one) that does a whole bundle of stuff, web ui, mathematical processing and modelling, and database-related stuff. A number of the processes that happen in PHP are quite slow, mostly because PHP sucks for mathematical processing. In the future, we'd like to break these s...
Google protocol buffers Protocol Buffers What is it? Protocol Buffers are a way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats. <endquote> It supports fast and efficient serialization for objects that you def...
6,018,499
6,018,533
constant parameters in a function
class foo { public: void set(const int a) {b=a;} private: int b; }; Here a is a constant parameter which is assigned to a non const
Applying the const modifier to a parameter indicates that the parameter may not be changed by the function. It does not mean, though, that if the parameter's value is assigned to another variable then that variable can't be changed. The purpose is to assure callers that data they pass to the method will not be changed....
6,019,094
6,077,251
Validating domain user credentials
I need a way to validate a user/password pair for native c++ on windows. Input is user and password, user can be in DOMAIN\user format. Basically I need to write a function that: If user/password is a valid local account, returns true. (part 1) If user/password is valid on the domain given, return true also. (part 2) e...
If you mean by the "." domain, domains that aren't "trusted" w/ the domain running the code from fail, then that is by design. Several years ago Microsoft best answer to this when we used a support ticket was to use WNetUseConnection() .
6,019,160
6,019,420
How do I output to the console, and overwrite text without clearing the screen and re-writing everything?
Like when using aircrack-ng, or any program that has tables of data that constantly update. =\
It depends somewhat on the system, and above all, how much you want to overwrite. For a lot of simply programs, outputting '\r' will do the trick: it will return the cursor to the start of the line (on almost all consoles), and you can overwrite the line. (I've used this in the past for continuously updated progress ...
6,019,174
6,019,269
Simple edit dialog box
I am modifying a program that runs in Windows that I would like to input a couple of values into as it starts. At the beginning of AppMain, the following pre-existing code allows the user to enter a filename: char our_file_name[260] = "TEST"; #ifdef WIN32 edit_dialog(NULL,"Create File", "Enter file name:", our_file_na...
The signature for the edit_dialog function probably takes a char* as it's 4th parameter. You are passing an int there when you call it with tolerance, so your code is treating the value of the int (in this case 400) as a pointer value (0x400) and going to look at the string located at the address 0x400... Boom. Crash....
6,019,307
6,019,633
is_same returning false when comparing class template instantiation with its base class template?
*Edit: Somehow I thought the compiler was creating B just as A<int, int, string>, leading to my assumption about how is_same should evaluate them, regardless of inheritance/derivation. My bad :( Sorry for subsequent misunderstandings :\ * Making some meta-functions to check for my custom types, and ran into this issu...
The is_same is basically a template with a specialization template<class T, class U> struct is_same : false_type { }; template<class T> struct is_same<T, T> : true_type { }; That will never give you true, unless you have exactly the same type. Note that there is only one T in the specialization. It can never match bo...
6,019,502
6,019,801
How to draw a PNG on a transaprent background?
I have a window with a WS_EX_LAYERED style and it has a alpha color key of magic pink (0xFF,0,0xFF). I'm trying to draw a PNG image over that window using GDI+ and it shows shades of pink around the icon edges (where the alpha blend is applied). Here's an example: http://img834.imageshack.us/img834/8241/stackoverflow.p...
Some points to check over: Have you seen the docs on MSDN? What options have you fed into your BLENDFUNCTION struct? How are you loading your .png? Does your image have an alpha channel?
6,019,930
6,020,025
What are some advantages & disadvantages of type inference in C#?
I have a coworker that is against type inference in C#. I believe most of his arguments surrounded lack of readability. My argument against that is that Visual Studio's intellisense features provide a simple way of viewing types, and reading them from the code isn't as necessary as it might be if we were coding out of ...
Type inference was invented for exactly the reason you give for C++, you can create anonymous types that don't HAVE a type name (see Lambdas and Linq in particular). So in that case it's needed. In the other case (when the type name is known) then it comes down to style. I use var when the type is really obvious: // I ...
6,020,240
6,021,033
atoi with ints and doubles
Can I use atoi to convert a text input to a dialog box to a double? I need to do a calculation on several double values that have been input using a dialog box. I only know of 'atoi' but is this for integers only?
Assuming Boost is an option, Boost.lexical_cast is a popular approach for converting to and from string representations of numerical values, e.g.: char const s[] = "1.2345"; try { double d = boost::lexical_cast<double>(s); ... } catch (boost::bad_lexical_cast &) { ... }
6,020,299
6,020,773
Reasons for structure of standard exception hierarchy
This is a picky thing and it is probably just my OCD flairing up but I was wondering why the standard exception class hierarchy is set up as it is. exception bad_alloc bad_cast bad_typeid bad_exception ios_base::failure runtime_error subclasses... logic_error subclasses... Couldn't all the bad_* ...
If I remember correctly, the logic was: logic_error would be the equivalent of an assert, but with less drastic behavior runtime_error would be the base of all others However, as you noticed, it does not quite hold, even in the standard library itself. The main issue I guess is subjectivity: is std::out_of_range a lo...
6,020,312
6,027,801
Language for non-unicode programs change ini reading
I've a non-unicode application which is using unicode versions of the ini reading functions like GetPrivateProfileSectionW and GetPrivateProfileStringW. The program is working well when "Language for non-unicode programs" is set to English. When I change this setting to Chinese (PRC), the functions GetPrivateProfileSe...
Michael Kaplan explains. The solution is to use Unicode INI files, which don't depend on the "Language for non-unicode programs".
6,020,314
6,020,835
Why is std::u16cout missing?
C++03 defines two character types: char and wchar_t. (lets ignore the signed char and unsigned char insanity). These two character are then applied to std::basic_string, std::basic_ostream, etc as std::string/std::wstring and std::ostream/std::wostream. From the streams the standard library also defines the globals st...
It was decided that implementing Unicode iostreams was too much work to be worth it: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2007/n2238.html From the paper: The rationale for leaving out stream specializations of the two new types was that streams of non-char types have not attracted wide usage, so it is no...
6,020,506
6,020,528
What is the C++ equivalent of C#'s readonly field modifier?
Locking down state is great. In C# you can ensure that a field doesn't change it's value/reference once the constructor completes by declaring it as readonly. class Foo { private readonly string _foo; public Foo() { _foo = "Unchangeable"; } public void ChangeIt() { _foo = "Darn"; ...
That would be const. Note that this keyword means a couple of different things in different contexts.
6,020,588
6,020,849
cudaMemcpy2D for shared memory copies
I have some memory that has been allocated on device that is just a single malloc of H*W*sizeof(float) in size. This is to represent an H*W matrix. I have a code where I need to swap the quadrants of the matrix. Can i use cudaMemcpy2D to accomplish this? Would I just need to specify the spitch and dpitch to be W*sizeo...
You can use cudaMemcpy2D for moving around sub-blocks which are part of larger pitched linear memory allocations. There is no problem in doing that. The non-overlapping requirement is non-negotiable and it will fail if you try it. The source and destination can come from the same allocation, but the address ranges of t...
6,020,640
6,024,884
Is it possible to dynamically change from FILE_FLAG_SEQUENTIAL_SCAN to FILE_FLAG_RANDOM_ACCESS?
Good afternoon, We are building a prototype of a Windows/LINUX deduper using the memory mapped file API of Windows and Linux. Our deduper starts out by doing a sequential scan of all the database records to be deduped. Therefore , we pass the flag FILE_FLAG_SEQUENTIAL_SCAN to the Windows API CreateFile during our intia...
The caching hint flags passed to CreateFile() do not affect the manner in which the memory manager satisfies page faults generated by de-referencing an address within a mapped section. Such I/Os use the same - they use the same cache pages as regular I/O. That said, when a handle to the file is created with FILE_FLAG...
6,020,762
6,021,316
Manipulating global variables
I have functions in two (linked) C++ files that both use the same variable. To me (a complete beginner) I could see two ways of handling this: Pass the variable from the first function to the second (they are sequential in the program), or Define the variable as a global value in a separate header file that both c++ f...
While you can resolve the issue of how to use a global, it is much better if you avoid it altogether. If you have two functions that modify a single variable, then the simplest thing you can do is to pass the variable as argument to the function: void foo( type & var ); void bar( type & var ); int main() { type t( c...
6,021,188
6,022,152
BHO HtmlEventObject crashes
I have a browser helper object written in C++ but I have a problem when recieving a OnHelp HtmlEvent. When I try to access a attribute the browser crashes. VARIANT_BOOL STDMETHODCALLTYPE OnHelp(IHTMLEventObj2 *pEvtObj) { std::cout << "OnHelp Event" << std::endl; if(pEvtObj != NULL) { VARIANT var; ...
The first arg for getAttribute is a BSTR, but your passing a wchar_t*/unsigned int * depending on VC compile settings. BSTR is a system string which is expected to be deallocated by the receiving method. Try #define DOM_ANON_STRING(x) (_bstr_t(x)) pEvtObj->getAttribute(DOM_ANON_STRING(L"formID"), 0, &var);
6,021,222
6,021,243
vector resize strange behavior
I have the following code. The interesting part is if I uncomment the resize() on vector, it is priting 10 numbers for an input value of 5. I am using eclipse with mingw and gcc on windows xp. Shouldn't the iterator go only for 5 elements? #include <iostream> #include <string> #include <vector> #include <map> #include ...
resize resizes the vector, inserting default values for each of the items it needs to create for the new size. You want reserve.
6,021,273
6,021,676
How to allocate thread local storage?
I have a variable in my function that is static, but I would like it to be static on a per thread basis. How can I allocate the memory for my C++ class such that each thread has its own copy of the class instance? AnotherClass::threadSpecificAction() { // How to allocate this with thread local storage? static MyCla...
#include <boost/thread/tss.hpp> static boost::thread_specific_ptr< MyClass> instance; if( ! instance.get() ) { // first time called by this thread // construct test element to be used in all subsequent calls from this thread instance.reset( new MyClass); } instance->doSomething();
6,021,686
6,021,714
C++, iterator to std::map
How to declare an iterator to std::map <T, Point <T> *> , where: template <typename T> struct TList { typedef std::vector < std::map <T, Point <T> *> > Type; }; In the following code int main () { .... std::map <T, Point <T> *> ::iterator i_map; //Error ... } g++ shows this error: error: dependent...
Use typename as: typename std::map<T, Point <T> *>::iterator i_map; //^^^^^^^^ here! Because iterator is a dependent-name (as it depends on the map's type argument T), so typename is required here. Read this FAQ for detail explanation: Where and why do I have to put the "template" and "typename" keywords?
6,021,710
6,021,853
Boost foreach and operator overloading
I'm learning boost and I wanted to rewrite my Matrix class. Instead of for loops I wanted to use BOOST_FOREACH, however I have some problems with operator overloading. This is the original version of overloading operator /= template<typename T> Matrix<T> Matrix<T>::operator /= ( double varValue) { for (int i=0;i<th...
You need to use a reference (based on the example at http://www.boost.org/doc/libs/1_39_0/doc/html/foreach.html). Also, you were missing a return statement: template<typename T> Matrix<T> Matrix<T>::operator /= ( double varValue) { BOOST_FOREACH(vector<T> &row,datavector) { BOOST_FOREACH(T &item,row) ...
6,021,720
6,021,773
C++ - Nested include - Avoiding 'include nested too deeply error'
What is the best way of declaring my header files if I want to have the following connections in my C++ code, just so that I don't get the 'include nested too deeply error'? On my edge class, I have some functions that need to return a Node object. Same for the Edge class, I have functions that need to return a Node ...
As others have suggested, use header guards. But also try forward declaring the classes in question. You may also have to work with pointers (rather than values) in at least one of your classes, but without seeing the code, we can't tell. So edge.h should like something like: #ifndef EDGE_H #define EDGE_H class Node; ...
6,021,888
6,083,053
Can I override the color of a control when Visual Styles are enabled?
I have an application in C++ Builder 2010 that has Visual Styles/Runtime Themes enabled to use the runtime look for buttons and tabs. However, I have a set of checkboxes (TCheckBox) for which I would like to override the runtime style, if possible. My checkboxes are used to toggle some graphical overlays for various c...
Put each checkbox on it's own panel and set it to the color you want.
6,021,947
6,022,051
Sending Files With Sockets
I'm trying to create a basic HTTP server to learn more about how it works. I'm having difficulties with sending binary files to the client. My code is as below: char * buffer = (char *)malloc(sizeof(char) * 512); fseek(content_file, 0, SEEK_SET); while (!feof(content_file)) { size_t read = fread(buffer, sizeof(char...
You problem is that sizeof(buffer) gives you the size of the pointer, not what it points to. Add a buffer_size and use that both for malloc and freed.
6,021,949
6,021,984
Visual Studio 2008: how to pause the running program to see a variable value?
I have started a long loop, and i dont want to start it over (been running 3 hours now, i calculated it to run only 1 hour instead), and i am afraid that my program is working incorrectly because its taking so long. I was too stupid to actually output any state values for myself (i didnt think it would take 3 damn hour...
What you want to do is attach to the running process Load the solution which represents the project Tools -> Attach to Process Select the running process and hit attach Hit the Pause Button on the IDE to stop the process or set a break point At this point you will be broken in the debugger and able to inspect the run...
6,022,087
6,112,813
Capture windows messages generated by an MFC app in plain C++ dll
First of all: Is this even possible? I have a third party dll that interfaces some hardware. It's written in MFC. I received (from the dll vendors) a sample Visual Studio 2010 solution which has only one project: An MFC application (.exe) which calls the third party dll in question. It works fine. When I try to use the...
Alright, I made it. Here's how: Create a class which inherits from CWnd Declare a message map associating the desired messages and their handlers When creating the Window, use the CreateEx function (I did it in my class's constructor), and pass it the HWND_MESSAGE flag in the last but one parameter. This will create ...
6,022,204
6,116,599
CUDA convolutionFFT2D example - I can't understand it
I studied the Cooley Tukey algorithm and I understood it. I got everything in the CUDA convolutionFFT2D example till these kernels: spProcess2D calls -> spProcess2D_kernel which calls a lot of -> spPostprocessC2C, mulAndScale and spPreprocessC2C Here's the complete code: http://nopaste.info/30c13e44fe.html (convolution...
It looks like the algorithm is doing something similar to the algorithm mentioned here. The preprocess step looks to be re-ordering the Real input of size N (after padding) to complex input of size N/2. The postprocess step is re-ordering the data to get back the FFT of the original input array.
6,022,343
6,026,121
Recording state changes in boost::statechart
For Unit Testing, I'm trying to record all the state transactions after I kick off a state machine event. E.g., if I post_event A to the fifo_scheduler of an async_state_machine, the state machine will go through states B, C, then back to D. Without being able to record all the event states, I can only check that it we...
This seems a bit hackish when I really want to hook into the async_state_machine just before it calls a state's react() method... Why don't you? Create a new class that extends async_state_machine and add your desired hooks into it. If access is a problem (It probably will be), do the ever spectacular #define private...
6,022,426
6,022,485
Why can this constructor declared with two parameters be called with just one?
I watched my lecturer's video from my university and he says about the Rational class that its constructor goes like this: Rational (int top=0 , int bottom=1) : t(top) , b(bottom) {normalize();} Until now everything is OK, BUT !! he also said that you can call the constructor only with 1 argument (top argument) and be...
The = in the constructor declaration give the parameters default values. If you don't provide a value yourself when you call the constructor, the compiler will fill in the declared default value for you. The constructor won't know the difference — it will see both parameters, and it will have no way of detecting whethe...
6,022,573
6,022,757
Objects and copy ctors created without RVO in C++
I am new to C++. Please consider the following code: class foo { int f; public: foo(int f1=0) : f(f1) { cout<<"In conversion ctor\n"; } foo(const foo & rhs) : f(rhs.f) { cout<<" In copy ctor\n"; } foo& operator=(const foo & that) { f=that.f; cout<<"In = optor\n"; return *this...
Looks right to me. You have to have an accessible copy constructor defined if you are going to copy objects. Even if the copy can be optimized away. That sounds right to me, though the precise ordering might be implementation defined. You would have to
6,022,813
6,022,858
Qt4 Creator/QMAKE equivalent to "-mcmodel=medium" GCC compiler settings
I'm using Qt Creator to create a GUI for a fairly memory intensive C++ application on Linux. In order for the application to run properly, the -mcmodel=medium compiler flag must be set during compilation, otherwise the application will abruptly crash during execution (tried compiling in Qt without it, and it crashes as...
QMAKE_CXXFLAGS += -mcmodel=medium
6,022,881
6,022,947
why is the address of a c++ function always True?
well why would, #include <iostream> using namespace std; int afunction () {return 0;}; int anotherfunction () {return 0;}; int main () { cout << &afunction << endl; } give this, 1 why is every functions address true? and how then can a function pointer work if all functions share (so it seems) the same addres...
The function address isn't "true". There is no overload for an ostream that accepts an arbitrary function pointer. But there is one for a boolean, and function pointers are implicitly convertable to bool. So the compiler converts afunction from whatever its value actually is to true or false. Since you can't have a...
6,023,001
6,023,460
Converting a member function to a static function in C++
I am writing a memory testing framework, in which I replace dynamic memory allocation functions with my own (eg. malloc, realloc, free, etc.). However, the system expects static functions (I can not change this). I have a MemoryTester class, which logs the memory calls, and I want to bind its member function implementa...
After the edit, the intent seems clearer to me. The simplest thing that you can do is using static member functions in the MemoryTester instead of non-static member functions. If they need to hold state, that state will have to be moved to be static members of the class.
6,023,195
6,023,286
How does sizeof work for int types?
I have a small program which compares (1) sizeof, (2) numeric_limits::digits, (3) and the results of a loop in an effort to make sure they all report the same thing regarding the size of the "int types" on any C++ implementation. However because I don't know about the internals of sizeof, I have to wonder if it is ...
Most likely sizeof() on most compilers causes the compiler to look the given type (or object's type) up in its internal type table and insert a literal for that type's defined size into the code it generates. This would happen at compile time, not runtime. To answer the question in the comments, there isn't any languag...
6,023,310
6,023,806
__sync_bool_compare_and_swap Compiler Flags and Includes
I am working on a lock free data structure, and am trying to CAS pointers. When using compare and swap, what flags should I pass into the compiler? I have gotten a license for http://locklessinc.com/ memory allocator. I am also using netbeans 7. Currently The only flags I have are under the linker, -march=native -lllal...
__sync_bool_compare_and_swap is a GCC intrinsic. You don't need any particular compiler flags for it; however, your IDE won't be able to find its definition, because it doesn't have one. And it may not work on other compilers; eg, the Visual Studio compilers call it InterlockedCompareExchange As for where your problem ...
6,023,378
6,023,473
Which one of these headers comes from MSVCR100.DLL?
I'm working on a cpp app, works fine on the virtual machine im developing but in my laptop (XP without c++ redistributable package) it shows an error saying the app needs MSVCR100.DLL and it's not in the computer. I am not referencing the dll directly anywhere in the app so I guess it could be because of the headers in...
Everything in the C library depends on it whenever you compile your program with Visual Studio 2010. So either you link statically with the C runtime, or you deploy the DLL with your application. If you want to know, stdlib.h, stdio.h, cmath.h depend on it, and also probably a lot of headers depending on the C runtime ...
6,023,400
6,051,557
OpenGL ES Texture Coordinates Slightly Off
I'm trying to draw a subregion of a texture in OpenGL by specifying the coordinates I want. What's happening though is that, depending on the size of the image, it seems there's a slight offset in the origin of where it selects the texture coordinates. The offset amount seems to be less than the size of a pixel & the o...
Keep in mind, that OpenGL samples textures at the texel centers. So when using linear filtering (like GL_LINEAR or GL_LINEAR_MIPMAP_LINEAR) the exact texel color is only returned if sampled at the texel center. Thus, when you only want to use a sub-region of a texture, you need to indent your texture coordinates by hal...
6,023,491
6,023,834
Is this well defined code?
I'm still slightly confused after reading this topic. Is the following C++ expression *d++ = ~(*d); well defined? Yes, I know compound expressions like this are ugly.. I didn't write it. I see a slight difference in the generated assembly when I compare it to: *d = ~(*d); d++; Assembly: *d++ = ~(*d); 0x83384 LDR ...
*d++ = ~(*d); In this expression no object is having a new value stored to it more that once. The value of d + 1 is stored to d as a side effect of the incremement operator (d++) and the value of the object pointed to by d before this increment is written to by the assignment operator. The issue is that d is read, not...
6,023,498
6,023,676
Parameters Framework for C++
I'm trying to find a parameters framework in C++ to synchronize parameters and variant types between a client/server. I've tried googling around, but I think I don't have the right search terms. Example: An object on the server could have the following parameters defined and mapped to the member variables: "name": s...
Let me rephrase. What you want is a data exchange format between clients and servers written in C++ that lets you pass around structures known to both sides in an efficient and easy to process way, that hopefully lets you be upwards compatible so that you can upgrade server and client separately. If so then http://code...
6,023,966
6,024,204
C++ static initialization of stateless class
Suppose I have a class T where T has no virtual functions. T instances have no state. T has static member instances of itself. T itself has no other state. Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should ...
To answer the first part of your question, if T has a constructor which has side effects then you can in fact get burned by static initialization fiasco.
6,024,095
6,024,171
transfer object ownership with placement new
I have a Visual Studio 2008 C++ project with a class that manages a resource that cannot be copied. I have implemented transfer-by-reference-structure semantics (ala std::auto_ptr). class Test; struct Test_Ref { Test& ref_; Test_Ref( Test& t ) : ref_( t ) { }; private: Test_Ref& operator=( Test_Ref const&...
Focusing on the main function, as that should indicate your intended semantics, there are two big problems: First, you are not allocating memory, which means that if the compiler would process the code, it would cause UB (would try to call the constructor of Test over the NULL address in the placement new operation. Th...
6,024,168
6,024,195
passing string around question
I have a member function like setResult(const std::string &s) { this->m_result = s; } After checking, I found this->m_result's address is the same as s. Will m_result disappear (or become garbage) when s goes out of scope if s is a stack object?
Probably not; if m_result is a std::string, it will deep-copy the data contents. Anyway, in places like assignment operators, you'd normally check against this kind of self-assignment. The idiom is: obj& operator=(const obj& o) { if ( this != &o ) // ... } The same goes for your case, where you could potentially ...
6,024,169
6,024,251
Can't allocate 2-4 Gb of RAM with new[]/ C++/Linux/ x86_64
For this easy test, and the linux box with 4Gb or RAM, 0byte of swap and CPU in x86_64 mode, I can't allocate more than 1 Gb of array. Source: #include <cstdio> int main() { for(int i=0;i<33;i++) { char*a=new char[1<<i]; *a=1; delete[]a; printf("%d\n",i); fflush(stdout); } } Run: $ file test test: ELF 64...
EDIT: I see in other answers that the issue is most probably related with the number passed to new[] becoming negative. I agree that that is most probably the case, I am leaving this answer only because I think that it contains information that might be relevant in some similar cases, where the issue is not with callin...
6,024,574
6,024,650
How to convert a `const char *` to simply `char *`?
I'm using the pdCurses library and am aiming to only really use strings in my C++ console game but the curses mvinstr() function or any insert function requires a non-const char * as a parameter. My solution at first to this problem was simply entering in string.c_str(), but that returns a const char * which apparent...
mvinstr(x,y,str) and others "take characters (or wide characters) from the current or specified position in the window, and return them as a string in str (or wstr)." The function will actually modify the string, so you cannot safely cast the const away, especially since c_str specifies that you should not modify the r...
6,024,589
6,024,699
adding sound to an OpenGL app
i am creating an OpenGL application and decided to look into adding sound... what is the best sound(api?) i was thinking about using OpenAL but i had issues finding any good resources... if possible could you please provide tutorial/info of some sort.
Here is one i used a while ago for 3D sound. http://www.ambiera.com/irrklang/ It is called IrrKlang, it has good documentation for the API and it really easy to integrate. You should be able to get sound playing within an hour or so of downloading it.
6,024,612
6,027,886
I can't compile opencv samples with VS2010 on vista
I am using visual studio 2010 on windows vista. I want to compile a sample file of OPENCV named "find_obj.cpp" created by liuliu. Here is the address of source code. https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/c/find_obj.cpp Other opencv codes works well but I couldn't compile this. please help I've i...
I solved the problem. In this sample it uses flann functions and I added the opencv_flann220d.lib to libraries section in visual studio. Now, program compiles with no error. And I learned that if you're getting "unresolved externals" error it is mostly because of missing of include directories or libraries. greetings
6,024,722
6,024,777
Error "undefined reference to" when I compile a C++ code, but the original makefile code compiles
I downloaded a generic AVL implementation from: http://sourceforge.net/projects/standardavl/files/standardavl/0.1/ The makefile in this project compiles correctly the code. The compiler produces the follow output: g++ -pedantic -Wall -O3 -c standardavl.cpp -o standardavl.o g++ -pedantic -Wall -O3 -c Point.cpp -o Point....
Assuming AvlTree.h declares a template class AvlTree<>, and AvlTree.cpp defines the implementation: You can't define the implementation of template code in a separate translation unit (.cpp) -- it must exist where it is used. That's why they included it in the header. Putting the implementation in a .cpp file to be i...
6,024,999
6,025,157
MPI Warning: Program exiting with outstanding receive requests
I wish to send a contiguous array of memory between two nodes using MPI. For this purpose, I use the following Non-blocking Send/Receive command (MPI_Isend, MPI_Irecv). While executing the run command, I see two warning statements as follows: Warning: Program exiting with outstanding receive requests Basically, I want...
It looks like you haven't called MPI_Waitall(). The "immediate" send and receive routines only begin the communication. You have to block your process to ensure the communication has finished. Blocking in MPI is with a variant of MPI_Wait(); in your case, you need MPI_Waitall().
6,025,008
6,025,031
Immutable classes and memory in C++
So, I'm getting deeper into C++ than I did in school as part of a personal project I'm working on. I'm a Java developer, so memory management is a little hard to get used to again, and now that I'm going out of my way to code a certain way, I have a quick question about immutable classes. When I think about them as a ...
In the case you've described, the assignment operator of MyImmutableClass is called to copy the right hand side of the assignment to the left hand side (overwriting whatever was on the left hand side). If your class really is immutable, it won't even have an accessible assignment operator, and you will get a compile er...
6,025,087
6,025,107
Why don't I get an integer overflow when adding two chars?
Possible Duplicate: Addition of two chars produces int Given the following C++ code: unsigned char a = 200; unsigned char b = 100; unsigned char c = (a + b) / 2; The output is 150 as logically expected, however shouldn't there be an integer overflow in the expression (a + b)? Obviously there must be an integer pro...
Neither C++ not C perform arithmetical computations withing "smaller" integer types like, char and short. These types almost always get promoted to int before any further computations begin. So, your expression is really evaluated as unsigned char c = ((int) a + (int) b) / 2; P.S. On some exotic platform where the ran...
6,025,113
6,025,238
What do I link in to define boost::thread_specific_ptr and related?
I want to use boost::thread_specific_ptr but need to know what to add to my gcc v3.4.6 link line to define what it uses: /usr/include/boost/thread/tss.hpp:35: undefined reference to `boost::thread_resource_error::thread_resource_error()' ../../src/utility/ARCH.linux_26_i86/debug/libmyApp.a(system.o)(.gnu.linkonce.t._ZN...
On my Ubuntu system I use -lboost_thread (since libboost_thread.so is already in my /usr/lib I don't need any -L options).
6,025,118
6,025,152
Specifying a lambda function as default argument
How do I assign a lambda as default argument? I would like to do this: int foo(int i, std::function<int(int)> f = [](int x) -> int { return x / 2; }) { return f(i); } but my compiler (g++ 4.6 on Mac OS X) complains: error: local variable 'x' may not appear in this context EDIT: Indeed, this was a compiler bug. Th...
You could use overloading: int foo(int i) { return foo(i, [](int x) -> int { return x / 2; }); } int foo(int i, std::function<int(int)> f) { return f(i); }
6,025,137
6,025,186
Memory management with low memory: finding and tracking duplicates of random function return values
Lets assume i have a function that takes 32bit integer in, and returns random 32bit integer out. Now, i want to see how many and which duplicate values this function will return on all possible input values from 0 to 2^32-1. I could make this easy if i had more than 4gigs free ram, but i dont have more than 1gig ram. I...
To check for 2^32 possible duplicates you only need 4 gigabits which is 512MB, since you need only a single bit per value. The first hit of a zero bit sets it to 1 and on every hit of a 1 bit you know you have a duplicate and can print it out or do whatever you want to do with it. I.e. you can do something like this: ...
6,025,284
6,025,312
Can I have an enum with unlabelled values in C++?
Basically I want to restrict variables to the values 0, 1 or 2. I have tried doing this with the following: enum Value { 0, 1, 2 }; Value var; But this is a compile error because the enum values are unlabelled. It just makes the code less readable to assign names like "ZERO", "ONE" and "TWO" rather than re...
If you want to use enum, then you need to name them. Since you're just working with integer values, and you apparently want them to actually represent integer values, your best bet is it use an int parameter, and do a quick check at the top of the method. A comment on the method specifying this constraint would be welc...
6,025,437
6,025,806
Invalid initialization of reference of type error
A million thanks to anyone, who is willing to help me with this. First, the code: #include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; void Beolvas (vector<vector<int> > mat); bool VanNemNull (const vector<vector<int> > &mat); int main() { cout << "Van-e a mátrixnak olyan o...
First your compile-error: vector<vector<int> > mat; ... if (VanNemNull(&mat[i])) cout<<"szupiiiiii"; does not match : bool VanNemNull (const vector<vector<int> > mat); you are passing a copy of a vector_of_ints (an element of vector_of_vector_of_int) as parameter. You should either call it like this : if (VanNemNull(...
6,025,453
6,026,013
Safely convert (vector of shared_ptr to objects) to (vector of shared_ptr to constant objects)
class A {}; typedef shared_ptr<const A*> AConstPtr; typedef shared_ptr<A*> APtr; vector<APtr> ptr; const vector<AConstPtr>* foo() { return &ptr; } This code does not compile, because "there is no implicit conversion from vector<Aptr>* to const vector<AConstPtr> * " Is there anyway to make this work, without cre...
There's no way to do such a conversion since different shared_ptrs aren't related types. First, are you really sure that you need to expose the implementation detail that there's an internal vector of shared pointers? That's really going to tie you to that implementation and it won't be subject to change without breaki...