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 |
|---|---|---|---|---|
790,687 | 790,689 | Using a free "char const*" at static initialization time | Initialization order of free objects is undefined in C++. But what about the following?
namespace foo {
char const* str = "hey";
struct A {
A() { cout << str; }
} obj;
}
Is this still undefined behavior, or is there a special provision for pointers initialized with string literals?
Aside from that:... | The initialisation order is defined - they are initialised in the order they appear in a compilation unit - see section 3.6.2 of the C++ Standard. The type of the things being initialised has no effect.
|
791,002 | 791,067 | joySetCapture doesn't work with fChanged = false | I am using joySetCapture with fChanged (4'th parameter) = true.
I am getting the messages only when position is changed, as I should.
However, I am not getting any message when a joystick button is pressed.
If I use fChanged = false, the wParam of the periodic messages is updated correctly.
How can I get messages only ... | The documentation for joySetCapture says that if fChanged is true, then messages are only sent when the position changes by more than the threshold. Since it doesn't mention the buttons, I would assume that it doesn't send messages when buttons are pressed. This seems like poor design to me, but if that's how it is, ... |
791,097 | 795,790 | Is there a decent C++ wrapper around Win32's lockless SList out there? | Windows provides a lockless singly linked list, as documented at this page:
Win32 SList
I'm wondering if there's an existing good C++ wrapper around this functionality. When I say good, I mean it exports the usual STL interface as much as possible, supports iterators, etc. I'd much rather use someone else's implementat... | You could quickly get up and running with boost and ::boost::iterator_facade.
No it wouldn't be optimal or portable and iterator semantics are something you should hear Alexandrescou suddenly come out against at DevCon. You are not locking the container, you are locking (and potentially relocking and unlocking ) the op... |
791,108 | 791,176 | Is it worth forward-declaring library classes? | I've just started learning Qt, using their tutorial. I'm currently on tutorial 7, where we've made a new LCDRange class. The implementation of LCDRange (the .cpp file) uses the Qt QSlider class, so in the .cpp file is
#include <QSlider>
but in the header is a forward declaration:
class QSlider;
According to Qt,
This... | Absolutely. The C/C++ build model is ...ahem... an anachronism (to say the best). For large projects it becomes a serious PITA.
As Neil notes correctly, this should not be the default approach for your class design, don't go out of your way unless you really need to.
Breaking Circular include references is the one rea... |
791,258 | 791,262 | Inserting and removing commas from integers in c++ | Very much a noob here, so it's best to assume I know nothing in any answers.
I've been writing a little app, and it's working well, but readability is a nightmare with my numbers.
Essentially, all I want to do is to add commas into the numbers displayed on the screen to make it easier to read. Is there a quick and easy... | Try the numpunct facet and overload the do_thousands_sep function. There is an example. I also hacked up something that just solves your problem:
#include <locale>
#include <iostream>
class my_numpunct: public std::numpunct<char> {
std::string do_grouping() const { return "\3"; }
};
int main() {
std::locale ... |
791,539 | 791,547 | How can I have folds for C++/Java in Emacs? | I know the thread about having folds for LaTex.
However, I want folds for C++/Java when I code.
How can you have either automatic or manual folds in Emacs for C++/Java?
| Make sure you have folding-mode.el. Then, insert
// {{{
// }}}
Around your code. Reload your buffer, and voila! You'll have folds.
|
791,636 | 791,655 | Undefined Symbol: _sf_open (Simple audio stuff on OSX) | I'm trying to get into C++ programming, and I'm quite struggling against the little details. Right now, I'm trying to get the snippet below to work, and apparently it will compile, but not link. (error message is a the bottom of this post)
I'm using libsndfile to open audio files, and the linker doesn't seem to find th... | You need to link in the library. Your compiler command should look something like:
g++ mystuff.cpp -lsndfile
|
791,687 | 791,730 | OpenGL: glTexImage2D conflicts with glGenLists & glCallList? | I have a simple OpenGL application where I have 2 objects displayed on screen:
1) particle system, where each particle is texture mapped with glTexImage2D() call. In the drawEvent function, I draw it as a GL_TRIANGLE_STRIP with 4 glVertex3f.
2) a 3D text loaded from an object file, where each point is loaded using glNe... | glTexImage2D uploads the texture to the video-ram (simplified said).
If OpenGL would allow you to place a glTexImage2D call inside the list it had to store the pixel-data in the list as well. Now what happends if you would execute the list? You would upload the same image data into the same texture all over gain.
Tha... |
791,856 | 791,879 | Which Windows GUI system should I choose with C++? | There are now so many ways to write windows apps, win32, MFC, ATL, .NET, WinForms, and probably some others that I don't know of. Which one should I choose? I'd like one that works on a fresh install of Vista, and is modern and easy to use.
| If you are amateur with C++ you'll have much easier time learning WinForms than any of the native Visual C++ frameworks (Win32, MVC, etc.). WPF will give you best versatily. It's a bit harder to master than WinForms but managed and so keeps you away from the nasty Win32 stuff.
The native frameworks are good mainly if y... |
791,937 | 791,943 | When is it safe to add object values to vectors on the heap? | Let's say I have a structure named vertex with a method that adds two vertices:
struct vertex {
float x, y, z;
// constructs the vertex with initial values
vertex(float ix, float iy, float iz);
// returns the value c = this + b
vertex operator+(vertex b);
};
vertex::vertex(float ix, float iy, flo... | This is not safe, since you are storing a pointer to an automatic or temporary variable, which will be reclaimed when the current function terminates.
Mixing dynamically allocated objects with automatically-allocated ones is a serious risk. Sometimes the best strategy is to completely disallow automatic allocation (e.... |
791,953 | 791,969 | When using Win32 code in your modern C++ app, should you use proper casting? | For example the following cast can be found littered throughout the MSDN documentation:
(LPTSTR)&lpMsgBuf
Should I bother converting that to:
static_cast<LPTSTR>(&lpMsgBuf);
Or should I just leave all the idiomatic C-esque Win32 portions as they are typically found in the docs, and save the more idiomatic C++ style/u... | New style casts were introduced for a reason: they're safer, more explanatory/self-commenting, easier to see, and easier to grep for.
So use them.
By more explanatory, we mean that you can't just cast to something, you have to say why you're casting (I'm casting in an inheritance hierarchy (dynamic_cast), my cast is im... |
792,040 | 792,078 | fstream replace portion of a file | When I do
fstream someFile("something.dat", ios::binary|ios::out);
someFile.seekp(someLocation, ios::beg);
someFile.write(someData, 100);
It seems to replace the entire file with those 100 bytes instead of replacing only the appropriate 100 bytes, as if I had specified ios::trunc. Is there a portable way to not have ... | You want the append flag, ios::app, if you want to write at the end of the file.
To do it somewhere arbitrarily in the middle of the file, you need to seek to the right place. You CAN do this by opening the file for in and out, but if I were you I'd create a temp file, copy input up to mark, write your new data, copy ... |
792,145 | 794,866 | Is there a grammar parser (similar to yapps for python) for C++? | I'm writing an experimental language, which is very close to pseudocode, for fun and to learn more about C++. One of the problems is that I need to parse some grammar, and my search to find a good C++ grammar parser has been unsuccessful (I couldn't find anything). What I want to accomplish is this:
set a to 4
And I... | Rolling your own can be as easy as writing the grammar in the first place! It's a great way to learn about parsing, glean a more intimate knowledge of your programming language, and most of all it's fun. The method is called Recursive Descent. It usually comes out much more simple and elegant than what a parser generat... |
792,152 | 792,156 | How similar is an std::vector to a raw array in C++? | I'm writing a hangman game. I'm having a logic fail, both with myself and my game logic. Char guess (the letter the person guessed) isn't being added into the correct memory slot of the vector guessArray. Assume that word is an inputted word by the user.
I assume this would work if guessArray were a raw array. Is ther... | A vector can be indexed with subscript notation [], and it is stored in contiguous memory. It is an STL container so, like an array, you can have one of any type.
A vector is automatically resized. An array is 'statically' sized, and cannot be easily resized (with the exception of a manual function called to realloc.) ... |
792,209 | 792,238 | Compact and Repair Database programmatically | How can I call Access's Compact and Repair Database utility from within C++? I'm already using ADO and ADOX, so a solution using either of those would be handy.
| Similiar to:
How can I programmatically repair (not merely compact) an Access .mdb file?
You can do this using COM to access the JRO.JetEngine object. There is an example in C# at CodeProject which shouldn't be too hard to convert to C++.
UPDATE: Thanks to @le dorfier, here is an article with C++ example.
|
792,217 | 792,322 | Simple makefile with release and debug builds - Best practices | I am new to makefiles. I learned makefile creation and other related concepts from "Managing projects with GNU make" book. The makefile is ready now and I need to make sure the one which I created is OK. Here is the makefile
#Main makefile which does the build
#makedepend flags
DFLAGS =
#Compiler flags
#if mode vari... |
It is one reasonable format. It is tied specifically to GNU Make, but that's a relatively minor problem if you have chosen to use GNU Make on every platform.
If there is a flaw, it is that you could end up linking object files built in debug mode to create the final build.
Some might argue that a 'mode=release' opt... |
792,355 | 792,797 | Custom widget plugin for qt designer is invisible | I've tried to create a custom widget plugin for QT Designer following this (http://doc.trolltech.com/4.3/designer-creating-custom-widgets.html) tutorial and was somewhat successful. Basically, I can place my new widget in Designer, but it doesn't draw (I get an empty square instead of whatever I try to draw in my paint... | without the source it's very hard to help you. Further I would prefer Qt 4.4 - it's much more reliable and faster.
Here some common problems/hints:
your DLL / .so file is not in /plugins/designer/
you have a buggy paint() method
your app or lib is missing some libs
Can you post your paint method?
ciao,
Chris
|
792,679 | 795,151 | How to write a regular expression for html parsing? | I'm trying to write a regular expression for my html parser.
I want to match a html tag with given attribute (eg. <div> with class="tab news selected" ) that contains one or more <a href> tags. The regexp should match the entire tag (from <div> to </div>). I always seem to get "memory exhausted" errors - my program pro... | You may also find these questions helpful:
Can you provide some examples of why it is hard to parse XML and HTML with a regex?
Can you provide an example of parsing HTML with your favorite parser?
|
793,327 | 795,466 | fixing glCopyTexSubImage2D upside down textures | Since I have started learning about rendering to a texture I grew to understand that glCopyTexSubImage2D() will copy the designated portion of the screen upside down. I tried a couple of simple things that came to mind in order to prevent/work around this but couldn't find an elegant solution.
there are two problems w... | What are you going to be using the texture images for? Actually trying to render them upside down would usually take more work than moving that code somewhere else.
If you're trying to use the image without exporting it, just flipping the texture coordinates wherever you're using the result would be the most efficient ... |
793,351 | 793,460 | Weird bug while inserting into C++ std::map | I'm trying to insert some value pairs into a std::map.
In the first case, I receive a pointer to the map, dereference it and use the subscript operator to assign a value. i.e.
(*foo)[index] = bar;
Later, when I try to iterate over the collection, I'm returned key/value pairs which contain null for the value attribut... | In your actual code you have:
(*cycleNodes)[tmp->getId()] == tmp;
This will not assign tmp into the map, but will instead reference into the map creating an empty value (see @Neil Butterworth) - you have == instead of =. What you want is:
(*cycleNodes)[tmp->getId()] = tmp;
|
793,375 | 793,972 | What could cause DAMAGE: after normal block error? | I keep getting this error after my application is running for 2 days.
I've been told it's been some kind of buffer overflow, but is it the only option?
The app is written in C++ using Visual C++ 6.0.
| In debug, when you get dynamic buffer by new, a special code gets inserted before and after the buffer to guard the buffer.
Ex:
<Guard>=====buffer allocated on heap of required size=======<Guard>
If you overrun the buffer, the guard inserted gets corrupted and when you try to delete the buffer, then debugger would as... |
793,469 | 794,514 | How to force the compiler to use explicit copy constructor? | I wrote a small test program with a sample class containing also self-defined constructor, destructor, copy constructor and assignment operator. I was surprised when I realized that the copy constructor was not called at all, even though I implemented functions with return values of my class and lines like Object o1; O... | Just for completeness with the other answers, the standard allows the compiler to omit the copy constructor in certain situations (what other answers refer to as "Return Value Optimization" or "Named Return Value Optimization" - RVO/NRVO):
12.8 Copying class objects, paragraph 15 (C++98)
Whenever a temporary class obj... |
794,015 | 794,116 | What do people mean when they say C++ has "undecidable grammar"? | What do people mean when they say this? What are the implications for programmers and compilers?
| This is related to the fact that C++'s template system is Turing complete. This means (theoretically) that you can compute anything at compile time with templates that you could using any other Turing complete language or system.
This has the side effect that some apparently valid C++ programs cannot be compiled; the c... |
794,244 | 794,261 | How should I correct this code that causes "value computed not used" warning? | I have an array of doubles and need to do a calculation on that array and then find the min and max value that results from that calculation. Here is basically what I have:
double * array;
double result;
double myMin;
double myMax;
// Assume array is initialized properly...
for (int i = 0; i < sizeOfArray; ++i) {
... | Assuming you don't need result outside of the loop, you could declare result inside the loop thusly:
for( int i=0; i < sizeOfArray; ++i ) {
double result = transmogrify( array[i] );
...
}
|
794,320 | 794,365 | are they adding copy_if to c++0x? | It's very annoying that copy_if is not in C++. Does anyone know if it will be in C++0x?
| Since the C++0x is not yet finalized, you can only take a look at the most recent draft.
|
794,462 | 794,470 | POSIX threads experience? (Or recommend better one) | I am looking for lightweight multi-threading framework for C++. I found POSIX Threads.
Please, share you practical experience with POSIX threads: before I start with it I want to know its pros and cons from real people, not from wiki.
If you practically compared it with anything (maybe, better), it would be interesting... | I found Boost.Threads to be really nice, especially after the 1.35 rewrite. POSIX threads on Windows is not so trivial, and it's a C API, so I would definitely prefer Boost to it. It has all the stuff you need, is portable and requires little setup.
|
794,601 | 794,673 | Prefix search in a radix tree/patricia trie | I'm currently implementing a radix tree/patricia trie (whatever you want to call it). I want to use it for prefix searches in a dictionary on a severely underpowered piece of hardware. It's supposed to work more or less like auto-completion, i. e. showing a list of words that the typed prefix matches.
My implementation... | Think about what your trie encodes. At each node, you have the path that lead you to that node, so in your example, you start at Λ (that's a capital Lambda, this greek font kind of sucks) the root node corresponding to an empty string. Λ has children for each letter used, so in your data set, you have one branch, for... |
794,625 | 794,659 | Boost linkage error in Eclipse | I've been banging my head fruitlessly against the wall attempting to include boost's thread functionality in my Eclipse C++ project on Ubuntu.
Steps so far:
Download boost from boost.org
./configure --with-libraries=system,thread
make
sudo make install
sudo ldconfig -v
In the eclipse project, set the include director... | Your linker line should be saying -lboost_thread-gcc43-mt-1_38.
|
794,632 | 70,814,302 | Programmatically get the cache line size? | All platforms welcome, please specify the platform for your answer.
A similar question: How to programmatically get the CPU cache page size in C++?
| You can use std::hardware_destructive_interference_size since C++17.
Its defined as:
Minimum offset between two objects to avoid false sharing. Guaranteed
to be at least alignof(std::max_align_t)
|
795,286 | 795,289 | What does the question mark character ('?') mean in C++? | int qempty()
{
return (f == r ? 1 : 0);
}
In the above snippet, what does "?" mean? What can we replace it with?
| This is commonly referred to as the conditional operator, and when used like this:
condition ? result_if_true : result_if_false
... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.
It is syntactic sugar, and in this case, it can be replaced with... |
795,391 | 795,433 | LoadLibrary fails: First chance exception 0xC0000139 (DLL Not Found) - How to debug? | I have a dll "mytest.dll" that when loaded via LoadLibrary(), returns NULL (and 127 as the GetLastError()). If I use DependencyWalker on "mytest.dll", it reports that it should load correctly and that all DLLs are found correctly. Running the profiler option of DependencyWalker on the host exe gives me this relevant ... | Could your application be trying to call a specific DLL function via GetProcAddress after the initial load (perhaps) which is not found? Is it a 32 or 64 bit application?
If it is loading correctly in another application as you suggest, then it probably has a correct entry point.
A quick google search suggests that ... |
795,443 | 795,482 | using BOOST_FOREACH with std::map | I'd like to iterate over a std::map using BOOST_FOREACH and edit the values. I can't quite get it.
typedef std::pair<int, int> IdSizePair_t;
std::map<int,int> mmap;
mmap[1] = 1;
mmap[2] = 2;
mmap[3] = 3;
BOOST_FOREACH( IdSizePair_t i, mmap )
i.second++;
// mmap should contain {2,3,4} here
Of course this doesn'... | The problem is with the first member of the pair, which should be const. Try this:
typedef std::map<int, int> map_t;
map_t mmap;
BOOST_FOREACH( map_t::value_type &i, mmap )
i.second++;
|
795,496 | 795,534 | C++: How is it possible that reading data can affect memory? | I've been going deeper into C++ recently and my bugs seem to get complex.
I have a vector of objects, each object contains a vector of floats. I decided I needed to create a further flat array containing all the float values of all objects in one. It's a little more complex than that but the gist of the problem is th... | This is not an array constructor:
float * flatFitness;
flatFitness = new float(popSize);
You're creating one float on the heap here, initialized with value popSize. If you want an array of floats you need to use brackets instead of parentheses:
float *flatFitness = new float[popSize];
This could easily be causing th... |
795,504 | 795,552 | List of study topics | I have experience developing MFC applications with C++ using Visual Studio 6.0. You can guess how long ago that was (hint: going on 10 years). I am trying to update my skills but a lot has changed. How would one go about bringing these skills up to date?
| in C++? boost is definitely worth playing with.
C# is a good complimentary language.
WPF is a good MFC alternative.
There have also been improvements to MFC so you can create modern looking apps, worth looking at. Still a number of people who create native code windows apps.
pick up a scripting language of
somesort,... |
795,674 | 795,748 | Which are the implications of return a value as constant, reference and constant reference in C++? | I'm learning C++ and I'm still confused about this. What are the implications of return a value as constant, reference and constant reference in C++ ? For example:
const int exampleOne();
int& exampleTwo();
const int& exampleThree();
| Here's the lowdown on all your cases:
• Return by reference: The function call can be used as the left hand side of an assignment. e.g. using operator overloading, if you have operator[] overloaded, you can say something like
a[i] = 7;
(when returning by reference you need to ensure that the object you return is ava... |
795,827 | 797,175 | Testing the performance of a C++ app | I'm trying to find a way to test how long it takes a block of C++ code to run. I'm using it to compare the code with different algorithms and under different languages, so ideally I would like a time in seconds / milliseconds. In Java I'm using something like this:
long startTime = System.currentTimeMillis();
function... | Use the best counter available on your platform, fall back to time() for portability.
I am using QueryPerformanceCounter, but see the comments in the other reply.
General advise:
The inner loop should run at least about 20 times the resolution of your clock, to make the resolution error < 5%. (so, when using time() you... |
795,972 | 826,558 | Chi-Squared Probability Function in C++ | The following code of mine computes the confidence interval using Chi-square's 'quantile' and probability function from Boost.
I am trying to implement this function as to avoid dependency to Boost. Is there any resource where can I find such implementation?
#include <boost/math/distributions/chi_squared.hpp>
#include ... | If you're looking for source code you can copy/paste, here are some links:
AlgLib
Koders
YMMV...
|
795,987 | 797,405 | C++ iterators & loop optimization | I see a lot of c++ code that looks like this:
for( const_iterator it = list.begin(),
const_iterator ite = list.end();
it != ite; ++it)
As opposed to the more concise version:
for( const_iterator it = list.begin();
it != list.end(); ++it)
Will there be any difference in speed between these two conventio... | I'll just mention for the record that the C++ standard mandates that calling begin() and end() on any container type (be it vector, list, map etc.) must take only constant time. In practice, these calls will almost certainly be inlined to a single pointer comparison if you compile with optimisations turned on.
Note th... |
796,099 | 804,935 | C++ new operator thread safety in linux and gcc 4 | Soon i'll start working on a parallel version of a mesh refinement algorithm using shared memory.
A professor at the university pointed out that we have to be very careful about thread safety because neither the compiler nor the stl is thread aware.
I searched for this question and the answer depended on the compiler (... | You will have to look very hard to find a platform that supports threads but doesn't have a thread safe new. In fact, the thread safety of new (and malloc) is one of the reasons it's so slow.
If you want a thread safe STL on the other hand, you may consider Intel TBB which has thread aware containers (although not all... |
796,106 | 796,117 | Replacing getpid with my own implementation | I have an application where I need to write a new getpid function to replace the original one of the OS. The implementation would be similar to:
pid_t getpid(void)
{
if (gi_PID != -1)
{
return gi_PID;
}
else
{
// OS level getpid() function
}
}
How can I call the original getpid(... | On many systems, you will find that getpid() is a 'weak symbol' for _getpid(), which can be called in lieu of getpid().
The first version of the answer mentioned __getpid(); the mention was removed swiftly since it was erroneous.
This code works for me on Solaris 10 (SPARC) - with a C++ compiler:
#include <sys/types.h... |
796,198 | 796,252 | How to create a boost thread with data? | I'm running into some issues with boost::bind and creating threads.
Essentially, I would like to call a "scan" function on a "Scanner" object, using
bind.
Something like this:
Scanner scanner;
int id_to_scan = 1;
boost::thread thr1(boost::bind(&scanner::scan));
However, I'm getting tripped up on syntax. How... | Keep in mind that the first argument to any member function is the object.
So if you wanted to call:
scanner* s;
s->scan()
with bind you would use:
boost::bind(&scanner::scan, s);
If you wanted to call:
s->scan(42);
use this:
boost::bind(&scanner::scan, s, 42);
Since I often want bind to be called on the object cre... |
796,321 | 796,330 | Strange C++ std::string behavior... How can I fix this? | This is driving me nuts. I have been at it for over 2 hours trying to figure this out...
Here is my problem. I am working on a fairly large program that works with Bayesian networks. Here is the main function:
using namespace std;
int main()
{
DSL_network net;
initializeNetwork(net);
setEvidence(net)... | That's bizarre. I always like to break a problem down to it's minimal case. What does the following program do when you run it?
using namespace std;
int main() {
string a = "test";
cout << a << endl;
return 0;
}
If that works, then there's something else wrong and you need to add in one line at a time un... |
796,364 | 796,462 | Fast Cross-Platform C/C++ Image Processing Libraries | What are some cross platform and high performance image libraries for image processing (resizing and finding the color/hue histograms). No gui needed. This is for C/C++.
So far I have looked in to
OpenCV
GIL as part of Boost
DevIL
CImg
My questions
How's the performance of the ones I have listed above
What are som... | OpenCV has quite good performance. It should be sufficient for most cases.
To improve performance, you can also use OpenCV together with Intel IPP, which is however a non-free commercial product. If OpenCV detects that IPP is installed it will use it where possible.
As a third option you can use IPP directly. IPP was... |
797,079 | 797,083 | How do I declare an array of strings in C++? | In C++ how can I declare an array of strings? I tried to declare it as an array of char but that was not correct.
| #include <string>
std::string my_strings[100];
That is C++, using the STL. In C, you would do it like this:
char * my_strings[100];
This reads as "my strings is an array of 100 pointer to char", and the latter is how strings are represented in C.
|
797,230 | 797,418 | Qt4 existing slots are not recognized | I am currently trying to complete a project using Qt4 and C++. I am using buttons to switch between states. While trying to connect the buttons' clicked() signals to the textEdit to display the relevant state, I got stuck on an error:
Object::connect No such slot
QTextEdit::append("move state")
Object::connect No ... | You can't pass in an argument (literally) to the append() slot when making a signal to slot connection.
You refer to it like a method signature:
SLOT(append(QString)) //or const QString, I'm not sure
If you need the textbox to append the words "move state" every time that button is clicked, then you should define your... |
797,574 | 797,580 | Resources for C++ Templates | I'm new to C++ Templates, and am finding it hard to understand and debug them. What are some good resources for doing both/either?
| I recommend the excellent book C++ Templates - The Complete Guide by Vandevoorde and Josuttis.
|
797,582 | 797,597 | Strange output after reading from a file | Using this code, the following execution yields strange results:
C 100
R
W
The text file's first line defines the number of elements to read from it, and it contains a few values under 15, but every time I run this, the first value in my array is always printed out as 87 (the ASCII value for 'W'). If I change the 'W' ... | Whatever you think
ELEMENT H [];
is doing, it probably isn't. C++ does not support dynamic arrays - you need to use the std::vector class.
And BTW, C++ by convention uses UPPERCASE to name pre-processor macros and constants. You should use mixed case to name your classes.
|
797,594 | 797,632 | When a compiler can infer a template parameter? | Sometimes it works sometimes not:
template <class T>
void f(T t) {}
template <class T>
class MyClass {
public:
MyClass(T t) {}
};
void test () {
f<int>(5);
MyClass<int> mc(5);
f(5);
MyClass mc(5); // this doesn't work
}
Is there a way to hack around the example above? I.e. force the compiler to infer the ... | Template parameters can be inferred for function templates when the parameter type can be deduced from the template parameters
So it can be inferred here:
template <typename T>
void f(T t);
template <typename T>
void f(std::vector<T> v);
but not here:
template <typename T>
T f() {
return T();
}
And not in class te... |
797,967 | 798,003 | How to stop EnumWindows running infinitely win32 | The code worked all along. Somehow I manage to get Visual C++ Express not hit the break point on the final return statement and it appeared to run for ever.
In the example code bellow EnumWindows enumerates infinitely.
How can one make it stop after all windows has been enumerated.
#include <Windows.h>
BOOL CALLBACK E... | Your code works for me, once I removed the wide-character stuff and added #include <stdio.h> to get the printf() declaration. What output does it produce on your system?
The code that works for me is:
#include <windows.h>
#include <stdio.h>
BOOL CALLBACK EnumWindowsProc(HWND hWnd, LPARAM lParam) {
char buff[255];
... |
798,002 | 798,641 | filling a boost vector or matrix | Is there a single-expression way to assign a scalar to all elements of a boost matrix or vector? I'm trying to find a more compact way of representing:
boost::numeric::ublas::c_vector<float, N> v;
for (size_t i=0; i<N; i++) {
v[i] = myScalar;
}
The following do not work:
boost::numeric::ublas::c_vector<float, N>... | Because the vector models a standard random access container you should be able to use the standard STL algorithms. Something like:
c_vector<float,N> vec;
std::fill_n(vec.begin(),N,0.0f);
or
std::fill(vec.begin(),vec.end(),0.0f);
It probably also is compatible with Boost.Assign but you'd have to check.
|
798,013 | 798,091 | Segmentation fault on string assignment in C++ | Take a look at this example function:
RuntimeConfiguration* conf_rt_conf() {
RuntimeConfiguration *conf;
conf = new RuntimeConfiguration();
conf->arch_path="./archive";
conf->err_log="./err_log";
conf->fail_log="./fail_log";
conf->msg_log="./msg_log";
conf->save="html, htm, php";
conf->... | Maybe this:
DatabaseInput *db_input[];
db_input = new DatabaseInput*[NUMB_SITES]; // Creates an array of pointers
for (int i=0; i<NUMB_SITES; i++) db_input[i]= new DatabaseInput();
could work? (I didn't test it)
Note, to free the memory used, you should do something like:
for (int i=0; i<NUMB_SITES; i++) delete db_inp... |
798,410 | 798,465 | Multi-threading strategies? (Modifying a scene in a multi-threaded engine through an Editor) | I'm trying to write an editor overtop a multi-threaded game engine. In theory, through the editor, the contents of the scene can be totally changed but I haven't been able to come up with a good way for the engine to cope with the changes. (ie delete an entity while the renderer was drawing it). Additionally, I'm hesit... | In addition to the two-stage process suggested by @lassevk you could use a Pipe structure to "push" commands to the renderer so that these changes gets the form of another work item for the render engine.
For example, say your engine follows a workflow like:
Calculate positions
Process Physics
Process Lights Process ... |
798,497 | 860,350 | How do I check for an unmangled C++ symbol when building a PHP extension? | I have a PHP module written in C++, which relies on a C++ library (Boost Date_Time) being installed.
Currently, in my config.m4 file I'm checking for the library as follows:
LIBNAME=boost_date_time
LIBSYMBOL=_ZN5boost9gregorian9bad_monthD0Ev
PHP_CHECK_LIBRARY($LIBNAME,$LIBSYMBOL,,
[
AC_MSG_ERROR([lib $LIBN... | You can check AC_TRY_COMPILE with something like that:
LIBNAME=boost_date_time
AC_MSG_CHECKING([for BOOST])
AC_TRY_COMPILE(
[
#include "boost/date_time/gregorian/greg_month.hpp"
],
[
boost::gregorian::bad_month* bm = new boost::gregorian::bad_month;
],
[
AC_MSG_RESULT(yes)
],
[
AC_MSG_ERROR([lib $LIBNAME not found. Tr... |
798,612 | 798,635 | Syntax for dereferencing a pointer in C (or C++) | I had a colleague check in code like this in C (syntax #1):
(*(*(*p_member).p_member).p_member).member
When I asked him why he didn't use -> (syntax #2):
p_member->p_member->p_member->member
he got really defensive stating that syntax #2 is more complicated than #1...I ended up changing his code because I had to mo... | The technical term for syntax # 1 is "nuts."
That said, I'd worry a little about code that has to go indirect 3 times too.
|
798,798 | 798,825 | ifstream::open not working in Visual Studio debug mode | I've been all over the ifstream questions here on SO and I'm still having trouble reading a simple text file. I'm working with Visual Studio 2008.
Here's my code:
// CPPFileIO.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <fstream>
#include <conio.h>
#include <iostream>
#i... | Try using the bitwise OR operator when specifying the open mode.
infile.open ("input.txt", ios::ate | ios::in);
The openmode parameter is a bitmask. ios::ate is used to open the file for appending, and ios::in is used to open the file for reading input.
If you just want to read the file, you can probably just use:
in... |
798,876 | 803,982 | How do I get an error message when failing to load a JVM via JNI? | I would like to retrieve an error message that explains why the jvm failed to load. From the examples provided here:
http://java.sun.com/docs/books/jni/html/invoke.html
I extracted this example:
/* Create the Java VM */
res = JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args);
if (res < 0) {
// retrieve verbose er... | I was able to get what I needed by using the "vfprintf" option described here:
https://web.archive.org/web/20111229234347/http://java.sun.com/products/jdk/faq/jnifaq-old.html
although I used the jdk1.2 options. This code snippet summarizes my solution:
static string jniErrors;
static jint JNICALL my_vfprintf(FILE *fp,... |
799,068 | 799,078 | What should i know about UDP programming? | I don't mean how to connect to a socket. What should I know about UDP programming?
Do I need to worry about bad data in my socket?
I should assume if I send 200bytes I may get 120 and 60 bytes separately?
Should I worry about another connection sending me bad data on the same port?
If data doesnt arrive typically h... |
"i should assume if i send 200bytes i
may get 120 and 60bytes separately?"
When you're sending UDP datagrams your read size will equal your write size. This is because UDP is a datagram protocol, vs TCP's stream protocol. However, you can only write data up to the size of the MTU before the packet could be fragme... |
799,076 | 799,210 | Returning a std::string from a C++ DLL to a c# program -> Invalid Address specified to RtlFreeHeap | In a function in my C++ DLL, I'm returning a std::string to my c# application. It pretty much looks like this:
std::string g_DllName = "MyDLL";
extern "C" THUNDER_API const char* __stdcall GetDLLName()
{
return g_DllName.c_str();
}
But when my C# code calls this function, I get this message in my output window:
I... | I managed to find the issue. It was the way the C# definition was done. From what I can understand, using the MarshallAs(UnmanagedType.LPStr) in combination with the string return type makes it so that it'll attempt to free the string when its done. But because the string comes from the C++ DLL, and most likely a total... |
799,090 | 799,196 | Tracing MFC message handling | Trying to upgrade an MFC app to use the new MFC feature pack, we are loosing the messages from a context menu. The menu appears and can be clicked, but the message seems not to be handled anywhere. We overrode OnCmdMsg() in lots of places but to no avail, the context menu's command message are not caught.
Is there a wa... | Try SPY++
> ...can be found on the Programs or All Programs menu in Windows. Click Microsoft Visual Studio 9.0, and then click Visual Studio Tools.
Provides a graphical view of the processes, threads, windows, and window messages of a system. For more information, click Help in the tool.
I explain more in this ans... |
799,314 | 799,342 | Difference between erase and remove | I am bit confused about the difference between the usage of std::remove algorithm. Specifically I am not able to understand what is being removed when I use this algorithm. I wrote a small test code like this:
std::vector<int> a;
a.push_back(1);
a.push_back(2);
std::remove(a.begin(), a.end(), 1);
int s = a.size();
... | remove() doesn't actually delete elements from the container -- it only shunts non-deleted elements forwards on top of deleted elements. The key is to realise that remove() is designed to work on not just a container but on any arbitrary forward iterator pair: that means it can't actually delete the elements, because ... |
799,558 | 799,581 | Generating data structures by parsing plain text files | I wrote a file parser for a game I'm writing to make it easy for myself to change various aspects of the game (things like the character/stage/collision data). For example, I might have a character class like this:
class Character
{
public:
int x, y; // Character's location
Character* teammate;
}
I set up my p... | When you encounter the reference the first time, simply store it as a reference. Then, you can put the character, or the reference, or whatever on a list of "references that need to be resolved later".
When the file is done, run through those that have references and resolve them.
|
799,599 | 799,877 | C++ custom stream manipulator that changes next item on stream | In C++, to print a number in hexadecimal you do this:
int num = 10;
std::cout << std::hex << num; // => 'a'
I know I can create a manipulator that just adds stuff to the stream like so:
std::ostream& windows_feed(std::ostream& out)
{
out << "\r\n";
return out;
}
std::cout << "Hello" << windows_feed; // => "He... | First, you have to store some state into each stream. You can do that with the function iword and an index you pass to it, given by xalloc:
inline int geti() {
static int i = ios_base::xalloc();
return i;
}
ostream& add_one(ostream& os) { os.iword(geti()) = 1; return os; }
ostream& add_none(ostream& os) { os... |
799,780 | 799,850 | Signal-slot architecture best practice | I am using libsigc++ to wire up an application, and is uncertain as to the easier way of going about it.
There is a preexisting object hierarchy that manages the data layer, and the top level object exposes all functions. All good so far.
To this I am adding a GUI object hierarchy, and in the application object I am ... | Personally, I don't see any problem by 'skipping' layers with the signal/slots mechanism. I prefer to see it this way: a component is sending signals into the wild, and whoever is interested in those signals may listen to them.
A couple of tips: avoid to send signals that are too generic, and don't rely on the order o... |
799,932 | 800,011 | Fast Cross-Platform C/C++ Hashing Library | What's a high performance hashing library that's also cross platform for C/C++. For algorithms such as MD5, SHA1, CRC32 and Adler32.
I initially had the impression that Boost had these, but apparently not (yet).
The most promising one I have found so far is Crypto++, any other suggestions? http://www.cryptopp.com/ Thi... | For usual crypto hashes (MD?, SHA? etc.), openssl is the most portable and probably fastest. None of the hashes you mentioned are good for high performance data structures like hash tables. The recommended hash functions for these data structures these days are: FNV, Jenkins and MurmurHash.
|
800,137 | 800,169 | Beginner for loop problem | [EDIT]Whoops there was a mistake in the code, and now all the responses to the question seem bizzare, but basically the for loop used to be, for(i=0; i<15; i++). I also edited to make the question more clear.[/EDIT]
I am trying to make a for loop, that checks a 16 element array, so it loops from 0 to 15. I then use the... | I suggest using some other variable other than i after your loop is finished. The criteria of using a for loop instead of a while loop is that you know beforehand exactly how many times a for loop will execute. If you already know this, just set some other variable to the ending value of your loop and use it instead ... |
800,368 | 800,384 | Declaring an object before initializing it in c++ | Is it possible to declare a variable in c++ without instantiating it? I want to do something like this:
Animal a;
if( happyDay() )
a( "puppies" ); //constructor call
else
a( "toads" );
Basially, I just want to declare a outside of the conditional so it gets the right scope.
Is there any way to do this without... | You can't do this directly in C++ since the object is constructed when you define it with the default constructor.
You could, however, run a parameterized constructor to begin with:
Animal a(getAppropriateString());
Or you could actually use something like the ?: operator to determine the correct string.
(Update: @Gre... |
800,576 | 800,588 | Learn C# to transition to C/C++? | Alright, so I just took an introductory class into Computer Science and the school's language choice was Java (I have basic knowledge of concepts like polymorphism, encapsulation, etc..). I want to learn C++ then C (I hear that one should learn C++ first then go to C), and was wondering if C# is a nice transitional lan... | Doubtful. C# is not significantly more C++-like than Java. It does support pointers in unsafe code, but beyond that I can't think of any reason it would make an especially good bridge from Java to C++. Also that is a feature I suspect more likely to be used by developers coming from the other direction. If you have oth... |
800,734 | 800,760 | What's behind the CAsyncSocket assertion problems and "improper argument" errors in my MFC sockets code? | I was asked to look at some code for a friend. (I rightly hesitated due to the MFC and lots of bad code, but he won...)
This is a dialog box based application that uses a CAsyncSocket.
The problem manifests in some nonstop debugbreaks and other similar things - there are also problem with an MFC ENSURE() macro - check... | Your choice really. If you think you'll have more luck with another sockets implementation, then do it.
However, Microsoft has a lot of developers (and I believe some of them may even be good ones). You may, just may, want to consider the possibility that the fault doesn't all lay at their end.
The amount of help you c... |
800,761 | 800,799 | When to use the keyword "static" in C++class? | Code
static void MyClass::ThreadEntryStatic()
{
//...
}
void MyClass::Begin()
{
CreateThread(..,ThreadEntryStatic,..);
}
In which condition we should use the static in class ?
| There are three places that the keyword static can be used. One is in the declaration of a struct/class when that context means that the method is a class method instead of an instance method. This means that this method is called directly and you don't need an instance. From this static method, you can not access i... |
800,955 | 800,984 | remove_if equivalent for std::map | I was trying to erase a range of elements from map based on particular condition. How do I do it using STL algorithms?
Initially I thought of using remove_if but it is not possible as remove_if does not work for associative container.
Is there any "remove_if" equivalent algorithm which works for map ?
As a simple optio... | Almost.
for(; iter != endIter; ) {
if (Some Condition) {
iter = aMap.erase(iter);
} else {
++iter;
}
}
What you had originally would increment the iterator twice if you did erase an element from it; you could potentially skip over elements that needed to be erased.
This is a common ... |
801,054 | 818,390 | OpenCV cvSaveImage Jpeg Compression Factor | I am using OpenCV and saving as a jpeg using the cvSaveImage function, but I am unable to find the Jpeg compression factor used by this.
What's cvSaveImage(...)'s Jpeg Compression factor
How can I pass the compression factor when using cvSaveImage(...)
| Currently cvSaveImage() is declared to take only two parameters:
int cvSaveImage( const char* filename, const CvArr* image );
However, the "latest tested snapshot" has:
#define CV_IMWRITE_JPEG_QUALITY 1
#define CV_IMWRITE_PNG_COMPRESSION 16
#define CV_IMWRITE_PXM_BINARY 32
/* save image to file */
CVAPI(int... |
801,199 | 832,474 | OpenCV to use in memory buffers or file pointers | The two functions in openCV cvLoadImage and cvSaveImage accept file path's as arguments.
For example, when saving a image it's cvSaveImage("/tmp/output.jpg", dstIpl) and it writes on the disk.
Is there any way to feed this a buffer already in memory? So instead of a disk write, the output image will be in memory.
I w... | There are a couple of undocumented functions in the SVN version of the libary:
CV_IMPL CvMat* cvEncodeImage( const char* ext,
const CvArr* arr, const int* _params )
CV_IMPL IplImage* cvDecodeImage( const CvMat* _buf, int iscolor )
Latest check in message states that they are for native ... |
801,209 | 801,240 | char* vs std::string in c++ | When should I use std::string and when should I use char* to manage arrays of chars in C++?
It seems you should use char* if performance(speed) is crucial and you're willing to accept some of a risky business because of the memory management.
Are there other scenarios to consider?
| You can pass std::strings by reference if they are large to avoid copying, or a pointer to the instance, so I don't see any real advantage using char pointers.
I use std::string/wstring for more or less everything that is actual text. char * is useful for other types of data though and you can be sure it gets deallocat... |
801,279 | 807,398 | Finding compiler vendor / version using qmake | Is there any way to get the version and vendor of the compiler used by the user through qmake? What I need is to disable building some targets of my project when g++ 3.x is used and enable them when g++ 4.x is used.
Update: Most answers targeted the preprocessor. This is something that I want to avoid. I don't want a t... | In addition to ashcatch's answer, qmake allows you to query the command line and get the response back as a variable. So you could to something like this:
linux-g++ {
system( g++ --version | grep -e "\<4.[0-9]" ) {
message( "g++ version 4.x found" )
CONFIG += g++4
}
else system( g++ --versi... |
801,284 | 801,433 | Is there a tool to monitor synchronisation objects (mutex, events, semaphores) in Windows? | In Windows, is there a tool to monitor the status of process synchronisation objects? ie.
event/mutex : signaled or not signaled
semaphore : count
Better yet, to log which thread did what, eg. "thread #5421 Signal Event - testevt"
| Memory Validator
Process Explorer
Handle usage: handle -s ==> Print count of each type of handle open.
[EDIT]:
How to monitor the status of process synchronization objects using Process Explorer.
Open Process Explorer
Click on your exe in the process section (for ex: MyApp.exe)
Click Show Lower Pane (or press C... |
801,385 | 801,658 | Are there any practical limitations to only using std::string instead of char arrays and std::vector/list instead of arrays in c++? | I use vectors, lists, strings and wstrings obsessively in my code. Are there any catch 22s involved that should make me more interested in using arrays from time to time, chars and wchars instead?
Basically, if working in an environment which supports the standard template library is there any case using the primitive ... | For 99% of the time and for 99% of Standard Library implementations, you will find that std::vectors will be fast enough, and the convenience and safety you get from using them will more than outweigh any small performance cost.
For those very rare cases when you really need bare-metal code, you can treat a vector li... |
801,657 | 801,671 | Is Python faster and lighter than C++? | I've always thought that Python's advantages are code readibility and development speed, but time and memory usage were not as good as those of C++.
These stats struck me really hard.
What does your experience tell you about Python vs C++ time and memory usage?
| I think you're reading those stats incorrectly. They show that Python is up to about 400 times slower than C++ and with the exception of a single case, Python is more of a memory hog. When it comes to source size though, Python wins flat out.
My experiences with Python show the same definite trend that Python is on the... |
802,138 | 802,141 | How should you return *this with a shared_ptr? | See also: Similar question
The code below is obviously dangerous. The question is: how do you do keep track of the reference to *this?
using namespace boost;
// MyClass Definition
class MyClass {
public:
shared_ptr< OtherClass > createOtherClass() {
return shared_ptr< OtherClass > OtherClass( this ); // b... | The key is to extend enable_shared_from_this<T> and use the shared_from_this() method to get a shared_ptr to *this
For detailed information
using namespace boost;
// MyClass Definition
class MyClass : public enable_shared_from_this< MyClass > {
public:
shared_ptr< OtherClass> createOtherClass() {
return ... |
802,170 | 802,202 | How to use WMI to add an IP route? | I need to add a route into the IP4 routing table on windows xp.
However, the Win32_IP4RouteTable class seems to only be able to query existing routes.
Basically I need the same functionality as:
route ADD 192.168.127.254 MASK 255.255.255.255 192.168.1.10
Is it possible to use WMI to add an entry into the IP4 routing t... | Do you need solution on WMI only? I usually use IPHelper. Specifically, you need CreateIpForwardEntry function.
|
802,499 | 802,513 | How can I enumerate/list all installed applications in Windows XP? | When I say "installed application", I basically mean any application visible in [Control Panel]->[Add/Remove Programs].
I would prefer to do it in Python, but C or C++ is also fine.
| If you mean the list of installed applications that is shown in Add\Remove Programs in the control panel, you can find it in the registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall
more info about how the registry tree is structured can be found here.
You need to use the winreg API in ... |
802,656 | 802,955 | Is runtime stack kept in data segment of memory? | I'm very curious of the stack memory organization after I experiment what's going on in the background and obviously saw it's matching with tiny knowledge I acquired from books. Just wanted to check if what I've understood is correct.
I have a fundamental program -- has 2 functions, first one is foo and the other is ma... | A little caveat at the start: all of these answers are somewhat affected by the operating system and hardware architecture. Windows does things fairly radically differently from UNIX-like languages, real-time operating systems and old small-system UNIX.
But the basic answer as @Richie and @Paul have said, is "yes." W... |
802,706 | 803,229 | libraries/approaches for implementing object models in C++ | Apologies if this has been asked before, I'm not quite sure of the terminology or how to ask the question.
I'm wondering if there are libraries or best practices for implementing object models in C++. If I have a set of classes where instances of these classes can have relations to each other and can be accessed from e... | You wrote about storing objects from your object model inside std::vector etc. and problems with using pointers to them. That reminds me that it's good to divide your C++ classes into two categories (I'm not sure about terminology here):
Entity classes which represent objects that are part of your object model. They a... |
802,717 | 802,748 | Variables, Pointers, Objects and Memory Addresses: Why do I get this strange result? | After I thought that I've understood how they work, I tried this:
NSString *str1 = [NSString stringWithCString:"one"];
NSString *str2 = [NSString stringWithCString:"two"];
NSLog(@"str1: %x, %@", &str1, str1); //bfffd3cc, one
NSLog(@"str2: %x, %@", &str2, str2); //bfffd3c8, two
str1 = str2;
NSLog(@"str1: %x, %@", &str1... | Remember that a pointer variable is a variable itself, so it has an address. So &str1 results in the address of the pointer variable, and str1 is an expression that results in whatever the pointer variable is holding - the address of the object it's pointing to.
Assume that:
the object holding the NSString "one" is a... |
802,784 | 802,797 | References and auto_ptr | If I have a auto_ptr I can pass it for a reference?Like:
auto_ptr<MyClass>Class(new MyClass);
void SetOponent(MyClass& oponent);
//So I pass SetOponent(Class)
And what is odd copy behavior of auto_ptrs?
| No you can't, you would have to dereference it:
SetOponent( * Class )
As for the copying behaviour, I recommend you read a good book on C++, such as Effective C++ by Scott Meyers. The copying behaviour of auto_ptr is extremely un-intuitive and possibly beyond the scope of an SO answer. However, nothing ventured...
Whe... |
802,970 | 803,005 | How to build a Visual C++ Project for Linux? | What's the best and easiest way to build (for Linux) a C++ application which was written in Visual Studio? The code itself is ready - I used only cross-platform libs.
Is it possible to prepare everything under Windows in Visual Studio and then build it with a CLI tool under Linux? Are there any docs describing this?
E... | We're using CMake for Linux projects. CMake can generate KDevelop and Visual Studio project files, so you can just create your CMake file as the origin of platform-specific IDE files. The KDevelop generator is fine, so you can edit and compile in KDevelop (which will in turn call Make).
On the other hand, if you have n... |
803,088 | 922,895 | My qhttp get() call does not work on Windows but does on Linux | I have written a program that uses qhttp to get a webpage. This works fine on Linux, but does not work on my Windows box (Vista). It appears that the qhttp done signal is never received.
The relevant code is:
Window::Window()
{
http = new QHttp(this);
connect(http, SIGNAL(done(bool)), this, SLOT(httpDone(bo... | This should not happen at all, i.e. QHttp works reliably both on Windows and Unix.
My advice is to check whether the serves gives proper response. This can be done e.g. by verifying that data transfer is fine. You can trace the status from QHttp's signal, e.g. dataReadProgress, requestStarted, requestFinished, and oth... |
803,161 | 806,142 | Saving image to file with IImageEncoder | do you have a working code to share.
I’m trying to figure out how to save to a file an IBitmapImage image.
I need to resize existing .jpg file and it seems like the only API for Windows Mobile. I managed to load it convert it to IImage -> IBitmapImage -> IBasicBitmapOps and resize it finally, but I have no clue how t... | Use IBitmapImage::LockBits to get access to the image data via its BitmapData* lockedBitmapData parameter. Use the BitmapData to prepare a bitmap file info header, then write that one and the image data in BitmapData::Scan0 to a file using regular file writing with ::WriteFile or higher level ones if you use such.
|
803,391 | 803,436 | What are some good approaches to learning the Half-Life 2 SDK? | I have been a Half-Life lover for years. I have a BS in CS and have been informally programming since High-School. When I was still in college I tried to become a mod programmer for fun..using the first Half-Life engine...didn't work so good. So i figured after all my great college learrning :-) I would have more insig... |
the comments are few and far between
and the documentation seems meager.
Any good approahces?
Welcome to the wonder that is the Source SDK. No, it's not documented. Experiment, hack, place breakpoints and see what happens if you change bits of code.
There is a wiki you may find helpful in some cases, but it's fil... |
803,506 | 806,574 | How do I reference an external C++ namespace from within a nested one? | I have two namespaces defined in the default/"root" namespace, nsA and nsB. nsA has a sub-namespace, nsA::subA. When I try referencing a function that belongs to nsB, from inside of nsA::subA, I get an error:
undefined reference to `nsA::subA::nsB::theFunctionInNsB(...)'
Any ideas?
| Need more information to explain that error. The following code is fine:
#include <iostream>
namespace nsB {
void foo() { std::cout << "nsB\n";}
}
namespace nsA {
void foo() { std::cout << "nsA\n";}
namespace subA {
void foo() { std::cout << "nsA::subA\n";}
void bar() {
nsB::fo... |
804,123 | 804,131 | const unsigned char * to std::string | sqlite3_column_text returns a const unsigned char*, how do I convert this to a std::string? I've tried std::string(), but I get an error.
Code:
temp_doc.uuid = std::string(sqlite3_column_text(this->stmts.read_documents, 0));
Error:
1>.\storage_manager.cpp(109) : error C2440: '<function-style-cast>' : cannot convert fr... | You could try:
temp_doc.uuid = std::string(reinterpret_cast<const char*>(
sqlite3_column_text(this->stmts.read_documents, 0)
));
While std::string could have a constructor that takes const unsigned char*, apparently it does not.
Why not, then? You could have a look at this somewhat related question: Why do C++... |
804,217 | 804,269 | Function template declaration order affects visibility (sometimes) | I'm trying to create a function:
template <typename T>
void doIt( T*& p )
{
if ( !p ) { return; }
T& ref = *p;
getClassName( ref );
}
where the behavior varies according to the type of p passed in. In particular, the version of getClassName called should depend upon the type of p. In the following example, I ... |
Why is it required that getClassName( std::vector& ) appear before doIt but not getClassName( MyClass2T& )
A declaration in scope is required for any function. When you instantiate your template function with a vector<int> it expects a function with the signature getClassName(vector<int>&) to be present (at least a p... |
804,777 | 804,813 | Counting down in for-loops | I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++
I currently have this:
for (i=0; i<domain; ++i) {
my 'i' is unsigned resgister int,
also 'domain' is unsigned int
in the for-loop i is used for going through an array, e... | I'm guessing your backward for loop looks like this:
for (i = domain - 1; i >= 0; --i) {
In that case, because i is unsigned, it will always be greater than or equal to zero. When you decrement an unsigned variable that is equal to zero, it will wrap around to a very large number. The solution is either to make i sign... |
804,826 | 804,854 | Why does std::ends cause string comparison to fail? | I spent about 4 hours yesterday trying to fix this issue in my code. I simplified the problem to the example below.
The idea is to store a string in a stringstream ending with std::ends, then retrieve it later and compare it to the original string.
#include <sstream>
#include <iostream>
#include <string>
int main( int... | std::ends inserts a null character into the stream. Getting the content as a std::string will retain that null character and create a string with that null character at the respective positions.
So indeed a std::string can contain embedded null characters. The following std::string contents are different:
ABC
ABC\0
A ... |
805,110 | 805,130 | Inter-Thread Communication (and libraries?) | If have I have a game engine that has multiple threads that all work with one scene graph, what are techniques to ensure everything is synchronized whenever that scene graph changes?
What kind of libraries are out there to help with that?
Thanks!
| See this question for a list of availiable synchronization primitives. What you need to use depends on what your threads do. How many threads read the graph? How many modify the graph? Do they operate on the same part of the graph or on distinct parts? If you provide some more details, I can give further suggestions.
|
805,356 | 805,435 | Learning Graphical Layout Algorithms | During my day-to-day work, I tend to come across data that I want to visualize in a custom manner. For example, automatically creating a call graph similar to a UML sequence diagram, display digraphs, or visualizing data from a database (scatter plots, 3D contours, etc).
For graphs, I tend to use GraphViz. For UML-li... | Here are some sources,
Graphic Layout and Design (Paperback).
Active Layout Engine: Algorithms and Applications in Variable
Data Printing
|
805,403 | 805,490 | What are the rules of the std::cin object in C++? | I am writing a small program for my personal use to practice learning C++ and for its functionality, an MLA citation generator (I'm writing a large paper with tens of citations).
For lack of a better way to do it (I don't understand classes or using other .cpp files inside your main, so don't bother telling me, I'll wo... | What is happening here is that std::cin >> firstName; only reads up to but not including the first whitespace character, which includes the newline (or '\n') when you press enter, so when it gets to getline(std::cin, articleTitle);, '\n' is still the next character in std::cin, and getline() returns immediately.
// cin... |
805,413 | 805,578 | Restrict inheritance to desired number of classes at compile-time | We have a restriction that a class cannot act as a base-class for more than 7 classes.
Is there a way to enforce the above rule at compile-time?
I am aware of Andrew Koenig's Usable_Lock technique to prevent a class from being inherited but it would fail only when we try to instantiate the class. Can this not be done ... | I'm tired as crap, can barely keep my eyes open, so there's probably a more elegant way to do this, and I'm certainly not endorsing the bizarre idea that a Base should have at most seven subclasses.
// create a template class without a body, so all uses of it fail
template < typename D, typename B> class AllowedInherit... |
805,487 | 805,799 | Where to start with FastCGI and C++ | Anyone have any links or resource regarding writing a proper C++ FastCGI application? (on top of Apache using mod_fastcgi or mod_fcgid).
| The obvious one would be the FastCGI Development Kit (for C/C++).
|
805,691 | 832,973 | C++ FastCGI parsing POST requests in to various form fields | I am writing a C++ app on FastCGI using libfcgi++. When I do a POST or GET request, is there a library out there that would parse the different fields?
For example for a GET /fastcgi.fcgi?var1=data1&var2=data2 would return something that's easier to access var1 and var2?
Same for a multipart POST request.
| Looks like fastcgi++ might do the trick.
|
805,957 | 806,004 | FastCGI C++ vs. A Script Language (PHP/Python/Perl) | What are the ups and downs of using FastCGI C++ vs. PHP/Python/Perl to do the same job.
Any performance or design pitfalls or using one over the other? Even your opinions are welcome. (Tell me why one or the other rocks, or one or the other sucks).
| Several years ago, I more or less learned web app programming on the job. C was the main language I knew, so I wrote the (fairly large-scale) web app in C. Bad mistake. C's string handling and memory management is tedious, and together with my lack of experience in web apps, it quickly became a hard-to-maintain project... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.