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,107,731
4,121,670
Understanding how dynamic linking works on UNIX
Consider we have the following situation: a program named program which depends dynamically on libfoo.so libfoo.so that depends on nothing (well, it depends on libstdc++ and stuff but I guess we can omit that) program runs perfectly. Suddenly, libfoo codes changes, and some function now uses internally func_bar() a f...
The problem arises when you have not linked libfoo.so against libbar. When you are compiling an executable, by default the linker will not let you leave undefined references. However, when you're compiling a shared library, it will - and it will expect them to be satisfied at link time. This is so that libfoo can us...
4,107,749
4,108,094
Add a button to MFC CDockingPane titlebar
Anyone knows how to add a button to the titlebar of a CDockablePane ? I tried the usual way with CDialog but it does not work for CDockablePane... Thanks
You need to create an instance of CMFCCaptionButton, then use the protected but undocumented m_arrButtons member of the CDockablePane class: yourDockablePane.m_arrButtons.Add(new CMFCCaptionButton(YOURCOMMANDID));
4,107,907
4,108,031
Few doubts about casting operators in C++
The reinterpret_cast as we know can cast any pointer type to any another pointer type. The question I want to ask regarding this cast operator are: How does reinterpret_cast work, What is the magic(the internal implementation) that allows reinterpret_cast to work? How to ensure safety when using reinterpret_cast? As f...
There is no magic. reinterpret_cast normally just means (at least try to) treat what you find at this address as if it was the type I've specified. The standard defines little enough about what it does that it could be different from that, but it rarely (if ever) really is. In a few cases, you can get safety from some...
4,107,934
4,108,103
Messy function pointer : how to remove the warning?
As I asked and answered in this post. I have the following example code. #include <stdio.h> char foo() { return 'a'; } char bar() { return 'b'; } char blurga() { return 'c'; } char bletch() { return 'd'; } char (*gfunclist[])() = {foo, bar, blurga, bletch}; char (*(*x())[])() { static char (*funclist[4])()...
You have to decide whether you are using C or C++. These languages are significantly different in their treatment of the situations like yours. In C++ a "pointer to an [] array" (i.e an array of unspecificed size) is a completely different type from a "pointer to an [N] array" (i.e. an array of specified size). This im...
4,107,947
4,116,308
How to determine buffer size for vswprintf under Linux gcc
I need to allocate a sufficient buffer for format function vswprintf(). When doing the same thing with ANSI string, I'm using: vsnprintf( NULL, NULL, pszFormat, args ); which returns me required size of a buffer. But it seems that unicode version of this function doesn't have this functionality. When I execute: vswpr...
Opening a dummy file to /dev/null (or NUL under windows) and printing to that file to retrieve the size works very well (it is faster than printing to a string): #if !defined(_MSC_VER)    printf_dummy_file = fopen("/dev/null", "wb"); #else    printf_dummy_file = fopen("NUL", "wb"); #endif ... n = vfprintf...
4,108,061
4,108,262
winsock recv gives 10014 error
I'll start with the code: typedef std::vector<unsigned char> CharBuf; static const int RCV_BUF_SIZE = 1024; SOCKET m_socket = a connected and working socket; // ... CharBuf buf; // Declare buffer buf.resize(RCV_BUF_SIZE); // resize buffer to 1024 char* p_buf = reinterpret_cast<char*>(&buf[0]); // change from unsi...
Found the answer myself while pasting the whole function, &pData[0] is a hint.
4,108,147
4,108,168
In C++, what happens if two different functions declare the same static variable?
void foo() { static int x; } void bar() { static int x; } int main() { foo(); bar(); }
They each see only their own one. A variable cannot be "seen" from outside the scope that it's declared in. If, on the other hand, you did this: static int x; void foo() { static int x; } int main() { foo(); } then foo() only sees its local x; the global x has been "hidden" by it. But changes to one don't ...
4,108,181
4,112,332
P/Invoke g++ from mono in ubuntu OS
Is it possible to invoke a g++ executable file's function from mono in Ubuntu? Note that both C++ and C# code compiled in Ubuntu Operation System. C++ application source: #include <stdlib.h> static int32_t Sum(int32_t a, int32_t b){ return a + b; } /* * */ int main(int argc, char** argv) { return (EXIT_SUCC...
You need to compile the library as a shared library: a static library can't be loaded at runtime with P/Invoke. The fact that you added a main() function suggests that you're compiling the code into an executable instead. So the first thing for you is to learn how to compile a shared library, you can try something like...
4,108,313
4,108,340
How do I find the length of an array?
Is there a way to find how many values an array has? Detecting whether or not I've reached the end of an array would also work.
If you mean a C-style array, then you can do something like: int a[7]; std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl; This doesn't work on pointers (i.e. it won't work for either of the following): int *p = new int[7]; std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;...
4,108,317
4,108,372
C++ API for Google Finance
Is there a C++ API for accessing stock quotes from Google finance?
There's no C++ client library, if that is what you mean - just for Java and Javascript. There are plenty of C++ libraries for HTTP and XML though, so you can certainly process the protocol directly if you wish. I guess you could call the Java client library using JNI also.
4,108,411
4,108,442
c++ pow function- invalid result?
Why is the output of the dResult invalid ? Env: Visual Studio 2008 int _tmain(int argc, _TCHAR* argv[]) { double dN = - 0.091023604111478473 ; double dD = 0.127777777777777; double dResult = pow( dN,dD ); //dResult = -1.#IND000000000000 return 0; }
See http://www.cplusplus.com/reference/clibrary/cmath/pow/ double pow (double base, double exponent ); "If base is negative and exponent is not an integral value, or if base is zero and exponent is negative, a domain error occurs, setting the global variable errno to the value EDOM."
4,108,528
4,109,896
Exponential-decay-like-random-distribution and Discretization of continuous distributions
sadly I'm not really experienced in using random numbers in programming, despite the use of uniform integers in range. Therefore i have to questions regarding this topic. Question 1 (more specific): I'm looking for a way to chose array elements (dynamic size, but known) according to a probability distribution similar t...
I think breaking this problem into two steps is a good place to start. First, if you had a discrete probability distribution, then the problem of drawing from this distribution isn't so bad. Boost random has method for doing this. Scroll down this page to the weighted dice example. It will return an integer from the gi...
4,108,574
4,108,740
How to initialize an array that is part of a struct typedef?
If I have a typedef of a struct typedef struct { char SmType; char SRes; float SParm; float EParm; WORD Count; char Flags; char unused; GPOINT2 Nodes[]; } GPATH2; and it contains an uninitialized array, how can I create an instance of this type so that is will hold, say, 4 values in Nodes[]? Edit: ...
You could use a bastard mix of C and C++ if you really want to: #include <new> #include <cstdlib> #include "definition_of_GPATH2.h" using namespace std; int main(void) { int i; /* Allocate raw memory buffer */ void * raw_buffer = calloc(1, sizeof(GPATH2) + 4 * sizeof(GPOINT2)); /* Initialize struct w...
4,108,609
4,108,656
constructor initialization lists order/allocation question
My question is simple, is the next code safe? struct Parent { B* _a; Parent(B* a) : _a(a) {} }; struct Child : public Parent { B _b; Child() : Parent(&_b), _b(2){}; }; int main() { Child c; return 0; } Two more points: I am interested in the part of passing a reference to a member object to...
In the sense that you describe, yes it is safe: the memory is allocated and it is perfectly fine to pass that pointer to the parent. The memory for Child::_b is actually integral part of the memory of the entire Child. It doesn't require any explicit additional "allocations". By the moment the Child::Child constructor ...
4,108,738
4,146,890
directx 9 setting a camra
this is basic question. im having touble setting the camra not how to set it but what values should i set it to. is there any app that can help with setting camra like you set it and it gives you the values or can you explain what the values stand for and how to are they scaled. D3DXMatrixLookAtLH(&matView, &D3DX...
The D3DXMatrixLookAtLH function is generating a camera matrix, that gets stored in your matView. After that, the function gets three vectors: position look-at up Those three vectors stand for: the position of your camera - where your camera is. It could be (0,0,0) for example. (Those are your x, y and z coordinates ...
4,109,303
4,110,521
Overlapped I/O: some functions are still missing
One of the things that I really like in Windows API is overlapped I/O. I've written dozens of network servers using overlapped I/O (for both sockets and files) with only a limited number of threads. I'm also a driver writer, so that I know well how overlapped I/O is implemented "behind the scenes". The only thing that ...
I suspect that no asynchronous version exists because CreateFile is fundamentally a blocking operation: http://www.osronline.com/article.cfm?article=484 (scroll down to Creates Are Even More Cancellable): Creates Are Even More Cancellable As you can imagine, creates are a bit of a special operation within the O/...
4,109,330
4,109,616
Is MOD operation more CPU intensive than multiplication?
Why is a mod (%) operation more expensive than a multiplication (*) by a bit more than a factor of 2? Please be more specific about how CPU performs division operation and returns the result for MOD operation. In the following example the threads each run for a second. The test was performed on a SPARC processor. // m...
Algorithms (processors execute the division and the multiplication by algorithms implemented in gates) for division are more costly than for multiplication. As a matter of fact, some algorithms for division which have a good complexity are using the multiplication as a basic step. Even if you use the naive algorithms ...
4,109,334
4,109,357
Show line number on Borland C++Builder 6 (2002)
I know it's a old IDE, but in my job I have to work with it. I spend a couple of days searching where could I set the line numbers to show on the left side of the text editor, but I couldnt find. I'm still hoping it's possible, never saw any IDE that didn't have that.
You'll not find it. Only Borland c++ 2005 and higher can do this. Sorry.
4,109,423
4,109,473
C++ -- Questions about "protected inheritance"
I assume that I understand the meaning of "protected inheritance". However, after discussing this issue with one folk here, I feel a little confused now. Here is my understanding of "protected inheritance" in c++ Assume the following class structure. class Base {} class SubClass : protected Base {} 1> If a subclass is...
For 1. - SubClass is still a subclass of Base. Protected inheritance is still inheritance. You are correct that automatic conversion from SubClass to Base is not possible, though. SubClass sub; Base* base(&sub); gives error C2243: 'type cast' : conversion from 'SubClass *' to 'Base *' exists, but is inaccessibl...
4,109,441
4,109,602
How can I compare two ostream objects in C++ for equality?
I overloaded the left shift operator in my class and the output works fine, so for example when I have a line which says cout << obj; I will output the fields seperated by a comma. ostream& operator<<(ostream& output, const MyClass& obj) { output << obj.field1 << ", " << obj.field2; return output; } I ...
Even if it did compile, you're basically comparing cout with itself ... Try writing to two distinct std::stringstreams, extracting their string values, and comparing these. If you also need to test ostream flags, define a comparison function and use TS_ASSERT_RELATION.
4,109,667
4,109,728
Class with multiple return types?
I'm making a game gui api. It will work with both Allegro and SDL. I use polymorphism for input and bitmap drawing. The issue comes with these 3 types: Bitmap, Font, and Color. SDL and Allegro are different on these. The problem is I cannot really use polymorphism here due to different return types. I wouldn't feel rig...
Since there are different types, you should use template specialization. template < typename WinManagerType > class AGBitmap; template<> class AGBitmap< AlegroWinType > { public : //... AlegroBitmapType GetBitmap(); }; template<> class AGBitmap< SdlWinType > { public : //... SdlBitmapType GetBitmap(); }...
4,109,891
4,109,939
C++ - Pushing a C-String onto a Template Stack
I am sure that for most this is a very easy question. But I am writing a token recoginzer for XML in c++ and I am using a stack to make sure there are matching begining and end tags. Well my tags are c strings... char BeginTag[MAX]; I am trying to push that onto my template stack. But I am unsure what type to pass th...
Arrays aren't assignable, so can't be used as a container value type. You could define a struct containing an array, though, and use that: struct Tag { char name[MAX]; }; stack<Tag> TagStack; Or just use a std::string for your tags.
4,110,021
4,110,197
Why does std::cin.getline not have an oveloaded method to take std::string?
I'm curious about the technical reason for cin.getline and the global getline function being in different places. What was the motivation for not simply defining all these function signatures for cin: //THESE TWO EXIST istream& cin::getline (char* s, streamsize n ); istream& cin::getline (char* s, streamsize n, char de...
See my answer for a similar question. It might be an oversight by the C++ Standard committee, but it can also be explained with dependency concerns. If the standard would require function overloads for std::string in the <iostream> header then it would require implementers to #include<string> in <iostream>. That's a de...
4,110,037
4,110,077
C/C++ Possible to get a "list" of instance members by querying a class?
Suppose we have a struct in C++: struct foobar { int age; bool hot; String name }; Is there a way, programatically, to query the above struct to extract its instance members? For example: String[] members = magicClass.getInstanceMembers(foobar); Members would have ["age", "hot", "name"] as it's val...
No, standard C++ doesn't support that type of reflection. There are some "hacky" ways using macros to create a type-traits-esque template that will use SFINAE to statically determine whether or not a particular class has a certain data member or member function, but nothing that will actually enumerate every member of...
4,110,061
4,152,477
C++ - RTSP Client with Qt GUI using live555 lib what else do i need?
i like to be able to watch video streaming with my application im doing in Qt first i checked vlc , but its GPL , and also i don't need all its option then i saw it is using live555 that is LGPL for streaming , my Question can i use this library in mt Qt application ? and how
First of all, what platform are you running on? You can use Live555 only for RTSP/RTP purposes. Live555 however does not contain any decoders, etc. VLC uses Live555 internally for RTSP AFAIK, but also contains a bunch of other plug-ins, decoders, demultiplexers, etc. You still need a media framework to handle the medi...
4,110,170
4,110,187
`auto-increment` std::map<string, int> :)
Ok, the problem is pretty straightforward - I am reading words from the input stream, the words may repeat. I need to populate a map so that all the words get indices from 0 to n-1. Here is my code: map<string, int> mp; string s; int n = 0; while(cin >> s) { if(mp.find(s) == mp.end()) { mp.insert(make_pair(...
You don't need to check whether there is an element at that key before you insert because insert doesn't change the mapped value if the key already exists. You don't need to keep track of the count separately; you can just call size() to get the next value: while (std::cin >> s) { mp.insert(std::make_pair(s, mp.si...
4,110,182
4,110,297
C++ - Comparing Strings Function not working?
I am currently writing an HTML token recognizer in c++. I am using stacks to check and see if there are beginning and matching tags. Before I can match my tags I need to make sure that the tag is valid. But for some reason my checking function is not working. I step through each step in the algorithm and from everythi...
As other people pointed out, you are comparing a pointer to char array (not the actual string content). If you can change the implementation to use std::string, the "==" overloaded operator should do the trick for you. However, if you need to stick with the char array. Do it c-style: { if(strcmp(check, tagNames[i])=...
4,110,292
4,110,728
worst that can happen if i don't obey the stateless custom allocators dogma?
I need to create a custom allocator for std:: objects (particularly and initially for std::vector) but it might eventually come to use others The reason I need to create a custom allocator is that I need to track allocated (heap & stack) resources by individual components of the application (this is an inherent feature...
Aside from the obvious answer ("if you violate any requirement, that's undefined behavior, good night and thanks for playing"), I imagine the worst that would likely happen, is that the vector implementation can rely on the requirement that "all instances of the allocator class are interchangeable" in the obvious way: ...
4,110,331
4,110,355
c++ edit box goes behind main window
i created a edit box but it doesn't show on the window. it shows if the window is not full screen. if it is full screen the edit box goes behind it. here is the function for the edit box HWND editbox=CreateWindowA("EDIT", NULL, WS_VISIBLE | WS_EX_TOPMOST | WS_BORDER | ES_LEFT, ...
All WS_EX_** styles should be passed as the first argument of CreateWindowEx, not the third of CreateWindow. This probably causes the problem. Use CreateWindowExA instead. All the arguments in CreateWindowEx remain the same, there's just one additional parameter at the beginning. HWND editbox=CreateWindowExA(WS_EX_TOPM...
4,110,334
4,110,343
C/C++/Java Design Question: Keeping Track of Many Variables by Saving To File and Parsing Afterwards
Suppose I have a game written in C/C++. For simplicity, I have: struct masterStruct { Coords player1; Weapon player1; Gravity player1; ... }; Suppose this struct contains 1000s of variables that relate to the player. I want to be able to create a "snapshot" of the player's state at time t...
Use a good serialization library with versioning support. Boost.Serialization is a very good library for this sort of thing. Of specific interest to you should be this feature (quoted from the docs): Independent versioning for each class definition. That is, when a class definition changed, older files can stil...
4,110,463
4,110,482
Is there a QList type datastructure in STL or Boost?
just a brief QList intro, QList is similar to QVector and STL vector but in addition it also reserves some space at the beginning; (and in the end too) I am looking for something similar in STL , if not atleast Boost Reserving space at the beginning improves prepending or removing the first item (constant time), becaus...
std::deque provides front and back insertion removal at constant time, if it is what you are looking for.
4,110,479
4,110,497
C++: Conceptual circular include problem
I'm making a component based entity system for a game engine. I have an entity class, which has to include the component base class header in order to define the array of components private Component* components[ 123 ] However, in the component base class I have to define a private Entity* ownerEntity, beacuse it is cr...
As long as you only need your class to contain pointers or references to the other classes, you can skip the real include file and use an empty forward declaration like class Component;. You will need the full include in the source file where you dereference the pointers or use the reference to call methods on Componen...
4,110,608
4,110,678
error tracing on a backtrace
I got this in my output. The program still runs and finishes normally but I would like to track down the error. Can someone tell me how I can use tis data to trace the stack or something to track down what's causing the error. I'm using eclipse with gdb to run C/C++ code. Here's the output: *** glibc detected *** /home...
It sounds like you are trying to free memory you don't own. I recommend running your program under valgrind. http://valgrind.org/docs/manual/quick-start.html As a side comment, errors like this usually come from doing explicit memory management in c++. You should generally never free or delete memory "by hand" in c++, ...
4,110,731
4,110,756
How to get the screen refresh rate?
Is this even possible? Since ive noticed v-sync doesnt work on my laptop at all, so i am building FPS limiter "manually" and now i would like to use the FPS limit the user has set to his screen. Edit: i mean the monitor hz rate. Edit3: heres the code i got working (i think... anything wrong there?): DEVMODE lpDevMode; ...
The Win32 EnumDisplaySettings function could be what you're looking for. The refresh rate is held in lpDevMode->dmDisplayFrequency.
4,110,899
4,110,904
Can I throw `std::bad_cast`?
Is it possible to throw an instance of std::bad_cast ? The underlying question is not whether it is good or not to do this, it is only about whether std::bad_cast has a default constructor or not. Thanks
18.5.2 of the C++ standard says "yes", it has a no-arg constructor.
4,110,939
4,110,983
Alternative to C, C++?
All, There are so many programming languages/Operating systems/device drivers i.e. softwares that are built using C and C++. I was wondering if C and C++ were the only 2 low level programming languages that all companies ever had to build their own product(s)? If there are, why do C and C++ get so much preference over ...
There are other low-level languages, but C had the benefit of a 'popularity snowball' effect. It's about as efficient as any reasonably portable language can be, so it's a good choice for systems programming. Once you build an operating system on it, it makes sense to build tools for the same system with it, so a lot ...
4,110,964
4,110,997
How does heap-spray attack work?
I've read two articles about heap-spraying: Wikiepdia and this blog post. I understand how the shell code is introduced in to the program's memory. But how the program is made to jump/call to the address memory located on heap? What kind of crash makes a call to heap? Does such attack needs to be conducted with a kind...
If I understand correctly, They commonly take advantage from the fact that these heap blocks will roughly be in the same location every time the heap spray is run. Execution flow can be redirected to the heap sprays via buffer overflow or heap overflow flaws. They're talking about a situation like this: ...
4,111,021
4,113,159
Boost::Python raw_function returning void
Using Boost::Python, the normal mechanism for wrapping functions works correctly with C++ functions returning void. Unfortunately, the normal mechanism also has limitations, specifically with regards to the function arity it supports. So I need to use boost::python::raw_function to wrap my function, but it doesn't co...
I think this is the way that raw_function() works. It expects your function to return a Python object. In Python the closest thing you will get to a function returning void is a function returning None. I think that approach would be best (and not even that ugly) in your case: #include <boost/python.hpp> #include <boos...
4,111,045
4,111,073
How to calculate (x,y) for a fixed arc length away from a point on a circumference
I've spent so many hours on this I can feel my sanity slowly slipping. So any help would be really truly appreciated. I'll try and be as succinct as possible. I have a circle on a 2D plane. I know the cartesian coordinates for it's central point(C) and the radius(R). My confusion stems from this problem. When provided ...
On a circle, an angle theta corresponds to an arc length of theta * R, meaning your arc will subtend an angle of theta = X / R. So if start with your point P = C + R * (sin(u), cos(u)) then just go up/down by theta/2: P1 = C + R * (sin(u + theta/2), cos(u + theta/2)) and P2 = C + R * (sin(u - theta/2), cos(u - theta/...
4,111,186
4,111,202
Why this weird compatibility of bool and pointers in C++?
Not only is this valid and doesn't give any warnings even with -Wall: void* p = false; // actually 'true' doesn't work here bool b = "Hello, Boolean!"; but also this compatibility rule permits selecting an overloaded function/operator for a wrong type. Let's say you overloaded your operator << for all fundamental typ...
What do you mean by "C can handle this correctly"? C doesn't permit function overloading, so you are guaranteed to have the bool <-> pointer conversion you're complaining about. Are you asking why this conversion exists? The first is not actually a conversion bool -> pointer, but is recognizing that the literal false ...
4,111,291
4,111,333
directx 9 meshes overlap c++
ok when i load three meshes and render them one of them goes over all of them. is there way to control which mesh would go in the front and which mesh would go in the back?
Either you have Z buffering turned on and the transformed triangles of that covering mesh simply end up closer to the camera, or you've set up the device to ignore Z buffering, and the appearance depends on the order in which you drew them. In either case, it sounds like you want to have Z buffering turned off, and th...
4,111,433
4,111,439
Members of structs and pointers, C++
I have the following snippet of code: struct Node { Node* left; Node* right; string data; }; void test() { Node thing; thing.data = "h"; thing.left = NULL; thing.right = NULL; cout<< "Thing data = " << thing.data << endl; Node* thing2; thing...
thing2 is a non initialized pointer. It doesn't point to a valid Node object. You should allocate it: thing2 = new Node; or make it point to a valid Node object: thing2 = & thing;
4,111,485
4,111,769
Drawing large numbers of pixels in OpenGL
I've been working on some sound processing code and now I'm doing some visualizations. I finished making a spectrogram spectrogram, but how I am drawing it is too slow. I'm using OpenGL to do 2D drawing, which has made searching for help more difficult. Also I am very new to OpenGL, so I don't know the standard way thi...
They are many ways to improve your drawing speed. The simplest would be to allocate a an RGB texture that you will draw using a screen aligned texture quad. Each time that you want to draw a new line you can use glTexSubImage2d to a load a new subset of the texture and then you redraw the quad.
4,111,495
4,111,526
Why is there an implicit type conversion from pointers to bool in C++?
Consider the class foo with two constructors defined like this: class foo { public: foo(const std::string& filename) {std::cout << "ctor 1" << std::endl;} foo(const bool some_flag = false) {std::cout << "ctor 2" << std::endl;} }; Instantiate the class with a string literal, and guess which constructor is calle...
It's very common in C to write this void f(T* ptr) { if (ptr) { // ptr is not NULL } } You should make a const char* constructor.
4,111,647
4,111,664
Disambiguating calls to functions taking std::functions
The code below doesn't compile on gcc 4.5 because the call to foo is ambiguous. What is the correct way to disambiguate it? #include <iostream> #include <functional> using namespace std; void foo(std::function<void(int, int)> t) { t(1, 2); } void foo(std::function<void(int)> t) { t(2); } int main() { ...
The best way is to explicitly create a std::function object of the correct type then pass that object to the function: std::function<void(int, int)> func = [](int a, int b) { cout << "a: " << a << " b: " << b << endl; } foo(func); or inline: foo( std::function<void(int, int)>( [](int a, int b) { cout ...
4,111,757
4,111,773
Built a little program to test code but can't get the loops to work correctly
I have been asking in previous questions about how to get multiple string inputs to control the flow of the program, using if else statements. and everything worked out fine. the code for the YES and NO is fantastic and i'm very happy, except I built a test rig in the form of a function that is called again and again i...
There are no looping constructs in your program. Instead, you're invoking YESNO twice via explicit calls. Try any of the following: // do...while executes the loop body once before testing the condition int loop = 0; do { loop = YESNO(0); } while (loop == 0); or // while loops test the condition before executing the...
4,111,855
4,111,861
Is there anything like method/function sentinels in C++/C?
In Objective-C you can say something like: NSArray *anArray = [NSArray arrayWithObjects:obj,obj2, nil]; In case you are not familiar with objective-c it is saying I want an object of type of NSArray, anArray, and I want to call the method arrayWithObjects and then it acts as a sentinel and accepts as many parameters (...
You can write a variadic function and use a sentinel to locate the last real argument. However, in C++, this is usually a bad idea because variadic functions are not type safe. It's preferred in C++ to put the elements you want to pass into a container, array, or class object of some kind and then pass that to the fun...
4,111,899
4,111,961
Is there an easy one-shot solution to the preprocessor namespace pollution introduced by the WIN32 API?
As we all know, including <windows.h> pollutes all namespaces in C++ by having one preprocessor #define per Win32 API function that can either take multibyte or UTF-16 input. An example is: #ifdef UNICODE #define CreateFont CreateFontW #else #define CreateFont CreateFontA #endif I've used the native Win32 API for quit...
The cleanest solution is not to call the Windows API functions directly in your program and instead to write an abstraction layer that can call the functions you need. This way, you only need to include the Windows API headers in a handful of source files and the macros are much more manageable. This also has the ad...
4,111,932
4,112,022
Where to put a member function template
An aspect of C++ that periodically frustrates me is deciding where templates fit between header files (traditionally describing the interface) and implemention (.cpp) files. Templates often need to go in the header, exposing the implementation and sometimes pulling in extra headers which previously only needed to be in...
A rule of thumb (the reason of which should be clear). Private member templates should be defined in the .cpp file (unless they need to be callable by friends of your class template). Non-private member templates should be defined in headers, unless they are explicitly instantiated. You can often avoid having to inc...
4,111,944
4,111,955
directx 9 mouse over an object
ok when i used to draw stuff using gdi+ i used to know the coordinates for objects but now when im using meshes in directx 9 i have no idea how to get the coordinates for the object so i can find if the mouse over an object. any idea how to find the coordinates ?
You need to cast the mouse position into the world and convert it to world-space coordinates, which then are tested against the various objects. You may be able to find a library to do this for you, I know OpenGL supports picking and most wrappers offer enhanced functions for that, but the principle is: Find the mouse ...
4,112,064
4,112,142
Efficiency of program
I want to know whether there is an effect on program efficiency by adopting object oriented approach to a problem as compared to the structured programming approach in any programming language but specially in c++.
I remember back in the early 1990's when C++ was young there were studies done about this. If I remember correctly, the guys who took (well written) C++ programs and recoded them in C got around a 15% increase in speed. The guys who took C programs and recoded them in C++, and modified the imperative style of C to an...
4,112,075
5,945,097
Trouble overriding save_construct_data when serializing a pointer to a class without a default constructor
I'm trying to follow this example http://www.boost.org/doc/libs/1_42_0/libs/serialization/doc/serialization.html#constructors but I keep getting errors. Following the example, I get an error trying to access a private variable (fair enough): bs.cpp:10: error: ‘const int my_class::m_attribute’ is private But, if I add...
save_construct_data has to be declared before it can be friended. Something about being in a different namespace. Like this: namespace boost { namespace serialization { template<class Archive> inline void save_construct_data(Archive & ar, const my_class * t, const unsigned int file_version); }} But, because that dep...
4,112,106
4,112,216
Anti-aliasing in OpenGL
I just started with OpenGL programming and I am building a clock application. I want it to look something simple like this: http://i.stack.imgur.com/E73ap.jpg However, my application looks very "un-anti-aliased" : http://i.stack.imgur.com/LUx2v.png I tried the GL_SMOOTH_POLYGON method mentioned in the Red Book. However...
Intel integrated videocards are notorious for their lack of support for OpenGL antialiasing. You can work around that, however. First option: Manual supersampling Make a texture 2x times as big as the screen. Render your scene to the texture via FBO, then render the texture at half size so it fills the screen, with bil...
4,112,116
15,179,175
Serializing a variables_map
How do I serialize/deserialize a boost::program_options::variables_map? I can't find an already implemented serialize function, and I don't know what functions in variables_map I can use to extract and reassemble the map.
It looks like you found out that boost::program_options::variables_map derives from std::map so you can use its serialization (but see the warning later on this). If the only remaining problem is serializing the boost::any values it contains then you're almost there. You can't serialize an arbitrary boost::any because...
4,112,316
4,112,444
Using multiple instances of getline in C++
I've been working on a class assignment for C++ and we're required to acquire input from a text file and assign those values to an array....one is a string, the second an int, and the third a double. We've only been introduced to arrays and I don't know anything yet about pointers or linked lists, or any of the higher ...
1) Instead of three different iteration, use only one 2) Pass string object in getline instead of pointers string buf; for (int i = 0; i < EMP_NUM; i++) // Get input from text file for names. { getline(inFile, buf, '*'); nameAr[i] = buf; getline(inFile, buf, '*'); //assuming delimiter is again * hours...
4,112,317
4,112,329
Easy way to get function prototypes?
A friend and I were discussing imaginary and real languages and a question that came up was if one of us wanted to generate headers for another language (perhaps D which already has a tool) what would be an easy and very good way to do this? One of us said to scan C files and headers and ignore function bodies and only...
You can use clang libraries to parse C/C++ source code and extract any information you want in particular function prototypes. Due to library-based architecture it is easy to reuse parts of clang that you need. In your case these are frontend libraries (liblex, libparse, libsema). I think this is a more feasible approa...
4,112,375
4,113,037
.so module doesnt import in python: dynamic module does not define init function
I am trying to write a python wrapper for a C function. After writing all the code, and getting it to compile, Python can't import the module. I am following the example given here. I reproduce it here, after fixing some typos. There is a file myModule.c: #include <Python.h> /* * Function to be called from Python */...
Since you're using a C++ compiler, function names will be mangled (for instance, my g++ mangles void initmyModule() into _Z12initmyModulev). Therefore, the python interpreter won't find your module's init function. You need to either use a plain C compiler, or force C linkage throughout your module with an extern "C" d...
4,112,421
4,112,434
How could OpenGL buffers' state persist between program runs?
I'm writing an OpenGL program that draws into an Auxiliary Buffer, then the content of the Auxiliary Buffer is accumulated to the Accumulation Buffer before being GL_RETURN-ed to the Back buffer (essentially to be composited to the screen). In short, I'm doing sort of a motion blur. However the strange thing is, when I...
No - there's no reason for your GPU to ever clear its memory. It's your responsibility to clear out (or initialize) your textures before using them.
4,112,489
4,112,850
Define sorting method ( that use std::sort for sorting) of a templated class in dll and calling it from another project
Sorry for my bad English. I have 2 projects. Project 1 is a MFC dll that contains class CMyContainer, class CEmployee. Project 2 is my main project. In project 2, I created an instance of CMyContainer of type CEmployee. Now I want to sort the container but I got an error "error LNK2019: unresolved external symbol "bo...
Try to export MyComparer from the .dll with _declspec(dllexport)
4,112,501
4,132,713
Exception Error at the line BOOST_AUTO_TEST_SUITE_END()
i have a problem with the boost-test from my teacher. When i'm debugging my project i get an error at this Line: BOOST_AUTO_TEST_SUITE_END() The Exception is the following: 0x7521b727 (KernelBase.dll) in homework2.exe: 0xC0020001: The string binding is invalid. i'm using Visual Studio 2010 ultimate and Win7 Profes...
I have changed my include; my teacher told me that the problem was with my binaries. When someone else has the same problem here is the solution: New Code: #define BOOST_TEST_MAIN #include <boost/test/included/unit_test.hpp> #include <string> BOOST_AUTO_TEST_SUITE( easy_stringtest) BOOST_AUTO_TEST_CASE( length_test) ...
4,112,553
4,121,406
Audio and Video synchronization with timestamps
I receive audio packets from net (4 packets per second, 250ms each) and video - 15fps. Everything goes with my own timestamps. How should I sync them? I've seen the source code of one of our developers but he did syncing VIDEO according to audio. I.e. audio is always played immediately and video can be dropped or buffe...
I needed in smth like that - http://www.freepatentsonline.com/7680153.html Pretty difficult to understand but I think this patent explains the basics of sync.
4,112,561
4,112,761
Boost.Python: Ownership of pointer variables
I'm exposing a C++ tree class using Boost.Python to python. The node class holds a list of child nodes and provides a method void add_child(Node *node) The Node class takes ownership of the provided Node pointer and deletes it's child nodes when the destuctor gets called. I'm exposing the add_child method as: .def("a...
Answering my own question: I've missed an FAQ entry in the Boost.Python documentation that gave me the right hint: //The node class should be held by std::auto_ptr class_<Node, std::auto_ptr<Node> >("Node") Create a thin wrapper function for the add_child method: void node_add_child(Node& n, std::auto_ptr<Node> child)...
4,112,619
4,112,733
which of these two methods of converting this array to integer you would suggest?
consider the following array of bytes that is intended to be converted into a single unsigned integer: unsigned char arr[3] = {0x23, 0x45, 0x67}; each byte represents the equivalent byte in integer, now which one of the following methods would you suggest specially performance-wise: unsigned int val1 = arr[2] << 16 | ...
This depends on your specific processor, a lot. For example, on the PowerPC, the second form -- writing through the character pointers -- runs into a tricky implementation detail called a load-hit-store. This is a CPU stall that occurs when you store to a location in memory, then read it back again before the store ha...
4,112,797
4,112,939
Knowing when GSM/CSD connection has broken
Background I have a GSM modem connected through a COM port. I open the COM port using CreateFile and I'm able to send various AT commands. I use ATD to place a CSD (data) call or ATS0=1 to receive one. Now the problem How can I know that the connection has broken in the middle of a data call? Actually, when a call is ...
The CD signal (Carrier Detect) will turn off. Named RLSD in GetCommModemStatus() and WaitCommEvent(). That's the moral equivalent of std::bad_alloc when you work with a modem.
4,112,810
4,112,877
Handling entities in a game
As a small exercise I am trying to write a very small, simple game engine that just handles entities (moving, basic AI etc.) As such, I am trying to think about how a game handles the updates for all of the entities, and I am getting a little bit confused (Probably because I am going about it in the wrong way) So I dec...
You're getting pretty close to the way most games actually do it (although performance expert curmudgeon Mike Acton often gripes about that). Typically you'd see something like this class CEntity { public: virtual void draw() {}; // default implementations do nothing virtual void update() {} ; virtual...
4,112,914
4,112,947
Is it better to pass by value or by reference for basic datatypes?
Possible Duplicates: How to pass objects to functions in C++? is there any specific case where pass-by-value is preferred over pass-by-const-reference in C++? I have members of a class implemented like this: void aaa(int a, float b, short c) { bbb(a, b); } void bbb(int a, float b) {} If the values of a, b and c ...
Standard doesn't have constraints about implementation of references, however usually they're implemented as autodereferenced pointers (actually with some exceptions). As you probably know, on 32 bit system pointer size is 4 bytes, that means that passing chars, shorts (types with sizeof() less than 4 bytes) by referen...
4,112,972
4,112,989
How to compile Qt as static
I am currently writing code in Qt. How to compile the code statically? From Qt document I came to know the following step 1) Visual Studio 2008 -> commandPrompt -> QtDir -> configure -static -> nmake But, it took 17 GB and at the end it exited before the completion stating that "the space is not enough". Is there any s...
You have already used the only way possible: compiling the source as static. Some things that have a very large impact on disk size (which seems to be the problem here), with corresponding configure arguments: Disable debug: -release Disable modules you don't need, especially QtWebKit: -no-webkit -no-script -no-script...
4,113,125
4,113,260
Is this C++ pointer container safe?
I want a safe C++ pointer container similar to boost's scoped_ptr, but with value-like copy semantics. I intend to use this for a very-rarely used element of very-heavily used class in the innermost loop of an application to gain better memory locality. In other words, I don't care about performance of this class so ...
No it is not. You have forgotten the Assignment Operator. You can choose to either forbid assignment (strange when copying is allowed) by declaring the Assignment Operator private (and not implementing it), or you can implement it thus: copy_ptr& operator=(copy_ptr const& rhs) { using std::swap; copy_ptr tmp(rhs);...
4,113,148
4,113,293
Conversion problem from char * to wchar_t*
The below line works. It prints Success. wchar_t * s1 = (wchar_t *) L"INSERT INTO OE(sqltext) VALUES('this text')"; if(WriteToSQL(s1) == 0) printf( "Success"); //Success else printf( "Failed"); I need to take user input to create dynamic sql. I need to do what L prefix is doing. When i take input and do...
You can't just cast a char * to wchar_t * and expect it to work. You must do proper conversion, for example using MultiByteToWideChar function. And in general, be very careful with type casts, and in particular avoid using C-style casts in C++ programs. This very case is a good example of why: you told the compiler to ...
4,113,164
4,113,183
#including a header from the previous directory (../)
Here is what I'm trying to do. I have a folder called Agui which is the lib's folder. In that folder there is another folder called Widgets. I want a file from Agui/Widgets to #include base.h from Agui folder. How should I do this so that it remains cross platform? Should I simply include <Agui/base.h> ? Thanks
#include "../base.h". And yes, that is portable.
4,113,335
4,113,610
C++ overloading << operator
I need to overload the << operator for streams to work with built-in types. For strings it's not a problem, since I simply overload the function like this: ostream& operator<<(ostream& os, const char* str) { /*...*/ } This works because this function is global, not a member. The problem is that I need to overload the ...
You shouldn't try to change what the operator in std::cout << 3; does. It's part of a standard API. If you need to output in some format which stream manipulators can't support, then for example you could write a little wrapper: struct MyFormatter { MyFormatter (ostream &o) : o(o) {} ostream &o; }; MyFormatter...
4,113,365
4,113,373
What does -> mean in C++?
Possible Duplicates: What is the difference between the dot (.) operator and -> in C++? What is the arrow operator (->) synonym for in C++? The header says it all. What does -> mean in C++?
It's to access a member function or member variable of an object through a pointer, as opposed to a regular variable or reference. For example: with a regular variable or reference, you use the . operator to access member functions or member variables. std::string s = "abc"; std::cout << s.length() << std::endl; But i...
4,113,421
4,113,458
ofstream output to same text file from multiple .cpp files of a single project
Dear All: I have a C++ project (in Visual Studio 2008) that comprises of header.h, source_1.cpp file that contains main() and source_2.cpp file. At certain points in the program, I need to output some intermediate results into a text file, say, "output.txt". The thing is, I am unable to do this. That is, I am unable to...
Best way: Pass a instance of type ostream& to all clients which need to output the result. I recommend to resist the temptation to define a global static ostream objects visible to anybody...
4,113,643
4,113,692
Importing a *.pyd library in IronPython's interpreter (ipy.exe)
Following this example, I've created a little hello.pyd library file, the contents of which are at the end of this question. When I enter python interpreter I get the following: D:\test\build\lib.win32-2.6>C:\Python26\python.exe Python 2.6.6 (r266:84297, Aug 24 2010, 18:46:32) [MSC v.1500 32 bit (Intel)] on win32 Type ...
You can try using Ironclad, but it hasn't seen much work recently.
4,113,804
4,113,820
How to implement the binOp functor for STL partial_sum with vector<pair<double, uint> >?
I want a partial_sum of my elements in a vector, where each element is a pair<double, unsinged int>. The partial_sum should incrementally add the double values (first of each pair). Example: vector<pair<double, unsigned int> > temp_vec; temp_vec.push_back(make_pair(0.5, 0)); temp_vec.push_back(make_pair(0.2, 1)); temp_...
struct pair_sum { pair<double, unsigned int> operator()(const pair<double, unsigned int> & sum, const pair<double, unsigned int> & i) { return pair<double, unsigned int>(sum.first + i.first, i.second); } }; This will add up the firsts and return the seconds unchanged.
4,113,815
4,113,847
Initializing an abstract class?
Here is my issue. I want to have something like this: class A { protected: int someInt; virtual void someFunc() = 0; }; class B : public A { protected: virtual void someFunc() { // uses someInt} public: B() {//tell the A inside of B to set someInt to whatever it wants} }; so basically, someInt can be changed, it's n...
You can use initializer lists in the constructor to call parent constructors: class A { protected: int someInt; virtual void someFunc() = 0; A(int x) : someInt(x) {} // Base-class constructor (initialises someInt) }; class B : public A { protected: virtual void someFunc() {} public: B() : A(10) {}...
4,113,845
4,172,519
Does it make sense to provide non-const reference getter
Sometimes I need to expose some of the class members. For example in the following example class Mechanic may need direct access to Engine component. I have read many times that all fields should be accessed by mutator (accessor) methods because of several reasons. But is there any advantage when providing non-const re...
I have found reasonable point to provide such getter. It makes integration of your software easier (for example, when you want to translate interface into another language and bind ABIs).
4,114,044
4,114,061
Template Issues - Having trouble passing function as args (invalid use of non-static member function)
Here's a template I made. I believe it is self-explanatory template <class N, class I> std::list<N*> selectiveList(I element, std::list<N*> & container, I (N::*f)() const) { typename std::list<N*>::iterator it; std::list<N*> selectiveListing; for (it = container.begin(); it != container.end(); ++it) if ((...
if (((*it)->*f)() == element)
4,114,126
4,114,148
Scope of friend function in GCC
According to the standard: A friend function defined in a class is in the (lexical) scope of the class in which it is defined. Then why the heck doesn't this work (several versions of GCC tested)? #include <iostream> using namespace std; class A { friend void function() { cout << "text" << endl; }; }; // void fun...
The quote means that the following works - the code is in the lexical scope of the class, such that unqualified name lookup will behave specially class A { typedef int type; friend void function() { type foo; /* type is visible */ }; }; If you had defined "function" in the namespace scope, then "type" wou...
4,114,154
4,114,170
Template declaration explanation
I was looking at C++ STL vector template code to understand exactly how it is implemented. I have very basic understanding of template programming, could you give a clear explanation of the expression typename _Alloc = std::allocator<_Tp> excerpt from STL vector as below: template<typename _Tp, typename _Alloc = std:...
This assigns a default type to a template parameter, so that you don't have to add it whenever you create a vector: std::vector<int> v; By default, the second parameter of the template is filled by the type std::allocator<_Tp>. Default template parameters allow to shorten data declarations by including some default fu...
4,114,159
4,114,195
UDP Encryption - Simple and Sorta Safe
Heyo! I am writing an application in Qt/C++ that creates connections between peers. The first step in my protocol is for a new peer to broadcast it's information, soliciting connections from established peers. The location of these peers is unknown. To do this I am using a UDP Broadcast. Since this broadcast contain...
You can use pretty much any encryption method you want what is more important/difficult is key distribution. E.G. if all the clients just use the same symmetric encryption method like AES then the broadcast information will be encrypted but anyone who decompiles your client may be able to find out the key. Have a look ...
4,114,180
4,114,283
Problems accessing pre-defined array of floats in C++
I'm trying to make use of precalculated values by outputting them to a header file and then compiling them for use. The precalculated values are cube co ordinates mapped onto a sphere and the data structure takes the form of: typedef float heightMapCubeFace[5][5][3]; I am defining each face seperately like so: hei...
layout is (heightMapSaved[6])[5][5][3] not (heightMapSaved[5][5][3][6])
4,114,193
4,114,333
Cross-platform support for various MFC\ATL classes
I'm trying to keep my C++ project cross-platform as much as possible.Albeit I do have dependencies on the following MFC\ATL classes: CString, CTime, CTimeSpan. Is there an open implementation somewhere of MFC\ATL classes? How common are these packages and should I use the open source libraries to start with, or should ...
Instead of CString use std::string Instead of CTime use boost::ptime Instead of CTimeSpan use boost::time_duration
4,114,431
4,114,451
Why in C++ do I need to use namespace after already using import directive?
In C# one only uses an using directive for a namespace. In C++ like in this example below, one must do an include then use a namespace, why isn't it the same thing like in C# ? #include <iostream> int main() { using namespace std; cout << "Hello world!" << endl; return 0; }
Because the compiler in C# works very differently than C++. The quick version - C# uses references in a (vaguely) similar fashion as C++ uses the linker, and forward declarations. C++ requires forward declarations so it can compile each source file to a translation unit, then link all those units together. The C# com...
4,114,454
4,114,522
How to check certain bits of a variable in C++?
Possible Duplicate: C/C++ check if one bit is set in, i.e. int variable e.g. if I had a integer and i wanted to check what the value of bits 20-25 were, or if i just wanted to check if one of the bits is 0 or 1, how would i do that?
int bitsToInt(int value, int s, int e) { int mask = ((1 << (e - s + 1)) - 1) << s; return (value & mask) >> s; } bitsToInt(7, 2, 3) returns 1 thinking about it a bit more, if what you want is to stuff several values into one int you can be better off doing bitfields and have compiler worry about masks and shif...
4,114,463
4,114,540
Are there any problems when using pure C (not class-wrapped) functions in C++ application?
I am planning to use pure C MPI library in C++ application, I don't want to add unnecessary bloat by running eg. Boost MPI layer that wraps all stuff in the MPI::<func> classes. Is there anything I should be aware of?
You should wrap all your includes for C-headers in an extern "C" block in order to avoid problems with the name mangling of C++ compilers. extern "C" { // include C-headers } Read more here.
4,114,503
4,114,555
Rules for Iterator Invalidation
What are the usual rules for Iterator invalidation when operating over STL container classes(Vector,Dequeue,list,map,multimap,set,multiset). Is it possible to categorize and sum up some general rules/guidelines that a C++ STL programmer must be aware of while working with containers and their Iterators?
These rules are container specific. In fact, these are important criteria for deciding which container you use. For instance, iterators to an std::vector can get invalidated when an object is inserted (depends in where the object is inserted and if reallocation takes place), and they get invalidated when an object is r...
4,114,513
4,114,733
Center Mouse on Window
This is daft, I'm trying to move the mouse to the center of the active window. I cant find a method on MSDN that gives me the coords (RECT) relative to the corner of the screen. ::GetClientRect returns 0,0 for the top left. Is there a method that returns 100, 134 or some such.
Did you look into GetWindowRect function?
4,114,747
4,114,802
Using-declaration to move name to another namespace?
Given: namespace One { void foo(int x) { munch(x + 1); } }; namespace Two { // ... see later } ... void somewhere() { using namespace Two; foo(42); ... is there any difference between the following two variants: a) namespace Two { void foo(int x) { munch(x + 1); } }; and b) namespace Two { ...
With a, they are actually different functions, but with b, the two functions are identical: assert(&One::foo == &Two::foo); This would rarely matter; a bigger concern is duplicating the logic.
4,114,794
7,378,683
array initialization, is referencing a previous element ok?
const QPointF points[] = { QPointF(r.left() - i, r.top() - i), QPointF(r.right() + i, r.top() - i), QPointF(r.right() + i, r.bottom() + i), QPointF(r.left() - i, r.bottom() + i), points[0] // is this line valid (according to the C++ standard)? }; While this compiles with the MS Visual Studio Compil...
C++03/C++11 answer No, it's not. On the right-hand side of the =, points does exist1 but the initialiser is only applied after all its operands have been evaluated. If points is at namespace scope (and thus has static storage duration and has been zero-initialized2), then this is "safe" but your use of points[0] ther...
4,114,823
4,115,343
BUTTONS, COMBO BOX and KEYBOARD KEYS block eachother (winapi)
In my interface I have a few buttons, a combo box and a window where I display sequence of images. Those buttons navigate through the sequence, but I also wanted to navigate through the LEFT and RIGHT arrows on the keyboard. After compilation the keyboard keys work fine, because Focus is set at the main window, but aft...
Yeah, your window procedure is for that window only, a combo box is a separate window. I like to handle my hotkeys inside the message loop like so: MSG msg; while (GetMessage(&msg, NULL, 0, 0) > 0) { if (msg.message == WM_KEYDOWN) { if ((UINT)msg.wParam == VK_SPACE) { return 0; // o...
4,114,916
4,114,949
Detecting if a type throws
Is there a way to detect statically if a any member of a class can throw an exception? Some metaprogramming trick?
No you can't (assuming you want to know that method throws an exception). Programmer may use "throw" keyword in method declaration but it is optional. So there aren't ways to know if a method throws an exception.
4,114,982
4,115,183
Compile time operators
Could someone please list a all compile time operators in available in C++?
There are two operators in C++ whose result can always be determined at compile-time, regardless of the operand(s), and those are sizeof[1] and ::[2]. Of course there are plenty of particular uses of other operators that can be resolved at compile-time, for example those listed in the standard for integer constant expr...
4,114,994
4,115,003
Detecting a type of a class
Is it possible to detect if a class is of certain type?
Yes: template <typename T, typename U> struct is_same { static const bool value = false; }; template <typename T> struct is_same<T, T> { static const bool value = true; }; is_same<int, float>::value; // false is_same<int, int>::value; // true These are called type traits, and you can find a slew of them in ...
4,115,023
4,115,068
Compile, Run, and Return output of C++ program, securly from PHP
I am making a program that will run a persons C++ code from PHP. How can I compile, run, return the output of a C++ program securly? By securly I mean how can I do it without making my system vulnerable to hackers? I guess I would just use the exec comman to GCC to compile the program then run the program using exec. B...
This is something just a little bit more advanced that something you would be able to do with a non-custom server. Most likely. Because most server providers won't let you execute processes, and even if, they SURELY won't let you install GCC there and run potentially unsafe code on their machine (executing processes, r...
4,115,067
4,115,093
I can't open variable file name
Is there any reason why Dev C++ is not letting me do file.open(file_name_variable)? I don't understand why it's not letting me open anything but a hardcoded name like file.open("abc.txt") how do get around this? Don't use Dev C++? here's basically what I have: int open_file(string file_name){ ifstream file; fil...
You need to pass it a c-string. Use: file.open( file_name.c_str() ); In C++11, this is no longer necessary. A signature that takes std::string was added.
4,115,114
4,115,140
Declaring variables with template defined type
template <class T> void foo(T arg) { T var = arg; } Is this possible? I have a similar situation and I can't get something like this to work. Thank you.
Yup, the above works fine, as this minimal compilable example shows: template <class T> void foo(T arg) { T var = arg; } int main() { foo(23); return 0; } The problem must be in other code you haven't posted yet :)
4,115,199
4,115,350
Using C++ code in C#
I have c++ dll with class in wich I want to send string from C# code, surly I can't use string because of CLR, i'll stried to change string into char in c++ dll, and send byte from c#(because c++ char=byte in c#) but c# don't understand c++ array I can send 1 byte and it will be ok, but not array, please help! dll Code...
Here is the working code of calling C++ dll function from C#: sbyte[] A_SB_array = new sbyte[0]; ArrayConvCtoSB(ref A_SB_array, ar_param.ToCharArray()); fixed (sbyte* SB_array = A_SB_array) return CPSFEW.getDataLength(SB_array); It's not the "very good code" but it illustrate what you need. PS: Her...
4,115,279
4,115,304
Most efficient way of erasing/deleting multiple std::vector elements while retaining original order?
i have a std::vector<int> and a second container holding iterators or indexes (no keys, i want constant access to the element) to this vector for deletion purposes. Let's assume i have a vector of 1000 elements and want to erase 200 of them. The order of the non-removed elements should be the same after the deletion o...
In <algorithm> there is a remove_if function which squeezes all values not removed to the front maintaining the order. This works if those 200 elements can be purely determined by the values, not index. This is essentially the Erase-remove idiom you have linked to. remove_if is guaranteed to perform O(N) comparisons (a...
4,115,459
4,115,486
Does Visual C++ runtime has an equivalent to Objective C runtime load method?
http://gcc.gnu.org/onlinedocs/gcc-2.95.3/objc-features_1.html#SEC2 The GNU Objective-C runtime provides a way that allows you to execute code before the execution of the program enters the main function. The code is executed on a per-class and a per-category basis, through a special class method +load.
Yes. Thoroughly read http://www.codeguru.com/cpp/misc/misc/threadsprocesses/article.php/c6945 but here's the basic gist of it: typedef int cb(void); #pragma data_seg(".CRT$XIU") static cb *autostart[] = { PreMain1, PreMain2 }; // Define PreMain1 and PreMain2 somewhere. They will be called before main(). #pragma data_...