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 |
|---|---|---|---|---|
2,810,232 | 2,810,738 | Unwanted debug session | Try this code I created,when I use it in Borland C++ and try the remove-function a debug session opens up and it points to a file called "xstring",and it is saying "EAccessViolation".
it points to this line in the file:
return (compare(0, _Mysize, _Right._Myptr(), _Right.size()));
//--------------------------------... | do a break; after l.erase(it);
iterator becomes invalid you incremante it by it++ check against it != l.end() succeds
(*it).name is used for comparison but is invalid and causes exception
|
2,810,280 | 2,810,339 | How to store a 64 bit integer in two 32 bit integers and convert back again | I'm pretty sure its just a matter of some bitwise operations, I'm just not entirely sure of exactly what I should be doing, and all searches return back "64 bit vs 32 bit".
| Use a union and get rid of the bit-operations:
<stdint.h> // for int32_t, int64_t
union {
int64_t big;
struct {
int32_t x;
int32_t y;
};
};
assert(&y == &x + sizeof(x));
simple as that. big consists of both x and y.
|
2,810,297 | 2,810,409 | How to handle server-client requests | Currently I'm working on a Server-Client system which will be the backbone of my application.
I have to find the best way to send requests and handle them on the server-side.
The server-side should be able to handle requests like this one:
getPortfolio -i 2 -d all
In an old project I decided to send such a request a... | To me it seems you're having two different questions.
For the socket part, I suggest you use Beej's guide to socket programming if you want to have full control about what you do. If you don't want to/don't have the time to treat this part yourself, you can just use a C++ socket library as well. There are plenty of the... |
2,810,530 | 2,810,561 | hiding inner class implementation using namespace | I am developing a library and a would like to provide my users a public interface separate from the real implementation that is hidden in a namespace. This way, I could change only the class HiddenQueue without changing myQueue that will be exposed to users only.
If I put the C++ code of HiddenQueue in the myQueue.cpp... | The compiler needs to know the exact memory layout of an object by looking at the header file it's defined in.
Your code says that class MyQueue has a member of type InnerQueue, which will be part of the memory layout of MyQueue objects. Therefore, to deduce the memory layout of MyQueue it needs to know the memory layo... |
2,810,887 | 2,810,924 | Win32 Event vs Semaphore | Basically I need a replacement for Condition Variable and SleepConditionVariableCS because it only support Vista and UP. (For C++)
Some suggested to use Semaphore, I also found CreateEvent.
Basically, I need to have on thread waiting on WaitForSingleObject, until something one or more others thread tell me there is som... | In your case I'd use an event myself. Signal the event when you want the thread to get going. Job done :)
Edit: The difference between semaphores and events comes down to the internal count. If there are multiple ReleaseSemaphores then 2 WaitForSingleObjects will also be released. Events are boolean by nature. If ... |
2,810,933 | 2,812,331 | template expressions and visual studio 2005 c++ | I'd like to build the olb3d library with my visual studio 2005 compiler but this failes due to template errors.
To be more specific, the following expression seem to be a problem:
void function(T u[Lattice<T>::d])
On the website of the project is stated that prpably my compiler is not capable of such complicated templ... | The compiler says that it cannot deduce the template type. You can always help it out by specifying the type itself in your code.
foo<int>(some_int_array);
However, the part between [] that is tripping it up is completely meaningless. Arrays decay into pointers and the value is ignored in the first place. You can just... |
2,811,130 | 2,812,999 | Is there any reason against directly calling AddRef() inside QueryInterface() implementation? | When implementing IUnknown::QueryInterface() in C++ there're several caveats with pointers manipulation. For example, when the class implements several interfaces (multiple inheritance) explicit upcasts are necessary:
class CMyClass : public IInterface1, public IInterface2 {
};
//inside CMyClass::QueryInterface():
i... | AddRef is pure virtual in IUnknown, and none of the other interfaces implement it, so the only implementation in your program is the one you write in CMyClass. That one method overrides both IInterface1::AddRef and IInterface2::AddRef. IUnknown doesn't have any data members (such as a reference count), so the diamond p... |
2,811,541 | 2,817,496 | Gethostname and IPv6 | Microsoft recommends not to use 'gethostname' on IPv6 and instead use 'getaddrinfo' or 'getnameinfo'.
http://msdn.microsoft.com/en-us/library/ms899604.aspx
But 'gethostname' doesn't seem to have any problem working on IPv6. Does anyone know any reason why 'gethostname' is not recommended on IPv6?
| The main different is the maximum host name length, gethostname() allows 255+1 characters, getnameinfo() supports the full DNS length of 1024+1. If you are using technologies like puny code host names this becomes more pertinent. Other differences are that you are not guaranteed a FQDN when using gethostname().
http:... |
2,811,596 | 2,811,859 | Embedding Python and adding C functions to the interpreter | I'm currently writing an applications that embedds the python interpreter. The idea is to have the program call user specified scripts on certain events in the program. I managed this part but now I want the scripts to be able to call functions in my program.
Here's my code so far:
#include "python.h"
static PyObject... | You need to bind that function to some module, see http://docs.python.org/extending/embedding.html#extending-embedded-python
Edit:
Basicly your code should work. Whats not working?
|
2,811,747 | 2,811,843 | boost doesn't bind to member function even using this | I am trying to use boost::bind with a boost::function using this.
It seems a trivial example but I cannot make it work. Can you help me?
Is it because it is not allowed or am I doing something wrong?
// .h
class MyClass{
publc:
void DoSomething(
const std::string& a,
const std::string& b);
void... | I think you want bind(&MyClass::DoSomething, this, _1, _2). I don't have a boost installation to test with though.
|
2,812,079 | 2,812,137 | Compile a shared library statically | I've got a shared library with some homemade functions, which I compile into my other programs, but I have to link the end program with all the libraries I have used to compile the static library. Here is an example:
I have function foo in the library which requires a function from another library libbar.so.
In my main... | Shared objects (.so) aren't libraries, they are objects. You can't extract part of them and insert it in other libraries.
What you can do if build a shared object which references the other -- but the other will be needed at run time. Just add the -lbar when linking libfoo.
If you are able to build libbar, you can ob... |
2,812,215 | 2,812,248 | Preprocessor directive #ifndef for C/C++ code | In eclipse, whenever I create a new C++ class, or C header file, I get the following type of structure. Say I create header file example.h, I get this:
/*Comments*/
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
/* Place to put all of my definitions etc. */
#endif
I think ifndef is saying that if EXAMPLE_H_ isn't defined, def... | This is a common construct. The intent is to include the contents of the header file in the translation unit only once, even if the physical header file is included more than once. This can happen, for example, if you include the header directly in your source file, and it's also indirectly included via another header.... |
2,812,338 | 27,240,116 | Reverse PInvoke and create a full unmanaged C# program | I know this is a strange question but the idea is simple: I prefer C# syntax rather than C++:
-Setters and getters directly inside a property
-interfaces
-foreach statement
-possibility to declare an implicit cast operator
other small things...
What I really don't know is if is possible to import a c++ dll (expecially ... | There's now something close to this
.NET Native compiles C# to native machine code that performs like C++. You will continue to benefit from the productivity and familiarity of the .NET Framework with the great performance of native code.
It's for Windows Store apps only (desktop apps may come in the future):
Deskt... |
2,812,470 | 2,812,501 | Why does GCC need extra declarations in templates when VS does not? | template<typename T>
class Base
{
protected:
Base() {}
T& get() { return t; }
T t;
};
template<typename T>
class Derived : public Base<T>
{
public:
Base<T>::get; // Line A
Base<T>::t; // Line B
void foo() { t = 4; get(); }
};
int main() { return 0; }
If... | GCC is right in this case, and Visual Studio mistakenly accepts a malformed program. Have a look at the section on Name lookup in the GCC manual. Paraphrasing:
[T]he call to [get()] is not dependent on template arguments (there are no arguments that depend on the type T, and it is also not otherwise specified that the... |
2,812,544 | 2,812,586 | C++ Beginner - Trouble using structs and constants! | I am currently working on a simple Scrabble implementation for a college project.
I can't get a part of it to work, though!
Check this out:
My board.h:
http://pastebin.com/J9t8VvvB
The subroutine where the error lies:
//Following snippet contained in board.cpp
//I believe the function is self-explanatory...
//Pos is a ... | #define TOTAL_ROWS 15;
#define TOTAL_COLUMNS 15;
Theses are preprocessor definitions, which must not end in a semicolon. The semicolon will become part of the substitution text, so the compiler sees something like (65 + 15;) which is clearly wrong.
In C++, it is better to use const variables instead of #defines. In th... |
2,812,760 | 2,812,774 | print TCHAR[] on console | I'm quite sure that it is a stupid issue but it drives me crazy..
how could i print on the console a TCHAR array?
DWORD error = WSAGetLastError();
TCHAR errmsg[512];
int ret = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, error, 0, errmsg, 511, NULL);
i need to print errmsg...
| It depends on what TCHAR is. If you compile with Unicode enabled, TCHAR is defined as wchar_t. Then you can use std::wcout, for example:
std::wcout << L"Error: " << errmsg << '\n';
If Unicode is not enabled, TCHAR is an ordinary char and you can use the ordinary std::cout:
std::cout << "Error: " << errmsg << '\n';
|
2,812,875 | 2,812,903 | how const keyword works in c | I want to know about const internals in c and c++ . How compiler imposes constantness ?
Can some one help me please.
| In general const is 100% compiler. When you declare something const, the compiler places restrictions on what it will let you write. It won't let you assign to const scalar, assign through a const reference or or pointer, or invoke a non-const function of const object.
There is no guarantee that the compiler will arran... |
2,812,959 | 2,813,000 | How does the where clause in MySQL work? | I have a doubt. Assume R and S are 2 relations with attributes A and B respectively . If I have a query
Select *
From R, S
Where R.A = S.B
Does this work like a double For Loop in say c or c++
For( i=0; i<n; i++)
For( j=0; j<n; j++)
if (i == j)
//DO some work
| First of all: there is no knowing how mysql will internally optimize the query (without knowing the internals of mysql).
In pure relational databases words, this is what you are doing:
SELECT * FROM R, S -> perform cross join, that generates all (r,s) tuples.
WHERE R.A = S.B -> now select those tuples that have this be... |
2,813,030 | 2,813,107 | yaml-cpp parsing strings | Is it possible to parse YAML formatted strings with yaml-cpp?
There isn't a YAML::Parser::Parser(std::string&) constructor. (I'm getting a YAML string via libcurl from a http-server.)
| Try using a stringstream:
std::string s = "name: YAML from libcurl";
std::stringstream ss(s);
YAML::Parser parser(ss);
|
2,813,045 | 2,813,437 | How to get rid of OCI.dll dependency when compiling static | My application accesses an Oracle database through Qt's QSqlDatabase class.
I'm compiling Qt as static for the release build, but I can't seem to be able to get rid of OCI.dll dependency. I'm trying to link against oci.lib (as available in Oracle's Instant Client with SDK).
Here's my configure line :
configure -qt-libj... | The .lib file you linked is not what you think it is. It is the import library for the DLL, the linker needs it so it knows what functions are implemented by oci.dll. I don't see a static version of the library available from Oracle but didn't look too hard. That's pretty typical for dbase interfaces.
You'll need to... |
2,813,190 | 2,813,361 | Beginner C++ - Trouble using global constants in a header file | Yet another Scrabble project question... This is a simple one.
It seems I am having trouble getting my global constants recognized:
My board.h:
http://pastebin.com/7a5Uyvb8
Errors returned:
1>C:\Users\Francisco\Documents\FEUP\1A2S\PROG\projecto3\projecto3\Board.h(34): error: variable "TOTAL_ROWS" is not a type name... | The way that is written, you are defining a function called _matrix that returns a vector. So TOTAL_ROWS is expected to be a type name, since it is being parsed as a paramter type. I assume what you are trying to do is define a variable called _matrix that is a vector.
What you want to do is leave off the construct... |
2,813,283 | 2,813,620 | Invalid Argument to getUInt64 when retrieving LAST_INSERT_ID() | I have added a record to my table which auto-increments the primary key. I am having no luck retrieving this new value. The MySQL documents say to use the SELECT LAST_INSERT_ID(); in a query. I have done this, but can't retrieve the results.
According the the metadata of the result set, the data type is BIGINT and... | Resolved.
I inserted a query_results->next() before retrieving the data and that worked.
|
2,813,672 | 3,891,586 | gcov and switch statements | I'm running gcov over some C code with a switch statement. I've written test cases to cover every possible path through that switch statement, but it still reports a branch in the switch statement as not taken and less than 100% on the "Taken at least once" stat.
Here's some sample code to demonstrate:
#include "stdio.... | I'm using mingw on windows (which is not the latest gcc) and it looks like this may be sorted out in newer versions of gcc.
|
2,813,970 | 2,814,023 | How to modify Keyboard interrupt (under Windows XP) from a C++ Program? |
We have been given a little project (As part of my OS course) to make a Windows program that modifies keyboard input, so that it transforms any lowercase character entered into an uppercase one (without using caps-lock) ! so when you type on the keyboard you'll see what you're typing transformed into uppercase !
I ha... | You can't get access to the Keyboard ISR unless you write a Ring 0 device driver. You are better off investigating the Windows Hook APIs. These accomplish the same thing.
Start here: http://msdn.microsoft.com/en-us/library/ms644990%28v=VS.85%29.aspx
|
2,814,013 | 2,814,892 | Double Free inside of a destructor upon adding to a vector | Hey, I am working on a drum machine, and am having problems with vectors.
Each Sequence has a list of samples, and the samples are ordered in a vector. However, when a sample is push_back on the vector, the sample's destructor is called, and results in a double free error.
Here is the Sample creation code:
class XSam... | The problem is you are dynamically allocating memory in your object but not declaring a copy constructor/ assignment operator. When you allocate memory and are responsible for deleting it you need to define all FOUR methods that the compiler generates.
class XSample
{
public:
// Pointer inside a class.
... |
2,814,164 | 2,814,284 | Differences between Static & Dynamic data structures | What are the main differences, advantages and disadvantages between static and dynamic data structures?
Under which categories do the most common data structures fall?
How could I know in which situation to use each?
| To start with an oversimplification:
There are just a few basic kinds of data structures: arrays, lists and trees. Everything else can be composed by using different types of these two structures (e.g. a hash table can be implemented with an array for the hash values and one list for each hash value to handle collision... |
2,814,188 | 2,814,216 | C++ Array of pointers: delete or delete []? | Cosider the following code:
class Foo
{
Monster* monsters[6];
Foo()
{
for (int i = 0; i < 6; i++)
{
monsters[i] = new Monster();
}
}
virtual ~Foo();
}
What is the correct destructor?
this:
Foo::~Foo()
{
delete [] monsters;
}
or this:
Foo::~Foo()
{
for ... | delete[] monsters;
Is incorrect because monsters isn't a pointer to a dynamically allocated array, it is an array of pointers. As a class member it will be destroyed automatically when the class instance is destroyed.
Your other implementation is the correct one as the pointers in the array do point to dynamically allo... |
2,814,347 | 2,814,584 | How to take snapshot in linux - programmatically C++ | I am currently involved in a project which requires me to repeatedly take snapshots of the screen. I am using qt's grabScreen function to do the same.
The screen freezes for half a second every time the program takes a snapshot causing the computer to seem to be very slow :(
Can anybody suggest me a better method of do... | You could look at the source of, say, ksnapshot which is the Qt-based KDE app doing this. Its SVN archive is here.
|
2,814,512 | 2,814,620 | Understanding C++ pointers (when they point to a pointer) | I think I understand references and pointers pretty well. Here is what I (think I) know:
int i = 5; //i is a primitive type, the value is 5, i do not know the address.
int *ptr; //a pointer to an int. i have no way if knowing the value yet.
ptr = &i; //now i have an address for the value of i (called ptr)
*ptr = 10;... | A few comments:
*ptr = 10; // Doesn't need to "go get" the value. Just overwrites it.
Also:
char **char_ptrs = new char *[50];
Node **node_ptrs = new Node *[50];
It is easier to think that you have two arrays. However, technically (and as far as the compiler is concerned) what you have is two pointers. One is a point... |
2,814,582 | 2,814,706 | Newbie: Render RGB to GTK widget -- howto? | Big picture: I want to render an RGB image via GTK on a linux box.
I'm a frustrated GTK newbie, so please forgive me.
I assume that I should create a Drawable_area in which to render the image -- correct?
Do I then have to create a graphics context attached to that area? How?
my simple app (which doesn't even address... | You should go through the scribble tutorial at least ( http://library.gnome.org/devel/gtk-tutorial/stable/c2422.html ), if not the larger tutorial of which this a part.
Since you tagged your question c++, I'd recommend using gtkmm, you'll find it much easier to develop in if you already know C++ pretty well. There is... |
2,814,779 | 2,814,845 | Program crashes in debugger before anything happens | I'm building an application for Windows XP using the MinGW tool chain and it sometimes crashes unexpectedly. So, I'm trying to use a debugger (Gdb) but the program exits with code 03 before anything happens. In fact, all I see from GDB is:
[New thread 3184.0x7b8][New thread
3184.0xef8]
Program exited with code 03.
... | Add a callback via signal(SIGABRT, <callback>) to catch the call to abort before it shuts down the process. If this happens before you hit main() you might have to resort to a static global and compiler trickery to catch it.
|
2,814,798 | 2,814,856 | OpenGL constant don't exist | I haven't got GL_GENERATE_MIPMAP_HINT, GL_GENERATE_MIPMAP constatns, why ? I have old version of opengl ? Where can I download new library version ?
| From here: http://www.opengl.org/wiki/Getting_started#OpenGL_2.0.2B_and_extensions
For Linux: http://www.opengl.org/registry/api/glext.h
For GLX: http://www.opengl.org/registry/api/glxext.h
For Windows: http://www.opengl.org/registry/api/wglext.h
|
2,814,858 | 2,814,923 | Select all points in a matrix within 30m of another point | So if you look at my other posts, it's no surprise I'm building a robot that can collect data in a forest, and stick it on a map. We have algorithms that can detect tree centers and trunk diameters and can stick them on a cartesian XY plane.
We're planning to use certain 'key' trees as natural landmarks for localizing... | The simple solution of calculating all the distances and scanning through seems to run almost instantaneously:
lim = 1;
num_trees = 1000;
trees = randn(num_trees,2); %# list of trees as Nx2 matrix
cur = randn(1,2); %# current point as 1x2 vector
dists = hypot(trees(:,1) - cur(1), trees(:,2) - cur(2)); %# distance from... |
2,815,317 | 2,815,363 | Launch IE with specific BHO enabled | I have a IE BHO plugin that I only want to be enabled when the user launches IE from my program (The program starts IE using CreateProcess()).
I don't want this BHO to be enabled when a user launches IE from outside my program, as that would mean any problems in the BHO could potentially mess up the user's normal brows... | Your approach is very error-prone, I advise against it. Instead, your BHO should always load with IE, but by default it should do nothing. What you need then is a way to tell it "start filtering" or "start recording" or whatever.
You've got lots of choices from there. The simplest is a flag somewhere in the environment... |
2,815,320 | 2,815,330 | run a function every x seconds in c++ | I'm trying to build a feed reader in C++, so I need the program to check for new feeds intermittently. However, the user needs still to be able to interact with the program, so the suggestion that I seem to keep finding, to have the system wait, doesn't work for me. Can anyone suggest a better solution, say a timer tha... | You can create a thread that sleeps for the specific time period. This is OS independent. Or, if you are programming in windows, you can set a timer to send a timeout event periodically. The use of timers depends on your deployment platform.
|
2,815,589 | 2,815,626 | operator "new" returning a non-local heap pointer for only one class? | Language : C++
Platform : Windows Server 2003
I have an exe calling a DLL.
EDIT :
(exe is not doing anything, it calls few global function which does everything related to DLL within DLL. It does not explicitly new any of DLL classes)
I allocate (new) the memory for class A within the DLL, it returns me a non-local he... | Export only global functions from DLLs and call only exported functions and through v-tables. Your problem is only one of many caused by trying to export entire classes. DLLs aren't the same as .so libraries.
EDIT: Since the question now reveals that the class isn't exported, but all of this is observed inside the si... |
2,815,667 | 2,826,761 | libmcrypt and MS Visual C++ | Has anyone tried using libmcrypt and visual c++? I was trying to use Crypto++ but it seems not fully compatible - and I need to decrypt data encrypted in PHP using linux libmcrypt.
I found only cygwin version of libmcrypt but no .lib files or header.
I'm using RIJNDAEL_128 - maybe there is easier way to decrypt it in V... | I finally found a working libmcrypt version compatible with Visual Studio
It is here http://files.edin.dk/php/win32/mcrypt/dev/ and worked correctly.
|
2,815,746 | 2,815,918 | Formatting an integer in C++ | I have an 8 digit integer which I would like to print formatted like this:
XXX-XX-XXX
I would like to use a function that takes an int and returns a string.
What's a good way to do this?
| This is how I'd do it, personally. Might not be the fastest way of solving the problem, and definitely not as reusable as egrunin's function, but it strikes me as both clean and easy to understand. I'll throw it in the ring as an alternative to the mathier and loopier solutions.
#include <sstream>
#include <string>
#... |
2,815,792 | 2,815,907 | How do I get started on a bigger project? | Most of the time I have been programming little apps either for myself or for the benifit of learning. Now that my programming skills are considered somewhat intermediate, I was wondering how I would tackle a large programming project.
Lets suppose I wanted to make an application that has a lot of features and is inten... | Although Steve has a good recommendation, I think that answer is probably a bit beyond where you are at.
The "simplified" version of how to go beyond what you've been doing is:
gather requirements from the users. Write them down in terms of required functionality.
Do simple screen layouts. The main part here is just... |
2,815,900 | 17,053,089 | Find location using only distance and bearing? | Triangulation works by checking your angle to three KNOWN targets.
"I know the that's the Lighthouse of Alexandria, it's located here (X,Y) on a map, and it's to my right at 90 degrees." Repeat 2 more times for different targets and angles.
Trilateration works by checking your distance from three KNOWN targets.
"I know... | What you're looking for is Monte Carlo localization (also known as a particle filter). Here's a good resource on the subject.
Or nearly anything from the probabilistic robotics crowd, Dellaert, Thrun, Burgard or Fox. If you're feeling ambitious, you could try to go for a full SLAM solution - a bunch of libraries are po... |
2,815,915 | 2,815,931 | what is better when creating new variable in a loop in c++ | What is the best way in C++ to use std::map in loops ?
dynamically allocated
stack allocated
Code:
for(int i=0;i<3;i++)
{
std::map<int,int>* m = new std::map<int,int>;
//or ...
std::map<int,int> m;
}
| Avoid new unless you really need it, i.e. the variable/structure has a lifetime unrelated to any calling scope. (If it "belongs" to the calling function, return by value.)
This is clearly not such a case. The second, preferable, example is called a local variable.
I would be making a choice between
for(int i=0;i<3;i++... |
2,816,201 | 2,826,591 | C++ return type overload hack | I was bored and came up with such hack (pseudocode):
1 struct proxy {
2 operator int(); // int function
3 operator double(); // double function
4 proxy(arguments);
5 arguments &arguments_;
6 };
7
8 proxy function(arguments &args) {
9 return proxy(args);
10 }
11 int v = function(...);
12 dou... | I'd rather use template specialization, just feels less "hacky" and probably will be faster (no object creation, although of course that can be optimized away by smart compiler).
But anyway, I'd rather see code like
template<typename T> T function();
template<> int function() {
return 1;
}
template<> float functi... |
2,816,229 | 2,816,533 | Can I un-check a group of RadioBottoms inside a group box? | radio bottoms inside a group Box will be treated as a group of bottoms. They are mutual exclusive. How can I clean up their check states??
I have several radio bottoms, one of them are checked.
How can I "clean" (uncheck) all radio bottoms??
"setChecked" doesn't work within a group, I tried to do following things but f... | The trick is to disable the autoExclusive property before unchecking it, then re-enabling it.
ui->radioButton->setChecked(true);
ui->radioButton->setAutoExclusive(false);
ui->radioButton->setChecked(false);
ui->radioButton->setAutoExclusive(true);
After this, the radioButton is unchecked.
|
2,816,285 | 2,816,480 | Classes with the same name - is it restricted only within the same translation unit? | Let's just I had the following code:
foo.h
class Foo
{
// ...
};
foo.cpp
#include "foo.h"
// Functions for class Foo defined here...
Let's say that Foo are built into a static library foo.lib.
Now let's say I have the following:
foo2.h
class Foo
{
// ...
};
foo2.cpp
#include "foo2.h"
// Functions for class F... | You can have more than one definition of a class type in multiple translation units subject to some fairly strong restrictions meaning that the definitions must be virtually identical. (3.2 [basic.def.odr])
This also applies to enumeration types, inline functions with external linkage, class template, non-static functi... |
2,816,293 | 2,816,317 | Passing optional parameter by reference in c++ | I'm having a problem with optional function parameter in C++
What I'm trying to do is to write function with optional parameter which is passed by reference, so that I can use it in two ways (1) and (2), but on (2) I don't really care what is the value of mFoobar.
I've tried such a code:
void foo(double &bar, double &... | The default argument of a (mutable) reference must be an l-value. The best I can think of, without overloading, is
static double _dummy_foobar;
void foo(double &bar, double &foobar = _dummy_foobar)
|
2,816,415 | 2,822,474 | List of header file locations for the Havok Physics Engine | I am trying to integrate the Havok physics engine into my small game. It is a really nice SDK, but the header files are all over the place. Many headers are deeply nested in multiple directories. That gets confusing when you are trying to include headers for different important objects.
I would like to know if there is... | In Visual Studio, right-clicking on a class and selecting Go to Declaration usually does a good job of finding the header. You can could also add the source directory to your list of directories to search for Find in Files. Once you've got the header open, you can copy the file path and convert it to a #include stateme... |
2,816,752 | 2,816,811 | Can a member struct be zero-init from the constructor initializer list without calling memset? | Let's say I have the following structure declaration (simple struct with no constructor).
struct Foo
{
int x;
int y;
int z;
char szData[DATA_SIZE];
};
Now let's say this struct is a member of a C++ class as follows:
class CFoobar
{
Foo _foo;
public:
CFoobar();
};
If I declare CFoobar's const... | Yes, this is defined behaviour according to the standard. 12.6.2 [class.base.init] / 3 : "if the expression-list of the mem-initializer is omitted, the base class or member subobject is value-initialized."
Be warned, though, if Foo wasn't a POD-type but still had no user-declared constructor (e.g. it had a std::string ... |
2,816,971 | 2,817,136 | C++ String tokenisation from 3D .obj files | I'm pretty new to C++ and was looking for a good way to pull the data out of this line.
A sample line that I might need to tokenise is
f 11/65/11 16/70/16 17/69/17
I have a tokenisation method that splits strings into a vector as delimited by a string which may be useful
static void Tokenise(const string& str, vector<s... | I see the question is tagged as C++ but the absolutely easiest way to do this is with scanf
int indices[3][3];
sscanf(buffer, "f %d/%d/%d %d/%d/%d %d/%d/%d", &indices[0][0], &indices[0][1],...);
|
2,817,019 | 2,845,811 | OpenCV (c++) multi channel element access | I'm trying to use the "new" 2.0 c++ version of OpenCV, but everything is else like in simple C version. I have some problem with changing the values in image.
The image is CV_8UC3.
for (int i=0; i<image.rows; i++)
{
for (int j=0; j<image.cols; j++)
{
if (someArray[i][j] == 0)
{
image... | Shouldn't you be using Vec3b instead of Vec3i ?
CV_8UC3 means your image is 8 bit, 3 channels, unsigned char. While Vec3iis for 3 channels integers and Vec3bis for 3 channels unsigned char.
So I think you should be using Vec3b
|
2,817,139 | 2,817,939 | Game loop in Win32 API | I'm creating game mario like in win32 GDI . I've implemented the new loop for game :
PeekMessage(&msg,NULL,0,0,PM_NOREMOVE);
while (msg.message!=WM_QUIT)
{
if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else // No message to do
{
gG... | I've always been using something like that:
MSG msg;
while (running){
if (PeekMessage(&msg, hWnd, 0, 0, PM_REMOVE)){
TranslateMessage(&msg);
DispatchMessage(&msg);
}
else
try{
onIdle();
}
catch(std::exception& e)... |
2,817,222 | 2,824,521 | Multithreaded SDL error in C++ | I'm building a program in C++, using SDL, and am occasionally receiving this error:
* glibc detected * ./assistant: double free or corruption (!prev)
It's difficult to replicate, so I can't find exactly what's causing it, but I just added a second thread to the program, and neither thread run on its own seems to caus... | Turns out that it was being caused by the threads not terminating correctly. Instead of terminating them from main, I allowed them to return when they saw that main had finished running (through a global 'running' variable), and the problem disappeared.
|
2,817,274 | 2,842,051 | Vim OmniCppComplete on vectors of pointers | I might have done something wrong in the set up but is OmniCppComplete supposed to provide the members/functions of classes when doing this?
vectorofpointers[0]->
At the moment all I get when trying that are things relating to the vector class itself, which obviously isn't very useful. I think it might have been worki... | I do not think it is possible to get proper code completion on the objects that are included in the vector, but someone please correct me if I am mistaken.
To disable the preview window, make sure to not set preview for the the completeopt option, type :help completeopt in Vim for more information.
|
2,818,416 | 2,820,251 | cygwin does not contain mysql.h .. How can i get it in cygwin? | I need mysql.h for my c++ program.
| The main reason MySQL isn't already in the Cygwin package repository is that there's little point in running the MySQL server under Cygwin, as that would only slow it down and not provide any compensating benefit.
All you actually need, though, is the C API client library. It's easy enough to build it yourself.
Firs... |
2,819,059 | 2,819,105 | Preallocating memory with C++ in realtime environment | I'm having a function which gets an input buffer of n bytes, and needs an auxillary buffer of n bytes in order to process the given input buffer.
(I know vector is allocating memory at runtime, let's say that I'm using a vector which uses static preallocated memory. Imagine this is NOT an STL vector.)
The usual approac... | I don't see how you can get precisely what you describe. Something like this could be a good compromise for you.
void processData(vector<T>& vec)
{
static vector<T> aux(vec.size());
if (vec.size() > aux.size()) {
aux.resize(vec.size());
}
...
}
|
2,819,205 | 2,819,265 | Multithreaded Multiplication of Large Non-sparse, Non-square Matrices in C/C++ | All,
I'm looking for recommendations for C or C++ libraries (preferably open source) that use multi-threaded techniques to multiply large, non-square, (e.g. 65536xn in size where n < 65536) non-sparse matrices. Thanks.
-&&
| Intel MKL (not open source)
AMD ACML (free, but not open source)
GOTO BLAS (free for academic use, IIRC, and you get the source, but not "open source")
ATLAS BLAS (open source)
|
2,819,245 | 2,819,287 | Is std::pair<int, std::string> ordering well-defined? | It seems that I can sort a std::vector<std::pair<int, std::string>>, and it will sort based on the int value. Is this a well defined thing to do?
Does std::pair have a default ordering based on its elements?
| std::pair uses lexicographic comparison: It will compare based on the first element. If the values of the first elements are equal, it will then compare based on the second element.
The definition in the C++03 standard (section 20.2.2) is:
template <class T1, class T2>
bool operator<(const pair<T1, T2>& x, const pair<T... |
2,819,521 | 2,820,729 | Dynamic-linked DLL needs to share a global variable with its caller | I have a static library libStatic that defines a global variable like this
Header file libStatic/globals.h:
extern int globvar;
Code file libStatic/globals.cpp:
int globvar = 42;
The DLL libDynamic and the executable runner are using this global variable. Furtheron, libDynamic is linked at run-time into runner (via L... | An easy way would be to let the .DLL point to the global variable of the executable. Right after loading you would call a special function inside that library (something like SetGlobVar(int*)). That way the library will always point to the same global variable as the .EXE.
|
2,819,558 | 2,820,862 | Looking to reimplement build toolchain from bash/grep/sed/awk/(auto)make/configure to something more sane (e.g. boost.build, etc) | I currently maintain a few boxes that house a loosely related cornucopia of coding projects, databases and repositories (ranging from a homebrew *nix distro to my class notes), maintained by myself and a few equally pasty-skinned nerdy friends (all of said cornucopia is stored in SVN).
The vast majority of our code is ... | You could use python-based build system, too -- http://code.google.com/p/waf/
|
2,819,600 | 2,819,664 | std::string insert method has ambiguous overloads? | Environment: VS2005 C++ using STLPort 5.1.4.
Compiling the following code snippet:
std::string copied = "asdf";
char ch = 's';
copied.insert(0,1,ch);
I receive an error:
Error 1 error C2668: 'stlpx_std::basic_string<_CharT,_Traits,_Alloc>::insert' : ambiguous call to overloaded function
It appears that the pro... | Known issue, ruled "Not A Defect". http://std.dkuug.dk/jtc1/sc22/wg21/docs/lwg-closed.html#84
|
2,819,937 | 3,462,187 | Invalidating non-client areas | I've a window which has custom border/caption, in order to do that I handle WM_NCPAINT message. My caption has two backgrounds a brighter one for the active window, and a darker one for the background window.
But under some circumstances, for example when the window loses/gain focus, my caption is not updated so I end... | Overriding non-client area is always fraught with peril. It seems the Window manager makes a lot of assumptions for optimization. Clearly it can be done, see Office, but it might take a lot of experimentation.
Just an idea. Call RedrawWindow twice, once to invalidate the non-client area then again to validate the cl... |
2,819,994 | 2,820,182 | How to split the definition of template friend function within template class? | The following example compiles fine but I can't figure out how to separate declaration and definition of operator<<() is this particular case.
Every time I try to split the definition friend is causing trouble and gcc complains the operator<<() definition must take exactly one argument.
#include <iostream>
template <ty... | The easiest is probably to make all these template operators friends:
#include <iostream>
template <typename T>
class Test
{
public:
Test(const T& value) : value_(value) {}
template <typename STREAM, typename U>
friend STREAM& operator<<(STREAM& os, const Test<U>& rhs);
private:
... |
2,820,206 | 2,820,224 | fstream file I/O question - when to close a file stream | I am trying to work out if I need to call close on a fstream object if the intial open failed.
i.e.
std::fstream strm;
strm.open( "filename" );
if( ! strm.fail() )
{
// Do something
strm.close(); // [1]
}
strm.close(); // [2]
Where should close be called here - should it always be called [2] or only if th... | The stream will be automatically closed by the fstream's destructor - there is no need to close it explicitly, unless your program logic demands it, for example if you are going to re-open it. However, closing a stream that didn't open won't cause any problems.
|
2,820,221 | 2,820,289 | Why was std::strstream deprecated? | I recently discovered that std::strstream has been deprecated in favor of std::stringstream. It's been a while since I've used it, but it did what I needed to do at the time, so was surprised to hear of its deprecation.
My question is why was this decision made, and what benefits does std::stringstream provide that ar... | The strstream returned a char * that was very difficult to manage, as nowhere was it stated how it had been allocated. It was thus impossible to know if you should delete it or call free() on it or do something else entirely. About the only really satisfactory way to deallocate it was to hand it back to the strstream ... |
2,820,285 | 2,820,393 | abort, terminate or exit? | What's the difference between those three, and how shall I end program in case of exception which I can't handle properly?
| My advice would be not to use any of them. Instead, catch the exceptions you can't handle in main() and simply return from there. This means that you are guaranteed that stack unwinding happens correctly and all destructors are called. In other words:
int main() {
try {
// your stuff
}
catch( ... ) {... |
2,820,367 | 2,820,452 | Qt/C++ regular expression library with unicode property support | I'm converting an application from the .Net framework to Qt using C++. The application makes extensive use of regular expression unicode properties, i.e. \p{L}, \p{M}, etc. I've just discovered that the QRegExp class lacks support for this among other things (lookbehinds, etc.)
Can anyone recommend a C++ regular expres... | http://site.icu-project.org/
ICU is a mature, widely used set of
C/C++ and Java libraries providing
Unicode and Globalization support for
software applications.
released under a nonrestrictive open source license
...
Regular Expression: ICU's regular expressions fully support Unicode
while providing very com... |
2,820,477 | 2,820,521 | Class members allocation on heap/stack? | If a class is declared as follows:
class MyClass
{
char * MyMember;
MyClass()
{
MyMember = new char[250];
}
~MyClass()
{
delete[] MyMember;
}
};
And it could be done like this:
class MyClass
{
char MyMember[250];
};
How does a class gets allocated on heap, like if i do MyClass * Mine = new MyC... | Yes, yes, and yes.
Your first example has a bit of a bug in it, though: which is that because it one of its data members is a pointer with heap-allocated data, then it should also declare a copy-constructor and assignment operator, for example like ...
MyClass(const MyClass& rhs)
{
MyMember = new char[250];
memcp... |
2,820,558 | 2,820,604 | copying program arguments to a whitespace separated std::string | I have a Visual Studio 2008 C++ application where I would like to copy all of program arguments in to a string separated by a whitespace " ". i.e., if my program is called as foo.exe \Program Files, then my folder string below would contain \Program Files
Below is an example of what I'm doing now. I was wondering if th... | How about this:
int main(int argc, char* argv[])
{
std::string path;
if(argc < 2)
{
std::cout << "Not enough arguments" << std::endl;
return;
}
path = argv[1]; // Assignment works from char* types
// Do the rest of your folder manipulation below here
}
That should work. Even wi... |
2,820,608 | 2,820,655 | Is correct name enough to make it happen? | I've just dipped into limits.h by Microsoft. I tried to check what's the return type for max() function and to my surprise I see something like this:
// TEMPLATE CLASS numeric_limits
template<class _Ty>
class numeric_limits
: public _Num_base
{ // numeric limits for arbitrary type _Ty (say little or n... | This is implemented through template specialization. Probably, you'll find something like this elsewhere:
template<>
class numeric_limits<int> : public _Num_base {
public:
static int min() {
return INT_MIN;
}
static int max() {
return INT_MAX;
}
};
If you use... |
2,820,621 | 2,822,064 | Why aren't unsigned OpenMP index variables allowed? | I have a loop in my C++/OpenMP code that looks like this:
#pragma omp parallel for
for(unsigned int i=0; i<count; i++)
{
// do stuff
}
When I compile it (with Visual Studio 2005) I get the following error:
error C3016: 'i' : index variable in OpenMP 'for' statement must have signed integral type
I understand that ... | According to the OpenMP 2.0 C/C++ API specification (pdf), section 2.4.1, that's one of the restrictions of the for loop. No reason is given for it, but I suspect it's just to simplify the assumptions that the code and compiler have to make, since there's special code to ensure that the range doesn't overflow the maxim... |
2,820,646 | 2,820,713 | Using std::ifstream to load in an array of struct data type into a std::vector | I am working on a bitmap loader in C++ and when moving from the C style array to the std::vector I have run into an usual problem of which Google does not seem to have the answer.
8 Bit and 4 bit, bitmaps contain a colour palette. The colour palette has blue, green, red and reserved components each 1 byte in size.
// C... | You need to use quads.resize(coloursUsed) in place of quads.reserve(coloursUsed). Reserve just sets the capacity of the vector object but does not allocate memory. Resize will actually allocate the memory.
|
2,820,882 | 2,823,258 | Vehicle 2 Vehicle Communication Questions | I have a rare opportunity to meet the man in charge of implementing vehicle 2 vehicle communication for the US Department of Transportation with 2 others in a few hours.
Do YOU have any questions for him?
I know this is a little outside the normal, but this is a 'reverse' thread and I felt he has some great knowledge... | The guy came and delivered a presentation. Every question I had from you guys he covered. If I didn't answer correctly, please let me know.
Most information can be found here: http://www.intellidriveusa.org/
|
2,821,012 | 2,821,337 | How to write curiously recurring templates with more than 2 layers of inheritance? | All the material I've read on Curiously Recurring Template Pattern seems to one layer of inheritance, ie Base and Derived : Base<Derived>. What if I want to take it one step further?
#include <iostream>
using std::cout;
template<typename LowestDerivedClass> class A {
public:
LowestDerivedClass& get() { return *s... | Here is what I've settled on, using a variation on CRTP's to solve the problem presented in my motivation example. Probably best read starting at the bottom and scrolling up..
#include "boost/smart_ptr.hpp"
using namespace boost;
// *** First, the groundwork....
// throw this code in a deep, dark place and never ... |
2,821,223 | 2,821,244 | How would one call std::forward on all arguments in a variadic function? | I was just writing a generic object factory and using the boost preprocessor meta-library to make a variadic template (using 2010 and it doesn't support them). My function uses rval references and std::forward to do perfect forwarding and it got me thinking...when C++0X comes out and I had a standard compiler I would d... | You would do:
template <typename ...Params>
void f(Params&&... params)
{
y(std::forward<Params>(params)...);
}
The ... pretty much says "take what's on the left, and for each template parameter, unpack it accordingly."
|
2,821,439 | 2,821,461 | C++ class derivation and superconstructor confusion | Hey, in a tutorial C++ code, I found this particular piece of confusion:
PlasmaTutorial1::PlasmaTutorial1(QObject *parent, const QVariantList &args)
: Plasma::Applet(parent, args), // <- Okay, Plasma = namespace, Applet = class
m_svg(this), // <- A member function of class "Applet"?
m_ico... | What you are seeing is a initialization list. They are encouraged by the C++ FAQ Lite and speed up member initialization, because your members don't need to take default values before entering the constructor.
|
2,821,807 | 2,822,091 | global counter in application: bad practice? | In my C++ application I sometimes create different output files for troubleshooting purposes. Each file is created at a different step of our pipelined operation and it's hard to know file came before which other one (file timestamps all show the same date).
I'm thinking of adding a global counter in my application, a... | I think, adding to file name current system time with high enough precision will be cleaner and easier to implement and maintain
//helper function to encapsulate details
string makeFileName(string filename)
{ return filename + getCurrentTime(); }
void MyClass::SomeMethod()
{
File f = CreateFile(makeFileName("myclas... |
2,821,859 | 2,826,578 | Specialization of a member of a template class for a template class parameter type | I have a templated class Matrix. I want to specialize a function for the type complex, where T can be anything. I have tried this :
6 template <typename T>
7 class Matrix {
8 public :
9 static void f();
10 };
11 template<typename T> void Matrix<T>::f() { cout << "generic" << endl; ... | In fact, I found a clever way to do it through Boost. Since I don't want my library to be dependant on Boost, here is the code :
template <class T, T val> struct integral_constant
{
typedef integral_constant<T, val> type;
typedef T value_type;
static const T value = val;
};
typedef integral_consta... |
2,822,016 | 2,822,039 | how to activate 'more' option on command prompt (visual studio) | My code dumps a hell amount of data on the command prompt. How do I activate the 'MORE' option for the output so that I see the output page by page? (MS Visual Studio)
For eg. Matlab has the command 'more on' to do the same!
Thanks.
| With the Windows command prompt you can append | more to your command, e.g.,
dir | more
|
2,822,139 | 2,822,180 | breadth first or depth first search | I know how this algorithm works, but cant decide when to use which algorithm ?
Are there some guidelines, where one better perform than other or any considerations ?
Thanks very much.
| If you want to find a solution with the shortest number of steps or if your tree has infinite height (or very large) you should use breadth first.
If you have a finite tree and want to traverse all possible solutions using the smallest amount of memory then you should use depth first.
If you are searching for the best ... |
2,822,146 | 2,822,176 | References and Object Slicing | I don't have my Effective C++ with me and this is bugging me so much that I have to ask for my own sanity. Given
class Foo : public Bar{}
void MyFunc(Bar &_input);
If I pass in a Foo, am I tangling with the slicing problem or have I avoided it?
| Not a problem, because you're passing in a reference. You're not creating a new object, just letting MyFunc access the original object.
|
2,822,243 | 2,822,280 | Store return value of function in reference C++ | Is it valid to store the return value of an object in a reference?
class A { ... };
A myFunction()
{
A myObject;
return myObject;
} //myObject goes out of scope here
void mySecondFunction()
{
A& mySecondObject = myFunction();
}
Is it possible to do this in order to avoid copying myObject to mySecondObject... | It is not allowed to bind the temporary to a non-const reference, but if you make your reference const you will extend the lifetime of the temporary to the reference, see this Danny Kalev post about it.
In short:
const A& mySecondObject = myFunction();
|
2,822,272 | 2,822,533 | How can I return an object into PHP userspace from my extension? | I have a C++ object, Graph, which contains a property named cat of type Category. I'm exposing the Graph object to PHP in an extension I'm writing in C++.
As long as the Graph's methods return primitives like boolean or long, I can use the Zend RETURN_*() macros (e.g. RETURN_TRUE(); or RETURN_LONG(123);. But how can I... | In your internal functions, you can only return zvals, not arbitrary C++ objects. In your case, you must encapsulate the Category object either in a resource or in an object (like you did for the Graph object). Either way, you cannot automatically use the C++ object's methods and properties. You must then provide funct... |
2,822,357 | 2,822,390 | How to profile my C++ application on linux | I would like to profile my c++ application on linux.
I would like to find out how much time my application spent on CPU processing vs time spent on block by IO/being idle.
I know there is a profile tool call valgrind on linux. But it breaks down time spent on each method, and it does not give me an overall picture of h... | I can recommend valgrind's callgrind tool in conjunction with KCacheGrind for visualization. KCacheGrind makes it pretty easy to see where the hotspots are.
Note: It's been too long since I used it, so I'm not sure if you'll be able to get I/O Wait time out of that. Perhaps in conjunction with iostat or pidstat you'll... |
2,822,487 | 2,825,959 | Template Syntax in C++ | I don't understand templates really and was trying to run a simple find the minimum for ints, doubles, chars.
First question, why is template<typename T> sometimes used, and other times template<>?
Second question, I do not know what I am doing wrong with the following code below:
#include <iostream>
template <typen... | It looks like your question is almost answered, but you still have a couple of outstanding issues...
std::cout << minimum(2.2, 2) << '\n';
This won't compile with the two template functions you have provided as there is no matching function for call to minimum(double, int). This leaves you two options:
You can change ... |
2,822,636 | 2,823,161 | call multiple c++ functions in python using threads | Suppose I have a C(++) function taking an integer, and it is bound to (C)python with python api, so I can call it from python:
import c_module
c_module.f(10)
now, I want to parallelize it. The problem is: how does the GIL work in this case? Suppose I have a queue of numbers to be processed, and some workers (threading... | Threads currently executing the C extension code for which the GIL was explicitly released will run in parallel. See http://docs.python.org/c-api/init.html#thread-state-and-the-global-interpreter-lock for what you need to do in your extension.
Python threads are most useful for I/O bound execution or for GUI responsiv... |
2,822,830 | 2,822,948 | How to get the Doctype Declaration in Xerces-C when using SAX2? | I am using SAX2 from Xerces-C to read an XML document. However, I would like to check the Doctype declaration (if there is any) to make sure that the XML file is in the format I am expecting.
I have tried the unparsedEntityDecl and notationDecl methods from the DTDHandler, and EntityResolver seems to be more low-level ... | Look at LexicalHandler - startDTD will get you the Doctype.
However, it does not validate that the document actually follows that Doctype.
You need to enable validation in the reader with setFeature to do that.
( I've only used Java Xerces, but from the docs, it looks like the methods
are basically the same. )
|
2,822,915 | 2,823,966 | Odd tcp deadlock under windows | We are moving large amounts of data on a LAN and it has to happen very rapidly and reliably. Currently we use windows TCP as implemented in C++. Using large (synchronous) sends moves the data much faster than a bunch of smaller (synchronous) sends but will frequently deadlock for large gaps of time (.15 seconds) causin... | The send blocking until the previous ACK is received almost certainly indicates that the TCP receive window is full (you can check this by using Wireshark to analyse the network traffic).
No matter how big your TCP window is, if the receiving application isn't processing data as fast as it's arriving then the TCP windo... |
2,822,965 | 2,822,983 | C++: combine const with template arguments | The following example is working when I manualy replace T wirh char *, but why is not working as it is:
template <typename T>
class A{
public:
A(const T _t) { }
};
int main(){
const char * c = "asdf";
A<char *> a(c);
}
When compiling with gcc, I get this error:
test.cpp: In function 'int main()':
test.cpp:1... | Try converting to const T&. Also, in these cases, you should let the compiler automatically deduce the template argument, and not specify it.
|
2,822,989 | 2,823,049 | Using boost::iterator | I wrote a sparse vector class (see #1, #2.)
I would like to provide two kinds of iterators:
The first set, the regular iterators, can point any element, whether set or unset. If they are read from, they return either the set value or value_type(), if they are written to, they create the element and return the lvalue r... | I'm not sure that you really want to use iterator_adaptor in your case - you might want to use iterator_facade instead.
More thorough explanation: iterator_adaptors are used when you have an existing iterator (let's say std::list<int>::iterator) and want to reuse its behaviour for your iterator, eg. your iterator will ... |
2,823,238 | 2,823,249 | Run-Time Binding C++ | I'm reading in my text book about virtual functions in C++ and my book doesn't elaborate on what exactly run-time binding is. It doesn't give me any information as to why I would need run-time binding.
Maybe the nice people at SO can provide me with some links or information?
Thanks :]
| How about this one? ;D
http://www.google.ca/search?hl=en&source=hp&q=virtual+function+runtime+binding+c%2B%2B&aq=f&aqi=&aql=&oq=&gs_rfai=
In all seriousness though... the first link looks decent.
Here's a preview:
The most prominent reason why a virtual function will be used is to have a different functionality in the... |
2,823,245 | 2,823,260 | Syntax for finding structs in multisets - C++ | I can't seem to figure out the syntax for finding structs in containers.
I have a multiset of Event structs. I'm trying to find one of these structs by searching on its key. I get the compiler error commented below.
struct Event {
public:
bool operator < ( const Event & rhs ) const {
return ( time < rhs.time );
... | You don't have a suitable constructor that accepts double. Just add the following constructor:
Event(double t) : time(t), eventID(/**/), hostIDeventID(/**/), s(/**/)
{ }
Here is how Event would look like:
struct Event {
public:
// Initialize other variables as needed
Event(double t) : time(t), eventID(/**/), hostID... |
2,823,456 | 2,823,671 | Are there any tools for porting c++ code to c# code? | I have a couple c++ utilities that I would like to port over to dot net. I was wondering if there are tools for porting a c++ application to c#?
I imagine that any automated tool would make a mess of any code, so perhaps, I should also be asking if this is a good idea or not?
| The better question is why would you ever just port working code without gaining added value (ie new features)? The effort will almost cetainly be harder and take longer than you expect. Better, use the many interop capabilities of .Net to call your c++ code from C#. Focus on adding new features in C#, but don't waste ... |
2,823,485 | 2,824,007 | How to befriend a templated class's constructor? | Why does
class A;
template<typename T> class B
{
private:
A* a;
public:
B();
};
class A : public B<int>
{
private:
friend B<int>::B<int>();
int x;
};
template<typename T>
B<T>::B()
{
a = new A;
a->x = 5;
}
int main() { return 0; }
result in
../src/main.cpp:15: error: invalid use o... | Per the resolution to CWG defect 147 (the resolution was incorporated into C++03), the correct way to name a nontemplate constructor of a class template specialization is:
B<int>::B();
and not
B<int>::B<int>();
If the latter were allowed, there is an ambiguity when you have a constructor template specialization of a ... |
2,823,700 | 2,823,817 | How can I make a child window topmost? | I have a parent form, with some child windows (not forms - just windows, for example label controls) inside it. Under certain circumstances, I want one of those child windows to be drawn "above" the others, to display a message over the entire main form.
I've tried setting HWND_TOPMOST and HWND_TOP on the child windows... | HWND_TOPMOST only applies to top level windows, not child windows.
Use SetWindowPos withthe HWND_TOP flag to change the target child window's zorder to put it at the top of the zorder among its siblings.
Note that zorder in child windows only applies to siblings - hwnds with the same parent.
|
2,823,713 | 2,823,727 | C++ preprocessing error in the code | #include "iostream"
#include "string"
using namespace std;
#define AA(bb) \
string(::##bb);
int main (int argc, char *argv[])
{
AA(aa);
}
This gives me a bunch of errors but I am trying to understand this error:
pre.cpp:11:1: error: pasting "::" and "aa" does not... | :: is already a separate token, you don't need the ## token-pasting operator for the code you showed.
|
2,823,730 | 2,823,768 | Is webserver bandwith the entire HTTP Request/Response? | Just a quick question. I'm making a web application where C++ communicates with a php script over HTTP Requests/Response. The data being set back and forth is quite small ~36 bytes. But I plan to have many computers connected, contacting the server quite often. I did the math, and I could potentially have gigabytes of ... | Assuming the web host is running Apache, You can assume the module mod_bw is being used to control the bandwidth (It's a standard). In this case requests are not part of the traffic being monitored, the only control on the requests are the amount of them, they do not count as "bandwidth" although it technically still i... |
2,823,858 | 2,823,870 | Working with strings in C++ | I'm working with strings in C++. I recently came across a problem when entering strings. I'm using cin >> string; to get my string as user input. When the user enters a space into the string, the next input is automatically filled out with the remaining letters, or sometimes left blank. As the next input string is ofte... | You probably want to get all input into the string up until the user presses enter. In that case, it can be said that what you really want is to read a "line" of text. To do that, you'd use std::getline, like so:
std::getline(cin, enemyName);
That is assuming enemyName is defined as an std::string. If enemy name is... |
2,824,014 | 2,824,025 | Explain this C++ operator definition | I have the following operator defined in a C++ class called StringProxy:
operator std::string&()
{
return m_string;
}
a) What is this and how does this work? I understand the idea of operator overloading, but they normally look like X operator+(double i).
b) Given an instance of StringProxy, how can I use this ope... | This is a conversion method. To get the m_string, simply use an explicit cast: (std::string)stringProxy to perform the conversion. Depending on context (e.g. if you're assigning to a string), you may be able to do without the cast.
|
2,824,046 | 2,824,083 | Sanity Check - will a stl::Container of new'd objects each be deleted when the container itself dies? | Title pretty much covers it. If I've added say 3 objects to a list and the list goes out of scope and dies, will it call delete on each entry before going out of scope? Pretty sure yes, but getting tired and need a sanity check.
| Survey says: I'm tired and no they won't delete themeselves unless they are within some sort of container safe smart pointer in the list itself. Nap time...
|
2,824,342 | 2,824,357 | Using Tortoise SVN with C++ in Visual Studio 2008 | I have an online repository with some .h and .cpp files that make up part of a project. I'm trying to check these out and use them in a new project, but am getting errors (C4627 and C1010). All the files have been added to the project (with Add>Existing Item...), and the subdirectories that contain these files have bee... |
Would I be better off having the entire project tree in the repository?
Most certainly yes. You should be able to check out and build without much effort. Creating a new project every time you want to build the source and having to configure it is way too much work.
My reason for not doing so is that my colleague ... |
2,824,431 | 2,824,465 | Get the signed/unsigned variant of an integer template parameter without explicit traits | I am looking to define a template class whose template parameter will always be an integer type. The class will contain two members, one of type T, and the other as the unsigned variant of type T -- i.e. if T == int, then T_Unsigned == unsigned int. My first instinct was to do this:
template <typename T> class Range {
... | The answer is in <type_traits>
For determining the signed-ness of a type use std::is_signed and std::is_unsigned.
For adding/removing signed-ness, there is std::make_signed and std::make_unsigned.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.