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,469,051
6,469,543
A x64-DLL injected into a x64-process hooking a x86-DLL fails using C++ and EasyHook
A x64-DLL injected into a x64-process hooking a x86-DLL fails using C++ and EasyHook. It works if Loader, InjectionLibrary and InjectionTarget(it's available in both versions and i need both to be hooked) are x86. Getting the address of the exported procedure(GetProcAddress itself) isn't a problem at x64. The Injection...
You cannot use a 32-bit DLL in a 64bit process, and indeed, this generalizes- you cannot mix and match x86 and x64 code, a single process is either entirely x64, or entirely x86. That's fundamental to x86-64 and there's nothing you can do about it. In the Windows control console, they make a 64bit process and a 32bit p...
6,469,849
6,469,872
One or more multiply defined symbols found
DebugUtil.h #ifndef DEBUG_UTIL_H #define DEBUG_UTIL_H #include <windows.h> int DebugMessage(const char* message) { const int MAX_CHARS = 1023; static char s_buffer[MAX_CHARS+1]; return 0; } #endif When I try to run this I get this error: Terrain.obj : error LNK2005: "int __cdecl DebugMessage(char co...
Put the definition (body) in a cpp file and leave only the declaration in a h file. Include guards operate only within one translation unit (aka source file), not across all your program. The One Definition Rule of the C++ standard states that there shall appear exactly one definition of each non-inline function that i...
6,469,923
6,475,071
Extending SWIG builtin classes
The -builtin option of SWIG has the advantage of being faster, and of being exempt of a bug with multiple inheritance. The setback is I can't set any attribute on the generated classes or any subclass : -I can extend a python builtin type like list, without hassle, by subclassing it : class Thing(list): pass Thi...
I found a solution quite by accident. I was experimenting with metaclasses, thinking I could manage to override the setattr and getattr functions of the builtin type in the subclass. Doing this I discovered the builtins already have a metaclass (SwigPyObjectType), so my metaclass had to inherit it. And that's it. This ...
6,469,954
6,470,036
Are standard library required to be standard conformant?
Are standard library required to be standard conformant? I've this feeling that standard library aren't standard conformant. The basis of this feeling is the error messages generated by the compiler(s). For example, sometime GCC gives error messages which starts with prefix __gxx and many others which I don't remember ...
Yes, standard libraries must adhere to the standard, but there is quite a bit of flexibility in that. The standard does not require a particular implementation of the functions, and the implementation is free to add internal functions, attributes... as long as the requirements are met. Note that there is a different co...
6,470,074
6,470,272
boost::random and boost:uniform_real works with doubles not with floats?
Pardon me if this has been discussed already. I've got a template function which uses boost::uniform_int and boost::uniform_real depending on the template argument and should return the same type: template <typename N> N getRandom(int min, int max) { timeval t; gettimeofday(&t,NULL); boost::mt19937 seed((int)t.tv...
The arguments 0.0,5.0 are doubles, not floats. Make them floats: float y = getRandom<float>(0.0f,5.0f);
6,470,084
6,471,162
Template format in C++
I came across the following snippet in the implementation of a N-ary tree in a textbook, template <typename Object, int N> From what I understand, a template's main purpose is to provide "generality" to the code so that a particular variable can be of any type, represented via Object i.e if you have template <typena...
In C++, templates can be instantiated on more than just types. They can be instantiated on specific values, if the programmer so desires. In template<int N> class Foo, N is treated as a constant, if you will: instantiate this template and make the constant N have this value. Arrays, for example, should be of fixed-size...
6,471,134
6,471,344
SPOJ question - WHat is going wrong here?
I was answering this spoj question: http://www.spoj.pl/problems/JAVAC/ I coded the submission in C++. I am pasting it below. The submission consistently gives wrong answer. I cannot find a test case for which it will fail. Can anyone help me out ? Thanks very much. #include<iostream> #include<string> #include<algorithm...
I haven't tried it (never used SPOJ), but could it be possible that there are other invalid formats? E.g.: 123asd _asd asd___a I am messing with your code now, see if I can make it works. Good luck! EDIT: Passed! Try add the following: Detect error when first or last letter is '_' Detect if there are consecutive '_'s ...
6,471,370
6,471,402
Looking for a tool to create C-arrays with data from a file
Input: filename.bin Output: char file_filename_data[] = { 0x47, 0x45, 0x54, 0x20, 0x2f, 0x63, 0x61, 0x6d, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x20, 0x48, 0x54, 0x54, 0x50, 0x2f, 0x31, 0x2e, 0x31, 0x0d, 0x0a, 0x48, 0x6f, 0x73, 0x74, 0x3a, 0x20, 0x79, 0x6d, 0x61, 0x70, 0x2e, 0x64, 0x79, 0x6e, 0x64, 0x6e, 0x73, 0x2e, 0x6f,...
xxd is what you're looking for. Example call could be: xxd -i filename.bin data_output.h data_output.h would have the contents of: unsigned char in_file[] = { 0x68, 0x65, 0x6c, 0x6c, 0x6f }; unsigned int in_file_len = 5;
6,471,421
6,471,851
Marshal C++ "char**" in C#
I'm calling C# method from C++ and passing char** as argument. It has to be char** because I need to return value through parameter. C# code: [ExportDll("test", System.Runtime.InteropServices.CallingConvention.StdCall)] public static int test([MarshalAs(UnmanagedType.AnsiBStr)] ref string p) { Console.WriteLine(p)...
You declare ref UnmanagedType.AnsiBStr but you expect a char**. This cannot work, since a ref to a BSTR is not a char**. See Default Marshaling for Strings for examples of marshaling declarations. These are possible declarations for an input-output string: PassStringRef2([in, out] BSTR *s); PassStringRef3([in, out] LPS...
6,471,556
6,474,464
Avoiding label indenting in C++
I guess this was asked before, but I could not find any similar question. When writing part of the scope operator in C++, Vim guesses that it's going to be a label (on the first :) and then indents it automatically, which is pretty annoying. Example: #1 - initial typing { std #2 - added : { std: #3 - added : { ...
Just tell vim not to de-indent labels with: :set cinoptions+=L0 For reference, if by "visibility" modifiers you mean access specifiers, these can be set to not indent with: :set cinoptions+=g0
6,471,623
6,471,659
C++ Downcasting to Derived Class based off Variable
Suppose I have a base class "Shape", and derived classes "Triangle", "Square", and "Circle". A member of "Shape" is an int "shapeType". If shapeType==1, then it's a triangle. If shapeType==2, then it's a square. If shapeType==3, then it's a circle. I'm interested in knowing given I have just a "Shape" object that was ...
If they've virtual functions, then use dynamic_cast: t = dynamic_cast<Triangle*>(shape); if ( t ) { //use t } But take a note: you should try defining the classes and virtual functions in such a way that you would hardly need to use dynamic_cast. Prefer well-defined interface, and polymorphism, in general. Here ...
6,471,712
6,472,395
WIN32: How Do I Tell an Owner Drawn Static Control to Refresh Itself?
I have a WIN32 owner-drawn static control that draws a progress bar using two source images (filled and unfilled). Works great on the initial draw: case WM_DRAWITEM: { DRAWITEMSTRUCT* draw = (DRAWITEMSTRUCT*)lparam; // Manually draw the progress bar. if( draw->hwndItem == hwndProgress ) ...
You aren't deselecting the bitmaps from the memory DC before you destroy the DC. Perhaps the bitmaps are in a state where Windows won't allow you to select them again, so the BitBlts are failing. P.S. RedrawWindow is what I use in this situation. InvalidateRect works too, but only if your message loop is running. Which...
6,471,765
6,471,863
Good C++ GUI library for FL SDK & VST
What is the best C++ GUI library that can be used in VST and especially in FL SDK (FL Studio SDK). Library that I searching for should not demand a central application object like for example QT does. It must just provide a pure GUI support. I've tested VST GUI, so what else library can I pick?
Have you checked out Juce, it might be helpful. You can also, check: IPlug - An open C++ platform independent framework for VST and AU audio plugins and GUIs & Plugin Developer - A resource for VST plugin development, that seems to focus on the IPlug framework.
6,471,826
6,471,915
Checking if my const variable has not been modified externally
My question now is if I've declared a constant using const, I read that it's possible for it to be modified externally (maybe by a device connected to the system). I want to know if it's possible to check if my constant has been modified or not. Naturally, I would try something like this: const double PI = 3.1412 ...
First of all, why won't your example compile? If you couldn't compare constants, they would be kind of useless. I would classify this as a waste of time. If something external to your program is modifying your memory, then what's to stop it from also modifying the memory you store your comparison at? In your example...
6,471,946
6,471,984
Verifying variable arguments are of expected type
I'm currently writing a function which will take a variable number of arguments. I pass the number of arguments into the function and then will iterate through the arguments list. Each of the passed arguments should be an integer. I will be adding this integer to a vector of integers which will be used later. I would l...
There is no sensible way you can do this. Variable-argument functions work by concatenating all the raw binary representations of the arguments into one big chunk of data on the stack. So it relies on both the caller and the callee agreeing on what the number and type of arguments are (otherwise you'll end up reading...
6,472,743
6,472,793
What does "use of class template requires template argument list" mean?
I am a newbie to templates so please excuse me for naive questions. I'm getting errors in this code: template <class t> class a{ public: int i; a(t& ii):i(ii){} }; int main() { a *a1(new a(3)); cout<<a1.i; _getch(); } Compile errors: 'a' : use of class template requires template argument list '...
a(t& ii):i(ii){} This should be : a(const t& ii):i(ii){} So that you can pass const literals, and temporaries to the constructor. And then do this: a<int> *a1(new a<int>(3)); You can also write: a<int> a2(3);
6,472,948
6,472,989
Converting Member Function Pointer to TIMERPROC
How do I convert a member function pointer to the TIMERPROC type for use with the WINAPI SetTimer? The code snippet below shows how I'm doing it now, but when I compile I get this error: error C2664: 'SetTimer' : cannot convert parameter 4 from 'void (__stdcall CBuildAndSend::* )(HWND,UINT,UINT_PTR,DWORD)' to 'TIMERP...
Member-function and TIMEPROC are not compatible types. You need to make the member function static. Then it will work, assuming parameter-list is same in both, static member function and TIMEPROC. class CMyClass { public: //modified void (CALLBACK *TimerCbfn)(HWND hwnd, UINT uMsg, UINT_PTR idEvent, DWORD dwTim...
6,472,968
6,473,079
new object causes corruption on the heap
I've been struggling with a heap corruption problem for a few days. I was first warned by the vs 2005 debugger that I may have corrupted the heap, after deleting an object I had previously new'ed. Doing research on this problem led me to gflags and the page heap setting. After enabling this setting for my particular...
Unfortunately, with the information given, it's not possible to definitively diagnose the problem. Some things you may want to check: Make sure BusinessLogicUnit has a virtual destructor. When deleteing objects through a base pointer, a virtual destructor must be present in the base class for the subclass to be proper...
6,473,218
6,473,250
What differences, if any, between C++03 and C++11 can be detected at run-time?
It is possible to write a function, which, when compiled with a C compiler will return 0, and when compiled with a C++ compiler, will return 1 (the trivial sulution with #ifdef __cplusplus is not interesting). For example: int isCPP() { return sizeof(char) == sizeof 'c'; } Of course, the above will work only if ...
Core Language Accessing an enumerator using ::: template<int> struct int_ { }; template<typename T> bool isCpp0xImpl(int_<T::X>*) { return true; } template<typename T> bool isCpp0xImpl(...) { return false; } enum A { X }; bool isCpp0x() { return isCpp0xImpl<A>(0); } You can also abuse the new keywords struct a { }...
6,473,391
6,473,424
Using UNIX sockets, how to wait for data while being able to send data?
I have a server in C++ using UNIX sockets that currently blocks on read() calls from a single client. I'd like to be able to extend the server so that I could write some data to the socket while still being able to read from the socket? Is a thread library like Boost.Thread the best way to accomplish this, or is there ...
You have lots of options. At least four: Use select (/poll/epoll/kqueue) Use separate threads for reading / writing (pthreads / Boost.Thread) Use asio Use asynchronous IO (for example libaio) The easiest is the one you know :). So for me asio would be nightmarish and epoll would be piece of cake. Your mileage may var...
6,473,438
6,473,499
Measure time elapsed in C++
Possible Duplicate: fast elapsed time on linux How can I measure how long a function takes to execute in C++? It would be best if I could get the time to a fraction of a millisecond, but if not accuracy to one millisecond should be good enough. I'm running Ubuntu 11.04 if that means anything.
#include <ctime> int main(){ clock_t start = clock(); // your program goes here clock_t ends = clock(); cout << "Time elapsed: " << (double) (ends - start) / CLOCKS_PER_SEC << endl; return 0; }
6,473,524
6,473,948
for_each C++ Problem
I'm confused about the for each loop in C++. I have this code in a main game loop: for each (Bubble b in bubbles){ b.Update(); } for each (Bubble b in bubbles){ b.Draw(); } It doesn't update anything, but does draw 1 bubble.. What's wrong with it? EDIT: This code works struct BubbleUpdater { void operator()(...
Change your BubbleUpdater class to accept it's argument by reference struct BubbleUpdater { void operator()(Bubble & b) { b.Update(); } } updater; With that, your call to std::for_each should work. If your compiler supports it (and VC10 does), then you can use lambdas instead of creating a distant function object clas...
6,473,552
6,473,692
A way around Qt apps size
A Qt app with the networking library and the GUI library gets to about 10MB; that is, without code. For people with Internet connection like mine, that is a bit inconvenient; specially when it comes to a program that is rarely used (i.e. used once and then left.) I tried to use LZMA and LZMA2 compressions to compress t...
You could try statically linking; this may be able to discard unused code from the library. Please note, however, that this may impact your obligations under Qt's open source licenses; distributing a closed-source (generally, non-LGPL) application statically linked against a LGPL-licensed library brings with it additi...
6,473,588
6,474,419
Serialize in C# (protobuf-net) , Deserialize in C++ (protobuf) : More than 5 fields in class
I'm having trouble deserializing an object in C++ that I had serialized in C# and then sent over the network with ZMQ. I'm fairly certain the ZMQ part is working correctly because the C++ server application (Linux) successfully receives the serialized messages from C# (Windows) and sends them back to Windows where it c...
I've parsed it through the reader in v2, and it seems to make perfect sense: 1=5 2=0 3= 4=yo 5=6 6=2 bytes, 68-69 7=how 8=are 9=you 10=sir Note that I've done that purely from the hex data (not using the .proto), but it should be close to your original data. But most notably, it seems intact. So: first thing to do; ch...
6,473,926
6,473,964
Building generic overloaded operator<<
How can we make a generic overloaded operator<< ? I wrote this code but clearly it has errors - missing type specifier - int assumed. Note: C++ does not support default-int. class b{ private: int i; public: b(){} b(const int& ii):i(ii){} friend ostream& operator<<(ostream& o,const t& obj);//Error here...
Put template<class t> into the friend declaration as well. I wouldn't design operator<< this way, however - why would it need access to private members? Better add a getter for i to both a and b and avoid the socializing stuff altogether. Edit In the given code the friend declarations would not even be required as i is...
6,474,039
6,474,067
What linux distribution should I virtualize from windows host to run Eclipse?
I need to use Eclipse on a Linux Virtual Box virtualization, Windows XP host, on a laptop. I don't know the specs of that laptop, but it's less than 2 years old. My first choice of Linux distribution is Ubuntu, but I've heard that in Ubuntu, Eclipse is can be bugged or slow. I don't mind if it's slow. I only need to kn...
Eclipse runs on Java. Any linux distro (apart from command line ones) will do. If you like Ubuntu go with it!
6,474,094
6,474,405
Ownerdrawn tray icon (winapi)?
Is it possible to make an ownerdrawn tray icon using winapi ? ( c++ non-mfc.) For now im using server generated png -> ico -> tray but this is ugly and slow ......
You could just dynamically create the HICON, no? Build up the image that you want (or convert from jpg/bmp/png) as a DIB and convert to an HICON. Use your created icon to send to Shell_NotifyIcon(). Old reference, but it should get you started. Icons in Win32.
6,474,158
6,474,182
Why is std::string incompatible with C unions?
Possible Duplicate: Why compiler doesn't allow std::string inside union ? I knew that I had this problem when I started with C++: The compiler wouldn't allow me to put a variable of the type std::string into unions. That was years ago, but actually I still don't know the exact answer. I read something related to a c...
From Wikipedia: C++ does not allow for a data member to be any type that has a full fledged constructor/destructor and/or copy constructor, or a non-trivial copy assignment operator. In particular, it is impossible to have the standard C++ string as a member of a union. Think about it this way: If you have a u...
6,474,211
6,474,708
How to set up a notification system in a game
I'm working on a 3D learning-based game which mainly utilizes C++ and Javascript. I'm trying to design a notification system for when the player has information sent to their notebook. I had a system set up, but the supervisor thinks it can be made better. This is where I need y'alls help! The very basic way it went: T...
Algorithm Improvements Don't use a static flag. Create an id system so that you can uniquely target a notification. In C++ you could keep track of a variable that auto-increments whenever you make a new notification. The id could be #notification_# where # is the id you want. Then your notify function will send the...
6,474,261
6,474,636
C++ Binding an Index to One Data Structure
Suppose I have two containers of elements: std::vector<std::string> foo = { "aa", "bb", "cc" }; std::vector<std::string> bar = { "dd", "ee" }; I pass around indecies into foo and bar between many classes that operate on these two containers. However, I find that I have to be very careful not to confuse which indecies ...
There isn't really a design pattern for differentiating what an index indexes into. There are some conventions. You could use typedefs to differentiate them. That is, typedef an int to be a FooIndex, and similarly for a BarIndex. You could also use a bit of Hungarian notation for the names (I know people hate that, but...
6,474,316
6,474,426
When should I worry about alignment?
I've learned a little about alignment recently but I am not certain in which situations it will be an issue or not. There are two cases that I wonder about: The first one is when using arrays: struct Foo { char data[3]; // size is 3, my arch is 64-bit (8 bytes) }; Foo array[4]; // total memory is 3 * 4 = 12 bytes....
struct Foo { char data[3]; // size is 3, my arch is 64-bit (8 bytes) }; Padding is allowed here, in the struct after the data member--but not before it, and not between the elements of data. Foo array[4]; // total memory is 3 * 4 = 12 bytes. No padding is allowed between elements in the array here. Arrays are re...
6,474,480
6,474,525
Link Error when using inline math library in combination with precompiled header file
I came about a rather weird problem today. I have a math library optimized for SSE, therefore almost all functionality is declared as inline. For simplification purposes I will only explain the problem using one class, Vector3: Vector3 is declared in Vector3.h, something like this: #ifndef VIRTUS_VECTOR3_H #define VIRT...
Each of the definitions inside vector3.inl needs to be explicitly defined with inline.
6,474,675
6,474,685
Why cant i use two ptrs in operator overload?
This is annoying, i can write a function with these parameters/return, but why cant i define an operator to do this? -edit- i am actually trying to overload << the below is just for reference. From msdn // C2803.cpp // compile with: /c class A{}; bool operator< (const A *left, const A *right); // C2803 // try the fol...
Because every user-defined operator overload needs at least one user-defined type as a parameter. A point isn't a user-defined type. C++03 standard, §13.5 [over.oper] p6: An operator function shall either be a non-static member function or be a non-member function and have at least one parameter whose type is a class,...
6,474,698
6,475,307
How does someone use thirdparty libraries to be included in Firefox addons/extensions?
I am currently learning how to create Firefox addons using XPCOM and I want to know how to include thirdparty libraries to develop them. I followed a few tutorials to compile .xpt and .dll from c++ files (noted in: https://developer.mozilla.org/en/How_to_build_a_binary_XPCOM_component_using_Visual_Studio and http://ner...
The tutorial you refer to is about developing applications, not extensions. So application.ini doesn't apply in your case. Extensions have a manifest file called chrome.manifest, starting with Firefox 4 all XPCOM components and XPT files need to be registered there - or they will be ignored. It no longer matters where ...
6,474,756
6,474,774
where to put using namespace std;
I'm wondering where to put using namespace std;. I saw a code with the using namespace std; in the int main(){} but I was putting it after #include <iostream>. Where should I put it and does it make any difference where I put it?
It makes a huge difference where you put it. If you put it inside a function, then it only applies in that function. If you put it outside a function in global scope then it applies to everything after that point. If you put it outside a function in global scope in a header file then it will even apply to ever file tha...
6,474,833
6,474,924
C++ Problem: Class Promotion using derived class
I have a class for Float32 that is derived from Float32_base class Float32_base { public: // Constructors Float32_base(float x) : value(x) {}; Float32_base(void) : value(0) {}; operator float32(void) {return value;}; Float32_base operator =(float x) {value = x; retu...
You can use CRTP if you only need one-level deep inheritance: template <typename T> struct A { T operator+ (const A&) { return T (); } }; struct B : A <B> { void lol () { } }; int main () { B a, b; (a + b).lol (); }
6,475,020
6,475,587
Actionscript library on c++
I'm looking for Actionscript library, written on c++, that contain Actionscrimp classs , like video , camera , netconnection , netstream and so on... Someone can help me with this?
You could try using openFrameworks: http://www.openframeworks.cc/
6,475,122
6,475,230
Intellisense on C++ (Visual Studio 2010)
Well, i've reinstalled Visual Studio 2010 (trial, from Microsoft site) but i'm noticing that Intellisense doesn't work. I've done this: The thing of "No common language RunTime Support" "Autolist Members" and "Parameter information" But still i only get: Intellisense: 'No additional available information' It's a not pr...
No common language RunTime Support This means you are not programming in C++. You're writing in C++/CLI instead. They are quite different languages; C++/CLI is more in character with C#. Visual Studio 2010 does not support Intellisense in C++/CLI projects. You need to use a native project, or live without Intellisens...
6,475,536
6,481,167
Select every even (or odd) argument in template parameter pack
I would like to allow use of the class I'm writing to specify as a template parameters a list of types along with a list of allocators of those types in a manner that types are at odd positions and allocators are at even ones: template<typename... T> class MyClass { // Stuff inside } int main() { MyClass<SomeType1...
Though the code got a little lengthy, I suppose the mechanism doesn't have unnecessary peculiarities. If I understand the question correctly, probably the following code will meet the purpose: // push front for tuple template< class, class > struct PFT; template< class A, class... T > struct PFT< A, tuple< T... > > { ...
6,475,571
6,475,580
VC++ Template Compiler Error C2244: Unable to Match Function Definition to an Existing Declaration
I've encountered a compiler error using Visual Studio 2010 which I've reduced down to the following code: template <int i> struct A { typedef int T; }; template<int i> struct B { static const int i = i; // <-- this seems to cause the problem typename A<i>::T F(); }; template<int i> typename A<i>::T B<i>:...
The problem is you are declaring the same name twice in the same scope. If you rename the static const int i, or the template parameter it should work.
6,475,588
6,475,672
Is it safe to declare a mutex as a static file-scoped variable?
According to http://msdn.microsoft.com/en-us/library/ms687032%28v=vs.85%29.aspx, WaitForSingleObject() has undefined behavior if a handle gets closed while waiting on it. Because we can't tell the order by which static variables are disposed, is it safe to declare a mutex as a static variable with file scope? namespace...
I would be very leery about calling any Win32 API function at namespace scope. Also, since you have to release it in your function anyway, why not allocate it there too? It's much more symmetrical that way.
6,475,596
6,475,661
C++ reading data from a file
Disclaimer: this question is directly related to my programming homework. My C++ assignment consists of opening a .txt file, performing a bunch of operations on it, and then saving the .txt file. Problem is, I'm having a hard time just grasping the basic concepts of reading and writing files. My code: #include <iostre...
You don't open a file for reading and writing at the same time. Well, not with two different objects that don't know about each other at any rate. You either use a std::fstream (which can do simultaneous reading and writing), or you read first, close the file, process the data, then write it. Also: //have to use char ...
6,475,629
6,475,642
forwarding an entire class with an operator
I am wondering. I hit a problem and here is a small repoduce. Essentially i want to forward everything. The problem is, using the first << will cause an error with o<<1 (or o<<SomeUserStruct(). If i include the second i get errors about it being ambiguous. Is there a way i can write this code so it will use T& when it ...
template<typename T> FowardIt& operator<<(const T&t) //^^^^^ put const here Make the parameter const reference, as shown above. Because temporaries cannot be bound to non-const reference. You don't need to define another function. Just make the parameter const, the problem will ...
6,475,799
6,476,044
Making Win32 Application work on ANSI & UNICODE
I want to make my Win32 C++ application able to be played on any encoding version (UNICODE & ANSI). Now I am a little confused as to what exactly is the difference between the two(or more?) encodings? To make my Win32 application cross-encoding compatible does that mean I have to go through my code & replace every std:...
What will happen if my application runs on a UNICODE machine & my application has one std::string in it? Computers are not ANSI or Unicode but the Operating Systems on which the computers operate on are. The last version of Windows that didn't support Unicode was Windows 3.11 for Workgroups. If you run a ASCII compile...
6,475,918
6,477,625
Debugging symbols present, but eclipse does not associate them with source code
I am working on modifying a rather large program (NS2 network simulator), and it would be nice to be able to debug it with Eclipse. I configured the makefiles ( add -g to CFLAGS ) to make gcc generate the debugging symbols, and they are indeed generated, but Eclipse refuses to actually find the code associated with tho...
Just tested it. Works for me. The only issue was that I forgot to add -O0 option to disable optimization; it can be an issue in your case too. What I can suggest: Try to disable optimization Check that compiler options you use are really applied. You use CFLAGS, but I see c++ in tags, so it is possible that you should...
6,476,283
6,476,483
Array : Largest possible number
Given an array of elements find the largest possible number that can be formed by using the elements of the array. eg: 10 9 ans: 910 2 3 5 78 ans: 78532 100 9 ans: 9100 I know this problem has a solution using customized string comparator but i dont understand how it really works. #include <iostream> #include...
Indeed, if we have two strings S and T, we will most commonly concatenate them in lexicographically reverse order, to make the biggest digits come forward. However, this approach doesn't perfectly work, when one of these strings is a prefix for the other one. Let T = SA, i.e. S is a prefix of T. We have two choices of...
6,476,323
6,476,334
c++ math/hex question
Sorry if this sounds a bit 'noobish' but I don't know c++ and I was looking at some code for the perlin noise, trying to figure it out when I came across & 0x7fffffff and (n << 13) ^ n; and I have no idea what those mean. I do know that 0x7fffffff is hex, but I don't know what the & means Any help?
The first expression is a bitmask. It basically clears out the upper bit of the number, or equivalently computes a mod of the number over 2^31. The second expression is a shift, followed by an xor. In arithmetic it would be the same thing as multiplying n by 2^13, then flipping all the bits that are common between th...
6,476,392
6,476,510
Qt - QTcpserver is not working properly
I am doing a simple server-client application. But, the client gets some undefined behaviour from the server side. After I retrieved the error code, I came to know that the server cut the connection. This is server-side main.cpp #include <QApplication> #include <QFile> #include <QFileDialog> #include <QMessageBox> #in...
The connection is getting closed because your server is exiting right after it's sent that message. This is probably because you're using QApplication, but don't actually have a long-lasting GUI widget. So the event loop stops short once you've finished displaying that first dialog box. Try either: using QCoreApplicat...
6,476,470
6,476,495
Convert this pointer to boost::shared_ptr?
I am having a base class and i want to convert its this pointer to its derived class shared_ptr. I can`t use inheriting enable_shared_from_this in my case. So is there any other efficient way around? eg typedef boost::shared_ptr <a> aPtr; typedef boost::shared_ptr <b> bPtr; Class a{ void fun(); } class b : pub...
You need boost::enable_shared_from_this. See the documentation: class Y: public boost::enable_shared_from_this<Y> { public: boost::shared_ptr<Y> f() { return shared_from_this(); } } int main() { boost::shared_ptr<Y> p(new Y); boost::shared_ptr<Y> q = p->f(); assert(p == q); assert(...
6,476,491
6,476,523
Which output method shoud I use for logging system?
I am working on a server programming on linux machine using epoll. I am printing log statements using printf(), but I was wondering which output method uses the least system resources. As you guys already know, server programming deals with a lot of log statements so I was wondering the best output method I should use...
Both printf and cout are console output methods, neither is going to trouble your CPU greatly, you are probably worrying about nothing. However C++ provides three standard output streams - cout, cerr, and clog. I suggest that you should use the latter since that is what it is for, and the output of your log is then sy...
6,476,613
6,477,209
__syncthreads() Deadlock
Will __syncthreads() cause a dead lock if only some threads execute it? i have a kernel like this: __global__ void Kernel(int N,int *a) { if(threadIdx.x<N) { for(int i=0;i<N;i++) { a[threadIdx.x]= //Some calculation using a and i __syncthreads() } } } if the number of ...
You should not use __syncthreads() in a divergent code. Its behaviour in such circumstances is undefined. __syncthreads() may appear in a conditional branch only if you are sure, this branch will be evaluated uniformly, in the same way, by all threads in a block (either all, or no threads from a block take the branch)....
6,476,677
6,477,259
multiple inheritance and data members
I never used multiple inheritance and stumbled into a design problem I never faced.. class A { //..methods.. } class B : public A { int b; //...methods.. } class C : public A { int c1,c2; } class D : public B,public C { } Here's the classical diamond. The fact is that C is really just an A with two...
Your code is working because you used a C-style cast, which can be a reinterpret_cast, and it's my understanding that you can reinterpret_cast between any two pointer types, even if it doesn't make sense. You must use a dynamic_cast when casting up from a multiply inherited base to a more derived class. A static_cast w...
6,476,706
6,476,731
Using itoa with a TCHAR
I have a Win32 C++ Application which supports UNICODE. I have a problem where I am using the itoa() function but I get a compile error because I am passing a TCHAR* as the parameter instead of a char*. What can I do to make it work? TCHAR buf[32]; itoa( taskState, buf, 10 );
There is no good reason to us TCHAR unless you're targeting Windows 9x with MFC in DLL, and you're sort of afraid to rebuild MFC. Just use wchar_t. Then read Microsoft's documentation of itoa. There you find at least one variant that you can use with a wchar_t string. It's generally not a good idea to use itoa family,...
6,477,013
6,477,042
Reverse Engineering virtual functions code in C++
I just compiled the following on VS2010(with optimization turned off). class Shape { public: int x,y; Shape() { x=10; y=20; } virtual void function1() { cout<<"function1"; } virtual void function2() { cout<<"function2"; } }; int main() { Shape *s = new Shape(...
Virtual dispatch is only involved when the dynamic type of an object is different from its static type (pointer-to-Base pointing to a derived class). Since you don't even have inheritance, and an exact type at the call site, why should it do the lookup in the vtable?
6,477,079
6,477,090
How do I get the stack trace information?
I am working on a server programming on linux machine using epoll and I have a problem with debugging. Right now I have placed log statements all over the place. It helps to see when it blows up but it is hard to see why.. So I was wondering if there is a way to print a stack trace or something more information in C++....
Try the backtrace function in Glibc.
6,477,351
6,478,854
Default button in Window created with CreateWindowEx()
I've created a window using CreateWindowEx which functions as a wizard dialog using the following code; DWORD dwStyle = WS_DLGFRAME | DS_CENTER | WS_POPUP | WS_CAPTION | WS_SYSMENU | WS_OVERLAPPEDWINDOW; m_hWnd = CreateWindowEx(WS_EX_APPWINDOW, _T("WIZARD"), _T("SETUP"), dwStyle, CW_USEDEFAULT, CW_USEDEFAULT, WIZARD_WI...
The DM_SETDEFID message is normally processed by DefDlgProc. If you're calling DefWindowProc instead, then you need to handle that message yourself so that when IsDialogMessage sends your window a DM_GETDEFID message, you'll know how to respond.
6,477,365
6,477,392
C++ templates template (double template?)
I want to build a Stack class so the user will be able to choose which container he wants to use for the implementation of the Stack. For example, List/Vector. Partial code: stack.h #ifndef STACK_H_ #define STACK_H_ template <typename T, template<typename T> class ContainerType> class Stack{ ContainerType<T> conta...
First, it would be std::vector, and nothing else, because vector resides in the std namespace and you are asking for a template template parameter, while std::vector<int> is not a template anymore. Next, a std::vector actually takes two template parameters, one for the type and the other for the allocator: template < ...
6,477,494
6,477,522
__do_global_dtors_aux and __do_global_ctors_aux
I disassembled a simple program written in C++ and there are these two function names. I guess that ctor means constructor and dtor means destructor, and word global maybe means that they create and destroy global objects. I cannot guess the name aux. What do these two functions do?
The addresses of constructors and destructors of static objects are each stored in a different section in ELF executable. for the constructors there is a section called .CTORS and for the destructors there is the .DTORS section. the compiler creates two auxillary functions __do_global_ctors_aux and __do_global_dtors_...
6,477,552
6,477,562
Problem with annuity program: too few arguments
I'm writing a program to work out a math equation to find annuity. the formula is as shown A = M=[(1+r)^n-1/r(1+r)^n] . The program compiler I am using is Devcpp it its worked with my other programs and i cannot find the error in this one. it tells me that there are too few arguments in the line with the formula. any...
cout<<(M * ( pow ((( 1 + r ), n ) - 1 )/(r * ((pow(1 + r), n))))); You're passing just one argument to the outerpow call. Where is the second argument? Why don't you simply it? Why did you make it so unreadable that even you cannot read and understand it properly? If you can't understand it yourself, how will others ...
6,477,568
6,477,580
How to create a text file in a folder on the desktop
I have a problem in my project. There is a project folder on my desktop. I want to create a text file and write something include this text file. That is my code: ofstream example("/Users/sample/Desktop/save.txt"); But I want to it could been run the other mac. I don't know what I should write addres for save.txt. Can ...
Create a file and write some text to it is simple, here is a sample code: #include <iostream> #include <fstream> #include <string> using namespace std; int main() { std::ofstream o("/Users/sample/Desktop/save.txt"); o << "Hello, World\n" << std::endl; return 0; } I hope th...
6,477,759
6,477,804
Uncatchable custom exception C++
This has been driving me crazy all night. class ExceptionImpl; /** * Custom Exception. */ class Exception : public virtual std::exception { public: Exception( const Exception& original ); Exception( const std::string& message ); virtual ~Exception( void ) throw( ); virtual const char* what( void )...
If catch (...) (in an enclosing function in the same thread) doesn't handle it, your crash is not caused by a thrown an uncaught exception after all. (Note: It's possible for an exception to be thrown and terminate the program even though it would have been caught. Throwing from a destructor or violating a throws clau...
6,477,774
6,477,871
input iterator + output iterator + X = forward iterator
I want to solve the equation in the title and find X. As far as I understand, an input or output iterator, unlike a forward iterator, gets invalidated as soon as a copy of it is advanced. Is there any additional requirement in order for a type T which satisfies both input iterator concept and output iterator concept to...
Iterator categories deal with operations allowed on an iterator. Dereferencing forward iterator must yield T& (C++03) while dereferencing input iterator must only yield a type convertible to T. As an example, vector<bool>::iterator is an input/output iterator, but not a forward iterator (because dereferencing it return...
6,477,780
6,477,845
template parameter as variable
Is there any way to use a template parameter as a variable? for example if I have a function template<int dim> void DomainGrid<dim>::getData(Data data_, int field_dim) { int size_ = field_dim *dim; // Compiler Error Here for(int i =0; i<size_; ++i) std::cout<<data_[i]<<std::endl; } Can I get a similar ...
Rename either the template parameter or the member function? That seems like the simplest, most straightforward solution. Whenever multiple symbols have the same name, you risk name clashes. So don't use the same name for multiple symbols in such cases. (This is assuming you have a member function dim(). I assume so ba...
6,477,958
6,478,057
QT - Is there any class for combine few images into one?
I would like do some matrix of images, show preview in some widget and after all save it to - for example - jpg file. I know I could copy every image pixel per pixel into big one, but it wasn't efficient method I suppose... Are there any better solution? Thanks in advice.
Instead of copying individual pixels, I would just directly draw each individual image on a QPixmap large enough to hold all images combined. The collage can then be generated by drawing each individual image on the collage as follows (untested code): QList<QPixmap> images; QPixmap collage; // Make sure to resize coll...
6,477,985
6,485,656
The efficiency of using a pthread_rwlock when there are a lot of readers
While I am looking the man page of pthread_rwlock_unlock function, I noticed that the func will return EPERM if the calling thread does not have the ownership of a rwlock. Since the rdlock allows multiple threads to get the lock, there must be a data structure like a link or array to store the ownerid of one specific ...
n.m has provided a good answer. Your assumption of structures to hold the lock ownership is wrong on the linux implementation you tagged and is similar to the count method n.m. touches upon. Here is an edited version of the pthread_rwlock_t type from /usr/include/bits/pthreadtypes.h struct { int __lock; un...
6,478,047
6,478,073
One class, two objects and strange behaviour with class data
I looked at similar titles in this site, but still could not find the answer. So maybe someone can clarify it for me. Lets say I have: // Example class class CFirst { public: CFirst{ } virtual ~CFirst{ } int i; float y; }; // Other class methods looks like this ......... CFirst *data = new CFirst(); ...
data1->i is not initialized and it can show any value for that matter. CFirst *data = new CFirst(); data->i = 10; data->y = 10.10; When you did the above steps for data you created a new CFirst object on the dynamic memory area(heap/Freestore) and assigned values to members i and y of CFirst object. For data object y...
6,478,191
6,478,280
SIGABRT when trying to throw an exception
I have a very strange problem, which took already several hours of my attention: With giving a wrong input to the software I am working on, I can produce an exception (which is of course intended). This works fine and I see a correct error message when executing the program. But when I pass the exact same input over th...
I wonder if you are calling some (not pure) virtual method from either a constructor or destructor, or possibly some cast going wrong. You should check this in your exception class, I guess, since you get the error while throwing one instance of it. Indeed, the compiler will prevent you from having a class with a not i...
6,478,306
6,478,494
GLOBAL__I_main function
I disassembled simple program written in C++ and there is a function: 080486a8 <_GLOBAL__I_main>: 80486a8: 55 push %ebp 80486a9: 89 e5 mov %esp,%ebp 80486ab: 83 ec 18 sub $0x18,%esp 80486ae: c7 44 24 04 ff ff 00 movl $0xffff,0x4(%esp) 80486...
As netrom mentioned, __static_initialization_and_destruction_0(int, int) arranges for global constructors and destructors to be called. Many compilers add nop instructions after functions to enable incremental relinking. If you change the function a bit and it grows, the linker doesn't have to move all functions that ...
6,478,503
6,478,586
Removing C-style casts in C++ code under Android
I saw this post on SO: Is there a way of disabling the old c style casts in c++, and was excited to apply -Wold-style-cast to my Android C++ code. I quickly ran into the following casts in stdio.h: static __inline int __sputc(int _c, FILE *_p) { if (--_p->_w >= 0 || (_p->_w >= _p->_lbfsize && (char)_c != '\n')) ...
Yes, it's perfectly valid for a C++ standard library header to include C headers. If you want to get around this (without modifying the standard library code), you can disable the warnings before including the header then re-enable them using GCC Diagnostic Pragmas. #pragma GCC diagnostic push #pragma GCC diagnostic ig...
6,478,783
6,479,278
What does the tilde (~) in macros mean?
Seen on this site, the code shows macro invocations using a tilde in parentheses: HAS_COMMA(_TRIGGER_PARENTHESIS_ __VA_ARGS__ (~)) // ^^^ What does it mean / do? I suspect it to just be an empty argument, but I'm not sure. Is it maybe specific to C(99) like the __VA_ARGS__ is s...
On the introduction page of Boost.Preprocessor, an example is given in A.4.1.1 Horizontal Repetition #define TINY_print(z, n, data) data #define TINY_size(z, n, unused) \ template <BOOST_PP_ENUM_PARAMS(n, class T)> \ struct tiny_size< ...
6,479,116
6,479,186
C++, win32 api: How to create an html rendering window so that your application would get callbacks from JS calls?
What I need is simple: we have a console app project. We want to have such a function that would open a simple window with nothing but html (default system based) html + js rendering window that would read some default html+js string (form string or const char*). we want to have our own api joined with default js api s...
CoCreate the MSHTML com object for HTML Documents: CComPtr spDoc; HRESULT hr = CoCreateInstance(CLSID_HTMLDocument, NULL, CLSCTX_INPROC_SERVER, IID_IHTMLDocument2, (void**)&spDoc); Do something like this to read your HTML string and make the document render it. Depending on what you need in terms of callbacks, you can...
6,479,136
6,479,823
Is there a better way to perform URL pattern matching in C++ than iteration?
I have a pattern matching routine that looks up values from a std::map based on the URL used to request the command. The URL mapping table is filled with values like: // Assume this->commands_ is defined elsewhere as std::map<std::string, int> // Providing a number of URL examples to give an idea of the structure of //...
The way I see it, you could split the URL into its components (using one of the suggestions in here maybe), and then use a decision tree to find the correct pattern. In this tree, every node would be a regular expression that matches a particular component of your URL, and the leaves would be the values you currently ...
6,479,226
6,479,260
Is there an atomic |= operation?
Is there such a thing as an atomic |= or and atomic or? If no what is the recommended technique for setting a bit in an variable that needs to be threadsafe? (I am avoiding locks)
There is not such thing in C++03, but you can use your vendor specific features. For example you can use InterlockedOr on windows. In C++0x you can use atomic_fetch_or. Note that atomic operations also require locking, although it's on the hardware level it's still expensive.
6,479,389
6,479,404
c++ find function for vector<unsigned char>
I want to find empty space char " " in my vector<unsigned char> message vector<unsigned char>::iterator pos; pos = find(message.begin(), message.end(), " "); And I get an error: /usr/include/c++/4.5/bits/stl_algo.h: In function ‘_RandomAccessIterator std::__find(_RandomAccessIterator, _RandomAccessIterator, const _Tp&...
You should use ' ' instead of " ": pos = find(message.begin(), message.end(), ' '); Note that " " is string literal, while ' ' is character literal. What you need to provide as third argument is character literal, because message is a vector of chars, not of strings.
6,479,483
6,479,530
Why is boost::thread::join seemingly so expensive?
I just recently started working with multithreading with boost::thread, and I'm still a little unclear about some details, but from what I understand, thread::join is used when you want the 'parent' thread to block and wait for the thread to finish (I'm sure there's more to it than that, but I believe that is one use)....
Surely it does not take two seconds to join a thread (assuming the system is not overloaded in general). The waiting time you're seeing is presumably caused by some other work being done either in the children after they notify the parent, or in the parent while it polls for notifications from the children.
6,479,564
6,481,634
C++, Qt, QtWebKit: How to create an html rendering window so that your application would get callbacks from JS calls?
What I need is simple: we have a console app project. We want to have such a function that would open a simple window with nothing but html QtWebKit html+js rendering window that would read some default html+js string (form string or const char*). we want to have our own api joined with default js api so that when JS c...
Have a look at QWebFrame::addToJavaScriptWindowObject(). It lets you expose a C++ QObject to the javascript in your page. Your html+js can then call C++ methods on that object from the web page.
6,479,604
6,480,078
How can I avoid static data member init fiasco in a thread-safe way?
Consider this: class A { public: A(const char* s) { /*...*/ }; static const A& get_default() { /* avoid static data memember init fiasco */ static const A& a = A("default"); /* ..but not thread-safe */ return a; } }; How can I make get_default() thread safe? Or how can I find a way to get t...
The following will take advantage of the fact that initialization before main() is called will take place on a single thread, and that the pInstance pointer must be zero initialized before dynamic initialization of static objects takes place (3.6.2 "Initialization of non-local objects"). class A { public: A(const c...
6,479,693
6,479,975
writing a cygwin makefile for ubuntu
I am trying to compile the open-source AAM-library. I have tried in Visual Studio, and although it compiled, it had a run-time error. Now I'm trying to compile it in Ubuntu 11.04 using G++. The only makefile provided is a cygwin makefile. I am trying to use this to compile in Ubuntu. (I have included the makefile below...
I agree that you should not use a .dll.a or .dll extension (I believe .a and .so are appropriate), but it seems you can't do without libaamlibrary[.dll].a. Since '--enable-auto-image-base' is prefixed with -Wl, this makes it a linker (ld) option. I searched 'man ld' and came up with this: --enable-auto-image-base ...
6,479,789
10,485,202
How setup C++ SDK in IntelliJ IDEA on linux?
I need to know how to configure the path to C++ SDK for IntelliJ IDEA 10.04. I installed C/C++ plugin, however I don't know what is the proper path to C++ SDK. I am using ubuntu 11.04.
after installing the c++ plugin you should see the C/C++ project option when you create a new module - i think you're seeing the point where it's asking you for the cpp sdk location. run sudo aptitude install build-essential Then restart intellij - it should autodetect that it's installed and offer you the option in ...
6,480,032
6,729,884
Matching a Boost.Proto grammar to a type
I'm trying to make a grammar in Boost.Proto that matches a vector type, but when I give it a terminal of that type, it doesn't match the grammar. The type definition looks like this: template <typename T, unsigned D> struct vector { typedef T scalar; enum { size = D }; scalar& operator[](unsigned i) { ...
Boost.Proto doesn't work with non-type template parameters. If you can, change your vector type to use integral type wrappers, like this: template <typename T, typename D> struct vector { typedef T scalar; enum { size = D::value }; scalar& operator[](unsigned i) { return m_components[i]; } ...
6,480,309
6,480,439
subtracting two values of unknown bitsize
I'm trying to subtract two values from each other using twos compliment. I have a problem with the overflowing bit. Since my container hold an unlimited bit sized integer, I don't know if the top bit of the result is really from the result or just the overflow. How would I get rid of the overflow without using - (I can...
If you calculate a - b you must somehow "arrange" the word - as you have to make for the 2 compliment a negation with the bitwidth of m=max(bitwidth(a), bitwidth(b)). To get rid of the of overflow you just do mask = negate(1 << m), and apply the mask with bitwise and. (Or you could just check that bit and treat it acc...
6,480,779
6,480,899
Ensure use of custom types
Considering this answer for the benefit of typedefs on basic types and why they are used, is there any way to ensure that in your project you did not use a basic type and used the typedef counterparts?
If you really, absolutely want to ban native types but allow typedefs, I guess you can always do something like: #include <stdint.h> #define int please_use_stdint_typedefs_rather_than_native_types int main() { int32_t good; // Good typedef. int evil; // Evil native type. } $ gcc -c int_forbidden.c in...
6,480,864
6,480,888
Link error in c++ & DirectX file include problem
I have two header files: DirectX_Engine.h #pragma once #include "Main.h" #include <d3d9.h> and: Main.h #pragma once #include <Windows.h> #include "DirectX_Engine.h" int imRunning = 1; After compiling, I get the following linker errors: error LNK1169: one or more multiply defined symbols found error LNK2005: "int imR...
Two ideas. Firstly, you are including DirectX_Engine.h in Main.h and Main.h in DirectX_Engine.h. This will obviously not work. Secondly, int imRunning gets included to each .cpp file that includes Main.h and the compiler treats it as a definition. Then the linker comes and sees imRunning defined in each of these files ...
6,481,260
6,481,325
Non-virtual interface design pattern in C#/C++
When designing an interface, someone recommended to use the non-virtual interface pattern. Can someone briefly outline what the benefits of this pattern are?
The essence of the non-virtual interface pattern is that you have private virtual functions, which are called by public non-virtual functions (the non-virtual interface). The advantage of this is that the base class has more control over its behaviour than it would if derived classes were able to override any part of i...
6,481,633
6,481,859
Including glew using only source files?
For reasons outside of my comprehension, glew will simply not work when statically linked. Is there a way to simply just include the glew.h, glxew.h, wglew.h and glew.c source files into my project and use #include "glew.h" instead of #include <glew.h> whenever i try i get an explosion of warnings: like warning C4273...
Have you seen the GLEW installation/building page? http://glew.sourceforge.net/install.html If you are building it statically (which it sounds like you are), you need to define the GLEW_STATIC macro before include glew.h (or else it won't compile). The easiest way to do this is to add an option to your project; or if ...
6,481,668
6,481,695
Protecting executable from reverse engineering?
I've been contemplating how to protect my C/C++ code from disassembly and reverse engineering. Normally I would never condone this behavior myself in my code; however the current protocol I've been working on must not ever be inspected or understandable, for the security of various people. Now this is a new subject to...
What Amber said is exactly right. You can make reverse engineering harder, but you can never prevent it. You should never trust "security" that relies on the prevention of reverse engineering. That said, the best anti-reverse-engineering techniques that I've seen focused not on obfuscating the code, but instead on br...
6,481,705
6,481,805
boost xpressive: wrong match?
I want to match a simple expression with boost, but it behaves strange... The code below should match and display "a" from first and second strings: #include <iostream> #include <boost/xpressive/xpressive.hpp> #include "stdio.h" using namespace boost::xpressive; void xmatch_action( const char *line ) { cregex g_...
Instead of printf() use the << operator to print the sub_match object (what[1]). Or you can try using what[1].str() instead of what[1]. See the docs: sub_match, match_results, regex_match
6,481,943
17,124,153
XCode 4 console won't take user input
In XCode 4, when I run something like this: string input; cout << "Enter command" << endl; getline(cin, input); cout << "You entered: " << input << endl; I see my "Enter command" prompt in the console. But when I place my mouse cursor below it and start typing the cursor doesn't move, and my keystrokes don't show up. ...
Are you pressing Return or Enter at the end of your input line? For some keyboard the enter and return are on the same button, but if you press "shift" key, while pushing the enter/return button scanf will work. Unshifted must be the Return Shifted must be the Enter.
6,482,074
6,482,102
What's the design principle of c++ standard library?
So the standard c++ library mainly contains roughly 7 categories, what's the rationale/prototype that make it deserve being the standard? BTW,which category does socket programing related stuff belong to in the c++ standard library?
what's the rationale/prototype that make it deserve being the standard? The same rationale/prototype that made C++98 a standard. In the 90's, a lot of compiler writers were poking with extensions to C. These usually involved adding object-oriented features to C (hence the term "C with Classes"). This was the early da...
6,482,338
6,482,532
How to create a list of tuples C++
I am fairly new to c++, I dont really have any background in it. I am tying to create a list of tuples, the first will be an int, the second will be a string. #include <string> #include <list> #include <boost/tuple/tuple.hpp> .... list< tuple<int,string> > time; And getting an error. I want to be able to c...
For a simple list use std::vector instead of std::list. You probably just want something simple such as: #include <iostream> #include <vector> #include <string> #include "boost/tuple/tuple.hpp" using namespace std; using boost::tuple; typedef vector< tuple<int,string> > tuple_list; int main(int arg, char* argv[]) { ...
6,482,566
6,482,583
Has "In class member initialization" feature made into C++11?
In class initialization feature, which allows to initialize normal members inside the class itself, struct A { int a = 0; // error: ISO C++ forbids in-class initialization of non-const static member ‘a’ }; This is giving error in latest compiler gcc-4.6 (with -std=c++0x). Has this feature made into the C++11 standar...
Yes, that is legal in C++0x. There is an example of this at N3290 §12.6.2/8: struct C { /* ... */ int j = 5; // OK: j has the value 5 };
6,482,780
6,482,795
Win32 Releasing Environment Variables causes Windows Breakpoint
I have a win32 c++ application & I getting all the environment variables & storing them in a map. When I call the Win32 function FreeEnvironmentStrings() in my application I get a weird Windows Breakpoint in MSVC++. First I dont know what this means & why its occuring? How can I fix my problem & what is going wrong? Th...
You're changing what environVar points to, so you're not handing the FreeEnvironmentString function a valid environment string pointer. Save the original environVar somewhere before modifying it and use that in the Free call. TCHAR* tobefreeed = GetEnvironmentStrings(); TCHAR* environVar = tobefreeed; ... FreeEnvironme...
6,482,827
6,482,856
Protected types in C++
Possible Duplicate: What are access specifiers? Should I inherit with private, protected or public? While going through the Qt API documentation, I came across protected types. What are protected types in C++? I found an example of protected types mentioned in the QT documentation.
"Protected types" are nested typedefs and nested classes and templates and enums (i.e. nested types) that are protected, that is, accessible only in scope of the member functions of the class and member functions of derived classes (and friends, of course). class A { private: typedef int Int_Private; p...
6,482,845
6,482,875
ICC on Linux: link to OpenMP
What are the steps to link to OpenMP with Intel C++ compiler? Does Intel compiler ship with its own OpenMP library or should I link to libgom?
It comes with its own implementation apparently. You don't need to specify additional libraries as long as you compile with the -openmp flag. $ icc -openmp t.c $ ldd ./a.out ... libiomp5.so => /opt/intel/Compiler/11.1/072/lib/intel64/libiomp5.so (0x00007fd8e7ac6000) ...
6,482,981
6,483,026
WinAPI edit control doesn't display newlines
Well, that's only half true. Newlines work fine for the most part, but when I load a file into it, none of the newlines are shown. Copying the text and pasting it into Notepad++ with view all characters turned on shows that the carriage return and line feed are there. My loading code: void open_file(HWND hwnd,const cha...
Since you're opening the file in text mode your text represents newline by \n. Possibly the text edit control requires \r\n. One possibility is to do like this (off the cuff) std::string line; std::ifstream file( fname ); while( std::getline( file, line ) ) { line += "\r\n"; // Append the line to the edit cont...
6,483,422
6,483,468
Qt - QList const correctness
A QList<T *> can't easily be const-correct. Consider the function void f(QList<T *> list) { list[0]->constFunction(); } I can change f to void f(QList<const T *> list) but then I can't do f(QList<T *>()); //Compile error anymore, since the compiler can't implicitely cast QList<T *> to QList<const T *>. Howeve...
The casting function you're considering, … template< class T > inline QList<T const*>& constList( QList<T*> const& list ) { return reinterpret_cast< QList<T const*>& >( const_cast< QList<T*>& >( list ) ); } … may be practical (probably QList does not change its object representation depending on th...
6,483,441
6,500,103
Controlled application shut-down strategy
Our (Windows native C++) app is composed of threaded objects and managers. It is pretty well written, with a design that sees Manager objects controlling the lifecycle of their minions. Various objects dispatch and receive events; some events come from Windows, some are home-grown. In general, we have to be very aware...
One possible general strategy would be to send an "I am shutting down" event to every manager, which would cause the managers to do one of three things (depending on how long running your event-handlers are, and how much latency you want between the user initiating shutdown, and the app actually exiting). 1) Stop acce...
6,483,453
6,483,463
Weird SIGSEGV (Segmentation fault) using enums
I'm currently getting a very wierd SIGSEGV (Segmentation fault), not using any pointers that is, just enums; this is my code: typedef enum { LIGHT, DARK, NONE } Color; class Board { public: Color toMove(); private: Color side; }; and the implementation is: Color Board::toMove() { ...
This lovely hint from your debugger (this=0x0) suggests you tried to call toMove() without a valid Board object.
6,483,523
6,494,435
Qt - How to get|compile Mysql driver
I am trying to make a MySql-dependent app in Qt. After some time I came to know that my shared-build is not having MySql driver(by default). Can Anybody say how to get|compile it (both in shared and static). Note: I am using Qt-4.7.2 in Windows platform EDIT: Thanks to "vrince". This is the way he showed => I did....
If you plan to rebuild Qt linked to MySQL you can stop now you don't have to ! SQL drivers are plugins (by definition dynamically loaded at run time) and can be compiled independently. Find the driver sources in the Qt source tree somthing like qt/src/plugins/sqldrivers/mysql then build it. The game here is to provide ...
6,484,130
6,485,471
Is Qt Quick mature enough for large desktop applications?
I'm planning to write a program that is especially designed for tablets, the main platform is MeeGo (because I'm taking a contest). Edited: My program has following needs: heavy C++ usage to deal with networking and low-level optimization dynamically generate contents (like what Flipboard app did) completely customize...
I don't have specific expertise in QtQuick, though I was evaluating it for our app last year. It's come on a long way since then and in particular it's much easier to embed QtQuick widgets within a native app or native widgets within a QtQuick app. Whether it's worth adopting will depend on the requirements of your a...