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,717,988
3,718,134
Why does the debugger need symbols to reconstruct the stack?
When debugging in Visual Studio, if symbols for a call stack are missing, for example: 00 > HelloWorld.exe!my_function(int y=42) Line 291 01 dynlib2.dll!10011435() [Frames below may be incorrect and/or missing, no symbols loaded for dynlib2.dll] 02 dynlib2.dll!10011497() 03 HelloWorld.exe!wmain(int __form...
I think this is because not all the functions follow the "standard" stack layout. Usually every function starts with: push ebp mov ebp,esp and ends with pop ebp ret By this every function creates its so-called stack frame. EBP always points to the beginning of the top stack frame. In every...
3,718,009
3,718,042
Strange #define in Template?
I've got a small bit of code from a library that does this: #define VMMLIB_ALIGN( var ) var template< size_t M, typename T = float > class vector { ... private: // storage VMMLIB_ALIGN( T array[ M ] ); }; And you can call it by doing //(vector<float> myVector) myVector.array; No parenthesis or anything. what? ...
Ultimately, myVector.array refers to the array variable in the class, and variables don't need the function-calling notation (). BTW / all-capital identifiers should only be used for preprocessor macros (as they are here). In this case, the macro VMMLIB_ALIGN must be being used to make it easier to later "enchance" th...
3,718,017
3,718,048
Clearing a carriage return from memory in C++
I have the following code: int main() { // Variables char name; // Take the users name as input cout << "Please enter you name..." << endl; cin >> name; // Write "Hello, world!" and await user response cout << "Hello, " << name << "!" << endl; cout << "Please press [ENTER] to continue..."; cin.get(); return 0; } A...
simplest answer: int main() { // Variables char name; // Take the users name as input cout << "Please enter you name..." << endl; cin >> name; cin.get(); // get return here // Write "Hello, world!" and await user response cout << "Hello, " << name << "!" << endl; cout << "Please press [ENTER] to continue..."; cin.ge...
3,718,162
3,718,180
fast retrieval of (void *) memory block
I have a system that returns a void* to a memory block. This memory block stores contiguous data records of different types(int,char,double etc.) and gives the number of bytes of each field in each record.I essentially look up the type of the record and get the value of the record. To retrieve all the records, I do swi...
If a single block can be of multiple types that can only be resolved at runtime, you will have to dispatch to handlers in a switch statement. Note that: unions are usually used in C for such things to save space switch statements are very fast and translate to constant-time lookup tables
3,718,301
3,718,623
Is there a way to optimize doxygen for C++?
For a Qt/C++ project we will use doxygen to generate some documentation, therefore I'm searching for a "optimal" config file. One thing that I was thinking about is that you have stuff like OPTIMIZE_OUTPUT_FOR_C = NO OPTIMIZE_OUTPUT_JAVA = NO OPTIMIZE_FOR_FORTRAN = NO OPTIMIZE_OUTPUT_VHDL = NO But I can't find...
It seems to me that Doxygen is by default optimized for C++. From what I can tell, C++ was the first language that Doxygen was designed to be used with; it was supported as far back as the "Change Log" goes. Java support, on the other hand, was not added until version 1.2.5. The OPTIMIZE_OUTPUT_FOR_C option was also no...
3,718,304
3,718,499
Predefined text replacements in C++ and Python
As a hobby project, I had like to implement a Morse code encoder and decoder in C++ and Python (both). I was wondering the right data structure I should use for that. Not only is this question related to this specific project, but in general, when one has to make predefined text replacements, what is the best and the f...
There's no simple optimal structure - for any given fixed mapping, there might be fiendish bit-twiddling optimisations for that precise mapping, that are better or worse on different architectures and different inputs. A map/dictionary should be pretty good all the time, and the code is pretty simple. My official advic...
3,718,424
3,718,433
Tools for Memory leaks in .Net executable
Possible Duplicate: What Are Some Good .NET Profilers? I am trying to test an application in Windows for memory leaks. I have looked at Linux alternatives (eg. Valgrind) and I am looking for a similar tool for Windows. The problem with .Net is that the memory is not released straight away like in Linux. My knowledg...
Redgate has a nice memory profiler you can download here. It even comes with a 14-day trial. I have used it and it is very good.
3,718,445
3,718,525
Changing Visual Studio default path for .cpp, .h file
I would like Visual Studio to automatically put my .h file in a folder /ProjectPath/include and my src file in /ProjectPath/src. That way, if I use the "Create class wizard" for instance, it would put the good path by default without me having to change the folder. Anyone know what setting I should change to get this ...
You can right click on a folder in solution explorer and go to properties, you need to set the Filter property. For example the Source Files folder by default has a filter like this in a C++ project: cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx
3,718,759
3,722,247
Mangled symbol table in Objective-C when linking static C++ library
I have a class called options written in c++, here is the header info: class Options { public: string filename; string chunkDir; string outFilename; string inFilename; BOOL compress; BOOL extract; BOOL print; BOOL reconstruct; int bits; Options(string inFilename); Options(int argc, char** argv); void unsupp...
In Objective-C, BOOL is a typedef to signed char. What definition are you using when compiling pure C++? If it's different, you'll get all sorts of weirdness, because the C++ code and the Objective-C++ code won't agree on the size or layout of the member variables.
3,718,816
3,719,078
sse inline assembly with g++
I'm trying out g++ inline assembly and sse and wrote a first program. It segfaults - why? #include <stdio.h> float s[128*4] __attribute__((aligned(16))); #define r0 3 #define r1 17 #define r2 110 #define rs0 "3" #define rs1 "17" #define rs2 "110" int main () { s[r0*4+0] = 2.0; s[r0*4+1] = 3.0; s[r0*4+2] = 4.0; ...
You're loading the data at s[0] into %edx and using it as a pointer. When you then try to access %edx + 0x30, you crash, because s[0] + 48 is not mapped for your process to read from. (Specifically, since s is global and therefore initialized to all zeros, you're trying to load from the address 0x30)
3,718,910
3,718,950
Can I get the size of a struct field w/o creating an instance of the struct?
It's trivial to get the size of a struct's field in C++ if you have an instance of the struct. E.g. (uncompiled): typedef struct Foo { int bar; bool baz; } Foo; // ... Foo s; StoreInSomething(s.bar, sizeof(s.bar)); // easy as pie Now I can still do something like this, but with the interface I'm implementin...
You can use an expression such as: sizeof Foo().bar As the argument of sizeof isn't evaluated, only its type, no temporary is actually created. If Foo wasn't default constructible (unlike your example), you'd have to use a different expression such as one involving a pointer. (Thanks to Mike Seymour) sizeof ((Foo*)0)...
3,718,998
3,719,031
Fixing Segmentation faults in C++
I am writing a cross-platform C++ program for Windows and Unix. On the Window side, the code will compile and execute no problem. On the Unix side, it will compile however when I try to run it, I get a segmentation fault. My initial hunch is that there is a problem with pointers. What are good methodologies to find and...
Compile your application with -g, then you'll have debug symbols in the binary file. Use gdb to open the gdb console. Use file and pass it your application's binary file in the console. Use run and pass in any arguments your application needs to start. Do something to cause a Segmentation Fault. Type bt in the gdb con...
3,719,675
12,305,620
Strange behavior for X.cpp/X.hpp files in Integrity
I'm having a project which compiles perfectly with gcc, but fails to compile under Greenhills Integrity environment. The problem boils down to this three files: MyVector.cpp // contains function testVector MyVector.hpp // contains template vector<> SomeFile.cpp MyVector.hpp contains template-class for a vector, and My...
Green Hills uses the Edison Design Group front-end, and until very recently (say, MULTI 5.0 or maybe even 5.2) the compiler turned on --implicit_include by default. Here's the Edison documentation for that option: --implicit_include --no_implicit_include -B Enable or disable implicit inclusion of source files as a...
3,719,896
3,719,934
Adding const-ness after the fact in C++
Possible Duplicate: Is there some ninja trick to make a variable constant after its declaration? Consider the following minimal example: void MutateData(std::string&); int main() { std::string data = "something that makes sense to humans."; ::MutateData(data); // Mutates 'data' -- e.g., only changes the order ...
What about: string MakeData(string const&) { ... return string(...); // for return value optimization } followed by int main() { string const& str = MakeData("Something that makes sense to humans"); } The difference with what you do is using a const reference, and only one function. If you cannot change ...
3,719,907
3,731,607
C++, JsonCpp, libcurl and UTF-8 woes
I had some problems making libcurl work with C++ JsonCpp library and, after a lot of research, I came up with this code: int post(const string& call, const string& key, const string& value) { // (...) char* char_data=NULL; struct curl_slist *headers=NULL; headers = curl_slist_append(headers, "Content-Type: a...
I found the problem. It wasn't on that part of code. I was actually doing a string split that was causing the problem.
3,719,979
3,720,001
C++ Unicode Bullet Point
I am trying to insert the Unicode character U+2022 (bullet •) in my C++ application. I can't figure out how to convert that U+2022 to a char/string for use in std::string constructor... char bullet = char(0x2022); mPassword.SetText( std::string(mText.length(), bullet) ); This one doesn't work. Hope you can help !! Th...
Unicode character has type wchar_t(see §2.13.4 of the C++ Standard). You could use it as follows: wchar_t bullet = L'\x2022'; In string it will look like: std::wstring str_w_bullet( L"some text with \x2022" );
3,720,005
3,720,024
What does `invalid initialization of non-const reference` mean?
When compiling this code I get the following error: In function 'int main()': Line 11: error: invalid initialization of non-const reference of type 'Main&' from a temporary of type 'Main' Here's my code: template <class T> struct Main { static Main tempFunction(){ return Main(); } }; int main() { ...
In C++ temporaries cannot be bound to non-constant references. Main<int> &mainReference = Main<int>::tempFunction(); Here you are trying to assign the result of an rvalue expression to a non-constant reference mainReference which is invalid. Try making it const
3,720,164
3,720,467
Generating Code from a Source File Using Doxygen
I'm using doxygen to generate HTML documentation. I have a C++ source file that contains only global functions. All of the global functions are document, and the documentation is properly generated. For all of the headers in the project there is a link to “see the code that this documentation was generated by.” (as a l...
You need to set INLINE_SOURCES = YES in the config file, see here for more details.
3,720,184
3,720,203
How many bits to ignore when checking for NULL?
The following crashes with a seg-V: // my code int* ipt; int bool set = false; void Set(int* i) { ASSERT(i); ipt = i; set = true; } int Get() { return set ? *ipt : 0; } // code that I don't control. struct S { int I, int J; } int main() { S* ip = NULL; // code that, as a bug, forgets to set ip... Set(&i...
There is no portable way to test for any invalid pointer except NULL. Evaluating &ip[3] gives undefined behaviour, before you do anything with it; the only solution is to test for NULL before doing any arithmetic on the pointer. If you don't need portability, and don't need to guarantee that you catch all errors, then ...
3,720,430
3,721,095
Lists of member pointer functions
Say I have a class: class A { public: void doSomething(); } Where doSomething does something that explicitly relies on the internal state of the instance of A. Now, I have a situation where I have a bunch of things of type A laying around, but I only want to call doSomething from a strict subset of them, so I want t...
It seems like you're confused about how member function pointers work. For a given class, there is only a single instance of any given function. They are differentiated by the use of the implicit parameter this. Basically, you can pretend you have the following mapping. struct Struct { void Function(); } Struct a; a...
3,720,502
3,976,972
How to resize an image in a QTextEdit?
How to click on the image, hold from a corner of it, and resize the image in the QTextEdit? Or at least how to get an image under cursor/that is selected in order to change width and hight?
Here how I have implemented: void AdvancedTextEdit::resizeImage() { QTextBlock currentBlock = m_textEdit->textCursor().block(); QTextBlock::iterator it; for (it = currentBlock.begin(); !(it.atEnd()); ++it) { QTextFragment fragment = it.fragment(); if (fragment.isValid()) ...
3,720,748
3,720,800
linux background card swipe reader
I currently have a USB card swipe attached to an embedded linux machine and from what I can tell and from what I have researched it acts as a keyboard, and inputs all the data as if I were typing. Now I have a perl script that takes all this data and saves it to a file. The only problem is, it only knows to take the da...
I have an idea, but it is very general. Can you constantly be monitoring for data in another program, buffer it, and then pipe the results into your perl script when the buffer reaches a certain size or goes for a certain period of time without activity? If you pipe it in, you shouldn't have to modify your perl script...
3,720,917
3,721,260
Way to check if type is an enum
How to check (without Boost or other nonstandard lib) if type passed to template is an enum type? Thanks.
Looking at http://www.boost.org/doc/libs/1_44_0/boost/type_traits/is_enum.hpp, If this evaluates to true: ::boost::type_traits::ice_or< ::boost::is_arithmetic<T>::value , ::boost::is_reference<T>::value , ::boost::is_function<T>::value , is_class_or_union<T>::value , is_ar...
3,721,078
3,721,103
typeid operator in C++
I have the following code int main() { cout << "Please enter your name..." << endl; cin >> name; cout << "Data type = " << typeid(name).name() << endl; cin.get(); return 0; } According to the various textbooks and pieces of documentation I've read about the typeid operator, I should expect to read ...
Nothing is wrong. Those text books, first of all, should have told you the result of name() is implementation-defined, and could very well be "". Secondly, that type is std::string. The std::string type is just a typedef of std::basic_string with char and friends.
3,721,081
3,721,858
Why do I not see the "Application Error" dialog box?
I was interested in learning more about mixing runtimes between exes and dlls. On a WinXP machine, I created a dll build against the release runtime (/MD) and an exe that calls a function in the dll that is built debug (/MDd). The function in the dll allocates memory to the heap and the exe deletes it. I expected th...
Your program has gone off into undefined and erroneous behavior. Why expect exactly the same result on different operating systems? If something even slightly different happens during the execution on each of those machines, it could plausibly have the result that one hangs while the other immediately crashes. Perhaps ...
3,721,097
3,723,513
gdb error message: DW_OP_reg, DW_OP_piece, and DW_OP_bit_piece
I'm debugging somebody else's Qt program and ran into the following error message which I don't understand: DWARF-2 expression error: DW_OP_reg operations must be used either alone or in conjuction with DW_OP_piece or DW_OP_bit_piece. I'm not sure what that means and Google isn't of much help. Here's the context - sLo...
The error message means that GDB is reading DWARF2 debug info from the executable, and is rejecting that info as invalid (not following the DWARF2 standard). The invalid info is likely due to a bug in GCC, fixed in SVN revision 147187: 2009-05-06 Jakub Jelinek <jakub@redhat.com> * dwarf2out.c (new_reg_loc_descr)...
3,721,115
3,722,571
Crossplatform building Boost with SCons
I tried hard but couldn't find an example of using SCons (or any build system for that matter) to build on both gcc and mvc++ with boost libraries. Currently my SConstruct looks like env = Environment() env.Object(Glob('*.cpp')) env.Program(target='test', source=Glob('*.o'), LIBS=['boost_filesystem-mt', 'boost_system-...
You'll need something like: import os env = Environment() boost_prefix = "" if is_windows: boost_prefix = "path_to_boost" else: boost_prefix = "/usr" # or wherever you installed boost sources = env.Glob("*.cpp") env.Append(CPPPATH = [os.path.join(boost_prefix, "include")]) env.Append(LIBPATH = [os.path.join(boost_...
3,721,170
3,752,605
C++ encode string to Unicode - ICU library
I need to convert a bunch of bytes in ISO-2022-JP and ISO-2022-JP-2 (and other variations of ISO-2022) into Unicode. I am trying to use ICU (link text), but the following code doesn't work. std::string input = "\x1B\x28\x4A" "ABC\xA6\xA7"; //the first 3 chars are escape sequence to use JIS_X201 character set in GL/...
I couldn't get the conversion to work for JIS_X201 character set in ISO-2022-JP encoding. And I couldn't generate a "valid" one using any tools at my disposal - tried Java (ICU and non ICU implementation of ISO2022) and C++. So I basically just wrote a function to do a code lookup and convert to Unicode using this tab...
3,721,217
3,721,222
Returning a c++ std::vector without a copy?
Is it possible to return a standard container from a function without making a copy? Example code: std::vector<A> MyFunc(); ... std::vector<A> b = MyFunc(); As far as I understand, this copies the return value into a new vector b. Does making the function return references or something like that allow avoiding the c...
If your compiler supports the NRVO then no copy will be made, provided certain conditions are met in the function returning the object. Thankfully, this was finally added in Visual C++ 2005 (v8.0) This can have a major +ve impact on perf if the container is large, obviously. If your own compiler docs do not say whet...
3,721,337
3,769,537
Renaming File Paths and Doxygen
I have a file that is located at a different path at development time, however at the time of release it will be in a different location. The title of the documentation, after being generated, is set to the development path. Is it possible to manually set the path of the filename? What I mean about title: The structure...
There's an option in doxygen to turn of using full path names in the documentation. Inside your doxygen configuration file set FULL_PATH_NAMES to NO. Here's what the documentation says about it: If the FULL_PATH_NAMES tag is set to YES doxygen will prepend the full path before files name in the file list and in...
3,721,375
3,721,549
How can a base class satisfy the definition of a parent's pure virtual function using another parent's function
I am extending an existing C++ project. I have a base class that derives from two parent classes. One of the parents has a pure virtual function. I want that pure virtual function to be defined by a function implemented in the other parent. So, I want another parent to satisfy the base class's obligation to define a...
Your second piece of code is fine, you're just not compiling it correctly. You need to compile with g++, not gcc. When you compile with g++, it automatically links in the C++ runtime libraries; when you compile with gcc, it does not. You can also manually add them yourself: # Option 1: compile with g++ g++ inheritan...
3,721,660
3,721,803
Quickfix support for fpml
I am trying to figure out if quickfix supports fpml. I am guessing not , since i could not tell by googling.
No. Neither QuickFIX nor QuickFIX/J support protocols other than FIX (4.0 - 4.4, 5.0).
3,721,919
3,722,139
Conditional operator correct behaviour in VS2010?
I'm wondering whether this bit of code is exhibiting the correct C++ behaviour? class Foo { public: Foo(std::string name) : m_name(name) {} Foo(const Foo& other) { std::cout << "in copy constructor:" << other.GetName() << std::endl; m_name = other.GetName(); } std::string GetName() co...
A fuller answer: 5.16/4&5: "4 If the second and third operands are lvalues and have the same type the result is of that type and is an lvalue. 5 Otherwise the result is an rvalue...." In other words, "bool ? lvalue:rvalue" results in a temporary. That would be the end of it, however you pass this into a function that, ...
3,722,539
3,724,829
What to watch out for when writing 32-bit software on 64-bit machine?
I am purchasing a comfortable laptop for development but the only operating system available to me is 64-bit (Win7) , now I am basically aware that 64-bit has 8-byte integers and can utilize more RAM, that is about it. My programming will vary (C++, sometimes PHP) but would like to know: Can I build my C++ application...
Processors have been 64 bit for some time. I'm perplexed about why people are afraid to make the move to a 64 bit operating system. A 32 bit OS can't address much more than 3Gb of RAM, so that's good enough reason to make the upgrade in my book! When you're coding, the biggest difference I've encountered to look out ...
3,722,684
3,722,733
how do i back insert to a vector with a const pointer
hello i have an error with the following code: in my h file i got the following vector: vector<Vehicale*> m_vehicalesVector; and in my cpp file i got the following function: void Adjutancy:: AddVehicale(const Vehicale* vehicaleToAdd) { m_vehicalesVector.push_back(vehicaleToAdd); } seems like the const Vehicale* v...
m_vehicalesVector.push_back() needs Vchicale* as its parameter, while const Vehicale* is given. Compiler denies this because const cannot be removed silently. Change vector<Vehicale*> m_vehicalesVector to vector<const Vehicale*> m_vehicalesVector can solve this problem.
3,722,704
3,722,748
C++ read numbers from file and store in vectors
I am having trouble "undoing" this method, that dumps essentially a matrix of numbers of variable size into a text file: void vectorToFile(char *name, vector<vector<double>>* a){ FILE* fp = fopen(name, "w"); for(int i=0;i<a->size();i++){ for(int j=0;j<a->at(i).size();j++){ fprintf(fp, "%f ",...
I'm new at C++ so I'm not sure if this is a good approach or not, but I would open the file, read in the input line by line, parsing each line as I read it. Here's some example code (untested, uncompiled): #include <iostream> #include <sstream> #include <fstream> #include <string> #include <vector> std::vector<std::ve...
3,722,775
3,722,827
Can I declare a string in a header file in a definition of a class?
Is it possible to declare a string at all in a header (.h) file, in the definition of a Class? When I want to set a default int, I do: class MyClass { static const unsigned int kDATA_IMAGE_WIDTH = 1024; Is there a way to do the same for the string object? class MyClass { static const string kDEFAULT_FI...
From the error message you gave (emphasis mine): error: invalid in-class initialization of static data member of non-integral type 'const std::string' You can do this in a header file, but you cannot do so in a class. That is: class MyClass { static const std::string invalid = "something"; }; is not valid, but s...
3,722,922
3,722,947
virtual function redefinition hides other overloaded functions of same name from another base class
Ok, I'm using virtual functions, overloaded functions, and multiple inheritance. Of course this doesn't turn out well. The scenario: Class base1 has a virtual function that needs to be specified by its child. Class derived derives from two parents base1 and base2, and should use base2's existing functionality to defin...
In the definition of the derived class, you can add a using declaration to make the function from base2 visible: using base2::samenameFunc;
3,722,971
3,723,008
how to work with const in a map?
I'm having problems with this call: m_baseMap.find(baseName)->second->AddVehicale(vehicaleToAdd); There's a red line under m_baseMap, the error is : "the object has type qualifiers that are not compatible with the member function". The base map is defined as the following: map <string, const Base*> m_baseMap; How can...
The issue is not with the find() but with the call AddVehicale because the map specifies const Base*. You either need to make the map be map<string, Base *> or make sure AddVehicale is a const method (which means you are promising not to modify the object pointed to in the map) e.g. void Base::AddVehicale(Vehicale &v)...
3,723,011
3,724,311
QT mouse event handling problem
Greetings all, As seen in the picture I have an extended QWidget object (which draws the cell images and some countour data) inside a QScrollBar. User can zoom in/out the Image (QWidget size is changed according to the zoomed size of the QImage ) using mouse wheel. I process the events (mouseMoveEvent(),wheelEvent().....
I'm uncertain if you want the scroll wheel to only ever be used for zooming the image or if you want the scroll wheel to control zooming when the image is smaller than the scroll area viewport and then use the scroll wheel to do scrolling when the image is larger than the scroll area viewport. In either case, you shoul...
3,723,112
3,723,126
2 overloads have similar conversions
A similar question to this C++ Function Overloading Similar Conversions has been asked and i understand the general premise of the problem. Looking for a solution. I have 2 overloaded functions: virtual IDataStoreNode* OpenNode(const char *Name, bool bCreateIfNotExist,int debug=0) { return 0; } virtual IDataStoreNod...
bool and int can be used to distinguish function overloads. As one would expect, bool arguments will prefer bool overloads and int arguments - int overloads. Judging by the error message (I assume that the title of your question is a part of the error message you got), what you are dealing with is the situation when th...
3,723,592
3,723,615
What is the C equivalent to the C++ cin statement?
What is the C equivalent to the C++ cin statement? Also may I see the syntax on it?
cin is not a statement, it's a variable that refers to the standard input stream. So the closest match in C is actually stdin. If you have a C++ statement like: std::string strvar; std::cin >> strvar; a similar thing in C would be the use of any of a wide variety of input functions: char strvar[100]; fgets (strvar, 10...
3,723,922
3,726,555
Getting random output from Crypto++
Can't figure out why I am getting seemingly random output from the Crypto++ RC2 decoder. The input is always the same, but the output is always different. const char * cipher ("o4hk9p+a3+XlPg3qzrsq5PGhhYsn+7oP9R4j9Yh7hp08iMnNwZQnAUrZj6DWr37A4T+lEBDMo8wFlxliuZvrZ9tOXeaTR8/lUO6fXm6NQpa5P5aQmQLAsmu+eI4gaREvZWdS0LmFxn8...
The parameters to the RC2::Decryption constructor are: (pointer to key-bytes, length of key-bytes). You are giving it a pointer to 16 bytes but using a length of 64 bytes. Crypto++ is reading uninitialized memory when reading the key, so you get random results. If you want to indicate an effective key-length, you can u...
3,724,092
3,724,154
Is it bad practice for a child object to have a pointer to its parent?
In a C++ application, let's say I have a window class, which has several instances of a control class. If my window wanted to notify a control that it had been clicked, I might use: control[n]->onClick(); Now let's say that the control needs to know the size of it's parent window, or some other information. For this I...
You can consider a hierarchy of controls as being a tree-like graph data structure; when you visualize it that way, it's quite reasonable for a control to have a pointer to its parent. As for whether objects or pointers to objects should be stored in a vector, well, it depends. You should usually prefer to store objec...
3,724,490
3,724,753
Problem with declaring Metatype in Qt
I am trying to declare my Class as Metatype for Qt but figuring out some problems. It seems that after the MetaType declaration he wants to get access to a copy constructor or something like this which is explicitly not allowed for QObjects as I thought. This is my header: #include <QtCore/QObject> #include <QtCore/Q...
You have to publicly inherit from QObject: class Message : public QObject By doing that, you don't need to declare metatype for class Message. Only for the pointer.
3,724,589
3,724,598
Is it meaningful to optimize i++ as ++i to avoid the temporary variable?
Someone told me that I can write for (iterator it = somecontainer.begin(); it != somecontainer.end(); ++it) instead of for (iterator it = somecontainer.begin(); it != somecontainer.end(); it++) ...since the latter one has the cost of an extra unused temporary variable. Is this optimization useful for modern compile...
It's a good habit to get into, since iterators may be arbitrarily complex. For vector::iterator or int indexes, no, it won't make a difference. The compiler can never eliminate (elide) the copy because copy elision only eliminates intermediate temporaries, not unused ones. For lightweight objects including most iterato...
3,724,772
3,724,845
Makefile for Unit Tests in C++
I'm struggling to write Makefiles that properly build my unit tests. As an example, suppose the file structure looks like this src/foo.cpp src/foo.hpp src/main.cpp tests/test_foo.cpp tests/test_all.cpp So, to build the executable test_all, I'd need to build test_foo.o which in turn depends on test_foo.cpp but also on ...
The common practice is one Makefile for each folder. Here is a simple Makefile.am script for the root folder: #SUBDIRS = src tests all: make -C ./src make -C ./tests install: make -C ./src install uninstall: make -C ./src uninstall clean: make -C ./src clean test: make -C ./tests test The c...
3,724,905
15,152,449
Visual Studio C++ compiler optimizations breaking code?
I've a peculiar issue here, which is happening both with VS2005 and 2010. I have a for loop in which an inline function is called, in essence something like this (C++, for illustrative purposes only): inline double f(int a) { if (a > 100) { // This is an error condition that shouldn't happen.. } // Do some...
For anyone interested, it turned out to be a bug in the VS compiler. Confirmed by Microsoft and fixed in a service pack following the report.
3,724,971
3,725,083
How to re-engineer an Ui-File from a given QWidget instance
Does anybody know if the Qt Toolkit provides a way to generate Ui Files from a given QWidget instance? Speaking in pseudo-code, I'm looking for something like this: //setup widget QWidget* pMyWidget=new QWidget(...); //fill widget with life pMyWidget->layout()->addWidget(new QLabel(...)); ... //finally write a Ui fil...
Use QFormBuilder::save() from the QtDesigner module.
3,724,987
3,725,028
Python ctypes, C++ object destruction
Consider the following python ctypes - c++ binding: // C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void A_someFunc(A* obj) { obj->someFunc(); } void A_destruct(A* obj) { delete obj; } # python from ctypes import cdll libA = cdll.LoadLibrary(some_path) class A: def __init__(self)...
You could implement the __del__ method, which calls a destructor function you would have to define: C++ class A { public: void someFunc(); }; A* A_new() { return new A(); } void delete_A(A* obj) { delete obj; } void A_someFunc(A* obj) { obj->someFunc(); } Python from ctypes import cdll libA = cdll.LoadLibrary(so...
3,725,073
3,726,345
Closing a MessageBox automatically
I have a third party encryption library, which may create a MessageBox if key creation fails. The failure can be caused by bad random number generation or other rarities, and in most cases, trying again will result in success. My code will attempt key creation up to three times before deciding it failed. Now, the issue...
Just before you begin the encryption process, install a WH_CBT hook, and in its callback watch for an nCode of HCBT_CREATEWND. If you get a matching class name ('#32770 (Dialog)' ?) and a matching title either return a nonzero value from the callback, or if that doesn't work post a WM_CLOSE (or a BM_CLICK to a relevant...
3,725,265
3,729,379
Play avi using animation control
I,m not c++ programmer on a daily basis, so I need help. I 'wrote' this. It's new project 'Windows Application' in DevC++. I add this #include <Commctrl.h> //... HWND film; //... film = Animate_Create(hwnd, 10, WS_CHILD | WS_VISIBLE | ACS_AUTOPLAY, hThisInstance); Animate_OpenEx(film, hThisInstance, "a.avi"); Animate...
As Raymond Chen once blogged about, that animation control has many limitations. It was purposefully designed for only simple animations. * The AVI must be non-interleaved. * The AVI must have exactly one video stream. * The AVI may not have an audio stream. * The AVI may not use palette changes. * The AVI must be eit...
3,725,308
3,725,406
cannot convert parameter 1 from 'overloaded-function' to '...'
Now I am try to use boost bind & mem_fn. But there's a problem to bind overloaded-function. How to resolve compile error of follow codes? boost::function< void( IF_MAP::iterator ) > bmf = std::mem_fun1< void, IF_MAP, IF_MAP::iterator >( &IF_MAP::erase ); boost::function< void( IF_MAP::iterator ) > bmf = boost::mem_fn< ...
std::maps member function erase() is overloaded, thus you have to manually disambiguate - see the Boost.Bind FAQ. E.g. for the size_type erase(const key_type&) overload: typedef IF_MAP::size_type (IF_MAP::*EraseType2)(const IF_MAP::key_type&); boost::function<void (const IF_MAP::key_type&)> bmf2; bmf2 = boost::bind((E...
3,725,325
3,725,414
C++ 2.5 bytes (20-bit) integer
I know it's ridiculous, but I need it for storage optimization. Is there any good way to implement it in C++? It has to be flexible enough so that I can use it as a normal data type e.g Vector< int20 >, operator overloading, etc..
If storage is your main concern, I suspect you need quite a few 20-bit variables. How about storing them in pairs? You could create a class representing two such variables and store them in 2.5+2.5 = 5 bytes. To access the variables conveniently you could override the []-operator so you could write: int fst = pair[0]; ...
3,725,415
3,725,461
Memcpy int to char buffer - as alternative to sprintf
#include <iostream> using namespace std; int main() { char buffer[8]; int field=534; memcpy(buffer,&field,sizeof(field)); cout<<buffer<<endl; return 0; } This returns an empty buffer. Why? Basically looking for an alternative to sprintf to convert int to char buffer. Itoa is not available....
You will have to use sprintf or itoa to convert a binary int to an ascii string. The representation if ints and and char arrays is totally different and ints can conytain bytes with a value of zero but strings can only have that as the last byte. for example Takes 0 - in int it is represented by 4 bytes with values 0 w...
3,725,425
3,725,440
Class method as winAPI callback
Is it feasible to set the winAPI message callback function as a method of a class. If so, how would this be best implemented? I wonder if it is even possible. Sorry for the short question, hopefully you will be able to provide useful responses. Thanks in advance :).
You cannot use non-static member functions for C callbacks. However, usually C callbacks have a user data pointer that's routed to the callback. This can be explored to do what you want with the help of a static member functions: // Beware, brain-compiled code ahead! typedef void (*callback)(int blah, void* user_dat...
3,725,826
3,725,968
How to encapsulate a C API into RAII C++ classes?
Given a C API to a library controlling sessions that owns items, what is the best design to encapsulate the C API into RAII C++ classes? The C API looks like: HANDLE OpenSession(STRING sessionID); void CloseSession(HANDLE hSession); HANDLE OpenItem(HANDLE hSession, STRING itemID); void CloseItem(HANDLE hItem); Plus ot...
By adding another layer (and making your RAII a little more explicit) you can get something pretty neat. Default copy constructors and assignment for Sessions and Items do the right thing. The HANDLE for the session will be closed after the HANDLE for all the items is closed. There's no need to keep vectors of children...
3,725,975
3,726,011
Simple c++ pointer casting
Can someone explain this to me: char* a; unsigned char* b; b = a; // error: invalid conversion from ‘char*’ to ‘unsigned char*’ b = static_cast<unsigned char*>(a); // error: invalid static_cast from type ‘char*’ to type ‘unsigned char*’ b = static_cast<unsigned char*>(static_cast<void*>(a)); // everything is fine W...
static_cast<void*> annihilate the purpose of type checking as you say that now it points on "something you don't know the type of". Then the compiler have to trust you and when you say static_cast<unsigned char*> on your new void* then he'll just try to do his job as you ask explicitely. You'd better use reinterpret_ca...
3,726,106
3,726,164
Another problem with templates
#include "stdafx.h" #include <iostream> using std::cout; template<class T> class IsPolymorphic { template<class T> struct Check { enum {value = false}; }; template<class T> struct Check<T*> { enum {value = true}; }; public: enum {value = Check<T>::value}; }; template<bool flag, class T, class U> struc...
Try this: template<class T, bool isPoly = IsPolymorphic<T>::value>
3,726,198
3,726,352
how can I use static library build by different version of mingw?
Greetings, I am facing a complicated situation about using a static library under windows. The static library is build by a specific version of mingw which is bundled with Eiffel studio. Since Eiffel studio uses mingw to create its output as a static lib, I have no control over this configuration. If I try to use th...
Though I don't have a lot of information here is what I would do: Try to compile with the newer version of mingw and see if you can make it work. Errors are very important in this case (you should check also the mingw manual/mailing lists/forums for finding about the compatibility between mingw versions Separate the l...
3,726,326
3,726,378
Is a logical right shift by a power of 2 faster in AVR?
I would like to know if performing a logical right shift is faster when shifting by a power of 2 For example, is myUnsigned >> 4 any faster than myUnsigned >> 3 I appreciate that everyone's first response will be to tell me that one shouldn't worry about tiny little things like this, it's using correct algorithms and...
Let's look at the datasheet: http://atmel.com/dyn/resources/prod_documents/8271S.pdf As far as I can see, the ASR (arithmetic shift right) always shifts by one bit and cannot take the number of bits to shift; it takes one cycle to execute. Therefore, shifting right by n bits will take n cycles. Powers of two behave jus...
3,726,350
3,726,415
Can I pass a constructor to a function?
I want to instantiate a base class pointer to point to a newly constructed derived class object. The actual class for the object will change depending on the application type, so I want to use a Factory method to switch on certain variables in order to construct the right object. However I don't want to have to do the ...
I think that's pretty sane. Just pass a function object and save it since it seems you need to recall it later (otherwise why not pass the pointer directly and create the object before?) class ContainingClass: { public: typedef boost::function<BaseClass*()> factory_fn; public: ContainingClass (factory_fn f ) ...
3,726,503
3,729,414
How can I add a static method to a QInputDialog for returning custom data?
QString QInputDialog::getText ( QWidget * parent, const QString & title, const QString & label, QLineEdit::EchoMode mode = QLineEdit::Normal, const QString & text = QString(), bool * ok = 0, Qt::WindowFlags flags = 0 ) [static] This function is defined to call a dialog get and return the text which wi...
I have done it, but I post for people that need this. Here is an axample of a dialog box, which is for resizing an image. To be more precise it is for representing user the current size of an image and provide him/her with an interface to change the size and get the new size with a QPair. class ResizeImageDialog : publ...
3,726,570
3,726,672
Using boost::lock_guard for simple shared data locking
I am a newcomer to the Boost library, and am trying to implement a simple producer and consumer threads that operate on a shared queue. My example implementation looks like this: #include <iostream> #include <deque> #include <boost/thread.hpp> boost::mutex mutex; std::deque<std::string> queue; void producer() { ...
You give your threads (producer & consumer) the mutex object and then detach them. They are supposed to run forever. Then you exit from your program and the mutex object is no longer valid. Nevertheless your threads still try to use it, they don't know that it is no longer valid. If you had used the NDEBUG define you w...
3,726,586
3,726,602
Easily initialise an std::list of std::strings?
In C++0x, what I want would be: std::list<std::string> colours = {"red", "blue", "green", "grey", "pink", "violet"}; What's the easiest way in standard, non-0x C++?
char const *x[] = {"red", "blue", "green", "grey", "pink", "violet"}; std::list<std::string> colours(x, x + sizeof(x) / sizeof(*x)); Or you can use the boost libraries and functions like list_of("a")("b")...
3,726,716
3,726,868
Qt interfaces or abstract classes and qobject_cast()
I have a fairly complex set of C++ classes that are re-written from Java. So each class has a single inherited class, and then it also implements one or more abstract classes (or interfaces). Is it possible to use qobject_cast() to convert from a class to one of the interfaces? If I derive all interfaces from QObject, ...
After some research and reading the qobject_cast documentation, I found this: qobject_cast() can also be used in conjunction with interfaces; see the Plug & Paint example for details. Here is the link to the example: Plug & Paint. After digging up the interfaces header in the example, I found the Q_DECLARE_INTERF...
3,726,812
3,727,233
How to send unicode keys with c++ (keybd_event)
My friend is learning Norwegian and i want to make a global hot key program which sends keys such as æ ø å My problem is that keybd_event function wont allow me to send those keys, i seem to be restricted to the virtual key codes is there another function that i could use or some trick to sending them?
You have to use SendInput instead. keybd_event does not support sending such characters (except if they are already in the current codepage, like on Norwegian computers). A bit of sample code to send an å: KEYBDINPUT kb={0}; INPUT Input={0}; // down kb.wScan = 0x00c5; kb.dwFlags = KEYEVENTF_UNICODE; Input.type = INPUT...
3,727,238
3,727,555
Sending a string from R to C++
There are lots of examples of sending integers to C++ from R, but none I can find of sending strings. What I want to do is quite simple: SEXP convolve(SEXP filename){ pfIn = fopen(filename, "r"); } This gives me the following compiler error: loadFile.cpp:50: error: cannot convert 'SEXPREC*' to 'const char*' for a...
Here's a method that uses R internals: #include <R.h> #include <Rdefines.h> SEXP convolve(SEXP filename){ printf("Your string is %s\n",CHAR(STRING_ELT(filename,0))); return(filename); } compile with R CMD SHLIB foo.c, then dyn.load("foo.so"), and .Call("convolve","hello world") Note it gets the first (0th) eleme...
3,727,294
3,795,655
Checking if a printer is attached
Is there a way in Windows (which works in Windows CE) to check if a printer is attached and communicating to LPT1 in C++? [Edit] More info: We are currently working with a generic Windows CE printer driver - pcl.dll - by passing it into CreateDC, to get the DC for the printer. We can't call PrintDlg() to show the prin...
I would also recommend enumerating devices, but you could try the following functions to see if it hangs quickly and gracefully (I don't currently have any way of testing this...): CreateFile("LPT1:", 0, 0, NULL, OPEN_EXISTING, ...); DeviceIOControl(HANDLE, IOCTL_PARALLEL_STATUS, ...); It is possible that this returns...
3,727,408
3,727,719
C++ & DirectX - geometry question
I am working on my own 3d engine and have the following question: I have an abstract object, that handles geometry (vertices and faces). It uses internal storage for this geometry, allows editing and my renderer object has a method RenderGeometry. With this design my rendering process includes a geometry caching step. ...
I am surprised that std::map is performing so bad. It might be worthwile ask a question (search for existing answers first!) specifically about std::map performance on pointers. Given that Geometry and CachedGeometry are objects that you control, you can do whatever you want to maintain links between them. One way is t...
3,727,420
3,727,460
Significance of Sleep(0)
I used to see Sleep(0) in some part of my code where some infinite/long while loops are available. I was informed that it would make the time-slice available for other waiting processes. Is this true? Is there any significance for Sleep(0)?
According to MSDN's documentation for Sleep: A value of zero causes the thread to relinquish the remainder of its time slice to any other thread that is ready to run. If there are no other threads ready to run, the function returns immediately, and the thread continues execution. The important thing to re...
3,727,461
3,728,565
How to enable Matlab to listen real time data through C++ application
I need to create a C++ add-in to Matlab where add-in will listen to packet coming from network and notify Matlab to draw an packet analysis graph. I understood that using a MEX file I can easily call c functions inside Matlab, but I could not find a way to notify Matlab when data is available at C++ end. Is there any w...
Have a look at Gurobi. It 'just' prints status information to the command window. Using a mex command like mexCallMATLAB you may access 'any' matlab function.
3,727,545
3,730,689
Dyld Symbol not Found Error
Here's my error. dyld: Symbol not found: __ZTIN8eqOsirix3ROIE Referenced from: /Users/slate/Documents/osirixplugins/CoreDataTrial_EQOsirix/build/Development/rcOsirix.app/Contents/MacOS/rcOsirix Expected in: flat namespace in /Users/slate/Documents/osirixplugins/CoreDataTrial_EQOsirix/build/Development/rcOsirix.app...
Based on our discussion on your question I'm sure it has something to do with the fact that all your methods are defined within the class definition. This means that gcc has no "key" function alongside which it can emit the symbol for the typeinfo object i.e. there is no single object file that the typeinfo object can ...
3,727,858
3,727,878
templated function pointer
I have an approach to call delayed function for class: //in MyClass declaration: typedef void (MyClass::*IntFunc) (int value); void DelayedFunction (IntFunc func, int value, float time); class TFunctorInt { public: TFunctorInt (MyClass* o, IntFunc f, int v) : obj (o), func (f), value (v) {} virtual void operato...
There are no template typedefs in C++. There is such an extension in C++0x. In the meantime, do template <typename T> struct TFunc { typedef void (MyClass::*type)(T param); }; and use TFunc<T>::type (prefixed with typename if in a dependant context) whenever you would have used TFunc<T>.
3,727,862
3,782,433
Is there any way to make Visual Studio stop indenting namespaces?
Visual Studio keeps trying to indent the code inside namespaces. For example: namespace Foo { void Bar(); void Bar() { } } Now, if I un-indent it manually then it stays that way. But unfortunately if I add something right before void Bar(); - such as a comment - VS will keep trying to indent it. This is...
Here is a macro that could help you. It will remove indentation if it detects that you are currently creating a namespace. It is not perfect but seems to work so far. Public Sub aftekeypress(ByVal key As String, ByVal sel As TextSelection, ByVal completion As Boolean) _ Handles TextDocumentKeyPressEvents.AfterK...
3,727,901
3,727,929
What do you prefer: C++ exception handling or passing a buffer to hold error messages as parameter?
I am currently involved in developing a low level network application. We have lately run into the issue of error reporting concerning both user land and debug land. Given that some errors might fire up from lower level functions, libraries ... reporting the exact error status (code, messages, env...) from one layer to...
The advantage of exceptions is that callers cannot ignore them. OTOH, I've seen so much code that ignores return values. Also, in some code, if you check all calls for possible errors, the algorithm will be buried under error handling code. With exceptions, that's not an issue.
3,727,943
3,728,388
Compiling NCURSES src on HPUX
I am trying to compile ncurses-5.7 from source and after running ./configure I get the following error: configure: error: Your compiler does not appear to recognize prototypes. You have the following choices: a. adjust your compiler options b. get an up-to-date compiler c. use a wrapper such as ...
Commenting the following line in configure file worked. export CC="cc" Got the answer from Here.
3,728,036
3,728,219
A link problem with Windows 7 shell functions
I'm trying to enumerate files through the Windos 7 library API, e.g. with SHLoadLibraryFromKnownFolder I'm using a C++ win32 console application and getting link errors, e.g., Error LNK2019: unresolved external symbol __imp__DSA_DestroyCallback@12 referenced in function "void __cdecl DSA_DestroyCallback(struct _DSA *,i...
The documentation for DSA_DestroyCallback states that you need to link against Comctl32.lib.
3,728,071
3,759,269
Create a dialog in UI Thread causes crash
I tried to create a dialog in a UI thread(CWinThread). However, it crashes when the CDialog::Create() is called. I had verified with previous implementation, the dialog is successfully created in non-threading mode. Does any guru here know the crash reason of creating a dialog in CWinThread? Without Threading: class CP...
I suspect that the problem is that your CProduction object has not been created when the PROD_CREATE_DLG message is being handled. This may be because of using PostThreadMessage. Using PostThreadMessage is fraught with problems. In particular, the messages may get lost, so the thread never sees the PROD_INIT message. I...
3,728,072
3,728,207
very simple io question c++
Just started learning c++ today and im pretty boggled. its an amazing language but im having some trouble overwriting a file #include <iostream> #include <fstream> using namespace std; int main( ) { double payIncrease = 7.6; double annual; double annualIncrease; double newAnnual; double monthly...
You can't open the same file as an istream and an ostream at the same time. Since you are closing the istream pretty early on, why not just put the ostream open call after the istream close? Alternatively you can use an fstream which will allow reads and writes.
3,728,409
3,728,425
Dynamically list all members of a class
Is it possible in C++ to dynamically (during run-time) get a list of all members of the class?
No, not without doing some work at compile time first manually. C++ has no reflection. Qt works around this with its moc system which scans your source files and generates meta data for all Qt (and inherited) classes
3,729,228
3,729,261
close an unopened stream
I have ifstream and an ofstream that in runtime might be opened or not (depends on what the user enters in command line. i declare the variables anyway, and i have a method that opens the stream if needed. my problem is at the end of the program i don't know if i need to close them or not. Is there anyway in c++ to k...
No close call needed - the streams close itself when they are open when they are destroyed. Also, the static there looks suspicious. main is called only once, so it doesn't have any effect here (apart from pedantic standardese differences that don't matter here, i think.... Definitely not in the case shown). That said...
3,729,428
3,741,226
How do I use a C++ class in a C# application without regard to platform?
I have a native/unmanaged C++ library with a number of classes that I would like to use from C#. Most of the solutions I've read (like this one and this one) suggest that I should create a C++/CLI wrapper, and use the wrapper in my C# project. Most of these suggestions, however, ignore platform. As far as I am aware, i...
Well there is a cunningish way to do it, but it does add extra code burden (although you could just do it at the start of your app). It relies on creating a new app domain with platform specific private bin paths from where to load assemblies. You then hide your native code in either the 32 or 64 bit dirs and it will l...
3,729,465
3,729,708
The importance of declaring a variable as unsigned
Is it important to declare a variable as unsigned if you know it should never be negative? Does it help prevent anything other than negative numbers being fed into a function that shouldn't have them?
Declaring variables for semantically non-negative values as unsigned is a good style and good programming practice. However, keep in mind that it doesn't prevent you from making errors. If is perfectly legal to assign negative values to unsigned integers, with the value getting implicitly converted to unsigned form in...
3,729,515
3,731,577
Visual Studio 2010 & 2008 can't handle source files with identical names in different folders?
Direct Question: If I have two files with the same name (but in different directories), it appears that only Visual Studio 2005 can handle this transparently?? VS 2008 & 2010 require a bunch of tweaking? Aside from my naming convention, am I doing something wrong? Background: I'm developing C++ statistical libraries....
So @Hans Passant pointed in the right direction, Thanks!! You don't have to list the file, a folder is sufficient. Then if you look in the defined macros at the bottom of the VS 2010 list, you'll see: %(RelativeDir)/ Univariate/ The problem, as posted, was actually a simplified version of what I'm working on -- a cou...
3,729,674
3,729,767
Vector class in c++ programing
Can anybody explain me, what is use of vector class? My Professor mentioned about below sentence in the lecture. Template: Each vector has a class parameter that determines which object type will be used by that instance, usually called T. I don't understand what exactly class parameters means?
The vector is defined as a template like: template<typename T> class Vector; To use it you need to instantiate the template like: Vector<char> myVector; Instantiating a vector effectively creates a new class. which is equivalent to what you would get if you'd replaced every occurrence of T in the definition of the te...
3,730,000
3,730,110
Can static local variables cut down on memory allocation time?
Suppose I have a function in a single threaded program that looks like this void f(some arguments){ char buffer[32]; some operations on buffer; } and f appears inside some loop that gets called often, so I'd like to make it as fast as possible. It looks to me like the buffer needs to get allocated every time ...
For implementations that use a stack for local variables, often times allocation involves advancing a register (adding a value to it), such as the Stack Pointer (SP) register. This timing is very negligible, usually one instruction or less. However, initialization of stack variables takes a little longer, but again,...
3,730,136
3,730,252
Show form from another form
I have 2 forms Form1 and Form2. How can I, inside code (Form1.h) show Form2 (something like Form2::Show())
Edit your .cpp file and arrange the #include directives, putting the 2nd form first: #include "stdafx.h" #include "Form2.h" #include "Form1.h" Then write code like this in, say, a button's Click event handler: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) { Form2^ frm = gcnew F...
3,730,292
3,743,988
How do I change the Projection so it shows my object?
I have an 2D object (GL_QUAD) with size (W,H) and sitting at (-W*0.5, -H*0.5). I'd rather not resize the object, because I need to be able to select points on that object relative to the texture. (i.e. (x,y) in openGL translates to (x,y) on the texture - no scaling needed). What I want to do is change the camera proper...
It sounds like your stuff is all 2D and really doesn't need the benefits of a perspective projection, in such a case an orthogonal projection would be much easier to use. An orthogonal projection makes it trivially easy to fit a quad to fill the screen. http://www.opengl.org/sdk/docs/man/xhtml/glOrtho.xml
3,730,429
3,730,471
What does this C code do?
I'm really new to C programming, although I have done quite a bit of other types of programming. I was wondering if someone could explain to me why this program outputs 10. #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h> #include <stdlib.h> int value = 10; int main() { pid_t pi...
About fork() : If fork() returns a negative value, the creation of a child process was unsuccessful. If fork() returns a zero to the newly created child process. If fork() returns a positive value, the process ID of the child process, to the parent. So in you case it bound to return a number greater than 0 & thus th...
3,730,594
3,730,795
How to convert a string representing decimal number in exponential form to float in Qt?
I have some decimal numbers in a text file represented in exponential form Eg: 144.2e-3. I want to store the values in float. In qt it returns "0" when i directly use the "number.toFloat()" method. Please help.
toFloat() should work. Check that your string contains only the number. If the string contains something else too, for example "144.2e-3 a", then the toFloat() returns 0. Note that also other numbers in the string will cause the conversion to fail, for example QString("144.2e-3 100").toFloat() will return 0. Additional...
3,730,635
3,730,753
How can I use C++ enum types like C#?
How can I use C++ enum types like C#? consider following definition in c++ : enum myEnum { A, B, C}; myEnum en = A; Now I want to write line #2 as following line like C# : myEnum en = myEnum.A; ??
C++0x introduces enum class that does exactly what you want: enum class myEnum { A, B, C }; myEnum en = myEnum::A; In C, I would probably use good old prefixing: enum myEnum { myEnum_A, myEnum_B, myEnum_C }; myEnum en = myEnum_A;
3,730,654
3,730,751
What's better to use, a __try/__except block or a try / catch block?
I'm wondering which is the better way to catch exceptions that I throw: is it a __try / __except block or a try / catch block? I'm writing in C++ and the program will only be used on Windows, so portability is not an issue. Thanks!
You should use a try/catch block. As others have already answered, __try / __except is for catching SEH (windows generated errors) not for catching general exceptions. Most importantly, __try and __catch may not run C++ destructors or correctly unwind the stack when an exception is thrown. Except in rare cases, you sho...
3,731,089
3,731,357
Working around the C++ limitation on non-const references to temporaries
I've got a C++ data-structure that is a required "scratchpad" for other computations. It's not long-lived, and it's not frequently used so not performance critical. However, it includes a random number generator amongst other updatable tracking fields, and while the actual value of the generator isn't important, it i...
While it is not okay to pass rvalues to functions accepting non-const references, it is okay to call member functions on rvalues, but the member function does not know how it was called. If you return a reference to the current object, you can convert rvalues to lvalues: class scratchpad_t { // ... public: sc...
3,731,227
3,731,282
Is it possible to change the tick count value returned from GetTickCount()?
I'm trying to do some testing and it requires the Windows system to be up and running for 15 Real-Time minutes before a certain action can ever occur. However, this is very time consuming to HAVE to wait the 15 real-time minutes. Is there a way to change the value GetTickCount() returns so as to make it appear that the...
Not directly. Why not just mock the call, or replace the chunk of code that does the time check with a strategy object? struct Waiter { virtual void Wait() = 0; virtual ~Waiter() {}; }; struct 15MinWaiter : public Waiter { virtual void Wait() { //Do something that waits for 15 mins } }; st...
3,731,529
3,731,567
Program is skipping over Getline() without taking user input
This is a very strange problem, when my program asks the user for the address, instead of waiting for input, it seems to skip the getline() function completely Answerinput: cout << "would you like to add another entry to the archive? (Y/N):"; cin >> answer; cout << endl; cout << endl; answer = toupper(answer); s...
Cin is probably leaving the carriage return in the buffer which getline retrieves. Try cin.ignore(1000, '\n'); cin.getline(Record[Entrynumber].Address,70); The >> operator doesn't remove the newline character after retrieving data, but ignores leading whitespace before retrieving data, while getline just retrieves w...
3,731,604
3,731,662
Are assignment operators not overloaded, when called upon pointers of a base class?
I have encountered the following problem which proved to me that I know far too little about the workings of C++. I use a base class with pure virtual functions class Base ... and a derived classes of type class Derived : public Base{ private: Foo* f1; ... Both have assignment operators implemented. Among o...
It's hard to say without seeing the relevant code. Here's an example that works: #include <iostream> using namespace std; class A { public: virtual A& operator=(A& a) {} }; class B : public A { public: B& operator=(A& a) { cout << "B" << endl; } }; int main() { A* foo = new B(); A* bar = new B(); ...
3,731,623
3,731,638
Are there any performance penalties when using nested structures?
Are there any performance penalties when I use multiple nested structures/classes (kinda like using muti dimension heap arrays) or is it just an organizational feature of the language to make it easier to keep track of data and the compiler doesn't actually see any difference? Thanks
Not really. Classes/structs are just defining offsets into memory, so if you have a class within a class within a class, the compiler just adds up the offsets. Performance comes into play once you have pointers (each pointer dereference is a memory read and potential L2 cache miss) or virtual functions (very bad, espec...
3,731,754
3,731,835
Eclipse CDT vs NetBeans C++ vs
Possible Duplicate: Best C++ IDE or Editor for Windows Hello, everyone. For a long time now, for C/C++ development, I have been using Notepad++ and the command line for compiling C/C++ programs. Now, I want to start using an IDE, and I have tried out quite a few. Currently, I am thinking of either Eclipse CDT or Net...
I have used Eclipse for years, and it is a solid IDE with a wide range of capabilities. If you haven't tried it out to see how well it fits your needs, I would recommend giving it a shot. That being said, I have recently started using NetBeans and I must say that I like it a bit better than Eclipse. It seems to be mo...
3,731,814
3,731,829
C++: How to prevent "potentially uninitialized warning" if im sure its not uninitialized?
Im getting this warning even though theres no possibility that it would remain uninitialized. The Visual Studio 2008 compiler fails to detect this. How do i suppress this warning at this piece of code only?
I would tend to side with the compiler on this one; you probably initialized it in a nested conditional statement which isn't always hit. But if you really insist on ignoring the warning, you can use the appropriate #pragma directive with the warning number.