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 |
|---|---|---|---|---|
1,990,963 | 1,990,971 | stuck at defining static pointer and using it | I stuck at defining a static pointer inside one of my class which is pointing to another class
here is the schema of what I've done :
#busineslogic.h
class BussinesLogic {
private :
static Samenamespace::otherclass_DataLogic::clsDL *DL;
};
#busineslogic.cpp
samenamespace {
businessnamespace{
clsBL{
Samenamesp... | // header:
#include <other/b.hpp>
namespace example {
struct A {
static other::B* name;
};
}
// implementation: (.cpp)
namespace example {
other::B* A::name;
}
Edit: With the cleanup of the question, it looks like B and A are in the same namespace, which would simplify the example:
// header:
#include <example/b.... |
1,991,065 | 1,991,076 | Role of C,C++,python,perl in Web development | Please bear with me experts i'm a newbie in web dev.
With html,css can take care of webpages..
javascript,ajax for some dynamic content..
php for server side scripting,accessing databases,sending emails,doing all other stuf...
What role do these programming languages play?
Can they do any other important task which can... | All languages can all do basically any task any other one of them can do, as they are all Turing complete.
PHP works as a server-side scripting language, but you can also use Perl, Python, Ruby, Haskell, Lisp, Java, C, C++, assembly, or pretty much any other language that can access standard input and standard output f... |
1,991,136 | 1,991,150 | How to teach Object Oriented Programming - Any idea where to start? | I'm teaching C++ for about 2 years in high schools, computer training institutes and etc. After teaching basics about variables, arrays, structures, functions, I always start object oriented examples part with traditional examples, like this one:
class Person {
public:
Person();
~Person();
char* getFirstName(); //... | I would start without code, with CRC cards. Let the class play out the cards roles, and do a real OO design session. There you can introduce the single responsibility principle, talk about has-a vs is-a and inheritance, encapsulation. I meet too many programmers who don't have a clue about OO and are still programming ... |
1,991,147 | 1,991,220 | Pure Virtual Function called error | I find this strange. In the ctor of Sample_Base, I call bar() which internally calls fun() which is a pure virtual function. I get the error "pure virtual function" called. Which is fine. Now, if I call fun() directly from Sample_Base's ctor, I don't get that error. I tried it on VC++ 2010 Beta 2 and on g++ 4.4.1 on Ub... | When you call the function directly, since you are in the constructor, the compiler resolves the static type of your object (Sample_Base) and calls Sample_Base::fun() directly. Since you provided an implementation for it, the compiler finds the function and it works.
When you call it indirectly, through bar(), the com... |
1,991,628 | 1,994,885 | Arduino web client class not working | I am trying to use the Arduino client class to fetch an HTML page from the Internet (example from the Arduino library itself), but it's not working (connection is not getting established).
It's failing at:
client.connect();
I have tried both Ethernet and Ethernet2 libraries.
My Arduino development platform version is ... | I don't know the reason but I had to modify the following setup() function to get the code working:
void setup() {
Ethernet.begin(mac, ip, gateway, mask);
Serial.begin(9600);
delay(1000);
Serial.println("connecting...");
for(int i = 0;i <100 ; i++) {
if (client.connect()) {
Serial.println("conn... |
1,991,713 | 1,991,834 | Using dynamic allocations in a mission-critical / life-critical software | Is it safe to use dynamic allocations in a mission-critical / life-critical system, or should it be avoided?
| With critical software you want your system to have as deterministic behaviour as possible.
Dynamic memory, memory fragmentation, possible leaks, and in some corner cases (not too rare) misbehaviour of malloc will make it that much harder to gain 100% determinism.
That said, if part of your program (say an algorithm) ... |
1,991,939 | 1,991,957 | Languages with direct C compatibilty | Apart from C++, which non-toy languages have direct or easy-to-use compatibility to C? As in "I can take a C library out there, and compile my code against it without having to find, write, or configure some kind of wrapper."
I know that lots of languages have compatibility with C through some form of external call o... | Objective-C, the bastard child of C and Smalltalk.
Objective-C is a direct superset of C (you can't get more compatible than that), but there are languages which compile to C. Some recent examples would be Vala and Lisaac.
Most statically compiled languages allow interfacing with C libraries. Examples of such languages... |
1,991,984 | 1,991,997 | Algorithm for finding the number which appears the most in a row - C++ | I need a help in making an algorithm for solving one problem: There is a row with numbers which appear different times in the row, and i need to find the number that appears the most and how many times it's in the row, ex:
1-1-5-1-3-7-2-1-8-9-1-2
That would be 1 and it appears 5 times.
The algorithm should be fast (th... | You could keep hash table and store a count of every element in that structure, like this
h[1] = 5
h[5] = 1
...
|
1,992,147 | 1,992,175 | Is there a C++ IDE which handles templates well? | Every IDE I've tried fails to provide code-completion when something template-related is used.
For example,
boost::shared_ptr<Object> ptr;
ptr->[cursor is here]
Is there IDE that can provide code completion in this case?
| Actually this is a fairly simple template use-case, Qt Creator can handle this easily and more complex template code aswell.
|
1,992,708 | 2,037,263 | How to make plugable factory work with lua? | class data is like this:
struct Base_data
{
public:
Base_data(){
protocolname = "Base";
}
string protocolname;
};
class HttpData : public Base_data
{
public:
HttpData(){
protocolname = "Http";
}
};
class Professor:
class Base_Professor
{
public:
void Process(Base_data &data)
... | Lua doesn't provide "classes" out-of-the-box. It has other features, somewhat different.
However you can simulate classes and inheritance functionality by using some of these functionalities (tables & metatables).
If you are not interested in knowing the technical details, you can use some already-built lua library.
I'... |
1,992,879 | 1,992,926 | C++/SDL 'void*' is not a point-to-object type | I'm new on C++ and I'm trying to make some testing with C++ and SDL and in SDL we have a function:
SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param);
which I can pass a callback for the timer created.
But apparently it converts my instance this to *void so I can't retrieve it again... | You don't need a reinterpret_cast - a static_cast should be OK:
Character * cp = static_cast <Character *>( param );
You should avoid reinterpret_cast - it is almost always implementation specific, and may hide problems - just like old-style C casts.
|
1,993,216 | 3,068,106 | boost::asio cleanly disconnecting | Sometimes boost::asio seems to disconnect before I want it to, i.e. before the server properly handles the disconnect. I'm not sure how this is possible because the client seems to think its fully sent the message, yet when the server emits the error its not even read the message header... During testing this only happ... | I think you should probably have a call to socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec) in there before the call to socket.close().
The boost::asio documentation for basic_stream_socket::close states:
For portable behaviour with respect to graceful closure of a connected socket, call shutdown() be... |
1,993,297 | 1,993,342 | Cygwin port not working => exits immediately on launch | I am trying to port a C++ program from Linux to Windows using cygwin. I have it building and linking fine now, but when I launch the program, it exits immediately with an error. When I try it in gdb, I get the following 'unknown target exception' result:
$ gdb ../../bin/ARCH.cygwin/release/myApp
GNU gdb 6.8.0.2008032... | Microsoft describes 0xC0000139 as STATUS_ENTRYPOINT_NOT_FOUND. That suggests your program isn't being linked properly. Double-check your build scripts to make sure it compiles and links all relevant files.
If you are using any libraries, then you might have a linking issue there (or maybe you are missing a DLL of some ... |
1,993,309 | 1,993,331 | Complete C++ "from scratch" frameworks | What C++ frameworks provide a complete skeleton, in the fashion of Ruby on Rails?
I think Poco C++ does it, are there other options?
| It's hard to provide a skeleton for client applications, because there is no common functionality like in the case of web applications. Qt does a pretty good job at providing what you might need in a new application though (yes, it does much more than just GUI).
|
1,993,356 | 1,993,421 | help with async_read_until | I'm having trouble implmenting the 3rd parameter in the function documented here:
http://www.boost.org/doc/libs/1_39_0/doc/html/boost_asio/reference/async_read_until/overload4.html
What I'd like to be able to do is use the callback on the 3rd parameter of async_read_until to detect when a complete chunk has arrived. My... | A sample match function is presented in the documentation.
std::pair<iterator, bool>
match_whitespace(iterator begin, iterator end)
{
iterator i = begin;
while (i != end)
if (std::isspace(*i++))
return std::make_pair(i, true);
return std::make_pair(i, false);
}
Dereferencing i here, pulls out one byte.... |
1,993,390 | 1,993,407 | Static linking vs dynamic linking | Are there any compelling performance reasons to choose static linking over dynamic linking or vice versa in certain situations? I've heard or read the following, but I don't know enough on the subject to vouch for its veracity.
1) The difference in runtime performance between static linking and dynamic linking is usual... |
Dynamic linking can reduce total resource consumption (if more than one process shares the same library (including the version in "the same", of course)). I believe this is the argument that drives its presence in most environments. Here "resources" include disk space, RAM, and cache space. Of course, if your dynamic ... |
1,993,391 | 1,994,132 | Boost numeric_cast<> with a default value instead of an exception? | Whenever boost's numeric_cast<> conversion fails, it throws an exception. Is there a similar template in boost that lets me specify a default value instead, or is catching the exception the only thing I can do in this case?
I'm not too worried about the performance of all the extra exception handling, but I'd rather us... | The numeric_cast function simply calls the boost::numeric::converter template class with the default arguments. One of the arguments is OverflowHandler, and the default value for that is def_overflow_handler, but you can specify silent_overflow_handler to suppress the exception instead.
Then specify the FloatToIntRound... |
1,993,431 | 1,993,457 | OpenGL: Rendering more than 8 lights, how? | How should I implement more than 8 lights in OpenGL?
I would like to render unlimited amounts of lights efficiently.
So, whats the preferred method for doing this?
| Deferred shading.
In a nutshell you render your scene without any lights. Instead you store the normals and world positions along with the textured pixels into multiple frame-buffers (so called render targets). You can even do this in a single pass if you use a multiple render-target extension.
Once you have your buffe... |
1,993,482 | 1,993,523 | Compiler error in declaring template friend class within a template class | I have been trying to implement my own linked list class for didactic purposes.
I specified the "List" class as friend inside the Iterator declaration, but it doesn't seem to compile.
These are the interfaces of the 3 classes I've used:
Node.h:
#define null (Node<T> *) 0
template <class T>
class Node {
public:
T ... | try adding a forward declaration
template <class T> class List;
at the start of Iterator.h -- that might be what you need to allow the friend declaration inside the Iterator class to work.
|
1,993,621 | 1,993,714 | compilation error about exceptions | I met some compilation error but do not know what the problem is. The code seems not use exception, but the error is about it.
//in misc.h:
char *basename(char *name); // line 94
// in misc.cc:
char *basename(char *name) { // line 12
char *result = name;
while(*name) {
if(*name == '/') result = name + 1;... | You may be picking up the definition of basename() from libgen.h. On my OpenSUSE system, the version in libgen.h is defined with "throw ()" at the end (via the __THROW macro).
One thing you can try is to tell gcc to only run the preprocessor stage by adding the -E flag and then search for basename to see what is being... |
1,993,682 | 1,994,108 | Why does my QGraphicsView not showing up in my MainWindow in Qt4? | This is probably something very obvious, but I have a new to Qt and can't figure it out. I have a simple MainWindow which has one button. When that button is clicked I want to create a QGraphicsScene, add a few lines and then show that in the Window. However when I run this code in a Window it does not show up.
BUT, i... | your QGraphicsView needs a centralwidget of the mainwindow (or whatever widget you want to put it on top of) to be set as a parent. Also you need to "new" your view and scene objects to put them on the heap so they don't get destroyed once drawScene finishes. See of following changes to your code would work fine for yo... |
1,993,738 | 1,993,754 | malloc Error in specific makefile | I have a software, code of which I have modified and run make again.
If I run the modified code in a black QtCreator project it runs well (nothing specific to Qt, just an example), but if I compile with software's original makefile, I get error on a line as:
(*F)=(double**) malloc((size_arr)*sizeof(double*));
Not in c... | Probably F is NULL or pointing to an invalid memory location. Since F gets dereferenced on the left side of the assignment, it needs to be properly initialized, so that it points to a memory location that can store the double** returned by malloc.
|
1,993,907 | 1,993,912 | What is 'v' in vtable? | What does v indicate in vtable or vptr
| The 'v' stands for 'Virtual'.
|
1,994,186 | 1,994,384 | Casting between integers and pointers in C++ | #include<iostream>
using namespace std;
int main()
{
int *p,*c;
p=(int*)10;
c=(int*)20;
cout<<(int)p<<(int)c;
}
Somebody asked me "What is wrong with the above code?" and I couldn't figure it out. Someone please help me.
| Some wanted a quote from the C++ standard (I'd have put this in the comments of that answer if the format of comments wasn't so restricted), here are two from the 1999 one:
5.2.10/3
The mapping performed by reinterpret_cast is implementation defined.
5.2.10/5
A value of integral type or enumeration type can be expli... |
1,994,258 | 1,994,276 | Resolving ambiguous calls in C++ with namespaces | I'm merging a static library (assimp) into an existing project (Spring RTS) where both the library and the project are under regular development. I'm trying to add the library in such a way that I can easily repeat the integration as new releases come out.
Anyway, the issue is that Spring requires the library to perfor... | If you only need the min function from the streflop namespace, you can use
using streflop::min;
instead of
using namespace streflop;
This will import only the name min, not the whole namespace.
Your error is because what you are doing imports every name from the streflop namespace so that they can be used unqualified... |
1,994,374 | 1,994,452 | Passing a Delegate as Callback to a Native C++ API Call | Could someone point me whats wrong with this code please? I'm having a very hard experience in mixing C++ and MC++. I have read a lot of blogs and tutorial regarding this subject (passing delegates) but now that looks my code is ok (its compiling and runs well when in debug mode and step by step) it crashs.
The main pr... | your are declaring the pin_ptr on the managed heap and then you pass it to an un-managed function
all the managed references to this pointer are inside CWaveIn::Open(int currentInputDeviceId)
so I guess the GC sees no reason to keep this object after CWaveIn::Open exits.
try to create it in the class scope instea... |
1,994,649 | 1,995,013 | Windows network packet modification | I'm looking to write a small program which will intercept network packets (on the local machine) and modify them before they go out on the network. I need to be able to modify the headers as well, not just the data.
I've already looked through several possibilities but am unsure which one is best to pursue. There are o... | Depends what kind of packets do you want to filter/modify.
If you're after application-level filtering, and want to get your hands on HTTP or similar packets, your best bet would probably be an LSP. Note however, following this path has certain disadvantages. First MS seems to be trying to get rid of this technology, a... |
1,994,676 | 1,994,722 | Hooking DirectX EndScene from an injected DLL | I want to detour EndScene from an arbitrary DirectX 9 application to create a small overlay. As an example, you could take the frame counter overlay of FRAPS, which is shown in games when activated.
I know the following methods to do this:
Creating a new d3d9.dll, which is then copied to the games path. Since the curr... | You install a system wide hook. (SetWindowsHookEx) With this done, you get to be loaded into every process.
Now when the hook is called, you look for a loaded d3d9.dll.
If one is loaded, you create a temporary D3D9 object, and walk the vtable to get the address of the EndScene method.
Then you can patch the EndScene ca... |
1,994,841 | 1,994,857 | Initialising C structures in C++ code | Is there a better way to initialise C structures in C++ code?
I can use initialiser lists at the variable declaration point; however, this isn't that useful if all arguments are not known at compile time, or if I'm not declaring a local/global instance, eg:
Legacy C code which declares the struct, and also has API's us... | If you can't add a constructor (which is the best solution in C++03 but you probably have compatibility constraint with C), you can write a function with the same effect:
MyStruct makeAMyStruct(int x, int y, int z)
{
MyStruct result = { x, y, z };
return result;
}
items.push_back(makeAMyStruct(5,rand()%100,ite... |
1,994,910 | 1,994,917 | convert Class member callback from __stdcall to DWORD_PTR | I'm trying to use a class member as a callback but the compiler gives me the following error:
Error 2 error C2440: 'type cast' : cannot convert from 'void (__stdcall CWaveIn::* )(HWAVEIN,UINT,DWORD_PTR,DWORD_PTR,DWORD_PTR)' to 'DWORD_PTR'
Is it possible to use a member function as a callback this way? and how do I co... | You cannot directly pass in class methods.
This is the right way :
class CWaveIn
{
private:
static void CALLBACK staticWaveInProc(HWAVEIN hwi, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR dwParam1, DWORD_PTR dwParam2)
{
CWaveIn* pThis = reinterpret_cast<CWaveIn*>( dwParam1 );
pThis->WaveInProc( ..... |
1,994,970 | 1,995,712 | C++ - Failed loading a data file ! | I have a simple data file that I want to load, in a C++ program. For weird reasons, it doesn't work:
I tried it on Windows assuming the file was in the same directory: failed.
I tried it on Windows by moving the file in C:\ directory: worked.
I tried it on Linux putting the file in the same directory: failed.
The sni... | The problem is the working directory.
When you specify a relative path for a file it uses the working directory (which may not be the same as the directory where you application is stored on the file system).
Thus you either need to use an absolute path.
Or you need to find the current working directory and specify th... |
1,995,051 | 1,995,058 | While(1) in constructor or using threads? | Is it recommed to put a while loop, which never ends in a constructor? Or should I use threads to get the same result?
Is it good when a constructor never terminates? Or is it more secure to avoid segmentation faults?
Hope you understand my bad English..
| An object does not exist if its constructor does not finish. So putting a while(1) loop in a constructor will prevent objects being created using that constructor. You need to describe what problem you think doing this will solve.
|
1,995,053 | 1,995,057 | const char* concatenation | I need to concatenate two const chars like these:
const char *one = "Hello ";
const char *two = "World";
How might I go about doing that?
I am passed these char*s from a third-party library with a C interface so I can't simply use std::string instead.
| In your example one and two are char pointers, pointing to char constants. You cannot change the char constants pointed to by these pointers. So anything like:
strcat(one,two); // append string two to string one.
will not work. Instead you should have a separate variable(char array) to hold the result. Something like ... |
1,995,062 | 1,995,084 | Why can't I run my OpenGL program outside of Visual Studio? | I have an OpenGL-program using GLSL, that I can run just fine with the Play-button in Visual Studio (2008) -- both in the standard Release and Debug configurations.
However, when I try to run the executable from Explorer, all I get is a flashing cmd-prompt with no text in it to indicate any kind of failure loading some... | Have you tried checking the paths of any external resources. The run button in Visual Studio will by default run the program with a different working directory than if you use explorer.
The other thing you should do is try adding some logging, (even just writing text to stderr at critical points). That way you can see,... |
1,995,109 | 1,995,131 | Why use string::iterator rather than index? |
Possible Duplicate:
Why use iterators instead of array indices?
string::iterator it;
for (it = str.begin(); it < str.end(); it++)
cout << *it;
cout << endl;
Why not:
for (int i = 0; i < str.size(); i++)
cout << str[i];
cout << endl;
It seems that string::iterator does not provide range check either. Why s... | The index can only be used for containers that support random access - direct access to a given position.
The iterator offers a unified way to access any collection/data structure. The flexibility when refactoring your code is immense.
|
1,995,269 | 1,995,287 | My Function chain doesn't want to work, why? | I have the following class:
GLRectangle.h
#include "XPView.h"
class GLRectangle
{
public:
int top, left, bottom, right;
public:
GLRectangle(void);
~GLRectangle(void);
GLRectangle* centerRect(int rectWidth, int rectHeight, int boundWidth=0, int boundHeight=0);
};
GLRectangle.cpp
#include "GLRectangle.... | It's an operator precedence problem. Try
// Add some brackets
wndRect = (new GLRectangle())->centerRect(400, 160);
|
1,995,290 | 1,995,322 | Should I make my functions as general as possible? | template<class T>
void swap(T &a, T &b)
{
T t;
t = a;
a = b;
b = t;
}
replace
void swap(int &a, int &b)
{
int t;
t = a;
a = b;
b = t;
}
This is the simplest example I could come up with,but there should be many other complicated functions.Should I make all methods I write templated ... | Genericity has the advantage of being reusable. However, write things generic, only if:
It doesn't take much more time to do that, than do it non-generic
It doesn't complicate the code more than a non-generic solution
You know will benefit from it later
However, know your standard library. The case you presented is a... |
1,995,311 | 1,995,621 | Drawing Text On Window | I want to make chat application and for the first step, I need to know which API there is to use to display text in lines and also erase if needed. thanks!
| Charles Petzold's classic book Programming Windows is one of the best ways to learn the Win32 API.
|
1,995,328 | 2,031,708 | Are there any better methods to do permutation of string? | void permute(string elems, int mid, int end)
{
static int count;
if (mid == end) {
cout << ++count << " : " << elems << endl;
return ;
}
else {
for (int i = mid; i <= end; i++) {
swap(elems, mid, i);
permute(elems, mid + 1, end);
swap(elems, mid, i... | Here is a non-recursive algorithm in C++ from the Wikipedia entry for unordered generation of permutations. For the string s of length n, for any k from 0 to n! - 1 inclusive, the following modifies s to provide a unique permutation (that is, different from those generated for any other k value on that range). To gener... |
1,995,495 | 1,995,513 | What are static variables? | What are static variables designed for? What's the difference between static int and int?
| The static keyword has four separate uses, only two of which are closely related:
static at global and namespace scope (applied to both variables and functions) means internal linkage
this is replaced by unnamed namespaces and is unrelated to the rest
in particular, others tend to imply some sort of uniqueness, but ... |
1,995,546 | 1,995,601 | linking objective c++ | I am trying to figure out why when I convert my main.m file to a main.mm file, it no longer will link properly.
I have reduces the problem to the following example code:
#import <Foundation/Foundation.h>
#import <AppKit/AppKit.h>
int main( int argc, const char ** argv ) {
return NSApplicationMain( argc, argv);
}
I am ... | The problem is that when you compile it as C++, the compiler mangles the name of the symbol NSApplicationMain, so it can't find it, since it's looking for something like __Z17NSApplicationMainiPPKc. You can use the nm program (from binutils) to see what symbols the object files are referencing:
$ # When compiled as Ob... |
1,995,554 | 2,127,821 | An Optimum 2D Data Structure | I've given this a lot of thought but haven't really been able to come up with something.
Suppose I want a m X n collection of elements sortable by any column and any row in under O(m*n), and also the ability to insert or delete a row in O(m+n) or less... is it possible?
What I've come up with is a linked-grid, where th... | I would create two index arrays, one for the columns, and one for the rows. So for your data
1 100 25 34
2 20 15 16
3 165 1 27
You create two arrays:
cols = [0, 1, 2, 3]
rows = [0, 1, 2]
Then when you want to sort the matrix by the 3rd row, you keep the original matrix intact, but just change the indices array ... |
1,995,734 | 1,995,979 | How are exceptions implemented under the hood? | Just about everyone uses them, but many, including me simply take it for granted that they just work.
I am looking for high-quality material. Languages I use are: Java, C, C#, Python, C++, so these are of most interest to me.
Now, C++ is probably a good place to start since you can throw anything in that language.
Als... | Exceptions are just a specific example of a more general case of advanced non-local flow control constructs. Other examples are:
notifications (a generalization of exceptions, originally from some old Lisp object system, now implemented in e.g. CommonLisp and Ioke),
continuations (a more structured form of GOTO, popu... |
1,995,744 | 1,995,780 | C++ (C3867) Passing a member function to a function call | I'm trying to pass a member function as an argument. Basically I have a class called AboutWindow, and the header looks as this (trimmed for brevity):
class AboutWindow
{
private:
AboutWindow(void);
~AboutWindow(void);
public:
int AboutWindowCallback(XPWidgetMessage inMessage, XPWidgetID inWidget, long inPa... | I assume you're using x-plane here.
Unfortunately XPAddWidgetCallback expects a callback in the form of
int callback(XPWidgetMessage inMessage, XPWidgetID inWidget,
long inParam1, long inParam2)
You provided a class member function. It would work if this were a global function. So this :
class AboutWindo... |
1,995,963 | 2,001,251 | Is (1 + sqrt(2))^2 = 3 + 2*sqrt(2) satisfied in Floating Point arithmetics? | In mathematics the identity (1 + sqrt(2))^2 = 3 + 2*sqrt(2) holds true. But in floating point (IEEE 754, using single precision i.e. 32 bits) calculations it's not the case, as sqrt(2) doesn't have an exact representation in binary.
So does using a approximated value of sqrt(2) provide different results for left and r... | This identity happens to hold when computed as written in IEEE-754 double precision. Here's why:
The square root of two correctly rounded to double precision is:
sqrt(2) = 0x1.6a09e667f3bcd * 2^0
(I'm using hexadecimal here because the representations are tidier, and the translation into the IEEE754 format is much ea... |
1,996,548 | 1,996,586 | segmentation fault in overloading operator = | I just got a seg fault in overloading the assignment operator for a class FeatureRandomCounts, which has _rects as its pointer member pointing to an array of FeatureCount and size rhs._dim, and whose other date members are non-pointers:
FeatureRandomCounts & FeatureRandomCounts::operator=(const FeatureRandomCounts &rh... | As mentioned, you have infinite recursion; however, to add to that, here's a foolproof way to implement op=:
struct T {
T(T const& other);
T& operator=(T copy) {
swap(*this, copy);
return *this;
}
friend void swap(T& a, T& b);
};
Write a correct copy ctor and swap, and exception safety and all edge cas... |
1,996,703 | 2,005,516 | Specializing a template by a template base class | I'm writing a template for which I'm trying to provide a specialization on a class which itself is a template class. When using it I'm actually instanciating it with derivitives of the templated class, so I have something like this:
template<typename T> struct Arg
{
static inline const size_t Size(const T* arg) { r... | I think there are three approaches:
1) Specialize Arg for derived types:
template <typename T> struct Arg ...
template <> struct Arg <IntArg> ...
template <> struct Arg <FloatArg> ...
// and so on ...
This sucks, because you can't know in advance what types you will have. Of course you you can specialize once you have... |
1,996,867 | 1,996,888 | Controlling access to output in multi-threaded applications | I have an application that creates a job queue, and then multiple threads execute the jobs. By execute them, I mean they call system() with the job string.
The problem is that output to stdout looks like the output at the bottom of the question. I would like each application run to be separated, so the output would loo... | Rather than using system().. you could use popen().
Then, read from each child's output in the parent program, and do what you want with it (e.g. synchronize on some mutex when outputting each line).
|
1,997,119 | 1,997,256 | View function template instantiations | I have a simple function template:
#include <iostream>
using namespace std;
template <class T>
T GetMax (T a, T b) {
T result;
result = (a > b) ? a : b;
return (result);
}
int main () {
cout << GetMax<int>(5, 6) << endl;
cout << GetMax<long>(10, 5) << endl;
return 0;
}
The above example will generate 2 f... | You can use the nm program (part of binutils) to see the list of symbols used by your program. For example:
$ g++ test.cc -o test
$ nm test | grep GetMax
00002ef0 T __Z6GetMaxIiET_S0_S0_
00002f5c T __Z6GetMaxIiET_S0_S0_.eh
00002f17 T __Z6GetMaxIlET_S0_S0_
00002f80 T __Z6GetMaxIlET_S0_S0_.eh
I don't know why each one ... |
1,997,778 | 1,997,788 | C++ comparing c string troubles | I have written the following code which will does not work but the second snippet will when I change it.
int main( int argc, char *argv[] )
{
if( argv[ 1 ] == "-i" ) //This is what does not work
//Do Something
}
But if I write the code like so this will work.
int main( int argc, char *argv[] )
{
string opti... |
Is it because the string class has == as an overloaded member and hence can perform this action?
You are correct. Regular values of type char * do not have overloaded operators. To compare C strings,
if (strcmp(argv[1], "-i") == 0) {
...
}
By comparing the strings the way you did (with == directly), you are comp... |
1,998,094 | 1,998,421 | Java JNI - associating resources allocated in C with java objects? | I want to allocate some memory in C and keep it associated with a java object instance, like this:
void configure(JNIEnv *object, jobject obj, ....) {
char *buf = new char[1024];
// associated <buf> with <obj> somehow
}
And then later free the memory when the java object gets garbage collected - I could do this by... | Generally, if you want to transfer a pointer from C to Java, it's recommended to use long so that there are enough bits to hold the pointer value in case the platform is 64 bits.
Then, have a look at ByteBuffer.allocateDirect() which creates a ByteBuffer instance which memory can be shared with C. You can allocate such... |
1,998,207 | 1,998,231 | Defining global array | I have the following static array in header file:
static MyStruct_t MyStructArray[] = {
......
......
......
}
But gcc issues a warning:
warning: `MyStructArray' defined but not used
What is the correct way to handle the situation?
UPD:
Defining the array as const:
const MyStruct_t MyStructArray[] = ... | Because you've declared the array static in a header file, each compilation unit (i.e. preprocessed .cpp file) gets its own copy of the array--almost certainly not what you intended, and the sure reason that you get the "defined but not used" error.
Instead, you probably want this in your header file:
extern MyStruct_t... |
1,998,251 | 1,998,344 | Basic C++ memory question | a friend of mine declared a new type using
typedef GLfloat vec3_t[3];
and later used vec3_t to allocate memory
vertices=new vec3_t[num_xyz* num_frames];
He freed the memory using
delete [] vertices;
Question:
1. Since vec3_t is an alias for GLfloat[3], does it mean that
vec3_t[num_xyz* num_frames]
is equivalent to... | 1. a two dimensional array can be thoght of as a one dimensional array where each element is an array.
using this definition you can see that new vec3_t[num_xyz* num_frames] is equivalent to a two dimensional array.
2. this array is made of num_xyz* num_frames members each taking a space of sizeof (vec3_t)
when n... |
1,998,632 | 1,999,004 | Invoke PostgreSQL Stored Procedure using C | I am referring to http://www.postgresql.org/docs/8.1/static/libpq.html
I try to find an example of C/C++ to call PostgreSQL stored procedure. However, I cannot find one. Can anyone point me the right direction?
| As as previously been answered, the easiest way is to use SELECT myStoredProcedure(1,2,3). You can also use the fast-path call interface to call a function directly. See http://www.postgresql.org/docs/current/static/libpq-fastpath.html for reference. But note that if you are working on modern versions of PostgreSQL, yo... |
1,998,744 | 1,998,883 | Benefits of a swap function? | Browsing through some C++ questions I have often seen comments that a STL-friendly class should implement a swap function (usually as a friend.) Can someone explain what benefits this brings, how the STL fits into this and why this function should be implemented as a friend?
| For most classes, the default swap is fine, however, the default swap is not optimal in all cases. The most common example of this would be a class using the Pointer to Implementation idiom. Where as with the default swap a large amount of memory would get copied, is you specialized swap, you could speed it up signific... |
1,998,752 | 2,000,646 | memset() or value initialization to zero out a struct? | In Win32 API programming it's typical to use C structs with multiple fields. Usually only a couple of them have meaningful values and all others have to be zeroed out. This can be achieved in either of the two ways:
STRUCT theStruct;
memset( &theStruct, 0, sizeof( STRUCT ) );
or
STRUCT theStruct = {};
The second vari... | Those two constructs a very different in their meaning. The first one uses a memset function, which is intended to set a buffer of memory to certain value. The second to initialize an object. Let me explain it with a bit of code:
Lets assume you have a structure that has members only of POD types ("Plain Old Data" - se... |
1,998,926 | 1,999,957 | mfc autosuggest textbox (like in Windows Start->Run dialog) | In Windows XP if you click Start, Run (or Windows-key + R) you get a little dialog for running things directly. If you start typing, a resizable scroll-list pops up underneath the edit-box.
I want something similar, so when a user is typing in a name to an edit-box, a list will suddenly appear if suggestions can be ma... | I'm currently looking at this one: http://www.codeproject.com/KB/combobox/akautocomplete.aspx Will try to remember to post my findings.
|
1,999,049 | 1,999,072 | c++ identify current thread in function? | let's say i have a singleton object with a static function:
static int MySingletonObject::getInt()
now i would like to return a different int depending on which workingthread (MFC threading) is calling the function.
I know that i can pass parameters to the threadingfunction when creating the thread. But Is there a way... | You can call GetCurrentThreadId() - will return an integer identifier - or GetCurrentThread() - will return a handle which can be cast to an integer identifier - from any thread - those values will be unique for any thread within the process.
|
1,999,150 | 1,999,210 | Is it possible to have identically named source files in one visual studio c++ project? | I'm working on a static library project for a c++ course I'm taking. The teacher insists that we define only one function per source file, grouping files/functions belonging to the same class in subdirectories for each class. This results in a structure like:
MyClass
\MyClass.cc (constructor)
\functionForMyClas... | You are right, by default all object files are put into the same directory and their filenames are based on the source file name. The only solution I can think of is to change conflicting file's output file path in here:
Project Properties-C/C++-Output Files-Object File Name http://img37.imageshack.us/img37/3695/output... |
1,999,348 | 1,999,371 | Pointers or references for dynamically allocated members that always exist? | I have a class CContainer that has some members CMemberX, CMemberY, which are independent of each other and other CClientA, CClientB classes that use CContainer.
#include "MemberX.h"
#include "MemberY.h"
class CContainer
{
public:
CMemberX & GetX() const { return m_x; }
CMemberY & GetY() const { return m_y; }
... | I think that's what the const variables are for:
CMember * const m_x;
Cannot change m_x after initialization...
|
1,999,706 | 1,999,817 | C++/POSIX how to get a millisecond time-stamp the most efficient way? | I'm using a open-source library for i2c bus actions. This library frequently uses a function to obtain an actual time-stamp with millisecond resolution.
Example Call:
nowtime = timer_nowtime();
while ((i2c_CheckBit(dev) == true) && ((timer_nowtime() - nowtime) < I2C_TIMEOUT));
The application using this i2c library u... | Its clear that your example call uses most CPU time in timer_nowtime() function. You are polling, and the loop eats your CPU time. You could exchange the timer function with a better alternative and so you may achieve more loop iterations, but it will still use most CPU time in that function! You will not achieve using... |
1,999,967 | 2,000,033 | Odd socket() error -- returns -1, but errno=ERROR_SUCCESS | I'm developing a dedicated game server on a linux machine, in C/C++ (mixed). I have the following snippet of code:
int sockfd=socket(AI_INET, SOCK_DGRAM, 0);
if(sockfd==-1)
{
int err=errno;
fprintf(stderr,"%s",strerror(err));
exit(1);
}
My problem here, is that socket is returning -1 (implying a failure) a... | I feel incredibly stupid. Carefully looking over my code, on my dev-computer shows:
if(sockfd==-1);
...
|
2,001,141 | 2,001,169 | Why doesn't g++ link with the dynamic library I create? | I've been trying to make some applications which all rely on the same library, and dynamic libraries were my first thought: So I began writing the "Library":
/* ThinFS.h */
class FileSystem {
public:
static void create_container(string file_name); //Creates a new container
};
/* ThinFS.cpp */
#include "ThinFS.h"... | -lfoo looks for a library called libfoo.a (static) or libfoo.so (shared) in the current library path, so to create the library, you need to use g++ -shared -fPIC FileSystem.cpp -o libThinFS.so
|
2,001,203 | 2,001,371 | Referencing an unmanaged C++ project within another unmanaged C++ project in Visual Studio 2008 | I am working on a neural network project that requires me to work with C++. I am working with the Flood Neural Network library. I am trying to use a neural network library in an unmanaged C++ project that I am developing. My goal is to create an instance of a class object within the Flood library from within another pr... | Yes. You need to do two things:
#include the respective header files, as you did
Add a reference (Visual C++ supports two types, "dependencies" which are outdated and should not be used anymore, and "references" which are the correct ones). Use them to reference the other project, which must be a part of your solutio... |
2,001,215 | 2,001,423 | STL algorithms on containers of boost::function objects | I have the following code that uses a for loop and I would like to use transform, or at least for_each instead, but I can't see how.
typedef std::list<boost::function<void(void) > CallbackList;
CallbackList callbacks_;
//...
for(OptionsMap::const_iterator itr = options.begin(); itr != options.end(); ++itr)
{
callba... | To do all this in a single transform call, you I think you need to call bind on itself, because you need a functor which calls boost:bind. That's something I've never attempted. Would you settle for something like this (untested)?
struct GetFunc {
ClassOutput *obj;
boost::function<void(void) > operator()(const ... |
2,001,286 | 2,001,307 | const char* 's in C++ | How does string expressions in C++ work?
Consider:
#include <iostream>
using namespace std;
int main(int argc, char *argv[]){
const char *tmp="hey";
delete [] tmp;
return 0;
}
Where and how is the "hey" expression stored and why is there segmentation fault when I attempt to delete it?
| Where it's stored is left to the compiler to decide in this (somewhat special) case. However, it doesn't really matter to you - if you don't allocate memory with new, it's not very nice to attempt to deallocate it with delete. You cannot delete memory allocated in the way you have allocated it.
If you want to control... |
2,001,354 | 2,003,522 | How can MATLAB function wavread() be implemented in C++? | How do I implement the MATLAB function wavread in C++?
It means read a WAV file into a vector array.
| If you want to do it in C++, there are two options. Use a library, or write your own function that can extract information from WAV files. Several C/C++ libraries such as Juce, SDL etc. have functions/classes that can read WAV files. This is probably total overkill for your case. If you want a simple(ish) library speci... |
2,001,604 | 2,001,784 | Class member function as callback using boost::bind and boost::function | I'm working through setting up a member function as a callback for a C-library that I'm using. The C-library sets up callbacks like this:
typedef int (*functionPointer_t)(myType1_t*, myType2_t*, myType3_t*);
setCallback(param1, param2, functionPointer, param4)
I would like to use boost::bind (if possible) to pass in ... | No. Functor types like boost::function don't convert to function pointers for use with C callback mechanisms.
However, most C callback mechanisms have some kind of token mechanism, so your callback function (which is static) has some kind of context information. You can use this to write a wrapper class which maps thes... |
2,001,913 | 2,002,038 | C++0x memory model and speculative loads/stores | So I was reading about the memory model that is part of the upcoming C++0x standard. However, I'm a bit confused about some of the restrictions for what the compiler is allowed to do, specifically about speculative loads and stores.
To start with, some of the relevant stuff:
Hans Boehm's pages about threads and the mem... | I'm not familiar with all the stuff you refer to, but notice that in the y==2 case, in the first bit of code, x is not written to at all (or read, for that matter). In the second bit of code, it is written twice. This is more of a difference than just writing once vs. writing twice (at least, it is in existing threadin... |
2,002,282 | 2,002,342 | C++ std::queue::pop() calls destructor. What of pointer types? | I have a std::queue that is wrapped as a templated class to make a thread-safe queue. I have two versions of this class: one that stores value types, one that stores pointer types.
For the pointer type, I'm having trouble deleting the elements of the queue on destruction. The reason is that I don't know a way to remove... | Online sources are worth what you pay for them - get a proper reference like Josuttis's book. pop() does not "call the destructor" - it simply removes an element from the queue adaptor's underlying representation (by default a std::deque) by calling pop_front() on it. If the thing being popped has a destructor, it wil... |
2,002,509 | 2,002,536 | Is it possible to refresh two lines of text at once using something like a CR? (C++) | Right now, I have a console application I'm working on, which is supposed to display and update information to the console at a given interval. The problem I'm having is that with a carriage return, I can only update one line of text at a time. If I use a newline, the old line can no longer be updated using a carriage ... | You might be able to find a curses library variant that works on your platform.
|
2,002,567 | 2,002,585 | Array of pointers member, is it initialized? | If I have a
class A
{
private:
Widget* widgets[5];
};
Is it guaranteed that all pointers are NULL, or do I need to initialize them in the constructor? Is it true for all compilers?
Thanks.
| It depends on the platform and how you allocate or declare instances of A. If it's on the stack or heap, you need to explicitly initialize it. If it's with placement new and a custom allocator that initializes memory to zero or you declare an instance at file scope AND the platform has the null pointer constant be bitw... |
2,002,752 | 2,002,972 | What will happen to namespace tr1 when c++ xx is approved? | I'm writing some stuff using the tr1 namespace in VS2008. What will happen when C++xx becomes ratified? Has this happened before with other C++ revisions? Will the tr1 stuff still work or will I have to change all of my include? I realize that I'm making the very large assumption that this ratification will someday occ... | std::tr1 will become part of std in C++1x (std::tr1::shared_ptr becomes std::shared_ptr, etc). std::tr1 will continue to exist as long as that compiler claims to implement TR1. At some point your compiler may drop that claim, and drop std::tr1 as a result. This probably will never happen.
std::tr1 has already been "cop... |
2,002,792 | 2,068,395 | OpenGL: Enabling multisampling draws messed up edges for polygons at high zoom levels | When im using this following code:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 6);
and then i enable multisampling, i notice that my program no longer cares about the max mip level.
Edit: It renders the last miplevels as well, that is the problem, i dont want them being rendered.
Edit3:
I tested and confirmed... | Ok. So the problem was not TEXTURE_MAX_LEVEL after all. Funny how a simple test helped figure that out.
I had 2 theories that were about the LOD being picked differently, and both of those seem to be disproved by the solid color test.
Onto a third theory then. If I understand correctly your scene, you have a model that... |
2,002,947 | 2,004,727 | Why is my call to TransmitFile performing poorly compared to other methods? | First, a bit of background --
I am writing a basic FTP server for a personal project. I'm currently working on retrieving files. My current implementation looks like this:
HANDLE hFile = CreateFile("file.tar.gz", GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
TransmitFile(sd, hFile, f... | Have you increased the socket's TCP buffer size (and potentially the TCP window size) by setting the the SO_SNDBUF and SO_RCVBUF socket options before you start transmitting? (do it after bind and before connecting)?
From the sound of the problem, faster start which then slows down, I'd guess at it being a TCP flow con... |
2,003,255 | 2,004,027 | Why the std::swap of Bits in a std::bitset instance doesn't work? | In the following example i expected the swap of the bits. Instead the second bit becomes overwritten, but why and how could i achieve the expected behavior?
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
bitset<2> test(string("10"));
cout << test; // Prints "10"
... | This is pure nasty. First we have to look at the declaration of swap:
template<class T>
void swap(T &left, T &right);
Now, operator[]() on bitset has two overloads:
bool operator[](size_type _Pos) const;
reference operator[](size_type _Pos);
Here reference is bitset::reference, a nested class in bitset that effective... |
2,003,266 | 2,004,287 | C++ explicit constructors and iterators | Consider the following code:
#include <vector>
struct A
{
explicit A(int i_) : i(i_) {}
int i;
};
int main()
{
std::vector<int> ints;
std::vector<A> As(ints.begin(), ints.end());
}
Should the above compile? My feeling is that it should not, due to the constructor being marked explicit.
Microsoft Visu... | I looked through GCC's STL implementation and it should have similar behavior. Here's why.
Elements of a vector are initialized by a generic function template which accepts any two types X and V and calls new( p ) X( v ) where v is a V (I'm paraphrasing a bit). This allows explicit conversion.
Elements of a set or map... |
2,003,395 | 2,188,476 | Finding boost::shared_ptr cyclic references | Is there any tips/tricks for finding cyclic references of shared_ptr's?
This is an exmaple of what I'm trying to find - unfortunately I can't seem to find the loop in my code.
struct A
{
boost::shared_ptr<C> anC;
};
struct B
{
boost::shared_ptr<A> anA;
};
struct C
{
boost::shared_ptr<B> anB;
};
| I used a combination of the above posts. I used a memory profiler, came up with some suspected cycles and broke those by using weak_ptr's.
I've used the built in CRT memory leak detection before, but unfortunately in my case there are several static singletons that dont get deallocated until module unload which I beli... |
2,003,506 | 2,055,958 | How to build a boost dependent project using regular makefiles? | I'm working on a c++ project, and we recently needed to include a small part of boost in it. The boost part is really minimal (Boost::Python), thus, using bjam to build everything looks like an overkill (besides, everyone working on the project feels comfortable with make, and has no knowloedge of jam).
I made quite so... | I had the same problem and found a solution in this tutorial. You 1) need to compile the source into an object file with the -fPIC gcc option, and 2) compile this object into a library with the -shared gcc option. Of course you have also to link against the Boost.Python library (generally -lboost_python, however for m... |
2,003,756 | 2,010,979 | nginx not forwarding POST to @fallback | I wrote a high-performance HTTP event server in C++ and I want to make it work flawlessly with nginx and PHP-FPM (fastcgi). This is a snippet of my nginx configuration.
location ~ \.eve$ {
gzip off;
proxy_redirect off;
proxy_buffering off;
proxy_pass http://127.0.0.1:9001;
pr... | I fixed the problem by simply rebuilding the most recent version of nginx. The config, as well as the POST and GET forwarding works perfectly. Weirdness.
|
2,003,895 | 2,003,920 | In C++ what causes an assignment to evaluate as true or false when used in a control structure? | So can someone help me grasp all the (or most of the relevant) situations of an assignment inside something like an if(...) or while(...), etc?
What I mean is like:
if(a = b)
or
while(a = &c)
{
}
etc...
When will it evaluate as true, and when will it evaluate as false? Does this change at all depending on the types u... | In C++ an attribution evaluates to the value being attributed:
int c = 5; // evaluates to 5, as you can see if you print it out
float pi = CalculatePi(); // evaluates to the result
// of the call to the CalculatePi function
So, you statements:
if (a = b) { }
while (a = &c) { }
are roughly eq... |
2,003,963 | 2,004,011 | MSVC and FreeGlut Compiler Error | Receiving alot of these messages when compiling which is making compiling a simple program very time consuming.
freeglut_static.lib(freeglut_callbacks.obj) : warning LNK4204: 'z:\CST328\Lab1\block\Release\vc90.pdb' is missing debugging information for referencing module; linking object as if no debug info
1>freeglut_st... | your pdb file is out of sync with the library binary
in Windows, the pdb holds the debug information for a module. it is linked to a particular build. if your rebuild your library you have to produce a new pdb file. the pdb file your have is out of sync so you either have to delete (or rename) it (find a file freegl... |
2,004,035 | 2,004,069 | Design alternative? Composition and construction | So I'm using composition to bring together a collection of objects, all of which are derived from a base class, lets say Component. E.g:
class Component {
public:
Component();
...
private:
int m_address;
...
};
class SpecializedComponent: public Component {
public:
SpecializedComponent()
... //and so on
};... | Component could have a constructor with one argument that initializes m_address.
|
2,004,089 | 2,004,104 | When using variable length argument lists (...), can you do anything besides step forward through va_list? | If each invocation of va_arg modifies the object declared with va_list so that the object points to the next argument in the list, is there any way to step back so that it points to the previous one, jump back to the first one, jump to the end? Go three quarters of the way though the list and then... you get the idea. ... | You can "jump back" to the beginning by executing va_start again. There is no other supported operation other than going on to the next argument.
However, most implementations use trivial pointer arithmetic. If you guarantee the code runs only on a particular architecture, then you can do the reverse of the arithmeti... |
2,004,323 | 2,004,330 | Is there any way I can find how many objects are instantiated from stack and how many objects from Heap | Is there any way I can find how many objects are instantiated from stack and how many objects from Heap. I don't wish to have the restrictions of scoping in objects from Stack.
If i use a static counter in constructor and destructor, it will be called in both the cases(object from stack and heap). One way is to exploit... | Override operator new and operator delete for the class. Have another counter there that is incremented/decremented in these operators. This will keep track of objects created on the heap. The constructor/destructor can increment/decrement another counter that will count all objects. The difference between the two is t... |
2,004,419 | 2,004,459 | How to check if a link exists or not in VC++? | I have a link. I have checked that the link is a valid URL through regular expressions. Now, I want to check if the link is a valid http link or not. i.e. it should not be a non-existing link.
Is there a way in VC++ 6.0 (MFC) to check that?
| One option is to try to get data from that URL by using the URLOpenBlockingStream function.
Example:
#include <Urlmon.h>
IStream* pStream = NULL;
if (SUCCEEDED(URLOpenBlockingStream(0, "URL string", &pStream, 0, 0))) {
// Release the stream immediately since we don't use the data.
pStream->Release();
retur... |
2,004,743 | 2,004,796 | different type of instantiating on c++ | since I've came from c# to c++ everything looks crazy for me in c++.
I just wondering If someone could explain me why do we have these kind of instantiating in c++ :
method 1:
ClassA obj1; // this is going to stack
method 2:
ClassA *obj1 = new ClassA(); //this is going to heap
whereas we don't have the common instant... | Indeed moving to C++ from a language like Java or C# can be daunting, I've gone through it as well.
The first and foremost difference is that in C++ you almost always manage your own memory. When creating an object on the heap you are responsible for deleting it so it does not leak memory - this in turn means you can ... |
2,004,808 | 2,006,360 | boost-test application initialisation | I'm just getting stated with boost-test and unit testing in general with a new application, and I am not sure how to handle the applications initialisation (eg loading config files, connecting to a database, starting an embedded python interpretor, etc).
I want to test this initialisation process, and also most of the ... | It seems what you intent to do is more integration test than unit-test. It's not to pinpoint on wording, but it makes a difference. Unit testing mean testing methods in isolation, in an environment called a fixture, created just for one test, end then deleted. Another instance of the fixture will be re-created if the n... |
2,004,820 | 2,005,142 | Inherit interfaces which share a method name | There are two base classes have same function name. I want to inherit both of them, and over ride each method differently. How can I do that with separate declaration and definition (instead of defining in the class definition)?
#include <cstdio>
class Interface1{
public:
virtual void Name() = 0;
};
class Inte... | This problem doesn't come up very often. The solution I'm familiar with was designed by Doug McIlroy and appears in Bjarne Stroustrup's books (presented in both Design & Evolution of C++ section 12.8 and The C++ Programming Language section 25.6). According to the discussion in Design & Evolution, there was a proposa... |
2,004,952 | 2,005,216 | How to set Native Microsoft compiler for VS 2003 if Intel Compiler is default compiler? | I am using a development environment with VS 2003 as IDE and Intel compiler as default compiler. I have to set Microsoft default compiler for compilation of my project. As I could not find where to set the compiler in VS 2003.
Thanks
Anil
| You cannot set the compiler explicitly, VS simply runs cl.exe. Windows tries to find a file named cl.exe to start, it searches the directories listed in the PATH environment variable. You do explicitly set which directories are in the PATH.
Not sure about VS2003, 2005 and up uses Tools + Options, Projects and Solutio... |
2,005,005 | 2,015,953 | C++ - global setlocale works, the same locale passed to _vsnprintf_l doesn't | I have following C++ code sample:
void SetVaArgs(const char* fmt, const va_list argList)
{
setlocale( LC_ALL, "C" );
// 1
m_FormatBufferLen = ::_vsnprintf(m_FormatBuffer, Logger::MAX_LOGMESSAGE_SIZE, fmt, argList);
setlocale( LC_ALL, "" );
//2
m_FormatBufferLen = ::_vsnprintf(m_FormatBuffer, Logger::MAX... | It turned out to be a CRT bug in VS2005 and above (2008 and 2010). Submitted to Microsoft here: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=523503#details
Bug applies to _sprintf_l, _vsnprintf_l, _sprintf_s_l, _vsnprintf_s_l and possibly other relatives.
|
2,005,075 | 2,582,882 | Add Exception to firewall on Mac either during installation of application or when application is launched | I have a client - server application, where I want to add a exception to firewall so that my applications can communicate properly.
I want to add add an exception to the firewall (without changing the setup for the other firewalls options).
I am using Carbon, Qt, C++. However, I feel this has more to do with some insta... | I'm not sure this is would be good practice without notifying the user or asking the user for permission. Since osx has a built in system for creating application signing and the user must explicitly enable this level of security.
That being said, you should have a look at
/usr/libexec/ApplicationFirewall/socketfilterf... |
2,005,385 | 2,031,790 | Qt app text size incorrect under MacOSX | Designing UIs with QtCreator under Windows, and porting the same .ui file under MacOSX leads to designs with some text parts very small -- actually, the HTML ones. It seems it comes from the fact that QtCreator uses pt instead of px as text size unit, and that the default screen resolutions are quite different under Wi... | As a rule of thumb you should not specify the font sizes for controls manually in Qt Designer/Creator as this leads to the prolems you have. The reason for inconsistency is the fact that different platforms use different DPI settings (96 dpi on Windows vs. 72 DPI on Mac OS X).
This results in fonts being displayed with... |
2,005,426 | 2,007,380 | Message queuing solutions? | (Edited to try to explain better)
We have an agent, written in C++ for Win32. It needs to periodically post information to a server. It must support disconnected operation. That is: the client doesn't always have a connection to the server.
Note: This is for communication between an agent running on desktop PCs, to com... | How is your current solution showing its age?
I would push the logic on to the back end, and make the clients extremely simple.
Messages are simply stored in the file system. Have the client write to c:/queue/{uuid}.tmp. When the file is written, rename it to c:/queue/{uuid}.msg. This makes writing messages to the que... |
2,005,596 | 2,007,777 | Quartz display services replacement for deprecated functions? | The Quartz display services reference manual lists several functions as deprecated, (for example CGDisplayCurrentMode), but doesn't mention what the replacement function is.
What should I be using to find information about the current video mode?
Is there a way to find out this kind of information? The reference manua... | I think CGDisplayCopyDisplayMode() looks like the replacement. It is new in 10.6.
http://developer.apple.com/mac/library/documentation/Carbon/Reference/ApplicationServicesRefUpdate/Articles/ApplicationServices_10.5-10.6_SymbolChanges.html#//apple_ref/doc/uid/TP40009185-SW41
|
2,006,146 | 2,006,260 | Linking MTL (Matrix Template Library) in Visual Studio | I have MTL header files; I want to use those header files in Visual Studio 2008. How can I link those header files so that I can write a matrix program using the MTL library?
| Maybe you're referring to how to tell the IDE to notice them? In that case, you can simply add them in a directory to your project. In VS, right-click the project, select Properties. Go to Configuration Properties -> C/C++ -> General. Add the MTL directory, and any sub-directory, to the Additional Include Directories f... |
2,006,225 | 2,006,406 | Getting location of file tnsnames.ora by code | How can I get the location of the tnsnames.ora file by code, in a machine with the Oracle client installed?
Is there a windows registry key indicating the location of this file?
| Some years ago I had the same problem.
Back then I had to support Oracle 9 and 10 so the code only takes care of those versions, but maybe it saves you from some research.
The idea is to:
search the registry to determine the oracle client version
try to find the ORACLE_HOME
finally get the tnsnames from HOME
public ... |
2,006,402 | 2,006,553 | Compiling CUDA examples gives build error | I am running Windows 7 64bit, with Visual Studio 2008. I installed the CUDA drivers and SDK. The SDK comes with quite a few examples including compiled executables and source code. The compiled executables run wonderfully. When I open the vc90 solutions and go to build in Win32 configuration I get this error:
Error ... | Check if you have x64 compiler installed. Then change project type to x64. I had the same problem when trying to compile 32bit cuda program with 64bit win7.
Also make sure you have added 64bit libs and includes to the search path.
|
2,006,627 | 2,006,652 | Print Hexadecimal Numbers Of a File At C And C++ | I'm now developing a home project, but before I start, I need to know how can I printcout the content of a file(*.bin as example) in hexadecimal?
I like to learn, then a good tutorial is very nice too ;-)
Remember that I need to develop this, without using external applications, because this home project is to learn mo... | To print hex:
std::cout << std::hex << 123 << std::endl;
but yes, use the od tool :-)
A good file reading/writing tutorial is here. You will have to read the file into a buffer then loop over each byte/word of the file.
|
2,006,634 | 2,006,759 | Compiling Qt app agains latest VC++ 2008 runtime | Hi I have a problem compiling my Qt app with Visual studio 2008 SP1.
For the sake of purity I created a windows XP virtual machine, installed VS 2008, then SP1 and then compiled Qt 4.6. Now from looking at the manifest of the Qt DLLs (using XN Resource Editor) I can see that they depends on 9.0.21022.8 CRT.
But at the ... | This should fix it: App does not run with VS 2008 SP1 DLLs, previous version works with RTM versions
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.