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
4,488,862
4,488,885
Why is 'new' an operator, not a function?
Are there any issues, like compile time operator, with sizeof associated with new?
new is an operator so you can overload it for some (or all) of your classes. EDIT: I'll try to clarify to address @sbi's comments below. Consider two classes: class Base { } class Derived : public Base { } Let's assume that new() is a function, and we want to specialize it for the Base class and its descendants. We w...
4,488,962
4,490,504
How to Disable UAC for my application
Well , when ever I am trying to run my application as administrator I am getting the following error, and whether to allow or not. If I am running the app directly and not as an administrator then this seems to work. Is there Some thing I need to do to get rid of the UAC , no I dont want user to manually change the UA...
In general, you can't disable UAC. The goal of UAC is to provide a defense in depth against malware. It would be counterproductive if an Tojan could just disable UAC. What you can do is accept that UAC exists, and roll with it. You shouldn't usually run as Administrator, so it's perfectly fine to get a UAC dialog when ...
4,488,990
4,489,525
Find remaining memory available to a process in 32 bit Linux using C++
My C++ program caches lots of objects, and in beginning of each major API call, I want to ensure that there is at least 500 MB available for the API call. I may either be running out of RAM+swap space (consider system with 1 GB RAM + 1 GB SWAP file), or I may be running out of Virtual Address in my process.(I may alrea...
Take a look at the source for the vmstat : here. Then search for domem() function, which gather all information about the memory (occupied and free).
4,489,167
4,556,703
C++ std method listing
I am new to C++ and XCode. I would like to know how I can get a list of available methods from namespace std or any other namespaces #include'ed in a cpp file., in a similar way you would do method scoping in Eclipse (ctrl+space). Thanks
With Xcode you use Esc, but it's auto-completion for C++ simply doesn't really work.
4,489,249
4,489,788
Compartmentalisation and Design of Classes in C++
In my spare time, I've been taking code I've written for various purposes and appropriating them into other languages just to have a look at what's out there. Currently I'm taking a genetic programming graph colouring algorithm, originally written in Java, and trying to coerce it into C++. The arbitrary data structure ...
If you have classes like Node, Graph and Edge, and their implementation is not too large, it makes perfectly good sense to define them in one and the same .cpp file. After all, they are meant to be used together. In C++, a package like this is called a component. Usually it makes more sense to think in components than ...
4,489,441
4,490,536
Why/when is __declspec( dllimport ) not needed?
In a project using a server.dll and a client.exe, I have dllexported a server symbol from the server dll, and not dllimported it into the client exe. Still, the application links, and starts, without any problem. Is dllimport not needed, then??? Details: I have this 'server' dll: // server.h #ifdef SERVER_EXPORTS #...
__declspec(dllimport) is a client-side MSVC attribute that can be specified for imported code and data. It isn't required for code. It is an optimization; a client-side compiler hint that a function call isn't direct but imported. The imported function pointer for a function named foo() will be __imp_foo. Without th...
4,489,604
4,489,710
Getting a HASP key with C/C++ (Problem)
I seem to be in need of some help (and by some, I mean a lot). Im trying to make a C program (or c++ if I get it to work, the language is not really important) to connect to a HASP USB. HASP is basically a USB drive that has some unique codes. The purpose of the HASP is to basically just "secure" another program, so th...
The code you pasted seems like an example how to use the API, not a working program by itself. It does not seem like it is intended to compile. So I guess you need to learn C/C++, or find someone at your job who can help.
4,489,639
4,490,524
Operator overloading in c (not c++) is it possible?
This question arises from my need to "convert" std::string to char* form. Preferably I would like to maintain as much code as possible and that includes plenty of "=" initialization/assignment operators. standard c operators exist for the basic data types (int, char, float, pointers to, etc...). Is it even possible to...
No, in C overloading of = is not possible, for a simple reason: it is well defined for (almost) all types. You'd really have to distinguish between assignment and initialization. Whereas initialization of arrays is possible, assignment is not. If your strings are compile time determined, all is easy: char copy[] = { "...
4,489,869
4,489,884
The left parenthesis '(' found at 'foo.cpp' was not matched correctly
Location of the error is indicated in a comment below. Please help fix this. #include<iostream.h> #include<string.h> #include<stdlib.h> class String { private: enum{sz=80}; char str[sz]; public: String() { strcpy(str,""); } String (char s[]) { strcpy(str,s); } void ...
The error occurs here: if(strlen(str) + (strlen(ss.str) < sz) That probably should be: if (strlen(str) + strlen(ss.str) < sz)
4,489,959
4,490,008
Simultaneous TCP Open
I am implementing "simultaneous TCP Open".That means both peer will try to connect each other at the same time. I confused whether listen is rquired or not in this case. or tell me the sequence of socket need to be called for each client. I am implementing this for TCp hole Punching. thanks,
From Wikipedia's article on TCP hole punching: Because both parties are connection TO each other (e.g. 2 x CONNECT(), no LISTEN(), ACCEPT(), etc.) to generate OUTBOUND traffic there is however a problem with: TCP Sequence numbers Acknowledgment numbers The required state is just like after the three-way-hand...
4,489,972
4,494,633
Reverse Engineering C++ code using "Enterprise Architect"
It is again a sort of "how to do it properly" question. Sorry if someone is annoyed. I've got to understand ca 150 TLOCs of C/C++ mixture. I've imported the code in UML-Tool "Enterprise Architect" and got a messy chart. Many Structs and Enums had anonymous names because of this C-ish constructs: typedef struct/enum {.....
I have Enterprise Architect, and almost invariably for doing what you are attempting on a large code body I use doxygen instead. It generates both class and call graphs. Use it with GraphViz and "UML-style" class diagrams, and you have a reasonably good code navigation and comprehension tool, with flexible configurati...
4,490,110
4,993,473
C++ class declaration and include issues in gsoap project
I compile a file in a gsoap project with the following command. Almost all files in my project are generated by the gsoap tools and i am new to C++ so i cant tell very much about it. All in all i need to understand if my project could compile at all. Do i need other flags? gcc -c -I/usr/include/gsoap soapAuftraegeImpo...
just to close this issue , i post my makefile C=g++ CCPLUS=g++ CFLAGS=-c #-Wall ### gsoap INCL=-I/usr/include/gsoap LIBS= -L/usr/lib/gsoap LINK= -lgsoap -lgsoap++ -lgsoapck -lgsoapck++ -lgsoapssl -lgsoapssl++ OLINK= -lgsoap++ #OBJ=soapServer.o soapServerLib.o soapC.o .SUFFIXES: .o .cpp .cc.o: @rm -f $@ ...
4,490,111
4,490,293
Have narrowing conversion error in C++ arm from Android NDK
I have narrowing conversion error in C++ arm from Android NDK. Have a following code: int16_t ax = li.A.x, ay = li.A.y; int16_t bx = li.B.x, by = li.B.y; Rect16 rcA = { ax - 8, ay - 8, ax + 8, ay + 8 }; Rect16 rcB = { bx - 8, by - 8, bx + 8, by + 8 }; And get this error, when try to compile: error: narrowing conversio...
Your problem stems from the fact that in the expression ay - 8 the compiler says you are calling int operator-(int, int). You need to tell the compiler that 8 is a short, using a method like in this question.
4,490,196
4,490,435
emacs public/protected/private label indentation of C++ header file not working for zero offset
I cannot get zero offset for some things for my C++ header files in emacs even if I have it defined in my .emacs file. The header file below shows a class definition inside two namespaces and most importantly the public keyword I would like to have with zero offset like below. namespace n1 { namespace n2 // no offset ...
I believe you want access-label instead of label. See here.
4,490,499
4,490,575
Erasing a container element using iterators
My current homework assignment has me creating an iterator class for a list. I'm stuck at creating a good erase(iterator where) function. Current code (reduced to fit question): class List { class _Iter { friend class List; public: _Iter(ListElem *pCurr, List *pList); /* *, ->, ++, ...
Do not use identifiers beginning with underscore followed by an uppercase letter. They are reserved for standard library and system writers. Although you are writing your own list class, you are not actually writing the standard library. end() is normally one element past the end of the list, not the last element. (To...
4,490,688
4,490,737
Infinite Loops and Early Return Statements
I have a simple console application that outputs a menu and waits for user input. After performing the appropriate action, the entire process repeats. The program exits when a specific string is entered. This is implemented with an infinite loop and an early return statement: int main() { while (true) { ...
This might be one of those rare cases where do...while is appropriate. I avoid adding extra boolean state variables unless they genuinely make the code clearer. int main() { string UserChoice; do { OutputMenu(); cin >> UserChoice; // ... } while (UserChoice != "exit"); } Howe...
4,490,914
4,491,122
How to "redefine" one char * to another char *?
Something like that: (it is task, how to do this, and not to change body of main function) I thought that it is too simple... but... I don't know how to do it... #include <iostream> #define "a" "b" int main( int argc,char ** argv) { std::cout << "a"; return 0; } // output: b How to do it?
Changing C++ output without changing the main() function for example from that topic: #include <iostream> #include <cstdio> #include <sstream> #define cout printf("a"); std::ostringstream os; os int main() { std::cout << "b"; } a simplier one: #include <iostream> #define cout cout << "a"; return 0; st...
4,491,234
4,491,293
When should this-> be used?
I was wondering if this-> should be used both: void SomeClass::someFunc(int powder) { this->powder = powder; } //and void SomeClass::someFunc(bool enabled) { this->isEnabled = enabled; } I'm wondering if the latter is necessary to be proper or if isEnabled = enabled would suffice. Thanks
this-> is needed when using the member directly would be ambiguous. This could happen with template code. Consider this: #include <iostream> template <class T> class Foo { public: Foo() {} protected: void testing() { std::cout << ":D" << std::endl; } }; template <class T> class Bar : public Foo<T> ...
4,491,350
4,491,378
undefined reference to `forkpty'
So I'm developing my project in Eclipse in Ubuntu 10.04. I have the following lines of code: #include <pty.h> pid_t pid; int master; pid = forkpty(&master, NULL, NULL, NULL); But when I try to build it within Eclipse, I get the error: undefined reference to 'forkpty' Any idea how to solve this problem?
You need -lutil command line argument (to use libutil shared library). For Eclipse: http://zetcode.com/articles/eclipsecdevelopment/ Select Project Properties. Expand the C/C++ Build tab. Select settings. From the Tool Settings tab, expand the GCC C Linker option. Click on libraries. Add the /usr/lib/libutil.so to the...
4,491,420
4,491,457
enable_shared_from_this and inheritance
I've got a type which inherits from enable_shared_from_this<type>, and another type that inherits from this type. Now I can't use the shared_from_this method because it returns the base type and in a specific derived class method I need the derived type. Is it valid to just construct a shared_ptr from this directly? Ed...
Once you obtain the shared_ptr<Base>, you can use static_pointer_cast to convert it to a shared_ptr<Derived>. You can't just create a shared_ptr directly from this; that would be equivalent to: shared_ptr<T> x(new T()); shared_ptr<T> y(x.get()); // now you have two separate reference counts
4,491,470
4,491,668
C/C++ function using float or double or int
I have seperate functions for reading from a text file (depending on whether its an int, float or double). I would like just one function with an additional argument (without using a subsequent IF statement). Does anyone have ideas? Below is the form of my current functions. float * read_column_f (char * file, int si...
You can't overload on return types. You either return value by reference as a function parameter: void read_column (char * file, int size_of_col, float&); void read_column (char * file, int size_of_col, int&); ... or create a template: template<class T> T read_column (char * file, int size_of_col);
4,491,490
4,491,620
c++ stl vector causing memory overflow?
I am making extensive use of stl vectors to manage memory (de-) allocation of large arrays of data. In particular I am generating perspective projections of anatomical structures from a large number of angles (180 in 2 degree steps), processing and analysing the results. The results are used to define radiation fields ...
Apparently, you are accessing the elements outside of container. It's impossible to say from this code, whether the indexes are correct or not, walk through this code in debugger and you will see. The suspicious looking piece: this->beamlets.at(beamletNumber-1).isOpen() What if beamletNumber is 0? You get invalid index...
4,491,508
4,491,526
c++ conversion operators no candidate is better
#include <iostream> #include <string> using namespace std; class test { private: std::string strValue; int value; public: test():value(0) { }; test(int a):value(a) { }; test(std::string a):strValue(a) { }; ~test(){}; operator int () { return value;...
std::ostream has numerous operator<< overloads, including both of the following: std::ostream& operator<<(std::ostream&, const char*); std::ostream& operator<<(std::ostream&, int); Your test class is convertible to both const char* and to int. The compiler can't select which conversion to use because both conversions...
4,491,610
4,491,797
How to pass a deleter to a method in the same class that is held by a shared_ptr
I have several classes from 3rd party library similar to the class, StagingConfigDatabase, which requires to be destroyed after it is created. I am using a shared_ptr for RAII but would prefer to create the shared_ptr using a single line of code rather than using a seperate template functor as my example shows. Perhaps...
I'll assume that create is static in StagingConfigDatabase because your initial code wouldn't compile without it. Regarding destruction, you can use a simple std::mem_fun : #include <memory> boost::shared_ptr<StagingConfigDatabase> pSDB(StagingConfigDatabase::create(), std::mem_fun(&StagingConfigDatabase::destroy));
4,491,649
4,494,004
How to convert yuy2 to a BITMAP in C++
I'm using a security camera DLL to retreive the image from the camera. The DLL call a function of my program passing the image buffer as a parameter, but the image is in yuy2 format. I need to convert this buffer to RGB, but I tried every formula I found on Internet with no success. Every example I tried (including htt...
Using the information from the Microsoft link in the question: for (int i = 0; i < width/2; ++i) { int y0 = ptrIn[0]; int u0 = ptrIn[1]; int y1 = ptrIn[2]; int v0 = ptrIn[3]; ptrIn += 4; int c = y0 - 16; int d = u0 - 128; int e = v0 - 128; ptrOut[0] = clip(( 298 * c + 516 * d + 128...
4,491,976
4,492,046
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)'
invalid conversion from 'DWORD (*)(void*)' to 'DWORD (*)(void*)' . cake==lie 1==0 I have no idea what this means ... I get it in this code HANDLE CPlugin::CreateWinampThread() || { __VVVVVVVV__ hWinampThreadHandle = (HANDLE)CreateThread(NULL, 0, StartWinampThread, (void*)this, 0,...
StartWinampThread must be static if it is member function.
4,492,034
4,492,097
What are best practices for dealing with out of memory errors?
I'm wondering, what are good practices for dealing with out of memory errors. void SomeTask() { try { SomeObj obj = new SomeObj(); } catch( std::bad_alloc& ) { // What should be done here? } // ... more code ... } I feel like silently returning is wrong because the program could be r...
Since it's a service, I would write an error to the system message log. In Windows, you can use the Windows Event Log API. Unless you've specified otherwise in your documentation, this is probably where a sysadmin will expect to see the failure report. Also, in most C++ compilers, std::bad_alloc() has superseded a null...
4,492,062
4,492,524
Why does a C++ friend class need a forward declaration only in other namespaces?
Suppose I have a class F that should be friend to the classes G (in the global namespace) and C (in namespace A). to be friend to A::C, F must be forward declared. to be friend to G, no forward declaration of F is necessary. likewise, a class A::BF can be friend to A::C without forward declaration The following code ...
C++ Standard ISO/IEC 14882:2003(E) 7.3.1.2 Namespace member definitions Paragraph 3 Every name first declared in a namespace is a member of that namespace. If a friend declaration in a non-local class first declares a class or function (this implies that the name of the class or function is unqualified) t...
4,492,151
4,492,224
How to simulate C++ friend in C# and VB.NET?
Because sometimes, I really need a friend. I can think of the following tricks: Read only wrapper - like ReadOnlyCollection. The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper. Write delegate - the friend gives the constructor of the object a reference to a delegate ...
You can also use the InternalsVisibleTo attribute. For a given assembly, A, you can specify which other assemblies can have access to A's internal types.
4,492,152
4,492,185
why do we even need VPTR?
And why don't we use the same method for non virtual functions? I mean, why do we use virtual functions in that way? Can't we just use them as non-virtaul ones and override them? And if this method is saving us time/space or what ever, why don't we use the same method for non-virtual functions? I mean it would make sen...
You can't have run-time polymorphism without using a level of indirection. That's what the vptr is for. The vptr is not used for non-polymorphic functions because that indirection costs something. The C++ philosophy is that you don't pay for what you don't use. EDIT: Here's some info on how virtual tables work: http://...
4,492,161
4,492,327
CRT 9.0 vsprintf_s Parameter Validation on a long format string
From here: The versions of these functions with _s and _p suffixes are the more secure versions. These versions validate the format strings and will generate an exception if the format string is not well formed (for example, if invalid formatting characters are used). I just discovered the format string is ...
Looks like the default behavior is to throw the CRT error if output buffer size is exceeded, regardless of source. I expected the output to be silently truncated if the output buffer size is exceeded. Thus, there is no point in attempting to fill in the format string if it is too long already.
4,492,171
5,245,289
Scintilla: How do you find the byte position given a specific character position
Given a specific character index on a line, e.g. 10th character on line 3, is there an easy way to calculate Scintilla's 'position' of that character? It's straight forward when using ASCII characters but I can't see an easy way to do it when using multi-byte UTF-8 characters, where a single character may take up sever...
Convert line text to UTF8 and then count the byte positions. Cache conversion if multiple requests may be made.
4,492,402
4,492,415
Why is the following C++ code printing only the first character?
I am trying to convert a char string to a wchar string. In more detail: I am trying to convert a char[] to a wchar[] first and then append " 1" to that string and the print it. char src[256] = "c:\\user"; wchar_t temp_src[256]; mbtowc(temp_src, src, 256); wchar_t path[256]; StringCbPrintf(path, 256, _T("%s 1"), temp...
mbtowc converts only a single character. Did you mean to use mbstowcs? Typically you call this function twice; the first to obtain the required buffer size, and the second to actually convert it: #include <cstdlib> // for mbstowcs const char* mbs = "c:\\user"; size_t requiredSize = ::mbstowcs(NULL, mbs, 0); wchar_t* w...
4,492,472
4,492,601
how do i include BSP library in a c++ program?
im trying to compile c++ parellel program using BSPlib , on a platfrom that has bsp compile ( bsp++). Nevertheless , it doesnt seem to recognize any of the bsp functions. what should i do in order to include / import/ tell the compiler that im using bsp? include bsplib? bsplib.h ? thanks
#include "bsplib.h" then add bsplib to the link library list.
4,492,777
4,493,571
Run specific code when overloading C++ operators
I have a class, let's call it Foo, which contains the 3 following methods (overloading the left-associative < binary operator): ... operator<(A a) { return *this; } ... operator<(B b) { return *this; } ... operator<(C c) { return *this; } A, B, C classes are not related in any way(if that, is of any matter). Now In my...
class PreFoo { public: PreFoo() { ... } PreFoo & operator<<(A a) { ...; return *this; } PreFoo & operator<<(B b) { ...; return *this; } PreFoo & operator<<(C c) { ...; return *this; } int aa, bb, cc; // save your information }; PreFoo MakeFoo() { return PreFoo(); } class Foo { public: Foo(con...
4,492,799
4,492,865
undefined reference to `__stack_chk_fail'
Getting this error while compiling C++ code: undefined reference to `__stack_chk_fail' Options already tried: added -fno-stack-protector while compiling - did not work, error persists added a dummy implementation of void __stack_chk_fail(void) in my code. Still getting the same error. Detailed Error: /u/ac/alanger/g...
libgurobi_c++.a was compiled with -fno-stack-protector (obviously). A few things come to mind: add -fstack-protector when linking. This will make sure that libssp gets linked. Manually link -lssp Make your dummy version of __stack_chk_fail(void) in it's own object file and and add this .o file to your linker command ...
4,493,440
4,493,473
C++ -- Difference between "throw new BadConversion("xxx")" and "throw BadConversion("xxx")"
// http://www.parashift.com/c++-faq-lite/misc-technical-issues.html class BadConversion : public std::runtime_error { public: BadConversion(std::string const& s) : std::runtime_error(s) { } }; inline std::string stringify(double x) { std::ostringstream o; if (!(o << x)) throw BadConversion(...
[A1] With throw new, you'll have to catch a pointer. The language doesn't specify in this case who is responsible for deallocation, so you'll have to establish your own convention (typically you'd make the catcher responsible). Without new, you'll want to catch by reference. [A2] If you're in a framework that commonly ...
4,493,771
4,493,809
how to combine two LPCWSTRs?
I have two variables that are LPCWSTRs. I want to create a new variable that will have the values of the first and second variable. I tried this but it didn't work. LPCWSTR d = L"sd"; LPCWSTR f = L"f"; LPCWSTR df = d + f; I get this error when i try that. 1 IntelliSense: expression must have integral or enum type...
In C++ it is usually a good idea to use std::string for manipulations with strings. In your case it could look like: LPCWSTR d = L"sd"; LPCWSTR f = L"f"; std::wstring df = std::wstring(d) + f; LPCWSTR dfc = df.c_str(); // if you are really need this
4,493,782
4,493,977
Compiling with icc -static issue
I have been using ICC to compile a program I wrote for my research (nothing impressive just a lot of floating point calculations) and I can compile it just fine using: g++ -O3 mixingModel.cpp configFile.cpp -o mixingModel or icc -O3 -ipo -static mixingModel.cpp configFile.cpp -o mixingModel However, as soon as ...
This is likely due to icc's inter-procedural optimization. It considers all object files, which can be a lot when doing static linking. So I recommend to drop -ipo. Apparently, this is an old problem.
4,494,003
4,494,101
NSOpenPanel from C++ boost thread
I'm invoking a NSOpenPanel from a thread created by boost C++. the panel behaves erratically and doesn't respond well to mouse, that is clicking on objects does nothing sometime when clicking on top level combo box does improve response. do i've to run a separate runloop I'm doing a runModalForDirectory which should ta...
NSOpenPanel is part of AppKit. AppKit functions and classes can only be safely used on the main thread. Show us the code you used with performSelectorOnMainThread so we can help figure out why you might still be seeing problems. I suspect you're calling individual methods with it--don't; it won't work the way you expec...
4,494,148
4,494,175
How does one test item membership in an unordered sequence (C++)?
I've used python for a long time, and I'm just beginning to use C++ In python, if one has a set or a dictionary it is relatively easy to get a boolean value indicating whether or not a particular item is in that sequence using the in keyword. i.e. a = set(2,4,3) if 4 in a print "yes, 4 is in a, thank you for aski...
You have functionality like this in std::set and tr1::unordered_set (not yet in C++ standard). #include <set> #include <cstdio> int main() { std::set<int> s; s.insert(1); s.insert(2); s.insert(4); if (s.find(4) != s.end()) puts("4 found!"); return 0; } In reality, if yo...
4,494,170
4,494,204
Grouping switch statement cases together?
I may be over looking something but is there a simple way in C++ to group cases together instead of writing them out individually? I remember in basic I could just do: SELECT CASE Answer CASE 1, 2, 3, 4 Example in C++ (For those that need it): #include <iostream.h> #include <stdio.h> int main() { int Answer; cou...
No, but you can with an if-else if-else chain which achieves the same result: if (answer >= 1 && answer <= 4) cout << "You need more cars."; else if (answer <= 8) cout << "Now you need a house."; else cout << "What are you? A peace-loving hippie freak?"; You may also want to handle the case of 0 cars and then al...
4,494,274
4,494,495
Remove element from vector of maps
I have a vector of maps: typedef map<string, string> aMap; typedef vector<aMap> rVec; rVec rows; How can I remove some elements from rows? The following code does not work. struct remove_it { bool operator() (rVec& rows) { // Validation code here! } }; rVec::iterator it = remove(rows.begin(), rows.end(), r...
1) First off: please provide a single compilable example. Your code posted above is problematic as rVec and rowsVector have been interchanged (you would have seen that yourself if you had posted real code). 2) You are using the wrong remove. It should be remove_if 3) It is normal for the functor to be const 4) The oper...
4,494,278
4,495,117
What message causes a button to send a WM_COMMAND message
I know that a Button, when clicked, sends the WM_COMMAND message to it's parent, but what message does it receive that makes it send this message? I am overriding the default WndProc of a button and the button does not receive the WM_COMMAND message, so I need to know what message causes a button to send the WM_COMMAND...
I found that it's actually a combination of WM_LBUTTONDOWN, WM_MOUSELEAVE, and a few other things. For example, the WM_COMMAND will only be fired if the mouse was depressed on the button, and is still on the button when WM_LBUTTONUP is fired. As for space, enter, etc, I believe it just handles the VK_ENTER message and ...
4,494,329
4,495,295
Is it possible to specify that an options is required with boost::program_options?
I can use all other public members of the class typed_value define in value_semantic.hpp such as: default_value, implicit_value, zero_tokens, multitoken, notifier, etc. But even if the member "required()" is also there, I cannot use it. I got the error: ‘class boost::program_options::typed_value<std::basic_string<char...
Is your boost version maybe too old? I found required() in the docs for 1.45, but not in the ones for 1.34 - I don't know when it changed.
4,494,347
4,494,373
Getting a past-the-end pointer
Possible Duplicate: Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not? const int n = ...; T a[n]; T* begin = &a[0]; //or just a T* end = begin + n; I know this is legal and fine. However I am wondering if the following is undefined behavior or is legal as well. Doe...
Yes. It is undefined behavior. No, the type of T doesn't matter. The accepted answer in the linked duplicate is in error by its very own selection of standard citations. Unfortunately he muddles logic at the end to come up with exactly the opposite conclusion. The note in 3.9.2/3 is contained within a paragraph tha...
4,494,355
4,494,435
How to use Memcpy() function
I want to use the memcpy in the end, instead of block_orig_left[i1][j1]=block_orig[i1][j1]; pred_orig_left [i1][j1]=block_pred[i1][j1]; I have an error using memcpy src/coder.c:909: error: invalid operands to binary * (have ‘unsigned int’ and ‘int **’) src/coder.c:910: error: invalid operands to binary * (have ‘u...
You are multiplying the size of an int** by an int**, which doesn't make sense. In other words, if you wanted to know the weight of all the cars on a truck, you can't multiply "weight of 1 car" by "truck". You have to multiply the weight of 1 car by the number of cars on the truck. The third parameter to memcpy is the ...
4,494,507
4,494,533
Lazy evaluation and problems with const correctness
I have made an openGL camera class that uses lazy evaluation to provide the final projection or model-view-projection matrices through getter functions. The user provides the various camera parameters throughout the life of the instance (FOV, position, etc. ), but rather than have the projection matrix and/or MVP matr...
Is there a language feature or design paradigm I'm unaware of to help with this? Perhaps, mutable ? A member of a class that is marked as mutable is always non-const even if it is accessed via a reference or pointer to the owning class which is a const reference or a pointer to const.
4,494,786
4,494,814
enable_shared_from_this - empty internal weak pointer?
I'm using enable_shared_from_this<Base> and then inherit from Base. When trying to use shared_from_this() in Derived's constructor (not initializer list), I get an exception. Turns out that the internal weak pointer is null and doesn't point to this at all. How can this happen? My other use case of exactly this works p...
You cannot call shared_from_this() in the object's constructor. shared_from_this() requires that the object is owned by at least one shared_ptr. An object cannot be owned by a shared_ptr before it is constructed. I would guess that the internal weak pointer is set when a shared_ptr takes ownership of the object for t...
4,494,919
4,495,069
"multiple definition of..." error for a full specialisation of a template function
I have a project with configuration: ./main.cpp ./type_traints/TypeTraints.cpp ./type_traints/TypeTraints.hpp ./type_traints/chapter_20.hpp The ./type_traints/CMakeLists.txt file is: cmake_minimum_required (VERSION 2.8) add_library(chapter_20 TypeTraints.cpp) and the ./CMakeLists.txt follows: cmake_minimum_re...
In short: an explicitly (i.e. fully) specialized template function is no longer a template. It is an ordinary function and it obeys One Definition Rule for ordinary functions. In other words you can't define explicitly specialized function templates in header file. Doing so will result in ODR violations. A template is...
4,495,275
4,495,306
How to check if a mouse is over a control
How does one check if the mouse is over a certain HWND? I have tried using the WM_MOUSELEAVE and WM_MOUSEMOVE messages to keep track, but if you click a button and drag the mouse out of the button, it doesn't receive the WM_MOUSELEAVE until the mouse is released, which is too late, because: When you click a button, t...
To duplicate this functionality, just call SetCapture() so that mouse messages are sent to your window even if the mouse leaves it. You can read the current mouse position as it moves and determine if it is still over your window/button (I'm still not 100% sure what you are doing). And, when the mouse button is release...
4,495,409
4,495,440
C++ -- Win32 API, GUI stuff
I've been messing with Win32 API for abit, and I've got a question regarding the GUI functions. How does one handle user input that is not managed through popup windows? I've been reading http://www.winprog.org/ but right when the interesting features comes -- lesson9 -- it becomes more abstract and I'm not sure how to...
You're correct, you want and EDIT control which is more commonly known as a TextBox and a BUTTON class which is a command button. To get the the input the Button will send a WM_COMMAND message to its parent window with a BN_CLICKED in the wParam high word. You can identify the particular button from the hWnd you get in...
4,495,481
4,495,502
How to print the #define statement?
How can I get cerr to print 5 < 6 as opposed to statement_? I have access to Boost and Qt. using namespace std; #define some_func( statement_ ) \ if( ! statement_ ) \ { \ throw runtime_error( "statement_" ); \ } ...
You need to use the stringize operator: throw runtime_error(# statement_); If statement_ may be a macro, you'll want to use the double stringize trick.
4,495,509
4,495,814
Static Control Background Color with C++
I am creating a basic GUI with the Windows API and I have run into an issue. It starts with a main window that opens with a custom background color I set (RGB(230,230,230)). It then displays text in the upper left corner with the static control. settingstext = CreateWindow("STATIC", "SETT...
For static text controls there's no permanent way to set the text color or their background. Even if you want to apply the changes to a single static control; you would still have to handle WM_CTLCOLORSTATIC notification message in parent dlgproc just when the control is about to be drawn. This is due to the DefWindowP...
4,495,733
4,495,783
Why did boost regex run out of stack space?
#include <boost/regex.hpp> #include <string> #include <iostream> using namespace boost; static const regex regexp( "std::vector<" "(std::map<" "(std::pair<((\\w+)(::)?)+, (\\w+)>,?)+" ">,?)+" ">"); std::string errorMsg = "std::vector<" "std::map<" ...
((\\w+)(::)?)+ is one of the so called "pathological" regular expressions -- it's going to take exponential time, because you have two expressions which are dependent upon each other one right after the other. That is, it fails due to catastrophic backtracking. Consider if we follow the example of the link, and reduce ...
4,495,933
4,498,204
How to use the Meego touch theme
I'm new to QT and Meego. I would like to know how to make use of Meego touch theme. I have already cloned the source for it from git://gitorious.org/meego-handset-ux/meegotouch-theme-meego.git . I don't see anything helpful though on how to use it. Can somebody give me a jumpstart or at least tell me how to make use...
The MeeGo themes are used by the MeeGoTouch library (which is built on-top of the QGraphicsView/Scene framework), see at http://meego.gitorious.org/meegotouch/libmeegotouch The latest API docs for the whole stuff are at: http://apidocs.meego.com/git-tip/mtf/ Styling specifics e.g. at http://apidocs.meego.com/git-tip/mt...
4,495,970
4,495,981
Why is the size of this struct 32?
This is the struct. //Structure pour communiquer les paramètres de traitement à travers le MMF struct params_traitement_mmf { int brilliance; double contraste; char convolution[9]; }; This is my code to display the size of this struct : char valeur[10]; sprintf(valeur, "%d", sizeof(params_traitemen...
What packing? And compiled for what platform? Alignment requirement differ between x86, AMD64 and IA64. And packing can wreak havoc in a struct size. Assuming default packing (8) and AMD64 target (or x86, wouldn't differ) you have 8 bytes for the brilliance (4 bytes size, 4 bytes wasted), 8 bytes for contraste and then...
4,495,990
4,496,056
How to implement a memory heap
Wasn't exactly sure how to phrase the title, but the question is: I've heard of programmers allocating a large section of contiguous memory at the start of a program and then dealing it out as necessary. This is, in contrast to simply going to the OS every time memory is needed. I've heard that this would be faster bec...
Most C and C++ compilers already provide a heap memory-manager as part of the standard library, so you don't need to do anything at all in order to avoid hitting the OS with every request. If you want to improve performance, there are a number of improved allocators around that you can simply link with and go. e.g. Ho...
4,496,002
4,496,049
O(n) algorithm to find out the element appearing more than n/2 times
I was asked in an interview to give an O(n) algorithm to print an element that appears more than n/2 times in an array, if there is such an element. n is the size of the array. I don't have any clue on how to do this. Can anyone help?
It's the Boyer's Voting algorithm. It's also O(1) in space!. Edit For those complaining about the site color scheme (like me) ... here is the original paper.
4,496,004
4,496,051
C++: Array with custom size in class
I want to do this: class Graphic { int *array; Graphic( int size ) { int temp_array[size]; array = temp_array; glGenTextures( size, array ); } } Will this work? And even if it will, is there a better way to do this? Thanks.
Using new means you have to remember to delete [] it; using compiler-dependent variable-size arrays means you lose portability. It's much better to use a vector. #include <vector> class Graphic { std::vector<int> array; Graphic( int size ) { array.resize(size); glGenTextures( size, &array...
4,496,061
4,496,243
is there a function in dlg class as getdocument()?
I want to get a doc* in dlg class, and i know in view class we can get doc* like doc* pdc=getdocument(); But how can i do it in dlg class?
MFC's CDialog class does not have built-in CDocument's. You can implement a CFormView that is derived from CView (which are part of the Document/View architecture of MFC), but CFormView is not a dialog. However, CFormView's can hold controls like a dialog - you can actually assign a dialog template to a CFormView.
4,496,411
4,496,422
C++: how to build my own utility library?
I am starting to be proficient enough with C++ so that I can write my own C++ based scripts (to replace bash and PHP scripts I used to write before). I find that I am starting to have a very small collection of utility functions and sub-routines that I'd like to use in several, otherwise unrelated C++ scripts. I kn...
"Shared objects for the object disoriented!" "Dissecting shared libraries"
4,496,423
4,496,478
memory alignment issues with union
Is there guarantee, that memory for this object will be properly aligned if we create object of this type in stack? union my_union { int value; char bytes[4]; }; If we create char bytes[4] in stack and then try to cast it to integer there might be alignment problem. We can avoid that problem by creating it in heap...
Well, that depends on what you mean. If you mean: Will both the int and char[4] members of the union be properly aligned so that I may use them independently of each other? Then yes. If you mean: Will the int and char[4] members be guaranteed to be aligned to take up the same amount of space, so that I may access in...
4,496,440
4,496,549
Multiple-File Template Implementation
With normal functions, the declaration and definition are often separated across multiple files like so: // Foo.h namespace Foo { void Bar(); } . // Foo.cpp #include "Foo.h" void Foo::Bar() { cout << "Inside function." << endl; } It is my understanding that this cannot be done with templates. The declarat...
Template code stays in the .hh file. There's no reason to make them separate files, though it is good practice to put the definitions after all the declarations. When the compiler generates template code, it flags it so that the linker knows that the instantiation of a template in one compilation unit (i.e. .o file) i...
4,496,633
4,496,737
accessing nested container members
I am trying to create a 2d array using nested containers. I want to print its members. Can anyone help me please.I am new to stl. Thanx in advance. typedef vector<int> v; vector<v>v1; v1.push_back(v(45,67)); v1.push_back(v(36,89)); v1.push_back(v(27,81)); v1.push_back(v(18,78));
You print the elements like this: for(size_t i = 0, mi = v1.size(); i < mi; i++) { for(size_t j = 0, mj = v1[i].size(); j < mj; j++) cout << v1[i][j] << ' '; cout << '\n'; } Then you'll see that you actually created an array that contains: {67,67,67,...,67}, // 45 times {89,89,89,...,89}, // 36 times {...
4,496,822
4,496,850
C++ How to draw letter same size
I'm working on my edit box that I'm creating. I need to find a font that draw letter at same size. I'm using directx
I'm guessing that by "find a font that draw letter at same size" you mean a font where all of the letters are the same size. This is called a Monospaced or Fixed Width Font. There should be several on most systems, the one that you should be able to count on always existing on Windows systems is "Courier New".
4,496,842
4,496,911
pass method with template arguments to a macro
I am unable to use Google Test's ASSERT_THROW() macro in combination with multiple template arguments. Consider that I want to make sure that construction of Matrix<5,1> throws: ASSERT_THROW(Matrix<5,1>(), std::runtime_error); (this example doesn't make a lot of sense, of course this shoud not throw, but it is what st...
the problem is the extra comma, you will need to protect it from the macro. Try ASSERT_THROW((Matrix<5,1>()), std::runtime_error);
4,497,031
4,501,039
c++ create text fits edit box
Well.. I know that title is not that clear, I couldn't think of better one. I wanna know how to do this... when you have edit box and it only can show 10 characters. Something like this ssssssssss let just say i have more than 10 characters. Some of them will go in the back. Like we have this string "123456789010" ...
You can calculate the display-length of the string in your control (there are several function for that) and adjust the size of the control accordingly.
4,497,083
4,497,161
overwrite in the middle of a File
The Problem is I am in the Middle of a File with fseek Next exists some Bytes of Length m that I want to replace with Bytes of length n. simple write will keep m-n bytes still there. If m > n and if m < n some Bytes (n-m) that I am not willing to change will be overwritten. I just want to replace a known startPos to en...
The most robust solution is to re-write the whole file, from scratch. Most operating systems will only let you overwrite bytes, not insert or remove them, from a file, so to accomplish that, you have to essentially copy the file, replacing the target bytes during the copy.
4,497,112
4,498,624
What is the merit of the "function" type (not "pointer to function")
Reading the C++ Standard, i see that there are "function" types and "pointer to function" types: typedef int func(int); // function typedef int (*pfunc)(int); // pointer to function typedef func* pfunc; // same as above I have never seen the function types used outside of examples (or maybe i didn't recogniz...
An example of why this is useful is boost, where you see this a lot. For example in the signals2 library: boost::signals2::signal<void (int, int)> MySignal; where the above declares a signal that will accept any function that takes two ints and has a void return type.
4,497,504
4,498,024
Ways to make it easier to work with shared pointers in C++
I am busy designing a new C++ application. In this application I want to minimize potential errors with pointers, and since the application should be plain C++ (no .Net or other fancy things), I am investigating shared pointers and I am considering using shared pointers everywhere (instead of normal pointers). I worke...
DON'T! The only way to minimize pointer errors is to use the right pointer types. And that's types, plural. Shared pointers are not a silver bullet. They become memory leaks as soon when you have cyclical references (and if plan to use them everywhere, those will show up pretty quickly) If you want error-free C++ appl...
4,497,896
4,497,960
Should you correct compiler warnings about type conversions using explicit typecasts?
In my current project, the compiler shows hundreds of warnings about type conversions. There is a lot of code like this iVar = fVar1*fVar2/fVar3; // or even iVar = fVar1*fVar2/fVar3+.5f; which intentionally assign float values to int. Of course, I could fix these warnings using iVar = (int)(...); but that looks kind ...
Yes. You should always fix the compiler warnings. Several reasons: *) It may be the cause of an error and need an actual fix rather than just a cast. You won't know until you look. *) Actual coding errors that manifest as warnings can get lost in the noise generated by hundreds of warnings *) It makes it clear to other...
4,497,908
4,497,947
Is there a difference between int(floatvar) and (int)floatvar?
Possible Duplicate: C++: What's the difference between function(myVar) and (function)myVar ? I have seen and used both variants of these typecasts: int(floatvar) (int)floatvar Is there any difference between the two? Are there any preferences about when to use which?
There is no difference between them. (int)floatvar is C way of doing the cast where as int(floatvar) is the C++ way (Although it is better to be explicit and use static_cast<>).
4,498,159
4,498,882
Packaging Linux software while keeping a sane file structure
So I have created a piece of software which I wanna package and post to Arch Linux User Repositories, AUR, -should note, that I have never packaged anything for any distro before - and I have also got it packaged and installed on my own machine via Arch's package manager Pacman successfully, but now I am wondering how ...
Very often you find in tarballs a directory called 'debian' which has the debian specific files in it. I would go the same route and create a directory 'archlinux' and put the files there. Then I would go on and put a file README in the archlinux directory that explains how to use the PKGBUILD properly. One solution co...
4,498,223
4,498,244
get %APPDATA% path using c++
I want to get the path to the %APPDATA% folder. In win 2000 & xp it's in: C:\Documents and Settings\user name\Application Data In vista & win7 it's in: C:\Users\user name\AppData\Roaming I know there is the function SHGetSpecialFolderPath but it retrieves a BOOL and I want to get the path as a string.
The third parameter of SHGetSpecialFolderPath(), named lpszPath, is marked as __out. Something like this should do: // Beware, brain-compiled code ahead! wchar_t buffer[MAX_PATH]; BOOL result = SHGetSpecialFolderPath( hWnd , buffer , CSIDL_LOCAL_...
4,498,365
4,498,388
expected `;' before "pennies"? C++ Debugging (Code Completed)
Can anyone tell me why I get an error on my last cout? #include <iostream> #include <cmath> #include <stdio.h> #include <cstring> #include <conio.h> using namespace std; inline void keep_window_open() { char ch; cin>>ch; } int main() { cout << "How many pennies do you have?\n"; int pennies; cin >> pennies; double...
Add more <<: cout << saying << pennies << penn << "\n" << saying << nickles << five << "\n" << saying << dimes << ten << "\n" << saying << quarters << twentyfive << "\n" << saying << half_dollars << fifty << "\n"; EDIT: Also, you are declaring variables in inner blocks - their names are no longer...
4,498,452
4,498,529
How do I change the exported name decoration for __stdcall in VC++?
This is how I have my export function declared at the moment: extern "C" __declspec(dllexport) Iexport_class* __stdcall GetExported_Class(); When VS2008 compiled the source for this, the dll produced contains this under its export table: _GetExported_Class@0 For compatibility with other compilers I need the above dec...
No. All __stdcall names are decorated this way. I'm amazed that you have some other compiler that won't expect __stdcall exports to be decorated like this. Overriding the linker with .def is pretty much all you can do- unless you want to alter the PE file after production.
4,498,617
4,498,642
recursive return type
I just browsed through Mark Probst's diploma thesis and stumpled over the following code: typedef void* cont(void); for (;;) { cp = (cont*)(*cp)(); } I'm pretty sure the cast should read (cont), not (cont*), because he explains: The function wishing to do a proper tail call returns the address of the function to...
No, typedef void* cont(void); cont defines a function type returning a void *. I think you are confusing it with typedef void (*cont)(void); or typedef void *(*cont)(void);. I don't believe that it's possible to eliminate the need for a cast in this scenario but I'm open to be convinced otherwise.
4,498,712
4,498,793
C++ virtual functions implementation outside the class
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class. Following code gives error: class B { public: virtual void f(); }; void B::f() { std...
You can't add members to a class outside of the class definition. If you want D to have an override for B::f then you have to declare it inside the class definition. Those are the rules. Declaring a member in a base class doesn't automatically give derived classes an identical member. Inheriting from the base gives the...
4,499,071
4,506,017
Native functions throw UnsatisfiedLinkError in custom view, despite working in main activity
For some reason I can only call native functions from my main activity and not any custom views that I've created. Here is an example file (I followed a tutorial, but renamed the classes http://mindtherobot.com/blog/452/android-beginners-ndk-setup-step-by-step/) See the usage of the native function "getNewString". pa...
Your problem is that you are trying to call the native function from a class where it dont belongs to. You defined the following JNI function in your c file: jstring Java_com_example_native_NativeTestActivity_getNewString() This states that the native function when loaded will bind with the method declared as native in...
4,499,074
4,500,712
Help with strange memory behavior. Looking for leaks both in my brain and in my code
I spent the last few days trying to find memory leaks in a program we are developing. First of all, I tried using some leak detectors. After fixing a few issues, they do not find any leaks any more. However, I am also monitoring my application using perfmon.exe. Performance Monitor reports that 'Private Bytes' and 'Wor...
Monitoring the app's memory use with PerfMon or Task Manager is not a valid way of checking for memory leaks. For example, your runtime may just be holding on to extra memory from the OS for pre-allocation purposes or due to fragmentation. The trick, in my experience, is the CRT debug heap. You can request information ...
4,499,080
4,499,192
How to get text from unmanaged application to a c# application?
I have a 3rd party application, which creates several windows of which each has a textbox with text I want. I then want to use that information within my application, so I just need to obtain that information (possible trigger some commands back to it later on by pressing buttons) The 3rd party application is un-manage...
The easiest interop with an unmanaged C++ is via C++/CLI. If there's already a simple C wrapper then P/Invoke will be sufficient.
4,499,095
4,499,386
replace line in a file C++
I'm trying to find a way to replace a line, containing a string, in a file with a new line. If the string is not present in the file, then append it to the file. Can someone give a sample code? EDIT : is there anyway if the line that i need to replace is at the end of the file?
Although I recognize that this is not the smartest way to do it, the following code reads demo.txt line by line and searches for the word cactus to replace it for oranges while writing the output to a secondary file named result.txt. Don't worry, I saved some work for you. Read the comment: #include <iostream> #includ...
4,499,484
7,776,942
Disable aero preview for MDI Window
In windows 7 the taskbar will preview all the mdi childs, any way to disable this with MFC?
Adding a FALSE parameter to the EnableTaskbarInteraction(...) call in the InitInstance method disables displaying MFC MDI child views in the Win7 Taskbar.
4,499,488
4,670,068
Is it possible to set the opacity of qt widgets?
I know that there is a function QWidget::setWindowOpacity(qreal level) but as written in the documentation this does only work for windows. Is there a way to make widgets that are lying inside layouts opaque too? What I'm trying to do is an animation where widgets are fading in. I once did that with a preferences-dialo...
Just use QGraphicsOpacityEffect in order to achieve this effect. Qt4: http://doc.qt.io/qt-4.8/qgraphicsopacityeffect.html Qt5: http://doc.qt.io/qt-5/qgraphicsopacityeffect.html Qt6: https://doc.qt.io/qt-6/qgraphicsopacityeffect.html
4,499,772
4,503,994
Eclipse CDT QT4 auto-complete not working
I cannot get auto-complete to work with Eclipse CDT and QT4. Whatever I try, auto-complete does not work for me! I can create and run QT GUI applications no problem, so the plugin must be installed... I do not know why the auto-complete does not work... For that matter, auto complete does not work at all? What setti...
You just have to setup include paths in the project properties, this will happen automatically if you use a pro file with qmake and let Eclipse import it as a Makefile based project.
4,499,808
4,500,391
How to save/serialize compiled regular expression (std::regex) to a file?
I'm using <regex> from Visal Studio 2010. I understand that when I create regex object then it's compiled. There is no compile method like in other languages and libraries but I thinks that's how it work, am I right? I need to store large amount of this compiled regexes in a file so I would just get chunk of memory blo...
I don't think it can be done without modifying the boost library to support it. I don't know specifically how the boost regex library is implemented, but most regex libraries compile things to a binary blob that's then interpreted later as a series of instructions for a sort of limited virtual machine. If boost's regex...
4,499,924
4,500,285
Making a char function parameter const?
Consider this function declaration: int IndexOf(const char *, char); where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when somethin...
Assuming you don't intend to adjust the value of either parameter: I would have the function definition as: int IndexOf( const char * const , const char ) { //... } But keep the function declaration as: int IndexOf( const char * , char ); In other words: I'd reveal the bare minimum level of const in the header, ...
4,500,007
4,500,042
How to get the number of bytes occupied by a specific string in the program?
Im using BSPlib and I want to use the bsp_put which requires me to set the size of the string I'm sending. Even if you aren't familiar with BSP, this is not closely related. thanks.
strlen returns the length of string of a plain C string. A C string is as long as the amount of characters between the beginning of the string and the terminating null character. If you're using the String object you can use the length or size method of the object: http://www.cplusplus.com/reference/string/string/l...
4,500,137
4,500,295
iPhone Fast App Switching with Objective-C++
I'm using Objective-C/C++ and I have an Objective-C class that is a wrapper for a C++ class, are there any special concerns I need to be aware of in order to use fast app switching? It is my understanding that the iPhone will auto-magically save state for Objective-C objects, but I'm not sure if I need to do any specia...
By fast app switching you mean multitasking? There's nothing additional you need to do - iOS 4 will handle the task suspension and resume transparently, unless you need to perform background tasks, regardless of whether you're using objective c++ or just plain objective c.
4,500,218
4,503,647
subscribing to c# CompositeCommand from c++
In a c# assembly I've got a global prism CompositeCommand to subscribe to like this: private static readonly CompositeCommand __myCommand = new CompositeCommand(); public static CompositeCommand MyCommand { get { return _myCommand; } } From c# I can subscribe to this command using: [...].MyCommand.RegisterCommand(n...
I'm going to assume that you're using managed C++ - anything else, and there's bigger issues to worry about. It looks like you're getting linking errors to your C# type. As such, I don't think the issue is related to any problems with Prism. In order for the C++ managed compiler to link to your C# assembly, you need ...
4,500,312
4,500,338
c++ CopyFile function problem
Hey guys i need to use CopyFile in win 2000 and above platforms. i want to copy my application to a different folder say c:. so this works: BOOL didThisFail = FALSE; if (CopyFile(L"MyApplication.exe", L"something.exe", didThisFail)) cout << "File was copied" << endl; but this dosen't: BOOL didThisFail = ...
GetLastError() will tell you why it failed, probably an access denied error.
4,500,430
4,502,619
Synchronize QGraphicView elements
I have two QGraphicView objects (based on the same derived class). They contain different scenes, but a few (sometimes many) items are the same. Such items have common coordinates. I alternatively display the one or the other, inside the same frame. I have had no trouble doing that. In both graphic views, i have added...
The translation issue is probably the 2 views are not centered to the same point after changing the transformation. By default the anchoring mode is to position the center of the scene to the center of the view after transformation change. Setting transformationAnchor to NoAnchor may help. You also need to make sure th...
4,500,515
4,500,525
C++ pointer to string type segmentation fault
I initialize a pointer to string type and allocate some memory with malloc function. My problem is when i try to use one of the string pointed by this pointer, i get segmentation fault. string anyString = "anyWords"; string *pointerToString; pointerToString = (string *) malloc(sizeof(string) * 5); pointerToString[i] = ...
Avoid using malloc with objects in C++. Instead, use new: std::string * str = new std::string("Hello"); // ... delete str; For an array: std::string * tab = new std::string[5]; // ... delete[] tab; // if you allocated with new[], release with delete[] The reason it's failing in this case is that malloc, unlike new, d...
4,500,516
4,500,579
How to use GetLastError() in VC++ 2010
Making the conversion from Java to c++ isn't easy so help me guys. i want to see if i'm getting an Access_Error violation in this code: BOOL didThisFail = FALSE; if (CopyFile(L"MyApplication.exe", szPath, didThisFail)) cout << "File was copied" << endl;
if (CopyFileW(L"MyApplication.exe", szPath, didThisFail)) { std::cout << "File was copied" << std::endl; } else if (GetLastError() == ERROR_ACCESS_DENIED) { std::cout << "Can't do that." << std::endl; } else { DWORD lastError = GetLastError(); //You have to cache the value of the last error here, becaus...
4,500,794
4,501,024
unit testing for CTRL-C sent to an application
I am developing an application handling CTRL-C. I am producing a signal handler to shut-down gracefully threads and other resources. I want to test CTRL-C in different scenarios where my application might be. I know how to setup those for the process under test, but I need a way (in the code of the running test suite) ...
First testing the behavior when some external signal is received does not look like unit testing but like functional testing. Also, the way you do it also sound too complicated and is likely force some kind of synchronization and hide some behaviors. On the other hand I do not really have something better to suggest ...
4,500,804
4,501,009
Fetching album art, as JPEG, PNG etc
Can anybody tell me if there is any simple Web API which returns album art as an image, just like the Google Static Map API (Google Static Map API? I have heard about Amazon's and Last.fm's APIs for this, but can't find any code for that (other than in web languages like PHP/Perl/Ruby etc). Moreover they are REST APIs....
It shouldn't be very hard to do by hand. The last.fm api spec for Album.getInfo method is pretty straightforward and the fact that it is a REST api makes it even simpler. Just get the xml response from the server, parse it and get a url of the image. I wrote this code a while ago but it should still be working: ...
4,500,928
4,501,138
How to get string with pattern from std::regex in VC++ 2010
Can I get the string with regular expression from std::regex? Or should I save it somewhere else if I want to use it later? In boost you can do this: boost::regex reg("pattern"); string p = reg.str(); or use << operator cout << reg; will print pattern. but in std::regex there is no str() or operator<<. Should I save m...
I just looked in N3225, section 28.4 (header <regex> synopsis) and indeed, the basic_regex template has no member function str, and there are no operator<< provided. The paragraph 28.8/2 provides a little insight on this : Objects of type specialization of basic_regex are responsible for converting the sequence of...
4,501,107
4,501,164
c++ adding two wchar_t vars
windows platform. szPath is pre defined. i want to add szPath2 to it but i don't want to use the PathAppend function because i 'll need to link the Shlwapi library. what should i do? i want to return a wchat_t.. wchar_t szPath[MAX_PATH]; wchar_t szPath2[MAX_PATH] = L"\\project\\MyApplication.exe";
Any reason you aren't using std::wstring? You can also use wcsncat
4,501,657
4,501,718
Reference to a subset of a container object
i have a quick question about having a reference to a subset of a collection. Consider i have a vector of objects. Now I want to create another vector which is a subset of this vector, and I dont want to create a copy of the subset of objects. One of the ways I was thinking about is creating a vector<auto_ptr<MyClass...
No ! See : Why it is wrong to use std::auto_ptr<> with STL containers ? Now, as an alternative, you could store raw pointers or boost::shared_ptr depending on your needs.