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
3,797,280
3,797,313
Injecting string to 'cin'
I have a function that reads user input from std::cin, and I want to write a unittest that inserts some strings into std::cin, such that later extraction from std::cin will read that string instead of pausing for keyboard input. Ideally, I would change the function signature so that I can pass a custom istream as param...
If you really, really want to use std::cin, try this: int main() { using namespace std; streambuf *backup; istringstream oss("testdata"); backup = cin.rdbuf(); cin.rdbuf(oss.rdbuf()); string str; cin >> str; cout << "read " << str; } You can restore std::cin's streambuf when you are done from backu...
3,797,447
3,798,072
Signaling failure in qt slots
I have a 'producer' object, that steps through some data and emits various signals depending on what data item is next in the queue. Each of those signals are processed by at most one 'consumer' object at a time (it takes care to disconnect its slots before attaching the producer's signals to the other consumer). If th...
You have a couple of inter-related questions. To me, the most important question is related to signal/slots working with threading. When using signal/slots within a single thread, Qt by default assumes a AutoConnection or "direct" connect. In direct connect mode, signal/slots acts almost exactly like a callback func...
3,797,695
3,797,978
Placeholder for C++0x's <thread> header in MSVC++ 2010
I already use some new features from C++0x in Visual C++ 2010, like regular expressions or lambda functions. But there is one major feature that is missing: the <thread> header. Do you know any code which could act as a replacement? For the moment I'm using boost's thread, but it's not exactly the same as the standard,...
I have used boost::thread in performance-sensitive production code and it's way more sophisticated and performant than anything we could have built ourselves in a sensible amount of time. The reader-writer lock in particular is a thing of beauty imo. You have the added benefit that the person who wrote the code and t...
3,797,708
3,797,720
millisecond-accurate benchmarking in C++?
I do not really wish to profile because I was wanting to do many different small benchmarks on different simple functions. For the life of me I cannot find a way to record the amount of milliseconds in C++, I am using Linux by the way. Can you suggest the method to get the system clock in milliseconds (I may settle wit...
using gettimeofday function from sys/time.h header file, i use this class: #include <cstdlib> #include <sys/time.h> class Timer { timeval timer[2]; public: timeval start() { gettimeofday(&this->timer[0], NULL); return this->timer[0]; } timeval stop() { gettimeofday(...
3,797,759
3,797,777
how to create c++ programs without the requirement of .net framework to run (like ccleaner and utorrent)
i was wondering how programs like ccleaner and utorrent are made? AFAIK they are written in C++ but they run without the need of .net framework and apparently run on windows 98 as well. How can this be done? Visual c++ requires .net framework to be installed to run the binary file. While .net framework is free, it can...
Visual c++ requires .net framework to be installed to run the binary file. No, it does not. In fact, C++ and the .NET framework are highly unrelated. You only need the .NET framework if your application is written in C++/CLI, which is far away from regular C++. If you develop an application in standard C++, you don...
3,797,802
3,798,066
How to check if an other program is running in fullscreen mode, eg. a media player
How can I check if an other app is running in full screen mode & topmost in c++ MFC? I just want to disable all of my auto dialogs (warnings) if media player or other players are running. (Like silent/gamer mode in Avast.) How could I do that? Thank you.
using a combination of EnumWindows, GetWindowInfo and GetWindowRect does the trick. bool IsTopMost( HWND hwnd ) { WINDOWINFO info; GetWindowInfo( hwnd, &info ); return ( info.dwExStyle & WS_EX_TOPMOST ) ? true : false; } bool IsFullScreenSize( HWND hwnd, const int cx, const int cy ) { RECT r; ::GetWindowRect...
3,797,839
3,797,864
C++: Store large numbers in a float like PHP?
In PHP if you go above INT_MAX it will cast it as a float, allowing very high numbers to be formed (that are non-decimal as well), is this possible to do in C++ or are the way they store floating point/double precision numbers different? The reason why is I am wishing to benchmark large factorials, but something such a...
The language will not make the switch for you, but has the datatypes float and double, which are usually 32 bit and 64 bit IEEE floats, respectively. A 64 bit double has enough range for 80!, but doesn't have enough precision to represent it exactly. The language doesn't have anything built in that can do that: you wou...
3,797,955
3,797,969
Capture MacBook Pro iSight video with C++
I'd like to grab a frame from my MacBook Pro iSight in C++ and do some elaborations on it. I already know how to do that in ObjC with QTKit, but is there any way to do the same thing in C++? NOTE: I tried to install OpenCV with macports, but the framework doesn't seem to support iSight cameras.
You could do that using OpenCV ( http://opencv.willowgarage.com/wiki/ ) And here is a sample code you can copy/paste to try it : http://www.geckogeek.fr/lire-le-flux-dune-webcam-camera-video-avec-opencv.html (article in french but code is in english)
3,798,000
3,798,044
My Visual C++ compiler compiles out of date source
I'm a beginner starting to use Microsoft Visual C++ Express 2010 for Windows Programming. I've created a new C++ application using native code, not managed or MFC. I had Visual Studio create for me the basic windows code to create one window with simple menus (chat.cpp). I modified this file and I was able to compile c...
Does intro.cpp have a header file? is that in your solution too? It's hard for me to imagine that this area of such a mature IDE has a bug here, so I would examine your file list first. Make sure that the Solution Explorer shows all the files you have added and are editing. This is the list that VS uses to determine ...
3,798,017
3,798,046
May a compiler ever generate code to unload parts of the code segment during execution?
Apart from Dll concept that provides ability of loading/unloading methods or functions at run-time, I'm wondering if a compiler may ever say something like, ok as this particular part of the code takes considerable amount of space in code segment and is never gonna be used again after this point during program executio...
A compiler can do anything it wants to, as long as that doesn't violate the standard. If it can figure out that the code is never called again, it can ditch it completely. It could even replace it with a smaller stub function that would reload the code, were it required. But you'll be very unlikely to ever see that in ...
3,798,025
3,798,061
Interprocess Communication over Network in C++
I'm using C++ to develop the server side of a game which multiple servers need to communicate with each other using Publisher/Subscriber pattern. Each server subscribes to some events on different servers. All servers are located on the same network so latency and packet-loss should be very low. The inter-server commun...
You should be able to combine Boost.ASIO (for async sockets I/O) with Boost.Signals (for Observer pattern) or Boost.Signals2 (threadsafe version of Boost.Signals) to achieve what you want. There is a simple example showing how this might work here. Note that this uses a wrapper on Boost.Signal, but you get the idea.
3,798,076
3,798,098
C++ FAQ Lite Smart_Ptr Class Not Functioning?
I'm currently doing a lot of things on exception safety. (Herb Sutter's Exceptional C++, C++ FAQ Lite, etc) In particular, I wanted to write and understand the reference counting example of C++ FAQ Lite, but I'm currently stuck on this part of the code: class Smart_Ptr; class Foo { private: friend class Smart_Ptr...
You can't write a function that returns Smart_Ptr by value, until Smart_Ptr is defined. A forward declaration isn't enough. The code you link to contains the comment, // Defined below class FredPtr {...};, but you have defined the create function in the Foo class definition. If you look closely at the code after "the c...
3,798,086
3,799,441
Autoconf not defining a variable properly
I am using GNU autotools for my project. The configure.ac script has the following snippet. AC_ARG_WITH(chkhere, AC_HELP_STRING([--without-chkhere], [do not compile]), [ac_cv_chkhere=$withval], [ac_cv_chkhere=yes]) # Check if chkhere is available if test "x$ac_cv_chkhere" = "xyes" then AC_DEFINE(HAVE_CHECKED) echo...
If you didn't call autoheader then config.h.in may be out of date and may not mention HAVE_CHECKED. I suggest you just ditch your sequence of commands and use autoreconf instead, it will run what you need.
3,798,184
3,799,199
Why the layout managers in QT doesn't work?
this->setWindowTitle(tr("数据转移程序")); edt_ftp_server = new QLineEdit; edt_ftp_port = new QLineEdit; edt_ftp_account = new QLineEdit; edt_ftp_pwd = new QLineEdit; edt_ftp_pwd->setEchoMode( QLineEdit::Password ); lbl_ftp_server = new QLabel; lbl_ftp_server->setText(tr("FTP服务器地址:")); lbl_ftp_server->setBuddy( edt_...
I suspect that the problem lies in the top level layout, which is winLayout. Set QMainWindow's central widget to winLayout's parent: winLayout = new QVBoxLayout(ui->centralWidget); I recommend using Qt Creator or Qt Designer for designing the user interfaces. Qt Creator creates the necessary code for layouts and other...
3,798,230
3,798,402
How to apply a normal map in OpenGL?
I'm learning to use normal maps (per pixel lighting?) in 2D graphics with OpenGL. New to normal mapping, I managed to wrap my head around the Sobel operator and the generation of normal maps (mostly thanks to this), that is creating a (2D) array of normals from a (2D) array of pixel data. (Most of the tutorials and for...
I recommend you look at: This nvidia presentation on bumb mapping I haven't looked at this for a while, but I remember it going over most of the details in implementing a bump map shader, should get a few ideas running. This other nvidia tutorial for implementing bump mapping in the cg shader langauge This bump mapping...
3,798,276
3,798,323
Initialize array in constructor without using default constructor or assignment
Consider: struct A { A (int); A (const A &); }; struct B { A foo [2]; B (const A & x, const A & y) : foo {x, y} /* HERE IS THE PROBLEM */ {} }; I was expecting this to work since I'm using C++0x support in GCC4.3, which allegedly supports initialiser lists. No joy. I have a class A which has no default cons...
Unfortunately, there really is no proper, clean way to do this. Consider it something of a language limitation that results from an awkward mixing of C++ constructors and C style arrays. The C++11 standard addresses this issue, but until then you'll have to settle for a workaround. Since A has no default constructor, ...
3,798,305
3,798,327
Loop over two vectors, remove elements of 1
I have the following toy code, intended to remove duplicates from a vector: void overlap_removal(vector<int> &vec1, vector<int> &vec2) { for (vector<int>::iterator it1 = vec1.begin(); it1 != vec1.end(); ++it1) { for (vector<int>::iterator it2 = vec2.begin(); it2 != vec2.end(); ++it2) { if ((*it1)*(*it2) < 1...
Try remove_if. The basic idea is you provide a function object such that true is returned if the passed in element should be deleted: class ItemInOtherVectorPred { const std::vector<int>& otherVec; ItemInOtherVectorPred(const std::vector<int>& vec) : otherVec(vec) {} // return true if removeVec...
3,798,307
3,798,484
directx apply texture
i found some examples how to apply texture on 2d object but nothing on 3d. if you know any tutorial or you can give me an example that would be greate.
Read about: Texture Coordinates Flexible Vertex Format Adding Textures Also, next time, please take time to search for tutorial contents in the web. It's not hard to search for DirectX Tutorials or Direct3D Tutorials in Google or your favourite search engine to find these contents ;)
3,798,350
3,855,167
LT_VERSION for libtool and autoconf not being recognized
My configure.in file has LT_VERSION="1.1". I am using the latest version of autoconf and libtool. While using autoconf or autoreconf, I am getting the following error message: configure.ac:41: error: possibly undefined macro: LT_VERSION If this token and others are legitimate, please use m4_pattern_allow. See the A...
I cannot find any reference to LT_VERSION in the libtool source tree (there is an LTVERSION, and an LTOBSOLETE_VERSION), so I'm assuming that string in your configure.in (which should be renamed configure.ac) is a private string and not something used by libtool. In that case, there are 2 things you should do. First,...
3,798,533
3,899,385
Owned windows on Windows Mobile
Developing for WM 6, I call CreateWindow with hWndParent set to the window I want to be the owner. I do not set the WS_CHILD style, but the window created becomes a child window nevertheless. What is the proper way of doing this? The MSDN article for CreateWindow mentions this behavior for WinCE 1.0: Windows CE 1.0 do...
The proper way of doing this is to give the window the WS_POPUP style, as outlined in Microsoft's Window Relationship Fundamentals document for WinCE 3.0: You can create an owner/owned window relationship between top-level windows when you create a window with the WS_POPUP style. Because top-level windows do not have ...
3,798,733
3,798,799
How do I programatically collect packets from passively sniffing?
I want to test the vulnerability of the server I just wrote against man in the middle attacks. How (on Mac OS X) do I analyze packets. (I'll be checking where they are going, pulling information from if they are heading to my server, and seeing what all is available) Then I'll figure out a way to encrypt everything.....
The best portable library for this is libpcap. There's even a java wrapper available for it.
3,798,932
3,801,818
C++ boost enable_if question
Do I have any way to simplify the following statements? (probably, using boost::enable_if). I have a simple class structure - Base base class, Derived1, Derived2 inherit from Base. I have the following code: template <typename Y> struct translator_between<Base, Y> { typedef some_translator<Base, Y> type; }; templat...
First, you'll have to pick your choice among: is_base_of is_convertible both can be found in <boost/type_traits.hpp>, the latter being more permissive. If you with to simply prevent the instantiation of this type for some combination, then use a static assert: // C++03 #include <boost/mpl/assert.hpp> template <typen...
3,799,040
3,799,100
different results in visual studio and linux(eclipse)
my code works perfectly in visual studio yet i encounter a problem running it in eclipse. in the function: City* Gps::FindCity(const char* city) { if(city != NULL) { City *tmp = NULL; if (! m_gpsCities.empty()) { for (list<City*>::iterator iter = m_gpsCities.begin(); iter != ...
You just want to achieve find_if for your specific predicate, which is indeed a variant of strcmp with less specific integer output. Try this: City* Gps::FindCity(const char* MyCityName) { if((MyCityName!= NULL)&&(!m_gpsCities.empty()) { for (list<City*>::const_iterator iter=m_gpsCities.begin(); i...
3,799,053
3,799,146
Check for writing permissions to file in Windows/Linux
I would like to know how to check if I have write permissions to a folder. I'm writing a C++ project and I should print some data to a result.txt file, but I need to know if I have permissions or not. Is the check different between Linux and Windows? Because my project should run on Linux and currently I'm working in V...
The portable way to check permissions is to try to open the file and check if that succeeded. If not, and errno (from the header <cerrno> is set to the value EACCES [yes, with one S], then you did not have sufficient permissions. This should work on both Unix/Linux and Windows. Example for stdio: FILE *fp = fopen("resu...
3,799,091
3,799,180
Is there a standardised way to get type sizes in bytes in C++ Compilers?
I was wondering if there is some standardized way of getting type sizes in memory at the pre-processor stage - so in macro form, sizeof() does not cut it. If their isn't a standardized method are their conventional methods that most IDE's use anyway? Are there any other methods that anyone can think of to get such data...
Depending on your build environment, you may be able to write a utility program that generates a header that is included by other files: int main(void) { out = make_header_file(); // defined by you fprintf(out, "#ifndef VARTYPES_H\n#define VARTYPES_H\n"); size_t intsize = sizeof(int); if (intsize == 4...
3,799,169
3,799,213
How to wrap a C++ lib in objective-C?
I have a C++ library (.h only) that contains the implementation of a data structure and I'd like to use it in my iPhone app. Firstly, I wrote a wrapper in objective-C++ as a class that, through composition, has an ivar of the C++ class. I then was 'obliged' to change the wrapper class extension to .mm, and it seemed f...
My recommendation is to wrap the C++ bits in #ifdefs: //MyWrapper.h #ifdef __cplusplus class ComposedClass; #endif @interface MyWrapper : NSObject { #ifdef __cplusplus ComposedClass *ptr; #endif } // wrapped methods here... @end This is a slightly lame version of the PIMPL idiom, but less code, and effective for h...
3,799,294
3,799,493
I'm having problems with WaitForDebugEvent EXCEPTION_DEBUG_EVENT
I'm starting an Explorer.exe instance with CreateProcess (flags NORMAL_PRIORITY_CLASS + DEBUG_PROCESS + DEBUG_ONLY_THIS_PROCESS), and then I'm doing this: procedure FakeDebugProcess; var wDebugEvent : DEBUG_EVENT; begin fillchar( wDebugEvent, sizeof( wDebugEvent ), 0 ); repeat if WaitForDebugEvent( wDeb...
Your code is fine, testing using other debuggers, like ollydbg, rpcrt4.dll still reports exceptions on attaching to some applications. The only way around this to be define filters(what ollydbg allows the user to do), based on the exception code, then based on the module. Thus if you recieve 0xC0000005(EXCEPTION_ACCESS...
3,799,408
3,799,526
Project dependencies does not imply linkage in VC++ 2010?
In Microsoft Visual Studio 2010, I use the wizard to create a solution with two projects: - theapp: a C++ Win32 console app, and - thelib: a C++ static library I add an h-file and a cpp-file to the library and write a do-nothing function in thelib. In main(), I call thefunc(). In project/dependencies theapp is set to...
Yes, this is done differently now. They call it a "project-to-project dependency". Not actually sure what that means. Right-click the EXE project, Properties, Common Properties, Framework and References. Click the Add New Reference button and select your .lib project. The "Link Library Dependencies" should be set t...
3,799,478
3,799,486
C++ #ifndef for include files, why is all caps used for the header file?
I wonder why the name after the #ifndef directive is always all caps and don't seem to match the name of the actual header file? What are the rules surrounding this? I've been looking around the webs but, I haven't found any explanation for this. If my header file is called myheader.h would it then be ok to use: #ifnde...
These are preprocessor symbols and have no such rules. (as long as they match the #defines in the headers) However, convention is to use all-caps for preprocessor symbols.
3,799,529
4,168,899
DirectX 9 advanced tutorials C++
I don't need tutorials talking about fvf or how to draw a triangle. I need some free tutorials that are about advanced things like meshes shadering.
There aren't too many good tutorials I've seen on mesh shaders, but it's not too hard to figure out yourself if you understand both shaders and meshes. If I understand what you mean by "mesh shadering" properly (guessing shaders applied to meshes, material shaders I call them), then you simply have to use the D3DXEffe...
3,799,574
3,799,616
What is the right way to link to a DLL which was linked to a static library and other shared libraries?
Greetings, I hope someone has the patience to read this. I have a setup at hand, which is slightly confusing me. I have a C source code directory generated by an Eiffel Compiler. I want to use this output from Java, so I need a DLL for JNI, in which I'll implement some JNI functions. When I compile the C code, it giv...
If your 'second' dll cannot be linked because of a symbol declared in the static library, it seems that either the second dll shouldn't see that symbol (why does it), or it also depends on the static library. It seems that the latter is unwanted, so you should try to find out through which path the linker finds the unw...
3,799,595
3,799,718
itoa function problem
I'm working on Eclipse inside Ubuntu environment on my C++ project. I use the itoa function (which works perfectly on Visual Studio) and the compiler complains that itoa is undeclared. I included <stdio.h>, <stdlib.h>, <iostream> which doesn't help.
www.cplusplus.com says: This function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. Therefore, I'd strongly suggest that you don't use it. However, you can achieve this quite straightforwardly using stringstream as follows: stringstream ss; ss << myInt; string myString = ss.str();...
3,799,845
3,799,868
What can I "forward declare" in C++?
I know I can do class Foo; and probably struct Bar; and global functions bool IsValid(int iVal); What about a typed enum? What about a typed enum within an undeclared class? What about a function with an undeclared class? What about a static member within an undeclared class? What about these within an unknown n...
You can forward declare Templates, including partial specializations Explicit specializations Nested classes (this includes structs, "real" classes and unions) Non-nested and local classes Variables ("extern int a;") Functions If by "forward declaration" you strictly mean "declare but not define" you can also forward...
3,799,891
3,799,929
pure/const functions in C++0x
In C++98/C++03, there are no pure/const function keywords in the language. Has this changed in C++0x? If so, is it possible to set such a flag even on function objects (std::function)? So I can pass some function pointer or lambda functions and additional give the information that it is a pure/const function? The call...
Has this changed in C++0x? No. There is a constexpr but it means compile time constant. If its parameters are constexprs too then it's executed at compile time, but it's a regular function otherwise. Since they must be defined in the same translation unit and consist of a single return statement they probably will ...
3,799,907
3,799,961
using c# dll in project c++
i want use dll made in c#(visual studio 2008) in c++ project(visual studio 2003). how to do that ? please heeelp
There is more than just COM interop, the MSDN FAQ also lists lesser known methods: 2.2 How do I call .NET assembly from native Visual C++? There are basically four methods to call .NET assembly from native VC++ code. Microsoft All-In-One Code Framework has working examples that demonstrate the methods. Native V...
3,799,972
3,800,064
Cross platform solution to undecorating a window?
This is a follow up to this question. Since, it I can't use GLUT to undecorated windows is there a cross-platform (which should include Mac, Windows, and Ubuntu at minimum) library or way to undecorated a window? I know there are ways to do this for individual operating systems but, I wanted a cross platform way to do ...
Have a look at borderless windows in Qt. Making a borderless window with for Qt
3,799,989
3,799,991
Argument of type float does not match GLfloat?
im trying to do something here but that error shows up i really have no idea how to get it done right i tried to put all the variables in the Figure.h as GLfloat instead of just float and the same error keeps appearing any idea? here is my Figure.h Class Figure { public: Figure(float x,float y,float z); ...
You need to call the functions: glNormal3f(p->paramx(), p->paramy(), p->paramz()); glVertex3f(p->paramx(), p->paramy(), p->paramz());
3,800,141
3,800,160
Ambiguous template error adding std::string to uint in Visual C++
I'm getting the following error when I compile the following code on Visual Studio 2008 / Windows SDK 7 const UINT a_uint; UINT result; throw std::runtime_error( std::string("we did ") + a_uint + " and got " + result ); Ironically, I ended up with this result: error C2782: 'std::basic_strin...
You can reduce that to this template<typename T> void f(T, T); int main() { f('0', 0); // is T int or char? } You try to add an unsigned int to a string. That does not make sense, and the std::string class does not need to take any precautions to add implicit conversions to char here because that would hide such pot...
3,800,179
3,800,281
Invalid use of class in C++?
hi im trying to pass some values to a class but it wont let me it says invalid use of class 'Figure' im trying to send 3 values x,y,z and thats all but it wont let me heres what im trying to do... here is the main.cpp and the function that calls the class Figure for (j = 0; j < num_elems; j++) { /* grab and eleme...
@dark_charlie's answer is almost correct. Here is a better version that will actually work, but still probably isn't what you want: class Figure { // ... public: void set(float x, float y, float z); // ... }; void Figure::set(float x, float y, float z) { // Your original code from the constructor this->x1 ...
3,800,235
3,800,461
For no copy classes, can I change the code so that the VS2010 compiler will flag an error on the offending line?
Can I change the code, so that the VS2010 compiler's error message points to the offending line of code? class NoCopy { //<-- error shows up here NoCopy( const NoCopy& ); //<-- and error shows up here NoCopy& operator=( const NoCopy& ); public: NoCopy(){}; }; struct AnotherClass :NoCopy { }; //<-- and error ...
The error is not shown at the correct line, because Visual Studio doesn't know where it came from, which is the automatically compiled AnotherClass(const AnotherClass&). You have to explicitly define this in order for Visual Studio to continue finding where the error came from. class NoCopy { NoCopy( const NoCopy& )...
3,800,581
3,800,614
Calculating quaternions from gyro + accelerometer data
I have gyroscope + accelerometer data at each time period T. Using C++, I want to calculate the rotation of the object at each time - it can rotate on its axes. I've read that it is convenient to represent the rotation of the system in terms of quaternions (not in Euler angles). How can I transform from angular veloci...
I'm not sure which language you're looking for, but the C++ Boost library has a working Quaternion class (quaternion.hpp). I've used this library to create a simple rotation class for computing the results or rotating points about arbitrary vectors with very little difficulty. UPDATE: Based on your comment, I don't th...
3,800,804
3,800,824
Is it safe to read a single c++ std::map object by different threads simultaneously without synchronization mechanisms?
I have a global object holding several c++ std::map objects. This object is supposed to be read only in a multithreaded environment. But i'm not sure whether there is any write operation when a C++ std::map object is being read within the implementation of std::map. The IDE is Visual Studio 2008. Should I provide some ...
Yes this will be OK provided nobody is writing to the map. See here for full details. Thread safety of std::map for read-only operations
3,800,841
3,800,968
C++: Container of original pointers
I need to store references to instances of derived classes in C++. I considered using a vector of shared_ptrs to the base class (for it needs to hold different types of derived classes), however, it's important that the container holds the original pointers, which is not the case with vectors (or other stl containers),...
In your example above, what you are printing out is the address of the pointer not the value of the pointer. Instead of: // different ptr value std::cout << &foos[0] << "\n"; Do // different ptr value std::cout << foos[0] << "\n"; Aside from that your vector<Foo*> will work just fine.
3,800,890
3,800,899
Why can't compiler optimize these 2 statements out?
Is there any reason that the compiler cannot optimize the following 2 statements out in main even I turned on fully optimization in Visual C++? Any side effect to access a int variable in memory? int _tmain(int argc, _TCHAR* argv[]) { volatile int pleaseOptimizeMeOut = 100; (pleaseOptimizeMeOut); return 0...
It can't optimise them out because you have declared the variable to be volatile. Loads and stores to volatile qualified objects are part of the "externally visible" effects of the C abstract machine. (By the way, there are plenty of side effects when accessing a variable in memory; it can update hardware memory cache...
3,801,121
3,801,924
OpenMP Parallelizing code-block inside a for loop?
Greetings all, I want to run the code block inside the loop ,in seperate OpenMP thread. Have I defined correct OpenMP directives in the following code snippet: #ifdef OPENMP_ENABLE #pragma omp parallel for #endif for(int i=0;i<numOfSlices;i++){ // Entire block inside this loop should be fu...
I found the issue.the reason was that the "cnty_extract_contour()" method is not thread-safe.
3,801,167
3,801,299
Templates :Name resolution:Dependent types: -->can any one tell some more examples for this statement?
This is the statement from ISO C++ Standard 14.6.2.1: Dependent types : A type is dependent if it is — a template parameter,#1 — a qualified-id with a nested-name-specifier which contains a class-name that names a dependent type or whose unqualified-id names a dependent type,#2 — a cv-qualified type where the cv-unq...
Working from 1) a type is dependent if it is a template parameter: template <typename T, int N, template <typename> class My_Template> struct X { 5 — an array type constructed from any dependent type or whose size is specified by a constant expression that is value-dependent, T a[5]; // array of dependent t...
3,801,518
3,801,555
linux tool to list all functions in a source file?
I am looking for a command line utility on *nix, that can dump the names of all the functions, classes etc. defined in a file(C/C++/Java)
ctags can give you that (and much more). It is included with most Linux distributions... http://ctags.sourceforge.net/whatis.html
3,801,552
3,805,609
run out of system resource (execute many programs in a shell script)
I'm running a shell script on the university's server. In this shell script, I will execute java, c, c++, python and perl programs. Because every program will be executed many many times(I'm a teaching assistant and will test the students' programs with many different inputs). The server always gives me an error: "runn...
Since you are automatically running students' programs then it may be that their programs are badly written and using more RAM than similar programs written by more skilled programmers would require. Even Java and Python programs can be written in such a way as to leak memory (think about a stack that never gets anyth...
3,801,648
3,801,788
Why doesn't shared_ptr have a virtual descructor? (and how can I get around this?)
I wanted to make a special version of shared_ptr that would perform specific operations when it was created or destroyed, but my plans appear to be foiled by the realization that shared_ptr's destructor is non virtual, meaning when I override it, my pointers never get cleaned up when the last instance of them are dest...
It already has this ability built in without the need to let people do dangerous things like derive from it: #include <boost/shared_ptr.hpp> #include <iostream> /* * Done as a function for simplicity. * But this can be done in so many ways */ void MyCleanup(int* x) { std::cout << "DONE\n"; delete x; } int ...
3,801,715
3,801,893
using OpenMPI or MPICH with Boost MPI using Win and Linux machines together
These days I am approaching MPI world. I am willing to use Boost MPI libraries probably with OpenMPI or MPICH ( even if with MPICH still I am not sure whether it will work fine because of some post I read around ). My real question is the following: with these 2 libraries and Boost MPI on top of it, is it possible to c...
I don't know much about the Boost MPI layer, but it is definitely possible to use MPICH2 with Linux and Windows machines simultaneously. In this case, you must use the same "variant" of MPICH2, and you must use the "smpd" process manager in each case (this is the only option on Windows, but it is not the default on Lin...
3,802,059
14,826,747
How to convert a char array into string based hex-stream (ostringstream)
in C++ (on Linux with gcc) I'd like to put a byte array (vector<unsigned char>) to a ostringstream or a string. I know that I can use sprintf but it doesn't seem to be the best way to use char* also. btw: this link did not help Edit: All answer work so far. But I did not meantion, that I'd like to convert the bytes/hex...
Little chance of getting an up-vote, but since it is exactly what the OP asked for, and no other answer, including the selected one, oddly, does so: #include <iostream> #include <sstream> #include <vector> #include <iomanip> // used by bin2hex for conversion via stream. struct bin2hex_str { std::ostream& os; b...
3,802,334
3,802,361
How to resolve dependent classes?
I have two classes which depend on each other. I've solved this problem before but I can not for the life of me remember how to fix this. My simplified code is this: struct MenuOption{ string Text; int Choice; bool UseSubMenu; Menu SubMenu; }; class Menu{ public: Menu(MenuOption optionlist[],int optioncount)...
Use forward declarations I.e.: // Forward declaration to assure A of B's existence. class B; class A { // uses B B* b; }; class B { // uses A A* a; }; Use pointers and not object instances: because the compiler needs to know how much space to allocate to the members of a class. Having an object instance there...
3,802,454
3,806,373
Can C++0x still explicitly allocate with global operator new?
Wikipedia states: A type can be made impossible to allocate with operator new: struct NonNewable { void *operator new(std::size_t) = delete; }; An object of this type can only ever be allocated as a stack object or as a member of another type. It cannot be directly heap-allocated without non-portable trickery. (S...
I believe you are right and wikipedia is wrong. The C++0x draft standard describes "deleted functions" (8.4p10) as functions which may not be used in any way (or else the program is ill-formed). They play no part in scope or name lookup different from normal functions. And the relevant paragraphs concerning new expr...
3,802,504
3,802,511
Initializing a structure in c++
g++ 4.4.3 I have the following structure from a API guide: typedef struct NETWORK_INFO { int network_id; int count; } NETWORK_INFO, *NETWORK_INFO; And in the source code they are doing this: NETWORK_INFO net_info = {}; Is the 2 curly braces initializing the object of the structure? But what would it initializ...
This will default-initialize all fields of variable net_info - set them both to zero. That's a handy one-liner used to initialize structs that don't have a user-defined constructor instead of using memset().
3,802,527
3,802,536
While loop, doesn't seem to do anything?
Hi there i'm trying to make a function in C++ that takes a number, i, and decides if it is a prime number or not by running through a loop to find it's multiples, and then makes sure it isn't prime through a series of test. However, it seems the loop isn't even being run through. I've told it to output no matter where ...
You are using = instead of == in while (p = false){ When you do that, you assign false to p and the result of the expression is false which gets tested in the while loop resulting in exiting of the loop.
3,802,546
3,805,096
Can we execute rightclick without using pCmdInfo->lpVerb
I am not agnaist using pCmdInfo->lpVerb but my problem is how will we handle the situation when we create the rightclick submenus dynamically. For example, I have the following scenario: if(strcmp(cRegKeyVal,"Connected")==0) { //g_bConnectStatus=TRUE; InsertMenu ( m_hSubmenu , 0, MF_BYPOSITION|MF_G...
You are supposed to store the menu item identifiers (or offsets?) in QueryContextMenu for use later in InvokeCommand: QueryContextMenu() { m_uConnectId = m_uCmdID++; InsertMenu( m_hSubMenu, "Connect" ); m_uHelpId = m_uCmdID++; InsertMenu( m_hSubMen, "Help" ); } InvokeCommand() { ULONG uCmdID = LOWO...
3,802,578
3,803,695
C++ JMS client or C++/C SOAP Client
I have an application in C++, but it'll need to 'talk' to Java based message-service. In the past we used WebSphere MQ and used their C++ libraries to do the 'talking'. So I am in search of (ideally) free C++ to Java solution which doesn't hold the whole JVM in memory. The other option I've looked into is SOAP. I've ...
There are a couple of points here which don't make sense to me, JMS is a java specific abstraction over a generic messaging API, much the same way that JDBC is a java specific abstraction over a generic database API. I can't imagine anyone wanting a JDBC driver for a C++ application, they would rather use an ODBC drive...
3,802,710
4,991,082
Getting pointer to bottom of the call stack and resolving symbol by address (like dladdr) under Windows?
I want to implement an analog of backtrace utility under windows in order to add this information to exception for example. I need to capture return addresses and then translate it into symbols names. I'm aware of StackWalk64 and of StackWalker project but unfortunately it has several important drawbacks: It is known ...
Capturing Stack Trace: RtlCaptureStackBackTrace Getting Symbols: Using DBG Help library (MSVC only). Key functions: // Initialization hProcess = GetCurrentProcess() SymSetOptions(SYMOPT_DEFERRED_LOADS) SymInitialize(hProcess, NULL, TRUE) // Fetching symbol SymFromAddr(...) Implementation can be found there
3,802,842
3,802,892
Modularity: Using Interfaces or not?
Since a few years, common sense seems to dictate that it's better to program against interfaces rather than against implementations. For high-level code this indeed seems logical, e.g. if I have a complex solver in my application, it seems better to have something like this: ISolver *solver = solverFactory.getSolver()...
Reasons to move to an interface are when it makes things simpler or reduces coupling. (Thats what an interface is for). Reasons to move away from an interface are if it makes things more complicated or kills performance (but profile that to be sure). I'd argue that your IComplexNumber class actually makes the class hei...
3,803,153
3,803,288
What are primitive types default-initialized to in C++?
When I use an initialization list: struct Struct { Struct() : memberVariable() {} int memberVariable; }; the primitive type (int, bool, float, enum, pointer) member variable is default-initialied. Is the value it gets implementation defined or is it the same for all implementations?
You are not correct. The object is not default-initialized but value-initialized. And its value is well-defined int = 0, bool = false, float = 0.0f, enum = (enum type)0, pointer = null pointer pointer to member = null member pointer Note that zero is in the range of values for any enumeration, even if it doesn't ...
3,803,465
4,043,813
How to capture stdout/stderr with googletest?
Is it possible to capture the stdout and stderr when using the googletest framework? For example, I would like to call a function that writes errors to the console (stderr). Now, when calling the function in the tests, I want to assert that no output appears there. Or, maybe I want to test the error behaviour and want ...
I have used this snippet before to redirect cout calls to a stringstream when testing output. Hopefully it might spark some ideas. I've never used googletest before. // This can be an ofstream as well or any other ostream std::stringstream buffer; // Save cout's buffer here std::streambuf *sbuf = std::cout.rdbuf(); /...
3,803,521
3,803,542
Question about const_cast in c++
all: this is quoted from Effective C++ 3rd editiion const_cast is typically used to cast away the constness of objects. It is the only C++-style cast that can do this. My question is can const_cast add constness to a non-const object? Actually i wrote a small programme trying to approve my thought. class ConstTest...
You don't need const_cast to add constness: class C; C c; C const& const_c = c; The other way around needs a const_cast though const C const_c; C& c = const_cast<C&>(const_c); but behavior is undefined if you try to use non-const operations on c. By the way, if you don't use a reference, a copy of the object is to be...
3,803,671
3,804,045
How can I perform network IO at the very end of a process' lifetime?
I'm developing a DLL in C++ which needs to write some data via a (previously established) TCP/IP connection using the write() call. To be precise, the DLL should send a little 'Process 12345 is terminating at 2007-09-27 15:30:42, value of i is 131' message over the wire when the process goes down. Unfortunately, all th...
Consider monitoring the process from a separate watchdog process. Determining If a Process Has Exited: http://msdn.microsoft.com/en-us/library/y111seb2(v=VS.71).aspx Tutorial: Managing a Windows Process: http://msdn.microsoft.com/en-us/library/s9tkk4a3(v=VS.71).aspx
3,803,825
4,152,299
VC++ CRT Redist problem
I've developed a 64 bit dll using C++ and Visual Studio 2008 and i'm trying to register it on a target machine using 'regsvr32.exe'. I've checked the manifest file and it clearly states what version of CRT is needed: <assemblyIdentity type='win32' name='Microsoft.VC90.CRT' version='9.0.21022.8' processorArchitecture='...
In the end I've managed to fix this by including a newer version of C++ redistributable merge modules into the setup along with all the required policy merge modules in order to redirect the calls to any old version to the new one that's available. Most important thing here is that the exe redistributable include the p...
3,803,853
3,803,879
Constructor and destructor calls
How can I check if my constructor or destructor were ever called? Because of implicit calls I don't know if they were actually called.
Why don't you just put in a couple of cout << "I'm here" in your ctor/dtor or use the debugger and set break points there?
3,803,961
3,803,981
C++ maximum non negative int
Is the following going to work as expected on all platforms, sizes of int, etc? Or is there a more accepted way of doing it? (I made the following up.) #define MAX_NON_NEGATIVE_INT ((int)(((unsigned int)-1) / 2)) I won't insult your intelligence by explaining what it's doing! Edit: I should have mentioned that I canno...
If you don't want to use defines (and you want a standard way of calculating the limits), then do this: #include <limits> std::numeric_limits<int>::min() These are the ANSI standard defines in limits.h: #define INT_MIN (-2147483647 - 1) /* minimum (signed) int value */ #define INT_MAX 2147483647 /* maximu...
3,803,970
3,804,043
What is the difference between operator overloading and operator overriding in C++?
What is the main difference between operator overloading and operator overriding in C++?
Some use the latter term to describe what's being done when you defined an own global operator new or operator delete. That's because your own definition can replace the default version in the library. The C++ Standard uses the words replaces and displaces for this. Using "override" is a bit confusing because that term...
3,804,079
3,804,098
How does virtual method invocation work in C++?
How does Virtual Method Invocation work in C++?
Through virtual tables. Read this article, http://en.wikipedia.org/wiki/Virtual_table. I could explain it here, but the wikipedia does a better job than I could.
3,804,183
3,804,261
How to nicely output a list of separated strings?
Usually, when I had to display a list of separated strings, I was doing something like: using namespace std; vector<string> mylist; // Lets consider it has 3 elements : apple, banana and orange. for (vector<string>::iterator item = mylist.begin(); item != mylist.end(); ++item) { if (item == mylist.begin()) { c...
Although not with std: cout << boost::algorithm::join(mylist, ", "); EDIT: No problem: cout << boost::algorithm::join(mylist | boost::adaptors::transformed(boost::lexical_cast<string,int>), ", " );
3,804,219
3,804,297
What is the difference between c++, objective-c and objective-c++?
I want to know the difference between c++ and objective-c and objective-c++. Can any one give me the difference and Can we use the c++ for iPhone development Thank you, Madan Mohan
C++ is Bjarne Stroustroup's language based on adding classes and metaprogramming to C in such a way that puts most additional work into the compiler, and relies on least possible effort at runtime. Objective-C is Brad Cox's language based on adding a SmallTalk-style dynamic message-passing runtime library to C, with a ...
3,804,570
3,804,892
Using Boost.build to include a library
I am using boost.build to compile a c++ code which references a library, CGNS, but am having some difficulty with using boost.build to do so. CGNS compiles to a library, with a folder for the platform, for example [path]/LINUX for the linux build. I would like to include the library [path]/LINUX/libcgns.a in the buil...
Using two references, http://www.highscore.de/cpp/boostbuild/, and http://www.boost.org/doc/tools/build/doc/userman.pdf, I created something that works, but it may not be the ideal. lib cgns : # sources : # requirements <name>cgns <target-os>linux:<search>../Dependencies/cgnslib/LINUX ...
3,804,573
3,804,627
C++ Prime factor program 2 problems
Okay so I"m writing a program (in C++) that is supposed to take a number, go through it, find out if it's factors are prime, if so add that to a sum, and then output the sum of all of the imputed number's prime factors. My program successfully seems to do this however it has 2 problems, 1) The number I am supposed to...
For 1), you need to use a larger datatype. A 64-bit integer should be enough here, so change your ints to whatever the 64-bit integer type is called on your platform (probably long, or maybe long long). For 2), the problem appears to be that you have a break before your return false. The break causes the code to stop t...
3,804,884
3,805,874
custom allocator using move for vector of thread
I'm currently learning about concurrency in C++ and came across using a vector of threads, which I believe will be possible in C++0x. However, my current compiler doesn't appear to have an implementation of move-aware containers and so I get errors generated because std::thread::thread(const std::thread&) is deleted, i...
If your compiler doesn't provide a move-aware std::vector then you'll have to write your own specialization of std::vector<std::thread> rather than just provide a custom allocator. The whole C++03 vector interface relies on copying: push_back() copies elements in; resize() initializes the empty elements with a copy of ...
3,804,932
3,804,990
Why is my heap is corrupted?
I'm getting an error - heap corruption, can't figure out why. My base : h: class Base { public : Base(char* baseName, char* cityName); virtual ~Base(); list<Vehicle*>::const_iterator GetEndList(); void PrintAllVehicles(ofstream &ResultFile) const; char* GetBaseName() const; char* GetLocatio...
There's nothing obviously wrong with the code you've shown, so chances are that the error is in code you haven't shown. The most immediately suspicious thing to me is that the Base class owns two pointers and does not have a copy constructor or assignment operator defined. This means that should you ever copy a Base ob...
3,805,041
3,805,048
Why would you "default" a copy/move constructor or a destructor?
C++0x lets you specify certain functions as defaulted: struct A { A() = default; // default ctor A(A const&) = default; // copy ctor A(A&&) = default; // move ctor A(Other); // other ctor ~A() = default; // dtor A& operator=(A const&) = default; // copy assignment A...
You might need to do this to change their access to non-public or to control which translation unit defines them. Non-public Even though these functions are commonly public, you may wish them to be non-public while still desiring the default implementation: struct A { protected: ~A(); private: A(); A(A const&); ...
3,805,319
3,805,363
Initialize already declared char array in C++
I want to use something like this: char theArray[]=new char[8]; theArray= { 1,2,3,4,5,6,7,8}; instead of char theArray[] = { 1,2,3,4,5,6,7,8}; Is a similar thing possible?
C++0x char* ch; ch = new char[8]{1, 2, 3, 4, 5, 6, 7, 8}; @David Thornley: then switch these lines and there is no problem. And seriously you're talking about reallocating char[8] in the same memory pool as the previous value, then you need to play with own allocators, something like: char* ch1 = new char[8]{'a', 'b'...
3,805,362
3,805,385
C++ reading in specific segments of data from a file redirected to my program
I'm working on a program that takes a redirected file as input. For example, if my program was called foo I would call the program with ./foo < input.txt. The files I'm running through my program are supposed to be formatted with a single integer on the first line, two integers on the second line. So something like 3 1...
If the file is of the form [number] garbage [number] [number] garbage and you know that the numbers are always in the correct position on the line, then I'd use std::getline() to read each line then attempt to read the expected number of integers from each line that you read.
3,805,611
3,805,673
Returning an argument pointer to an object
In C++ for Windows, I have some object factory that is supposed to create a series of Info object by passing a pointer to the object to a Create function and returning a created object. void CreateInfoObject(AbstractInfo** info); // The creation function AbstractInfo is a base class of which we have many types of In...
Let's think about a possible implementation of CreateInfoObject: void InfoFactory::CreateInfoObject(AbstractInfo** info) { *info = new SuperInfo; } Now, SuperInfo and MyInfoObject do not have anything in common right ? This is why, in general, the following is forbidden: struct Base {}; struct D1: Base {}; struct D2...
3,806,361
3,806,397
How do plugin systems work?
I'm working on a project where I would find a basic plugin system useful. Essentially, I create the base class and can provide this base class to a plugin developer. Then the developer overrides it and overrides the methods. Then this is where it becomes a bit unclear to me. How does it work from here? Where could I fi...
The plugin systems I know of all use dynamic libraries. Basically, you need to define a small, effective handshake between the system kernel and the plugins. Since there is no C++ ABI, plugins must either only use a C API or use the very same compiler (and probably compiler version) as the system's kernel. The simples...
3,806,525
3,806,551
"missing type specifier" error on constructor declaration
I have 2 classes in 2 different files: RegMatrix.h: #ifndef _RM_H #define _RM_H #include "SparseMatrix.h" ... class RegMatrix{ ... RegMatrix(const SparseMatrix &s){...} //ctor ... }; #endif SparseMatrix.h: #ifndef _SM_H #define _SM_H #include "RegMatrix.h" ... class SparseMatrix{ ... SparseMatr...
You can't have circular #includes (one file #includes another which #includes the first file). Forward declaring one of the classes instead of the #include will break the chain and allow it to work. Declaring the class name allows you to use the name without having to know about the internal bits of the class. BTW, t...
3,806,665
3,806,686
How important is consistent usage of using declarations?
Most of the research I've done on the use of using declarations, including reading relevant sections of various style guides, indicates that whether or not to use using declarations in C++ source files, as long as they appear after all #includes, is a decision left to the coder. Even the style guides I read, which usua...
I think the whole point of using is that you use it inconsistently among names. Names you need very frequently in some block can be declared locally with a using declaration, while others are not. I don't see a problem with that. Declaring a name to have namespace scope is always much harder to take. I think if the na...
3,806,739
3,806,772
Why firefox is written in C++ and javascript UI?
Well..I am learning java now and I am curious to know will this yield a noticeable performance increase ? And If many developers are following similar methodology for windows programming ( C++ back end and Java UI ) or other languages are used like python? *this : C++ back end and other languages for UI instead of usi...
Firstly, Java and JavaScript are completely different and unrelated languages. Firefox uses JavaScript; it does not use Java at all. Secondly, this was not done for performance reasons, it was done to make it simpler to write add-ons and extensions that can be used with Firefox on any platform. C++ code needs to be com...
3,807,163
3,807,263
std::cin in an Array
I am a CS student trying to grasp some C++ basic concepts. I am trying to get the input of a user from std::cin and put it to an array. example : Input > ab ba cd[Entey key pressed] then I would like the array to contain [ab][ba][cd]. So far I have : #include <iostream> #include <string> int main(int argc, char** arg...
std::string::compare does not return a boolean value -- it returns an int. This is used for sorting strings. It will return <0 if the left string is less, >0 if the right string is less, and 0 if they are the same. 0 is the same as boolean false, so your if statement is actually breaking whenever the string is NOT "...
3,807,346
3,807,491
Bi quinary coded examples
i have following problem To decode the Biquinary code use the number 5043210. At each digit multiply the biquinary number by the number 5043210. This will give you one decimal digit. For example take the number 0110000. To change this into decimal: (5 × 0) + (0 × 1) + (4 × 1) + (3 × 0) + (2 × 0) + (1 × 0) + (0 × 0) = 4...
Try changing (b>>(1<<(n-1-i))) to just (b>>(n-1-i)&1). Edit: Forgot to mention that the given program also counts the null terminator on the string. The computation of n should subtract one to correct for it: int n=sizeof(a)/sizeof(char)-1;.
3,807,505
3,807,618
C/C++ - overriding default functions
I have the following question: Does Microsoft Visual Studio (I'm using 2008 SP1) offer any way to override standart C functions such as malloc, memcpy? Suppose I have some externally built library, which contains malloc.obj and memcpy.obj. Library is called library.lib. How should I build my project so that the compile...
Have not tried this but - in Project properties -> Linker -> Input, set 'Ignore All Default Libraries' to Yes. Then set 'Additional Dependencies' = library.lib;libcmt.lib. This ought to include your library ahead of the standard static CRT. Provided function linkage is the same in each this should do what you want. ...
3,807,600
3,807,657
Properties of Properties as Templates
I try to implement C++ properties as templates as defined in WikiPedia template <typename T> class property { T value; public: T & operator = (const T &i) { ::std::cout << i << ::std::endl; return value = i; } // This template class member function template se...
Casting one object to another type results in a temporary copy that goes out of scope as soon as that line of code is done. Did you mean to write ((A&) b.pB1).pA1=1; ?
3,807,606
3,807,622
while(true) versus for(;;)
Possible Duplicates: Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it? for ( ; ; ) or while ( true ) - Which is the Correct C# Infinite Loop? Is there any appreciable difference between while(true) (or while(1)) and for(;;)? Would there be any reason to choose one over the other?
With optimizations enabled, they will compile identically. You should use whichever one you find more readable.
3,807,635
3,807,650
C++ converting an int to an array of chars?
Possible Duplicate: C++ convert int and string to char* Hello, i am making a game and I have a score board in it. The score is stored in an int variable but the library im using for the game needs an array of chars for its text outputting for my scoreboard. So how do i turn an int into an array of chars? int score...
ostringstream sout; sout << score; dbText(100,100, sout.str().c_str());
3,807,791
3,807,855
Cold startup optimization
I tried to search, but so far with no luck. Does anyone know a good resource how one should do cold start optimizations? The app in question is C++/MFC app, compiled with VS2010, full version, with built in profiler available. I have tried to cut down all the extra weight to get the load times acceptable for warm start...
One thing that might help is to have a look into profile guided optimisation, which reorders the executable so that things load in the most efficient order. But really you should try and work out where the time's going - sounds like it might be doing a lot of disk access - are you loading a lot of big data (images, etc...
3,807,826
3,807,851
calling an objects function while inside a different objects function
For some reason i can't seem to get this right ok i have 2 objects class score { public: int scored(int amount); private: int currentscore; } int score::scored(int amount) { currentscore += amount; return 0; } class collisions { public: int lasers(); } // ok heres my issue int collisions::lasers() ...
This is your problem: collisions collisions; score score; You should not declare a variable with the same name as its type. Make the types uppercase and everything should work OK for you. Also do not forget to move the definition of those two variables above the functions they are being used in.
3,807,857
3,807,869
Access Objective-C variable from C++ function
I'm working on a project that just needs to be rewritten but that is not an option at this point. I have a C++ function that is called and does all kinds of stuff. I need it to read a variable from the App Delegate class. For example I have: @interface MyAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *...
Xcode supports Objective-C++, which enables you to use Objective-C calls from C++ code. Change the extension of your C++ code file from .cpp (or .cc) to .mm and you'll be able to get the value from your C++ code just as you would from Objective-C code.
3,807,945
3,808,184
MFC data forwarding to main thread via PostMessage
I have a C++/MFC application I need to restructure. The app used to process most of the data on the main thread, therefore blocking the input, and now I want to change it so, that all GUI updates are done through PostMessage. Unfortunately, I can't seem to find a good source on how to achieve this goal. Right now I'm t...
Your messages will get there. I'm not sure why you think PostMessage isn't guaranteed to work -- it is. (EDIT: Assuming PostMessage() returns TRUE! Check your return codes!) You want to avoid using a queue to communicate data between the threads. Any queue that is accessed by both threads will need to be protected...
3,807,978
3,808,058
C++ restrict implicit construct to specific value
Suppose: struct P { P(int v); }; int v; P p = 0; // allow P q = v; // Fail at compile time How can achieve that? any template trick? I am trying to write allocator which has special pointer properties. unfortunately std implementation uses implicit conversion from int to NULL pointer: { return __n != 0 ? _M_impl...
You can do it but you won't like it struct P { private: struct null_absorb; public: P(null_absorb *v); }; int v; P p = 0; // allow P q = v; // Fail at compile time This will only allow null pointer constants. In other words, zero compile time values.
3,808,148
3,808,204
Project Euler Problem 12 - C++
I'm working on problem 12 regarding the first triangle number with 500 divisors. I tried to brute force the solution. I get 300 divisors in about 35 seconds and can't get 400 within 10 minutes. I'm going to alter my solution to use the prime factor method but I've seen now that people are still getting this solution...
You currently check for divisors up to dividend/2. You can reduce this to sqrt(dividend), which is asymptotically faster. A special case may be needed if dividend is square. My C++ code for problem 12 (which does essentially the same as yours, but uses this lower limit, and also just counts divisors rather than storing...
3,808,220
3,808,243
Are type fields pure evil?
As discusses in The c++ Programming Language 3rd Edition in section 12.2.5, type fields tend to create code that is less versatile, error-prone, less intuitive, and less maintainable than the equivalent code that uses virtual functions and polymorphism. As a short example, here is how a type field would be used: void p...
When you "know" you have a very specific, small, constant set of types, it can be easier to hardcode them like this. Of course, constants aren't and variables don't, so at some point you might have to rewrite the whole thing anyway. This is, more or less, the technique used for discriminated unions in several of Alexa...
3,808,393
3,808,420
Bad C++ programmer behaviors in C#
Possible Duplicate: Most common or vicious mistakes in C# development for experienced C++ programmers I'm a long time C++ programmer about to start working on C# projects. What are some conceptual changes to be aware of, and most importantly, what should I avoid doing in C# that I would normally do in C++? What bad ...
Just one example: In C++ there is no difference between a struct and a class. Over the years this has led groups and individuals to define their own rules for using one over the other. In C# there is a concrete difference. A struct is a value type and a class is a reference type. When C++ programmers bring thier old, a...
3,808,480
3,808,536
Deallocating objects stored in a vector?
I have a class that creates a vector of objects. In the deconstructor for this class I'm trying to deallocate the memory assigned to the objects. I'm trying to do this by just looping through the vector. So, if the vector is called maps I'm doing: Building::~Building() { int i; for (i=0; i<maps.size(); i++) { ...
It depends on how vector is defined. If maps is a vector<myClass*> you delete each element with something similar to: for ( i = 0; i < maps.size(); i++) { delete maps[i]; } If maps is a vector<myClass> I don't think you need to delete the individual elements.
3,808,708
3,808,715
Delete parts of a dynamic array and grow other
I need to have a dynamic array, so I need to allocate the necessary amount of memory through a pointer. What makes me wonder about which is a good solution, is that C++ has the ability to do something like: int * p = new int[6]; which allocates the necessary array. What I need is that, afterwards, I want to grow some ...
You achieve this behavior by using std::vector: std::vector<int> v(6); // create a vector with six elements. v.erase(v.begin() + 2); // erase the element at v[2] v.insert(v.begin() + 2, 4, 0); // insert four new elements starting at v[2] Really, any time you want to use a dynamically allocated array, yo...
3,808,728
3,808,798
boost library..........pre-built variants?
im just installing the boost library using an installer. Its asking me which variants (about 8 options, 6 multithreaded and 2 single threaded) do i want to install. Im only installing this to get to grips and have a practice with boost, so im unsure? Also, how do i use the libraries from VS02010 once ive 'installed' th...
Boost documentation is your friend. A read of the information on getting started on Windows would save you much time. Most of the libraries are header-only. You can use these just by including the correct headers as described in the individual library docs. If you want to use any of the ones that are not, you are go...
3,808,778
4,134,859
How to handle exceptions from C++ via SWIG to Java
We are implementing a wrapper on C++ code for exposure to Java clients. I have seen the SWIG documents about exception handling but what does this translate to in coding terms in the three layers (C++/SWIG/Java)? If anybody has working example(s) or advice, I would be grateful.
Since I've wrestled with this (see my blog from my profile, it's on python, SWIG, exceptions and directors but should help) let me give you a few pieces of advice: Don't send C++ exceptions up to the Java stack. It'll crash your application. Make sure they're all wrapped in the correct manner. I know you're asking ...