question_id
int64
25
74.7M
answer_id
int64
332
74.7M
title
stringlengths
20
150
question
stringlengths
23
4.1k
answer
stringlengths
20
4.1k
4,073,723
4,073,797
Overloaded template parameters - why is this example a problem?
I've started reading C++ Templates - the complete guide by Josuttis and Vandevoorde. And my tiny mind is stuck. The authors state that "You should limit your changes to the number of parameters or to specifying template parameters explicitly", using this as an example that causes problems: template <typename T> inline ...
The problem is that the overload for "maximum of two C-strings" takes its two arguments by value, but then returns a reference to one of them. Returning a reference to a local variable is A Bad Idea (once the local variable is destroyed when the function returns, the reference cannot be used, so it's useless). You can...
4,073,736
4,073,777
How to create a mathematical curve (probably just an image) in C/C++
Pretty much the title explains what I try to achieve. Having a set of points in two dimensions, I want to create somehow the curve tha passes from all these points. Whether it will be a graphical window with the mathematical curve or just a jpg produced, is of no importance. Any help? Thx!
First of all, please refrain from tagging questions with C and C++, or using the term C/C++. C and C++ are two distinct, very different languages. That being said, it seems you are looking for a way to plot data. There are different libraries allowing you to do that, among those are: http://codecutter.org/tools/koolplo...
4,073,737
4,073,772
How to create a makefile without having to include every single source file in the project?
I'm taking some C++ classes and have send the teacher 9 exercises, each exercise is a simple directory with the name 'ex$' where $ is the number. Each directory has a single source file named 'ex$.cpp. I want to create a makefile that will allow me to type: make ex$ And it will build a executable that corresponds to ...
If all your C++ targets can be built with essentially the same command, you can do this fairly easily. Read this. Look for $@, in particular. Since this is part of an education, I'll leave the rest vague.
4,073,815
4,074,004
How can I dynamically get the system architecture?
Well as the title says is there any way to get the system architecture within c++? Thanks!
Based on "dynamically" and "Visual C++", I'm going to guess you want to do this at run-time under Windows. In that case, you can use GetSystemInfo or GetNativeSystemInfo to retrieve some basic information about the system and processor. If you need more information about the processor and specific features it supports,...
4,073,836
4,073,910
Testing a class that depends on static functions of another class
I am currently working on a class that uses another class which has only static functions. Everything worked fine until I tried testing my class. Here is a simple code example of the problem: class A { static String getSometing() { return String("Something: ") + heavyCalculation().asString(); } } class...
I have had success in unit testing in similar situations by refactoring out the references to the static functions (in my case it was external dependencies) into new private functions and overwriting them on the tested stub, so I can recommend this approach If the refactored functions remain private, they should not im...
4,073,862
4,094,302
What is the easest way to secure WWSAPI client to WCF server communications?
I'm looking for the simplest way to connect a WWSAPI client to a WCF server that satisfies a couple of requirements: No certificate management required. Is secure. WWSAPI obviously doesn't support message level security so standard WSHttpBinding is out, so I was hoping for people more conversant with the technology w...
Given the lack of answers I'll summarize my own findings after researching this over the past week: WWSAPI's lack of support for message level security rules out using HTTP with message level security. My self-imposed restriction on certificate management rules out HTTPS. That leaves TCP as the only secureable system ...
4,074,117
4,074,138
When should exceptions be thrown?
I'm making a c++ game gui lib and wondering when i should be throwing exceptions. Right now, for example, if I get a NULL pointer, the function silently fails. Should I instead throw an exception? Its not something that would really cause it to crash though. What are some examples of good places to throw exceptions? th...
The usual answer to this question is that you should only throw exceptions in 'exceptional' circumstances. But what are exceptional circumstances. Some examples: Events outside of your control (e.g. out of memory, missing file) Illegal parameters passed to your methods (i.e. you specify your method requires a handle...
4,074,410
4,074,460
Getting a Matrix from a file and assigning it to an array with a max size
Okay, so i have an array a[maxsize] [maxsize] where maxsize=10 how do i get an array to work correctly when taking an array from a file that is smaller than the max size. Example matrix: 1 2 3 4 5 6 7 8 9 Is coming out: 1 2 3 4 5 6 7 8 9 My code: `int main() { const int maxsize = 10; double original_matrix[ma...
If you want the matrix to come out in matrix form, why dont you: for(i=0; i<maxsize; i++) { for(j=0; j<maxsize; j++) { fin >> original_matrix [i][j]; } cout << "\n" } That way it comes out as a box instead of a single line. I think you will also have to play around with maxsize, because yo...
4,074,607
4,074,608
integer operations with <<
I've recently bee seen a number of code examples with stuff like 1 << 20 although I knew this operator could be used on integers I'm not sure what it does and every google search I try doing on it returns stuff about cout << but nothing on the integer operations. Could someone tell me what this operator does to inte...
<< is Bit wise left shift operator C++03 [5.8/2] The value of E1 << E2 is E1 (interpreted as a bit pattern) left-shifted E2 bit positions; vacated bits are zero-filled. If E1 has an unsigned type, the value of the result is E1 multiplied by the quantity 2 raised to the power E2, reduced modulo ULONG_MAX+1 if E1 has t...
4,074,651
4,075,484
Why are global anonymous unions required to be declared as static?
C++ 0x draft 9.5.6 Anonymous unions declared in a named namespace or in the global namespace shall be declared static. Why is this?
My guess is that if it were allowed to define the union in a non static way it may violate the ODR (one definition rule)
4,074,802
4,074,821
C++ xml parser with unicode support & without COM registration
I need to use a C++ XML parser/writer for implementing virtual registry on the basis of the following 2 conditions. It should not write entries in registry It should support unicode characters. I have tried the following parsers but none have solved the 2 conditions: Msxml (writes in to registry for COM creatio...
Tinyxml is enought. So you can conversion your unicode characters to utf8 first.
4,074,874
4,074,904
how did you learn directx 9?
Possible Duplicates: Good books or tutorials for beginning Direct X with c++ directx tutorials c++ what tutorials did you use to learn directx 9 or books.......
I started with Frank D. Luna's book: http://www.amazon.com/Introduction-Game-Programming-Direct-9-0c/dp/1598220160/ and then coded myself into all sorts of trouble until I got things working.
4,074,935
4,074,941
Why don't some languages allow declaration of pointers?
I'm programming in C++ right now, and I love using pointers. But it seems that other, newer languages like Java, C#, and Python don't allow you to explicitly declare pointers. In other words, you can't write both int x and int * y, and have x be a value while y is a pointer, in any of those languages. What is the reaso...
Pointers aren't bad, they are just easy to get wrong. In newer languages they have found ways of doing the same things, but with less risk of shooting yourself in the foot. There is nothing wrong with pointers though. Go ahead and love them. Toward your example, why would you want both x and y pointing to the same me...
4,075,276
4,075,307
Variable Scope in C++
If I had the following code: for(int myvar = 0; myvar < 10; myvar++); if(1) { int var2 = 16; } Then, afterwards I wrote the following: myvar = 0; var2 = 0; Would that be legal? My VC++6 compiles it correctly, but I think this should be illegal. (It gives a compiler error in one of my other compilers.)
VC6 is rather old, and not always ... rigid ... in its application of the standard :-) It actually leaked scope in certain circumstances like: for (int i = 0; i < 10; i++) { } // You can still use 'i' here. This led to some funky macro magic to get around this problem. If you're using a ISO-conformant compiler, both t...
4,075,398
4,161,542
QT-Graphics - How to constrain the item's movement
I am doing a picture mingling project using QGraphics Scene. So I am placing the pictures inside the QGraphicsscene as QgraphicspixmapItem. But the problem is when I am moving the itm(by mouse drag), the QGraphics view is automatically expanding. I want to constrain this action. Can anybody help me in this?
At last I used the QGraphicsScene->signal(cnanged). I combined this with apppropriate function which checks the selected item's position and maintains it within the given area.
4,075,439
4,075,451
Shuffling a deck of cards
I'm making a Deck class for a C++ program. It needs to have two methods: one to pop a card off the top of the deck, another to shuffle the deck. I'm concerned with the latter. Cards are represented as integers 1 to 52 inclusive. What is the fastest algorithm to shuffle the deck (assuming a 'good' level of randomness)?
If you wish to implement the shuffle yourself, a very straightforward but also functional shuffling algorithm: Fisher–Yates shuffle. To shuffle an array a of n elements: for i from n − 1 downto 1 do j ← random integer with 0 ≤ j ≤ i exchange a[j] and a[i] Of course, the C++ standard library also has things lik...
4,075,856
4,134,380
Lowest Common Ancestor (boost graph)
Is there a built-in method in boost to find the lowest common ancestor of two or more nodes in a tree (which is a boost::graph instance)? If not, I would appreciate suggestions on the best way to do this. Wikipedia claims there are efficient algorithm to achieve this in O(1) time (with O(n) pre-processing), but it does...
Found the algorithm in Wikipedia: function TarjanOLCA(u) MakeSet(u); u.ancestor := u; for each v in u.children do TarjanOLCA(v); Union(u,v); Find(u).ancestor := u; u.colour := black; for each v such that {u,v} in P do if v.colour == black print "Tarjan's Least Common Ancestor of " + u...
4,075,931
4,076,144
How to best encapsulate window handles?
I'm developing a system composed of many independent subsystems. Two of such subsystems are the Window and the GraphicsAdapter subsystem. The GraphicsAdapter requires a low-level window handle (HWND or X11 Window Handle, depending of the operating system), and the Window subsystem is a way to abstract those OS specific...
Both HWNDs and X11 Window Handles are pointer types. You can use this to your advantage. Do something like this: struct WindowHandleImpl; typedef WindowHandleImpl *WindowHandle; C++ allows you to work with pointers to incomplete types just fine - just don't define the contents of WindowHandleImpl anywhere and WindowHa...
4,076,143
4,076,166
How can I see which MFC version an executable needs?
How can I see which MFC (Microsoft Foundation Classes) Version an executable needs?
Have you tried using depends.exe? It will show you which MFC DLL it's linked to.
4,076,467
4,076,506
map contains value as a list+how to print in C++
I have a map having strings as keys and lists of file names as values. ex: Map(firstDir, list(file1,file2,file3)) I know that by using following code I can print value which is of String { cout << "Key: " << pos->first << endl; cout << "Value:" << pos->second << endl; } But if pos->second contains a List, how ...
overload operator << for list std::ostream& operator << (std::ostream& out, std::list<ListElemType> const& lst) { for(std::list<ListElemType>::iterator it = lst.begin(); it != lst.end(); ++it) { if(it != lst.begin()) out << /*your delimiter*/; out << *it; } return out; } now you c...
4,076,563
4,076,583
Is using an invalid pointer value legal in C?
The following code is undefined behavior in C++ (although it will work okay on almost any widely used implementation): int* pointer; //uninitialized - likely illegal pointer value pointer++; //incrementing an illegal pointer is UB Is the above code legal in C?
It's undefined behavior in C as well because on certain architectures, loading an invalid pointer into a register triggers a hardware fault. See Is storing an invalid pointer automatically undefined behavior?
4,076,664
4,076,678
c++ dynamic size of the array
I have got a small problem with 1D array in c++. I have got a function line this: void func(int (&array)[???]) { // some math here; "for" loop { array[i] = something; } } I call the functions somewhere in the code, and before I made math I'm not able to know dimension of the array. The array goes ...
Use a pointer, not a reference: void func(int *a, int N); Or, easier, use a vector: void func(std::vector<int> &a); Vectors can be allocated by simply saying std::vector<int> a(10); The number of elements can be retrieved using a.size().
4,077,010
4,077,028
Why do we use printf() function in C++?
Why do we use printf() & scanf() functions in c++?
I think some programmers find them easier or more accessible than the stream-based ones that are more common in C++. Also, when doing complicated string formatting, the C way of using a formatting string can be perceived as being more concise and readable. I'm not arguing that it is, I'm just saying that in some cases ...
4,077,101
4,077,448
MinMax Heap Algorithm Implementation
I searching minmax heap algorithm implementation, i remember some things about this structure, her implementation is on one heap. Even levels (floors) in heap tree is a min colored, and rest of nodes is max colored. I remember some draft of workings of this but i searching some good document about it or some C or C++ c...
I made a little search on google and find this: http://www.coldbrains.com/code/code/C++/Data_Structures/Min-Max_Heap/MinMaxHeap.C.html http://www.coldbrains.com/code/code/C++/Data_Structures/Min-Max_Heap/MinMaxHeap.H.html
4,077,110
4,077,164
template disambiguator
I'm trying to find any information about template keyword used as disambiguator, but there is nothing about that. Probably I'm searching wrong keywords, but there is nothing like .template or ->template in standard. Google shows only GCC problems from different forums, but not really explanation what is it used for. Co...
Short answer : Because the standard says so ISO C++03 14.2/4 When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-id explicitly depends on a template-parameter (14.6.2), the member temp...
4,077,446
4,077,640
M_PI in VS2010: working in Debug conf but not in Release
In my unmanaged C++ source i have: #define _USE_MATH_DEFINES #include <cmath> and then I use M_PI a couple of times. Compiling in Debug configuration works flawlessly but in Release it gives: error C2065: 'M_PI' : undeclared identifier What could be the configuration property causing this?
Solved. I had put #define _USE_MATH_DEFINES before #include "stdafx.h" With Precompiled Headers on (/Yu), as it's in Release mode, everything above it is ignored.
4,077,559
4,077,604
Convert symbol in Classname::FunctionName( Para1, Para2 )
I'm using the GNU extension "char** backtrace_symbols(void *buffer, int size)" to get the stack trace, when an exception is thrown. Is there a library function which converts the symbol into a "human readable" string - to redo the name mangling? If not, I would write my own function according to this Wiki article. Conc...
#include <cxxabi.h> #include <iostream> #include <cstdlib> int main() { int status; const std::string name = "_ZN10CTLTestApp12ExecuteGroupEPK19CTLTestCaseRegisterNS_11EReportTypeE"; char *realname = abi::__cxa_demangle(name.c_str(), 0, 0, &status); std::cout << realname << "(" << status << ")" << std::endl; ...
4,077,609
4,077,681
Overloading output stream operator for vector<T>
What is a recommended way to overload the output stream operator? The following can not be done. It is expected that compilation will fail if the operator << is not defined for a type T. template < class T > inline std::ostream& operator << (std::ostream& os, const std::vector<T>& v) { os << "["; for (std::vec...
Did you actually try this code? It works fine on gcc with a small tweak std::vector<T>::const_iterator, needs to be declared as typename std::vector<T>::const_iterator You may be better off with using std::copy and std::ostream_iterator. EDIT: types, dependent types and typename Can't fit it all in the comments, so her...
4,077,768
4,077,792
In C++ what does "Template and Inline are orthogonal" mean?
In C++ what does it mean that template and inline are orthogonal?
If two things are "orthogonal" it means they are independent. In this case, it means that a template can be inline, a template can be noninline, a nontemplate can be noninline, and a nontemplate can be inline. I think the question arises because there is some surface similarity between the two in that both should b...
4,077,774
4,077,802
Calculating with integers and floating point numbers using c/c++
I have a problem with the following code: #include <stdio.h> #include <iostream> int main () { int a, b; printf("Please type in your number a: "); scanf_s("%d", &a); printf("Please type in your number b: "); scanf_s("%d", &b); printf("Solution 1 (divide and modulus): %f\n", a / b + a % b); printf("Solut...
The result of a/b + a%b is an integer (%d), but you are printing out a float (%f).
4,077,940
4,077,990
Check if string is empty
I got a project in C++ which I need to edit. This is a declaration of variable: LPSTR hwndTitleValue = (LPSTR)GlobalAlloc(GPTR,(sizeof(CHAR) * hwndTitleSize)); How to check if this string is empty? I tried simply with if(hwndTitleValue == "") but it always returns false. How to check if this string is empty? EDIT I a...
I believe that hwndTitleValue is a pointer, at least in Hungarian Notation it would be. Your method is allocating a array of bytes (an ANSI C string), so the best way to do it would be #include <string.h> // ... other includes ... int isEmpty(LPSTR string) { if (string != NULL) { // Use not on the resu...
4,078,050
4,078,236
std::stringstream efficient way to get written data, copy to another stream
Without writing a custom rdbuf is there any way to use a stringstream efficiently? That is, with these requirements: the stream can be reset and writing start again without deallocating previous memory get a const char* to the data written (along with the length) without creating a temporary populate the stream witho...
Use boost::interprocess::vectorstream or boost::interprocess::bufferstream. These classes basically meet all of your requirements. boost::interprocess::vectorstream won't return a const char*, but it will return a const reference to an internal container class, (like an internal vector), rather than returning a tempor...
4,078,277
4,078,397
Text Editor API. Scintilla for experimental IDE. Do you use something else?
I have discovered Scintilla/Notepad++ API this week end. As there is a nice Template vcproj for Notepad++ Plugins available on line then I could start to play with some pseudo code-source really really fastly. I have just looked briefly at the Scintilla documentation which expose the API which looks promising. Sometim...
I found Scintilla to be very feature-packed, and covered everything I needed. You have to do a bit of work to get all the functionality out of it (ensuring that keyboard short-cuts perform the desired effect, etceteras), but it was incredibly easy to compile, include and get working, though as I said you have to do a ...
4,078,401
4,079,685
Trying to optimize line vs cylinder intersection
My brain has been melting over a line segment-vs-cylinder intersection routine I've been working on. /// Line segment VS <cylinder> // - cylinder (A, B, r) (start point, end point, radius) // - line has starting point (x0, y0, z0) and ending point (x0+ux, y0+uy, z0+uz) ((ux, uy, uz) is "direction") // => start = (x...
The cylinder is circular, right? You could transform coordinates so that the center line of the cylinder functions as the Z axis. Then you have a 2D problem of intersecting a line with a circle. The intersection points will be in terms of a parameter going from 0 to 1 along the length of the line, so you can calculate ...
4,079,387
5,225,148
VS2010 Add-in cpp/h automatic tab groups
Is there any Visual Studio 2010 add-in that will automatically group cpp and header files in different tab-groups, and also maybe automatically open/close corresponding cpp/header files when opening a certain file?
This addin looks like providing the first feature that you wanted, though I don't know whether it works with h/cpp files: http://visualstudiogallery.msdn.microsoft.com/EBF6137E-AA2D-4DC9-860A-F04168F11CD7. About the second, I'm not sure you really always want to do. I think most of the time that can actually be annoyin...
4,079,451
4,081,401
What about the types int2, int3, float2, float3 etc
I've seen different code snippets using these types, but I haven't seen if they are defined in some <standard header file> or just defined in a "local header file" or even at file level. So what Im wondering is: Is there any standard header file that defines these types? Or is there some standard definitions that every...
These types aren't a part of standard C++. They might either be defined in some third-party library, or you're looking at some other dialect or language. GPU code (Shader languages such as GLSL, Cg or HLSL, or GPGPU stuff like CUDA or OpenCL) typically defines types like these though, as names for the corresponding SIM...
4,079,794
4,079,847
template functions, how to send different structures and create a if/else statement based on type?
i'm trying to build a general purpose template function which should function with 2 different type of structure i'll write an example struct sa { int a; int b; char d; } struct sb { int a; int b; int c; } template < class T> void f_print(T & s_passed, bool s_typeB){ std::cout << s_passed.a << endl ; std::cout << s_pa...
You could move the specialized parts in separate functions and call these from your generic template: void f_print_special(sa & s_passed) { std::cout << s_passed.d << endl ; } void f_print_special(sb & s_passed) { std::cout << s_passed.c << endl ; } template <class T> void f_print(T & s_passed) { std::cout <...
4,080,026
4,080,048
Does strcpy'ing a string into into a larger char array cause a memory leak?
Hey all, just wondering whether the following would cause a memory leak? char* a = "abcd" char* b = new char[80]; strcpy(b, a); delete[] b; Will it delete the whole block of 80 or just the 4 characters copied into it by strcpy? Thanks!
You allocated 80 bytes into b, so delete[] will free 80 bytes. What you did with the array in the meantime is irrelevant. (Unless, of course, you corrupted the heap, in which case delete[] will probably crash.) EDIT: As others have pointed out, since b is an array, you need to use delete[] b; instead of delete b;. Some...
4,080,034
4,080,180
How to read an unknown contents of a text file into a 2d array
I am trying to read the unknown contents of a text file into a 2D array and have it come out looking like: M [0] [0]=2 M [0] [1]=1 M [0] [2]=0 M [1] [0]=0 M [1] [1]=1 M [1] [2]=3 M [2] [0]=8 M [2] [1]=9 M [2] [2]=1 M [3] [0]=3 M [3] [1]=5 M [3] [2]=2 when the text file looks like this: 2 1 0 0 1 3 8 9 1 3 5 2 -2 3 -1 ...
Just use 'fstream'. It ignores new lines and works just like 'iostream'. You just need to keep track of your matrix row and column. //open "myFileName.txt" with an input file stream std::ifstream inputFile("myFileName.txt"); while(!inputFile.eof()) //Check for end-of-file character { //do this while keeping track ...
4,080,148
4,080,185
Adding an Event Handler to a Newly Created Window using C++
How do I add an event-handler to a newly created window using C++? _hWnd = CreateWindow( NULL, NULL, 0, 0, 0, 0, 0, NULL, NULL, NULL, NULL ); It is a dummy window that is intended to do nothing but wait for the WM_DEVICECHANGE event and is to be registered using RegisterDeviceNotification. How do I attach the event-h...
You can do it by setting the window procedure with SetWindowLongPtr and the GWL_WNDPROC flag. SetWindowLongPtr(_hWnd, GWL_WNDPROC, myWndProc);
4,080,253
4,080,919
Create getter and setter members for a C++ class in Vim
I'm creating a class with many double (or something else, the type doesn't matter) members. class CalcParameters { public: CalcParameters() {} ~CalcParameters() {} // getters and setters here private: double _param1; double _param2; ... }; Is it possible, in Vim, to write a script to automatically gener...
I wrote a ftplugin for this purpose a long time ago. The idea is to type ;AA and to answer the questions Vim asks you. It has a primitive form of const-correctness understanding (i.e. an int would be copied while a string would be exchanged by const-ref) I should rewrite it some day now that I know how to fetch the typ...
4,080,601
4,327,772
Not using C++ exceptions by design, in llvm/clang
llvm/clang are considered good C++ code bases. I wonder why C++ exceptions arenot used in them at all? Memory is managed using something like pools, and erros are reported with returnd values and codes like in C. They even wrapping operator new to be placement new that returns error and not exception when no memory. D...
Chris Lattner recently clarified this issue in the LLVM project coding standards. Not using exceptions and RTTI reduces executable size and reduces overhead. (You might argue that zero-cost exceptions have no overhead unless thrown. At a minimum, they actually break up the code into smaller basic blocks and inhibit s...
4,080,668
4,080,733
_iterator_debug_level value '0' doesn't match value '2'
I've just moved over a Visual Studio (C++) solution over to another computer, setup all the directories and settings as far as I can see, and did a clean/rebuild on the solution. I get the error above on a bunch of .obj's on compile, not sure what to do about it.
It seems that you are mixing object files built with different settings. Try to do a full clean rebuild and check all project file settings to make sure that the _ITERATOR_DEBUG_LEVEL macro is the same (e.g., you are not mixing debug and release built objects).
4,080,700
4,081,082
Async File IO under Unix and finding out how many bytes are left
I'm doing asynchronous file I/O under unix using open/close/etc. I have everything working fine and I'm able to initiate background reads and writes and wait for them to finish using a select. I have one issue left, however. I would like to find out how much data is left to read/write. Now I assume this is an easy io...
If you are doing reads from a standard file, you could use lseek using SEEK_CUR and a value of 0 for the offset to get the current file position, and then lseek to the end to get the end of file position and subtract them. Not sure how you would know how much data is left to write, since you are the one writing it. Th...
4,080,702
4,083,059
F12 key in SDL causes breakpoint?
I have recently taken two SDL projects - a demo project, and one of my own and compiled with SDL under VC++ 6.0. In Debug configuration, I can get all key presses fine with the exception of the F12 key. If I press F12, I get a "user breakpoint" in NTDLL, no matter what. Has anybody else experienced this or able to help...
:-) The reason this happened was that I was running my app in Debug configuration.. and after 9 years I had no idea that the F12 key causes a break to occur within MSVC.
4,080,742
4,080,799
Segfault during C++ array deallocation
I'm getting a weird problem in memory deallocation. I have the following code for class MemoryPartition: #include <cstring> #include <iostream> #include "memorypartition.h" MemoryPartition::MemoryPartition(int maxSize) { this->partitionArray = new char[maxSize]; memset(this->partitionArray, ((int) '$'), maxSi...
Its impossible to tell from the code above. But my guess is that you need to define the copy constructor and assignment operator. See Rule of 4 (Google/Wiki it). Try the following: class MemoryPartition { // Just add these two lines (keep them private) MemoryPartition(MemoryPartition const&); // Do...
4,080,814
4,081,181
Randomly Generating a 2d/3d Array
I've thought about this for awhile but what is maybe a good way to go about randomly generating a 2-d or possibly 3-d array. Im not looking for specific code per se, but more just a general idea or way one might think of doing it. edit: Sorry I mistyped, What I meant is say you have an array (2d or 3d) filled with empt...
If you were trying to sparsely fill a large 2D array with uppercase ASCII characters it would be something like the following in C: int array[A][B]; for (int i = 0; i < SOMETHING; ++i) { //Note: Modulus will not give perfect random distributions depending on //the values of A/B but will be good en...
4,081,334
4,081,383
Using CreateWindowEx to Make a Message-Only Window
I'm trying to use CreateWindowEx to generate a message-only window: _hWnd = CreateWindowEx( 0, NULL, NULL, 0, 0, 0, 0, 0, HWND_MESSAGE, NULL, NULL, NULL ); When my application executes this line it always returns _hWnd = 0. What am I doing wrong?
lpClassName shouldn't be NULL. Register class using RegisterClassEx function and pass it to CreateWindowEx. static const char* class_name = "DUMMY_CLASS"; WNDCLASSEX wx = {}; wx.cbSize = sizeof(WNDCLASSEX); wx.lpfnWndProc = pWndProc; // function which will handle messages wx.hInstance = current_instance; wx.lpsz...
4,081,410
4,081,449
What is the result of i + ++i?
Possible Duplicate: Could anyone explain these undefined behaviors (i = i++ + ++i , i = i++, etc…) Why this code is generating 8 as a result ? #include <iostream> using namespace std ; void myFunction(int i) { i = i + 2 + ++i; cout<<i<<endl; } void main () { int i = 2; myFunction(i); cin>> i...
The order of evaluation of terms on the right hand side of this expression i = i + 2 + ++i; is undefined. i.e. they can occur in any order. In this case the compiler has chosen to increment i first (++i, third term), before evaluating i (first term), which results in 3 + 2 + 3.
4,081,491
4,081,551
Printf for struct? (C/C++, VC2008)
Just build&run this in VC2008: struct A { int a; int b; int c; }; A a = { 10, 20, 30 }; printf("%d %d %d\n", a); Is it normal? 10 20 30 I'd like to cast! but it don't works: struct A { int a; int b; int c; operator int() { return a + b + c; } }; A a = { 10, 20, 30 }; printf("%d\n", a)...
If you want a cast, then cast it: struct A { int a; int b; int c; operator int() { return a + b + c; } }; A a = { 10, 20, 30 }; printf("%d\n", (int)a); the output will be 60
4,081,904
4,081,934
Would C/C++ code compiling on Mingw guarantee full compatibility with GCC(on linux and Mac)
I'd like to produce cross-compiler compatible C++ code. I've produced a somewhat "exotic" code, that push the C++ language in its gray, weird, mysterious areas. Considering my code only depends on boost and the STL, that the issue is to check code compatibility, and not lib compatibility: Would my code compiling both m...
Not at all. Compiling your code with MSVC and MinGW guarantees that your code is compatible with Microsoft's C/C++ libraries. I understand you're only talking about code compatibility, but such a thing doesn't exist. If you're pushing C++ into the gray areas, it might well be that the same code will have different resu...
4,082,051
4,082,075
is there any irc chat room for directx 9 c++?
is there any active irc chat room that have people to talk to?
Try stackoverflow's new chat utility. Perhaps people can answer your questions there. You could also try irc.rohitab.com - some talented coders are often present there.
4,082,065
4,082,111
Zombie objects after std::move
I'm confused about the state of an object after it's been moved using C++0x move semantics. My understanding is that once an object has been moved, it's still a valid object, but its internal state has been altered so that when its destructor is called, no resources are deallocated. But if my understanding is correct,...
Edit (New and correct answer) Sorry, looking closer at the code, it seems the answer is much simpler: you never invoke the move constructor. You never actually move the object. You just pass a rvalue reference to the work function, which calls a member function on that reference, which still points back to the original...
4,082,118
4,082,202
Open application in separate console window
I'm currently writing an application that I would like to open in a new terminal window, resizing it in the process, rather than the one in which the invoking command was typed. How should I go about doing this? I'm using the gnome terminal and will be writing the app in C++.
Try gnome-terminal --geometry="20x10" -e 'command' (20 is height, 10 is width). In C++, you can call a command by using system().
4,082,128
4,085,518
How to guard data structure consistency when calling external logic via observers?
I am currently refactoring an application in which classes can call observers if their state changes. This means that observers are called whenever: the data in an instance the class changes new instances of the class are created instances of the class are deleted It is this last case that makes me worry. Suppose th...
The basic problem here is that the Book collection gets modified (without knowledge by the application) while the application is iterating over that same collection. Two ways to deal with that are: Introduce a locking mechanism on the collection. The application takes a lock on the collection and as long as that loc...
4,082,300
4,082,678
Connect to MS SQL Server through ODBC
I have a Qt 4 application that is trying to connect to an MS SQL Server 2008 database using the Qt ODBC driver. The application runs fine when it is running in Windows; however, the target OS for the application is to have it run in GNU/Linux. When the application runs in GNU/Linux I get the following error: QSqlError(...
I don't really know much about unixODBC, but have a look here: unixodbc.org/doc/ For connecting to MSSQL, the following might be useful: http://www.unixodbc.org/doc/FreeTDS.html or .../FreeTDS2.html
4,082,503
4,086,633
dyld: Library not loaded: libqscintilla2.5.dylib
I'm trying to use QScintilla on MacOS X, I added LIBS += -lqscintilla2 in the .pro, with this quite simple code: #include <QApplication> #include <Qsci/qsciscintilla.h> int main(int argc, char* argv[]) { QApplication app(argc, argv); QsciScintilla *qscintilla = new QsciScintilla; qscintilla->show(); ...
Well I copied the .dylib into /etc/lib/, it works now, but I'd like to make the app distributable...
4,082,522
4,082,855
Troubleshooting an x64 com interop marshaling issue
I have a C++ COM Server which I have recently recompiled to 64 bit. This COM server has a method that contains a struct parameter which contains some ints and a BSTR and another structure. Now, I am trying to call this COM server from a 64 bit .Net C# application. I can successfully load my COM server and call this ...
A struct is COM's Achilles heel. The actual layout of the members of the struct is highly compiler dependent. They were not support in COM automation for quite a while until they came up with the IRecordInfo hack. Not getting used here. In unmanaged code, the #pragma pack directive is very important. For type libra...
4,082,542
4,082,578
Should I ONLY have to worry about new and match them with deletes?
I have a C++ code in which I have multiple data types. Importantly, I have a class: class coordinate{ int x, y; public: void set_values(int, int); } I then might say: coordinate* origin = new coordinate; Obviously, to recover memory allocated to origin I would finally say: delete(origin); So far, so goo...
The answer is: it depends. If your code allocates anything (a string, an instance of coordinate class, a stringstream etc.) with new, some code (maybe yours) should delete it. Otherwise, if you create a string on stack and pass it around with copy constructors, you don't have to delete it. And: NAME.end() is not needed...
4,082,663
4,082,710
How to test if output to std::cout (connected to a pipe) will block
I have a C++ program that is launched by another executable that ingests the output of that program via a pipe. In certain conditions, the parent process reads slower than the child writes, and the child blocks when the pipe buffer in the pipe manager (QNX) becomes full. Is there a standard way to test if cout << will ...
No, detecting that is operating-system specific.
4,082,789
4,082,859
Problems Using RegisterClassEx
In my Win32 C++ DLL I find that if I try to use RegisterClassEx this way it works just fine: WNDCLASSEX wx = {}; wx.cbSize = sizeof(WNDCLASSEX); wx.lpfnWndProc = (WNDPROC)WndProc; // function which will handle messages wx.hInstance = GetCurrentModule(); wx.lpszClassName = pClassName; atomRet = RegisterClassEx( &...
In your first example, WNDCLASSEX wx = {}; the declaration of wx is also zero-initializing all the fields. In your second example, you don't show how _pWndClassEx is being initialized, but you mention getting memory for the structure using malloc(). To be equivalent to the first example, you'll need to clear out the ...
4,082,878
4,082,913
Garbage collection question
Consider the following segment of code: function loadSomeContent() { URLLoader loader = new URLLoader("http://www.somesite.com/"); loader.addEventListner("onLoadComplete", loadCompleteHandler); loader.sendHttpRequest(); } function loadCompleteHandler(event) { log("Load response received"); } Do not ...
When you call loader.sendHttpRequest() a new thread is created that will actually send the request in the background. This thread keeps a reference to the loader so that it can call the load complete function when the load is finished. As a result the loader will always be referenced by some thread, just not the thre...
4,082,883
4,082,912
C++ heap and ifstream read function
for my assignment I am building a heap, the data for the heap is coming from a file. One of the functions is to get the data, but I am having trouble understanding the ifstream read() function and am getting quite a nasty error because of it this is what I have: template<class T, class P> void get_list(vector<T>& v, co...
The prototype for std::ifstream::read is istream& read ( char* s, streamsize n ); So where you have inFile.read( &data, sizeof(T)); should be inFile.read( (char*) &data, sizeof(T)); However this assumes you are reading raw bytes from a binary file. If you are parsing a text file with the integers represented in dec...
4,082,972
4,083,001
struct and typedef in C versus C++
I am currently using a C++ IDE for something that will need to work on C, and wanted to make sure that I won't have problems with this later on. After making the struct below: typedef struct test { int a; int b; }; I then create an instance of it using test my_test; then stuff like my_test.a = 5, etc... and thi...
The difference between: struct Name {}; And typedef struct Name {} Name; Is that, in C, you need to use: struct Name instance_name; With the former, whereas with the latter you may do: Name instance_name; In C++, it is not necessary to repeat the struct keyword in either case. Note that your example in which you cr...
4,082,989
4,102,068
Calling Ruby function from C++ in a loop results in "stack level too deep"
I'm trying to run blocks of Ruby code from C++. I have two Ruby functions, one called Init(), and one called Loop(). The problem I have is that I can only Loop() so many times before I get a "stack level too deep" from SystemStackError. My Ruby code is not recursive as far as I can tell. As you can see, so far this Rub...
OK, so I pared it down until I got a working version similar to my C implementation but the problem has nothing to do with C++ vs C. What's not shown above (because I didn't think it was relevant) is that this is a Qt application, and I have two slots--one to initialize ruby and load the program, and another to call th...
4,083,124
4,083,160
C++ - Stack with Linked List - Bad Memory Error?
I am currently writing stack that is being implemented with a linked list. I am get this error: Unhandled exception at 0x75249617 in STACK_LinkedList.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x002ee8f8. I believe it is possibly coming from either my push() or pop() functions. I can't find my e...
You should not delete your temp in push! It's a part of the list. So when you access this data later, you get surely an exception. Second, you have to initialize your pred with NULL in pop(), otherwise you'll get an undefined value assigned to theTop if the stack contains only 1 item. Third, you should delete in pop() ...
4,083,150
4,084,803
Using Cython to expose functionality to another application
I have this C++ code that shows how to extend a software by compiling it to a DLL and putting it in the application folder: #include <windows.h> #include <DemoPlugin.h> /** A helper function to convert a char array into a LPBYTE array. */ LPBYTE message(const char* message, long* pLen) { size_t length = strlen(...
I think the solution is to use both. Let me explain. Cython makes it convenient to make a fast plugin using python but inconvenient (if at all possible) to make the right "kind" of DLL. You would probably have to use the standalone mode so that the necessary python runtime is included and then mess with the generated c...
4,083,151
4,083,186
Number of cycles taken for C++ or ANSI C?
Is there anywhere on the web where i can get an idea of what the various programming language syntax take in terms of processor (Core i7 and Core 2) cycles? At university i learnt the ARM assembly language and we could map the number of cycles taken to do a subtraction operator etc. I just wondered if its possible to d...
No. That's completely dependent on the compiler you use, and what optimization settings you use, etc. You can use your favorite compiler and settings to generate assembly code, and from the assembly code you can make these kinds of predictions. However, remember that on modern architectures things like memory latency a...
4,083,229
4,083,266
issue with int to float
Here is my issue. I have a constructor that makes a color from 4 floats ranging 0 to 1. I want to add compatibility with 0 to 255 int so I have another constructor like this: AguiColor::AguiColor( int r, int g, int b, int a ) { double num = 1.0f / 255.0f; AguiColor((float)(r * num), (float)(g * num), (float)(b * n...
C++03 doesn't support constructor delegation (a/k/a chaining). When you call that other constructor, Java-style, it creates a temporary object, without affecting the object under construction. This might fix it, but isn't as efficient as initializing the members directly would be. AguiColor::AguiColor( int r, int g, i...
4,083,306
4,083,484
Open GL Lighting Problem
I've been working on a game engine for a month now, and I've finished the basic OpenGL stuff. However, the one thing that I can't get to work like I expect it to is the lighting. (Note: This is the first time I seriously worked with OpenGL) What I want is a close to realistic lighting simulation - where the surfaces fa...
The first thing to do is make sure you have glEnable(GL_LIGHTING); called at some point. Past that, the first thing to check is that your normals are correct. For lighting to work properly you will need to have a normal set for every vertex you draw. If you have already set your normals, you should make sure that they ...
4,083,428
4,083,445
c++ linked list insert function
I get a compile error for a create function I use with the insert function. It works though when I do the different calls in the if clause, but I want to move it to a seperate create function instead. Any help regarding the compile error I get is appreciated |76|error: cannot convert list_link*' tosorted_list::list_li...
The class list_link is: Declared in the scope of sorted_list Marked as private In order to have a freestanding function create an object of this type, you will need to make the type public, and you will also need to either prefix it with sorted_list::, or you wil need to declare it outside of the sorted_list class. I...
4,083,490
4,083,586
How do I pass a 2D array in C++ to a Fortran subroutine?
I am writing a small C++ program which passes a 2-D array (of complex numbers) to a Fortran subroutine and receives it back filled with values. I wrote a version which passes and receives a 1-D array, and this works well. The 2-D version doesn't work (my true goal is to write a 4-D version with large dimensions - so th...
Multidimensional arrays in Fortran are stored as flat column-major arrays in memory. They are not pointers to pointers—they're really just 1D arrays where you have to do some extra arithmetic to compute array indices. The correct way to pass the array from C++ is like this: extern "C" void carray_(struct cpx *A); ... ...
4,083,597
4,083,683
Is std::string a better idea than char* when you're going to have to pass it as a char*?
In a recent question, I learned that there are situations where you just gotta pass a char* instead of a std::string. I really like string, and for situations where I just need to pass an immutable string, it works fine to use .c_str(). The way I see it, it's a good idea to take advantage of the string class for its ea...
In the example you give, you can generally read a line into a std::string using the std::getline function: http://www.cplusplus.com/reference/string/getline/ Of course this doesn't do everything that a curses library does. If you need a non-const char* so that some C function can read into it, you can use a vector<cha...
4,083,658
4,083,781
Why aren't the SDL_Rect* arguments of SDL_BlitSurface const?
int SDL_BlitSurface(SDL_Surface *src, SDL_Rect *srcrect, SDL_Surface *dst, SDL_Rect *dstrect); Why are the srcrect and dstrect arguments not const? Are they modified in the function? At the moment I'm const-casting my Sprite class member variables to use BlitSurface... It seems silly.
The documentation specifies that dstrect, if non-NULL, is modified to contain the resulting clipped rectangle. srcrect is not modified, so it very well could be made const. Why? Who knows. I'd guess that it was probably an oversight by the people who wrote SDL.
4,083,712
4,083,736
C/C++ string memory leaks?
I'm using the STL string within an application of mine, and I was recently testing it for memory leaks, and I noticed that a lot of my strings weren't being properly deallocated by the end of the program. I tested the following code (not verbatim) with one of the strings: const string* cppString = &obj->objString; cons...
What you're seeing is undefined behavior—it's not actually a memory leak. The memory for the C string has been deallocated (at least as far as you're concerned), but the data there is still technically accessible. When you deallocate memory, the memory usually doesn't get erased, so the data there often stays around ...
4,083,751
4,083,903
Preferable to embeb dependencies on interfaces or let that job to the concrete classes?
Here is a question that I have to face a lot when doing the design of my little apps. Is there a reason I should prefer over ? If yes, why? If not, are there any specific circunstances where there is a clear advantage in one approach over the other? I tend to use the first approach, although I am not too sure why. I ...
It sounds like you understand the subject quite well. I agree with your argument that there might be an implementation which does not have the dependency and so it's best not to be tied down. I typically prefer the first approach, like you, for that very same reason and typically encourage that choice. In general, I wo...
4,083,838
4,083,875
Are derived classes considered friends?
If I create base class A and A is a friend of class B, can a class derived from A access B to its liking, or else what is it allowed? Thanks
struct A{}; struct Ader : A{}; struct B{ friend struct A; }; No. Friendship is not inherited in C++. It is also not transitive. Ader can not access B as a friend unless explicitly given friendship by B, just because it's base A is a friend of B.
4,083,944
4,083,983
OpenGL Texture Mapping
I am new to game programming and graphics programming. However, I eagerly wish to learn, so I have begun building a game engine with OpenGL. I have implemented all of the basic graphical features, and now I want to add texture support for my triangle meshes. The only tutorials I can find for texture mapping is for a si...
Here's a page showing an example of reading out the texture coordinates: http://newsgroups.derkeiler.com/Archive/Comp/comp.graphics.api.opengl/2005-07/msg00168.html However, not all 3ds files contain texture information - see warning in: http://www.groupsrv.com/computers/about186619.html
4,083,971
4,083,993
Is it possible to initialize static const member object in a class in C++?
Is it possible to initialize a static constant member in a class definition? Please see below for the code, class foo { public: foo(int p) : m_p(p){} ~foo(){} private: int m_p; }; class bar { public: bar(){} ~bar(){} public: static const foo m_foo = foo( 2 ); //is this possible?...
Short answer: No, until the static member is const and is of integral or enumeration type. Long answer: $9.4.2/4 - "If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expressio...
4,084,053
4,084,521
Passing non-const references to rvalues in C++
In the following line of code: bootrec_reset(File(path, size, off), blksize); Calling a function with prototype: static void bootrec_reset(File &file, ssize_t blksize); I receive this error: libcpfs/mkfs.cc:99:53: error: invalid initialization of non-const reference of type 'File&' from an rvalue of type 'File' libc...
Yes, the fact that plain functions cannot bind non-const references to temporaries -- but methods can -- has always bugged me. TTBOMK the rationale goes something like this (sourced from this comp.lang.c++.moderated thread): Suppose you have: void inc( long &x ) { ++x; } void test() { int y = 0; inc( y );...
4,084,087
4,084,109
Singleton pattern in C++
I'm new and a little ignorant in C++ and I encounter a C++ code that used a singleton pattern, class CFoo { public: static CFoo& getInstance() { static CFoo self; return self; } private: CFoo(){} ~CFoo(){} }; I am just confused why return a static reference? Is this a valid code? Why the pr...
Why use a pointer? A reference is simple and matches what I want to do: alias an object, not point to it. The static doesn't apply to the reference, it applies to the function, making it callable without an instance. (Even better, why use a singleton?)
4,084,110
4,084,130
ERROR problem with a function. C++
In function Determininant i keep getting an error.... #include <iostream> #include <fstream> #include <cmath> using namespace std; const int maxsize = 10; ifstream fin; ofstream fout; void transpose (double omatrix[][maxsize],double tmatrix [][maxsize], int array_size) { for(int i = 0; i < array_size; i++) ...
Exactly what the error message says: d is a double and you can't call it as a function. Perhaps you meant Determinant(temp, array_size - 1)?
4,084,239
4,084,247
How can you get pointer to a templated member function from a template type?
The following code does not compile ... any idea why? Is this illegal C++? class Handler { public: template <typename T> void handle(T t) {} }; class Initializer { public: template <typename T, typename H> void setup(H *handler) { void (H::*handle)(T) = &H::handle<T>; // fails } }; int main() { ...
You need template: void (H::*handle)(T) = &H::template handle<T>; Because the template handle is qualified with a dependent type. (Just like you use typename if a type is qualified with a dependent type.)
4,084,283
4,084,288
Error incomplete universal character name \U
I'm trying to write a C++ program that alters a .txt file. However when I run it I get a strange error. The error: 6:20 C:\Dev-Cpp\Homework6.cpp incomplete universal character name \U My code: #include <iostream> #include <fstream> using namespace std; int main () { ofstream myfile ("C:\Users\My Name\Desktop\test...
"C:\Users\My Name\Desktop\test\input.txt" The backslash (\) is a special character. You must escape it: "C:\\Users\\My Name\\Desktop\\test\\input.txt". EDIT: Alternately, use forward slashes (/). Windows doesn't care.
4,084,376
4,084,380
Alter a .txt file of a variable directory
I'm trying to write a program that alters a .txt file of a variable directory. However when I attempt to do so I get an error. My error: no matching function for call to `std::basic_ofstream<char, std::char_traits<char> >::basic_ofstream(std::string&)' My code: #include <iostream> #include <fstream> using name...
The fstream constructors take C strings, not std::string, so you need std::ofstream myfile(file_name.c_str()); The reason why they take C strings instead of std::strings is purely historical; there's no technical reason. C++0x adds constructors that take std::strings.
4,084,458
4,084,508
How do I change the case of a string in C++?
I have a string that may contain numbers as well as upper and lower case letters. I need to convert all the uppercase letters to lowercase and vice versa. How would one go about this?
Iterate the string and use isupper() to determine if each character is uppercase or not. If it's uppercase, convert it to lowercase using tolower(). If it's not uppercase, convert it to uppercase using toupper().
4,084,751
4,084,799
Gathering the contents of a .txt file as a string, C++
I currently have a little program here that will rewrite the contents of a .txt file as a string. However I'd like to gather all the contents of the file as a single string, how can I go about this? #include <iostream> #include <fstream> #include <string> using namespace std; int main () { string file_name ; ...
The libstdc++ guys have a good discussion of how to do this with rdbuf. The important part is: std::ifstream in("filename.txt"); std::ofstream out("filename2.txt"); out << in.rdbuf(); I know, you asked about putting the contents into a string. You can do that by making out a std::stringstream. Or you can just add i...
4,084,772
4,085,318
How to expose a subset of the public interface to a class
I have a class - PluginLoader which deals with another class Plugin to carry out its functions. Plugin class uses some functions in PluginLoader. Both these classes are abstract base classes so I can't declare Plugin as a friend of PluginLoader. And I don't want the functions Plugin uses to be available in the public i...
Assuming your PluginLoader interface contains more than just the Register... methods and that you want to manipulate loaders via that interface but provide a separate communications channel between plugin and loader you can simply create another interface, PluginRegistra, perhaps, which would have the public Register.....
4,084,777
4,084,810
Creating a thread pool using boost
Is it possible to create a thread pool using boost's thread? i was looking all over boost's libs and I couldn't find a thread pool manager (or something like that)... Is there a way to do it? tnx!
There is an unofficial (yet) threadpool in boost. But it's not a problem to implement one yourself especially if great genericity is not a primary goal. Idea: your threadpool can be parametrized with TaskType type and the number of workers. The TP must be given the handler function which takes TaskType. TP contains a q...
4,084,917
4,086,678
Help needed while setting up basic multiplatform cmake-enabled project
tl;dr the questions are at the bottom. I am a developer trying something new - my last poison is c++. As I am spending half of my time on my linux laptop and the other half on Win XP PC, I tried to find a way to create basic, barebone project, using good c++ practices (well, I don't know them from experience, I just re...
1) what are the guidelines for writing multiplatform CMakeLists.txt file (which will work independly of the os and the location of the project files), which preferably will allow me to easy swich my project configuration from one os the other one? Well, I'm certainly no expert, but I can share my 10-month experience ...
4,084,940
4,085,028
Where's the source-code for base::Thread
I was looking up something, and stumbled upon this code: http://google.com/codesearch?q=kBrowserThreadNames Where can I find the source for base::Thread? (Thing is, in debugging something running under firefox.exe, I notice Gecko_IOThread is setting it's thread name in some kind of way and wanted to look up how.)
A quick Mozilla MXR lookup seems to indicate that it's defined in mozilla/ipc/chromium/src/base/thread.h Edit: I was also curious about the presence of Chronium code in Mozilla so I googled a bit and found this on the blog of Benjamin Smedberg the commiter of the code: IPDL is a language which precisely describes th...
4,084,972
4,084,996
namespaces, classes and free functions - when do you need fully qualified names
In my example below, why do I have to fully qualify the name of the free function in the cpp to avoid linker errors and why does it work for the class function without? Can you explain the difference? ctest.h: namespace Test { int FreeFunction(); class CTest { public: CTest(); ...
int FreeFunction(void); is just a declaration whereas the below is a definition. class CTest { public: CTest(); ~CTest(); }; If you want to provide definition for an already declared entity in a namespace (e.g. in an enclosing namespace), it has to be fully qualified name. EDIT2: Here is s...
4,085,050
4,085,342
how to ignore LNK2005 & LNK1169?
So I have a Visual Studio 2010 project that uses external libraries and in order to get it compile without LNK2005 I had to juggle arround with the order of the libraries in the linker settings. I got it to compile fine in release mode, but for whatever reasons I don't manage to get it to compile without LNK errors in ...
You may try the linker-option /FORCE (Force File Output in the Linker General tab of the Project Properties). This will force the linker to create a exe/dll even when such errors occur. But its left to you to find out if this exe does work at all or even correctly. After all i would not recommend this strategy. Linker ...
4,085,436
4,085,457
Convert a raw pointer to a clone_ptr
I have a clone_ptr implementation, as was shown in this question and I have a problem where I need to create a clone_ptr from a raw pointer returned from a function. Here is the code: DOMDocument* doc = impl->createDocument( 0, // root element namespace...
Giving your clone_ptr implementation, and the fact that doc is a pointer, wouldn't it be document.reset(doc)?
4,085,508
4,085,593
How can I use a floating-point value as a non-type template parameter?
Is there any reason for not being able to have double as a parameter type with templates? For example: template<int N>//-< Legal struct { }; template<double N>//-< Illegal struct { }; Is there any update on this in C++11?
This is to do with precision, floating point numbers cannot be precisely represented, and the likelyhood of you referring to the same type can depend on how the number is represented. Consider instead using an integer mantissa and exponent as the template parameters...
4,085,591
4,087,244
g++ template name mangling
I need to use the address of a member of a template class in g++ inline assembly (as a compile-time constant value). Is it possible to express this? (I think that I need the mangled name of T<U>::x). template < typename U > struct T { static int x; }; template < typename U > void f () { asm ("somecommand T<U>::x")...
Assuming you're using linux, you can use nm. nm --demangle foo.o gives you the demangled names for your symbols nm --no-demangle foo.o gives you the mangled names for your symbols. Then you can compare the output of these 2 files to match up the mangled name to the demangled name.
4,086,374
4,086,613
OpenGL LookAt function: is the up vector arbitrary?
I am trying to understand the glLookAt function. It takes 3 triplets. The first is the eye position, the second is the point at which the eye stares. That point will appear in the center of my viewport, right? The third is the 'up' vector. I understand the meaning of the 'up' vector if it is perpendicular to the vecto...
It works as long as it is "sufficiently perpendicular" to the up vector. What matters is the plane between the up-vector and the look-at vector. If these two become aligned the up-direction will be more or less random (based on the very small bits in your values), as a small adjustment of it will leave it pointing abov...
4,086,438
4,086,468
How can I make a portable executable?
It's there a way to compile a c/c++ source file to output a .exe file that can be run on other processors on different computers ? I am asking this for windows platform. I know it can be done with java or c# , but it uses virtual machine. PS: For those who said that it can be done just with virtual machines or the sou...
Different computers use different instruction sets, OS system calls, etc., which is why machine code is platform specific. This is why various technologies like byte code, virtual machines, etc., have been developed to allow portable executables. However, generally C/C++ compiles directly to platform-specific machine...
4,086,508
4,086,707
const reference for temporary lifetime lengthening
I have a question about some C++ standard compliance or lack of it. In my project I'm using some simple Guard class that uses the const reference trick. I'm using Visual Studio 2005 and there are two configurations - one for normal release build and the second one for unit tests. In both cases there is some temporary h...
Both behaviours are standards conforming. If you have code like this: T foo() { return T(); } int main() { const T& x = foo(); } Then, conceptually, in foo, a temporary object is created. This temporary is copied to the return-value of foo. In main, this copy (which is also a temporary object) is bound to x. The ...
4,086,536
4,086,699
How to add a QDockWidget to QGraphicsScene?
Is it possible to add a DockWidget to my QGraphicsScene scene .? If yes how to do it.
The best way I see to achieve this would be to create a QMainWindow, set your graphicsScene as the central widget with QMainWindow::setCentralWidget(QWidget* widget); After that, simply add your QDockWidget in the QMainWindow with QMainWindow::addDockWidget(Qt::DockWidgetArea area, QDockWidget* dockwidget); This opti...