question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,845,666 | 4,845,672 | casting const to pass it to function that takes reference, what happens? | Can anyone tell me what happens here when passing to g in the main, is it static_cast?
int & g (int&x){x++ ; return x ; }
int main()
{
const int a=5 ;
cout<<g((int&)a)<<endl;
}
I am sure that no copy is made, since the code above is similar to the one below :
class A
{
public:
A()
{
cout <<... | static_cast cannot remove constness. This is a const_cast.
At runtime, this code (the first example) yields undefined behavior because you modify a const object.
|
4,845,707 | 4,857,514 | MATLAB and C/C++. How to choose between different C/C++ specifications | I have the following problem compiling a C++ file from a third-party library in mex using Visual C++ 2010's compiler (cl.exe).
The compiler complains in multiple lines on a statement like the following::
plhs[i] = mxCreateNumericMatrix(nclass, 1, mxDOUBLE_CLASS, 0);
with:
error C2664:
'mxCreateNumericMatrix_730' : ... | C++ doesn't allow implicit conversion from int to enum values (ever! Not in C++98, 2003, 0x), unlike C, so you need to use the actual enum values for such a parameter.
Or you can compile as C, since the code they wrote isn't C++ (because of the above).
Note 1: Unfortunately, I don't know in
what C++ standard the lib... |
4,845,898 | 4,846,778 | Emulating the registry and running an executable to use that registry | I am currently writing a program that takes other programs, copies them, and stores them in a different folder. The point of my program is to be able to run other programs with different settings. For programs that use config files, this works perfectly. However, for some of the programs, the config values they hold ar... | Using VirtualRegistry to Redirect Registry Keys on Windows Vista
Registry Virtualization
I have not used this before, but it sure looks promising.
|
4,845,907 | 4,845,933 | Example of Visual C++ nonconformant code? | What are some examples of code that are not standards compliant when using visual C++? Something that is allowed to compile under visual C++ but nothing else.
| You can find all the Microsoft language extensions here; you may also want to have a look to the areas of the language where VC++ is not compliant to the standard.
One that I thought was standard (I noticed it when I enabled the /Za switch) is the "magic l-value cast":
char *p;
(( int * ) p )++;
|
4,846,079 | 4,846,202 | Is it better to have one class for a new item dialog and an edit item dialog or different classes? | I'm making a program in which I have a list of items. You can add a new item or you can edit an existing one. The dialog window for editing an item and adding a new one is practically the same, one small detail that changes is that well, one edits and the other one adds the item, very little else is different.
I was w... | I usually use the same MVC classes for both CREATE and EDIT mode. The model holds a flag to indicate which mode. The View would read the flag in the Model to determine which controls to be displayed/enabled etc. The Controller would also read the flag on the Model to determine which service layer method to call when t... |
4,846,093 | 4,846,120 | C++ this (what would be a link to current class in such situation) | So having:
struct A { void foo(int) { } };
typedef std::function<void(int)> Function;
typedef std::vector<Function> FunctionSequence;
typedef FunctionSequence::iterator FunctionIterator;
FunctionSequence funcs;
A a;
funcs.push_back(std::bind(&A::foo, &a, std::placeholders::_1));
funcs.push_back(std::bind(&B... | If I understood correctly your question, the answer should be yes. &variable is always equal to this as seen by the instance methods called over variable.
|
4,846,308 | 4,846,329 | Creating windows forms application in C++ (w/o .NET) | I would like to create a windows forms application in C++, but I don't want to use .NET framework.
I also don't want to code everything from scratch. I'd like to have a toolbox such as the one in Visual Studio. Could you recommend some editor/compiler for this task?
Any help would be greatly appreciated!
| You might want to look up MFC or the Qt framework. both have a nice GUI editor and integrate with visual studio (MFC actually comes with visual studio)
Winforms is a strictly .NET thing so whatever you do, it won't be Winforms.
|
4,846,357 | 4,846,389 | Finding size of perfect quad tree | I need to find the size of a perfect quad tree.
This means I have 1 root node that splits into 4 nodes that splits into 4 nodes etc.
so a quad tree of height 1 would be size 1
height 2 = size 5 (1 + 4)
height 3 = size 21 (1 + 4 + 16)
height 4 = size 85 (1 + 4 + 16 + 64)
etc..
I know that the size of a perfect binary t... | This is a geometric series. So the relevant formula is:
S = a * (1 - r^n) / (1 - r)
where a is the first value, r is the common ratio, n is the number of terms, and ^ denotes "to-the-power-of".
|
4,846,396 | 4,846,403 | How do I overload the operator * when my object is on the right side in C++? | I want to implement "operator * " overloading INSIDE my class, so I would be able to do the following:
Rational a(1, 2), b;
b = 0.5 * a; // b = 1/4
Notice that b is on the right side, is there a way to do such a thing inside "Rational" class?
| No. You must define operator* as a free function. Of course, you could implement it in terms of a member function on the second argument.
|
4,846,473 | 4,846,492 | Why am I getting excessive CPU Usage with "clock( )"? | I'm trying to create a simple timer using the clock() method. When the application is executed, my CPU usage jumps from 0% to 25%. For a simple program that does nothing but count from 60 to 0 in seconds, it's a bit excessive.
I was following this: http://www.cplusplus.com/reference/clibrary/ctime/clock/
Any reason fo... | See:
http://msdn.microsoft.com/en-us/library/ms686298%28v=vs.85%29.aspx
The code you reference:
while (clock() < endwait) {}
will clearly just chew CPU while waiting for the time to pass, hence the 25% usage ( one core).
while (clock() < endwait) { Sleep(1);}
should solve your problem.
|
4,846,486 | 4,846,584 | how to link two template classes in many-to-many friendship? | assume that I have the following two template classes :
template <class _A>
class First
{
private:
int a;
};
template <class _B>
class Second
{
private:
int b;
};
how can I link them in many-to-many friendship. for example, adding a method in First that prints b of a parameter object of Second.
is my questio... | template <typename T>
class First {
int a;
template<typename> friend class Second;
};
template <typename T>
class Second
{
int b;
template<typename> friend class First;
};
This will enable every First<T> to access the internals of every Second<U>. Now, while this is the technical solution, you might want t... |
4,846,540 | 4,846,597 | C++11 lambda in decltype | For the following code:
auto F(int count) -> decltype([](int m) { return 0; })
{
return [](int m) { return 0; };
}
g++ 4.5 gives the errors:
test1.cpp:1:32: error: expected primary-expression before 'int'
test1.cpp:1:... | You cannot use a lambda expression except by actually creating that object- that makes it impossible to pass to type deduction like decltype.
Ironically, of course, the lambda return rules make it so that you CAN return lambdas from lambdas, as there are some situations in which the return type doesn't have to be speci... |
4,846,588 | 4,846,618 | Marshalling error when using a C++ library from a C# application | I am trying to use a C++ DLL in C# and having some issues between the two with a specific function.
In C++ the function is defined as:
byte* GetEntityUserData(TEntity entity)
In C# I've defined it as:
[DllImport(EngineDll)]
public static extern object[] GetEntityUserData(TEntity entity);
When I try to do the followin... | What is the data supposed to represent? I would change the C# signature to return byte[], not object[]. You won't be able to get a reference type back from an unmanaged function. Only value types, which means primitive types and struct's.
|
4,846,798 | 4,846,882 | Why would map be much faster than unordered_map? | I implemented a search caching results that consist of keys of type State (a class with 7 short ints) and values of type Score (a class of 3 doubles.) Using unordered_map was at least 20 times slower than map. Why?
Edit: Darn it! My hash function was
namespace std {
size_t hash<State>::operator()(State const& s... | The speed of unordered_map is directly proportional to the speed of your hashing function. It is never a straight forward relationship. Case in point, if you use the simplest hashing function:
std::size_t myHash(MyObjectType _object){ return 1; }
then what you'll end up with is a collection which behaves like a list... |
4,847,080 | 4,847,117 | Free image analysis libraries? | I'm looking for some Free (preferably LGPL'd) image analysis/comparison libraries.
The most important thing they should be able to do, is compare two different images and say if they're similar, with adjustable sensibility (i.e the higher the sensibility the more they have to look like each other to get a positive resu... | Comparing if two images are "similar" is an extremely hard, research-class problem. The approach you'd use will depend heavily on the types of similarities/differences that you are expecting between your images.
It will be hard to find something that works off-the-shelf, unless your comparison requirements are very spe... |
4,847,100 | 4,847,114 | C++ inheritance - inaccessible base? | I seem to be unable to use a base class as a function parameter, have I messed up my inheritance?
I have the following in my main:
int some_ftn(Foo *f) { /* some code */ };
Bar b;
some_ftn(&b);
And the class Bar inheriting from Foo in such a way:
class Bar : Foo
{
public:
Bar();
//snip
private:
//snip
};... | You have to do this:
class Bar : public Foo
{
// ...
}
The default inheritance type of a class in C++ is private, so any public and protected members from the base class are limited to private. struct inheritance on the other hand is public by default.
|
4,847,110 | 4,847,116 | A newbie question in Qt | MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
In this section of code, after : what does
QMainWindow(parent),
ui(new Ui::MainWindow)
mean?
| This is actually a C++ question. What you're looking at are called initialization lists. The QMainWindow(parent) calls that constructor for MainWindow's superclass (QMainWindow) and ui(new Ui::MainWindow) constructs ui member.
|
4,847,217 | 4,847,259 | c++ vector construct with given memory | I'd like to use a std::vector to control a given piece of memory. First of all I'm pretty sure this isn't good practice, but curiosity has the better of me and I'd like to know how to do this anyway.
The problem I have is a method like this:
vector<float> getRow(unsigned long rowIndex)
{
float* row = _m->getRow(row... | Vector's default allocator doesn't provide this type of access to its internals. You could do it with your own allocator (vector's second template parameter), but that would change the type of the vector.
It would be much easier if you could write directly into the vector:
vector<float> getRow(unsigned long rowIndex) ... |
4,847,829 | 4,847,881 | How do you inherit from template class when you need to inherit not from template? | Sounds bad.. but having
template < int ArrayLength, typename SomeValueType > class SomeClass{
SomeValueType SomeValue;
SomeValueType SomeArray[ ArrayLength ];
...
};
how do you for example ceae a class that expands SomeClass that is SomeClass < 20, int >
is something like
class MyClass : SomeClass < 20, ... | If you want private inheritance:
class MyClass : SomeClass < 20, int > //private by default!
{
//...
};
If you want public inheritance:
class MyClass : public SomeClass < 20, int >
{
//...
};
|
4,847,929 | 4,847,984 | Help understanding the working of Function Objects? | I found this code on Wikipedia
class compare_class {
public:
bool operator()(int A, int B) const {
return A < B;
}
};
...
// Declaration of C++ sorting function.
template <class ComparisonFunctor>
void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
...
int main() {
int items[] = {4, 3, ... | To understand why sort_ints takes its parameter by value, you have to remember that the object being passed into it as the comparator is not necessarily a function pointer. If, for example, you're using the compare_class function object to do the comparison, then what you're passing into the function is a concrete obj... |
4,848,083 | 4,848,099 | How to copy a structure with pointers to data inside (so to copy pointers and data they point to)? | so I have a structure like
struct GetResultStructure
{
int length;
char* ptr;
};
I need a way to make a full copy of it meaning I need a copy to have a structure with new ptr poinnting on to copy of data I had in original structure. Is It any how possible? I mean any structure I have which contains ptrs will have ... | For the specific scenario you describe, use a std::vector or some other sequence container. If you do so, then simply copying objects of type GetResultStructure will make copies of the pointed-to data as well:
struct GetResultStructure {
std::vector<char> data;
};
GetResultStructure a = GetData();
GetResultStruct... |
4,848,124 | 4,848,841 | Boost Threads - Racing | I'm playing around with some Boost threads, and I've written the following code:
#include <boost/thread.hpp>
#include <iostream>
volatile int threads = 0;
const int iterations = 200;
volatile char output[iterations*4];
volatile int k = 0;
void w() {
threads++;
for (int i = 0; i < iterations; i++) {
... | The main reason for observing the sequential filling of the output buffer is that you threads complete too soon. 200 iterations are not enough for the worker threads to be interrupted. Instead of printing output, I appended this to your main():
int switches = 0;
for (int i=1; i<iterations*4; ++i)
if (output[i] != o... |
4,848,159 | 4,848,169 | Why it says 'push_back' has not been declared? | Why it says 'push_back' has not been declared ?
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector <int> v(30);
v[0].push_back(0);
return 0;
}
| v[0] is a reference to the initial element in the vector; it isn't the vector itself. The element is of type int, which is not a class type object and therefore has no member functions.
Are you looking for v.push_back(0);?
Note that vector<int> v(30); creates the vector with 30 elements in it, each with a value of ... |
4,848,298 | 4,848,740 | How do I make projectiles? | I am totally stumped on this one. I'm using C++ and SFML 1.6 for a game I'm developing, and I have no bloody idea. How do I make projectiles (like bullets)? I just don't understand it. It could be my lack of sleep but I don't know.
So my question is how do I create a Sprite that moves in a definite direction based on w... | Easiest solution:
If the mouse is at Mx,My and the ship is at Sx,Sy then calculate the direction from the ship to the mouse:
Dx=Sx-Mx
Dy=Sy-My
Now normalise D (this means scale it so that it's length is one):
DLen=sqrt(Dx*Dx + Dy*Dy)
Dx/=DLen;
Dy/=DLen;
Now Dx is the distance you want to move the bullet on the x axis ... |
4,848,373 | 4,855,534 | How can I call __strlen_sse2 from a C/C++ program? [Linux] | I'll state off the bat that I'm not a programmer, and am probably in over my head.
I'm trying to track down a bug in in the __strlen_sse2 (assembly) function installed in Debian as part of libc6-i686.
I already have a copy of the assembly code (.S file) and I need to figure out a way to call it from a C/C++ program. Ho... | You can't directly call the copy of __strlen_sse2 inside the usual, dynamically-linked /lib/libc.so.6 because it is a "hidden symbol" -- accessible to code inside libc itself, but not available for external linking.
You say you have the .S file that defines __strlen_sse2, from glibc's source code, but you're going to n... |
4,848,380 | 4,848,845 | How to implement copy operator for such C++ structure? | So having
struct ResultStructure
{
ResultStructure(const ResultStructure& other)
{
// copy code in here ? using memcpy ? how???
}
ResultStructure& operator=(const ResultStructure& other)
{
if (this != &other) {
// copy code in here ?
}
return *this
... | You might want to explain why you want to manually deal with raw memory. I haven't done this in a long time, it's what std::string and std::vector where designed for:
struct ResultStructure
{
// nothing else needed
std::string data; // or std::vector<char>
};
But if you really need to do this the hard way (i... |
4,848,760 | 4,848,793 | No match for 'operator <<' in std::operator << [With _Traits = std::char_traits<char> ] | I have a class Foobar with string conversion operator:
#include <string>
class Foobar
{
public:
Foobar();
Foobar(const Foobar&);
~Foobar();
operator std::string() const;
};
I attempt to use it like this:
//C++ source file
#include <iostream>
#include <sstream>
#include "Foobar.hpp"
int main()
{
Fooba... | Foobar fb is not converted to a string before being placed into your stream. There is no requirement that arguments to the << operator must be strings.
You should either convert it to a string manually
ss << "Foobar is: " << std::string(fb);
Or define an operator<< for Foobar.
Defining an operator<< would be the smart... |
4,848,847 | 4,848,989 | c/c++ optimize for constant variable in calling functions | C/C++ compilers optimize single layer functions with constant parameters (known at compile time) only when using -Os, -O1 and -O2. They do not optimize all the layers. Only -O3 can do that. gcc is WinAVR 4.3.3 which does not support attribute "optimize".
void inner(double value)
{
//operations using value
//...... | Somewhat similar to the macro option (3), but without the disadvantages of a macro, you can make specific functions inline, which will typically result in the desired constant optimizations. Of course this only helps if you're calling the relevant functions from one place (or from a few places), otherwise code bloat be... |
4,848,905 | 4,851,215 | Is this reinterpret_cast between RECT and POINT array safe? | Windows SDK contains a set of typedefs:
typedef long LONG;
typedef struct tagPOINT
{
LONG x;
LONG y;
} POINT;
typedef struct tagRECT
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT;
then, there's a WinAPI function that expects a pointer to an array of POINT structs and th... | For this particular Win32 structure, yes. You should of course make this assumption explicit:
static_assert(sizeof(struct tagRECT) == 2 * sizeof(POINT));
static_assert(offsetof(struct tagRECT, right) == sizeof(POINT));
|
4,849,131 | 4,849,201 | Import feature added to my program breaks OOP encapsulation. How do I restore encapsulation? | I have a program that stores it's information in an XML file. This file is read in and a corresponding object model is created. The object model has a tree hierarchy. The object type we'll call BigHierarchy.
Now, my program has a feature that allows the user to import another file. So, when he selects the file he wish... | To get to the exact design you need to first define what would be your merge strategy in case there is a conflict between private members at their most atomic level.
Overwrite with latest
Keep original
Merge the changes
If you go with approach 1, then you will overwrite the existing BigHierarchy with new one. In thi... |
4,849,289 | 4,849,323 | virtual base class and initialization lists |
Possible Duplicate:
gcc c++ virtual inheritance problem
Hi all,
I'm wondering about how the compiler would handle different initialization values when using multiple inheritance from a virtual base class. Consider the notorious 'diamond of dread' inheritance scheme:
Base
/ \
/ \
D1 D2
\ /... | It shoudn't compile. Virtual bases are initialized by the most derived class which is Join. Join doesn't explicitly initialize Base but Base has no accessible default constructor.
[It also won't compiler because definitions of classes need to be terminated with a ; but I've assumed that this is a typo. main should also... |
4,849,422 | 4,849,458 | How to convert epoch time to year | I have time in epoch format.
I just want to retrieve Year from it.
how should we do it in c or c++ ?
Actually i have time since epoch in seconds and i need to calculate age depending on it.
So input will be seconds since epoch and out put should be Age based on current date.
Thanks,
PP.
| In C timestamps (ie: seconds from epoch) are usually stored in time_t, while human-wise dates are stored in structure tm. You need a function that converts time_ts in tms.
gmtime or localtime are two C standard function that do your job.
struct tm *date = gmtime( your_time );
printf( "Year = %d\n", date->tm_year );
Wa... |
4,849,428 | 4,849,727 | std::merge using 2 mmaped arrays? | I'm mmaping two text files with an integer written on each line.
I read them from the drive and I wanted to do a sorted merge on them.
The two input files "1piece0" and "1piece1" have a list of sorted integers.
The output file does have the size as the two files combined, but not that many integers.
Problem: The two in... | You cannot treat text lines as binary blobs to be manipulated as int pointers.
You can treat text files as text to be extracted and used:
void merge_ints(std::istream &a_in, std::istream &b_in, std::ostream &out) {
int a, b;
std::istream *remaining = 0;
if (!(a_in >> a)) {
remaining = &b_in;
}
else if (!(... |
4,849,447 | 4,849,574 | Detect if application is running on laptop |
Possible Duplicate:
How can I tell if a user is using a laptop
I'm trying to find out if the application is running on a laptop or on a desktop, any ideas on how to achieve this?
Note: I'm interested only in API's written in Delphi and/or C++.
EDIT: my target platform is Windows XP+, even Windows 7 only is OK.
| Use this struct : SYSTEM_POWER_STATUS, and check the value of ACLineStatus field.
ACLineStatus = 0 => The system is not using AC power > Laptop + battery
ACLineStatus = 1 => The system is using AC power => Laptop + AC
ACLineStatus = 255 => AC power status is unknown => Desktop
Disclaimer : Try experimenting with the... |
4,849,556 | 4,850,352 | Does C++0x allow decltype() in function signature? | This question obviously assume that we don't want to use templates for this type (for whatever reasons).
class Product
{
public:
Product( decltype(mPrice) price_, decltype(mLabel) label_ ) // 1.
: mPrice( price_ ), mLabel( label_ )
{}
decltype(mPrice) price() const {return mPrice;} // 2.
decltype(mL... | All you have to do is declare mPrice and mLabel before you use decltype:
class Product
{
private:
float mPrice ;
std::string mLabel;
public:
Product( decltype(mPrice) price_, decltype(mLabel) label_ ) // 1.
: mPrice( price_ ), mLabel( label_ )
{}
decltype(mPrice) price() const {return mPrice;} //... |
4,849,578 | 4,850,034 | Windows application consumes too much memory. Any advices? | Visual studio 2008 application using C++ under windows XP.
Any useful advices beyond the "always delete new objects" advice?
Edit: Actually I am looking for some programming advices.
| Depends what you mean by "consumes too much memory".
A) By design i.e. it requires to load or generate large data structures that you expect to cause problems.
In this case is it i) too much phyical memory i.e. it becomes slow because the hard drive starts swapping pages in and out or ii) too much address space i.e. it... |
4,849,632 | 4,849,646 | vector<int>::size_type in C++ | What is meant by this C++ statement?
vector<int>::size_type x;
And, what is the use of the scope operator :: here? In other words, how do we read this statement in English?
For example, for X::x(){...}, we say that x() is a member function of class X.
| size_type is a (static) member type of the type vector<int>. Usually, it is a typedef for std::size_t, which itself is usually a typedef for unsigned int or unsigned long long.
|
4,849,678 | 4,849,780 | C++ for-loop - size_type vs. size_t | In the C++ Primer book, Chapter (3), there is the following for-loop that resets the elements in the vector to zero.
for (vector<int>::size_type ix = 0; ix ! = ivec.size(); ++ix)
ivec[ix] = 0;
Why is it using vector<int>::size_type ix = 0? Cannot we say int ix = 0? What is the benefit of using the first form on the th... | The C++ Standard says,
size_type | unsigned integral type | a type that can represent the size of the largest object in the
allocation model
Then it adds,
Implementations of containers
described in this International
Standard are permitted to assume that
their Allocator template parameter
meets the foll... |
4,849,845 | 4,850,797 | Usage of Different IPC mechanism | I am a c++ programmer.
I wanted to know a real time scenario where we can use different IPC mechanisms like PIPE/Named, Shared Memory.
I roughly know where I can use socket and message queue. But for PIPE/Named PIPE and shared memory I am not getting any idea.
This is just for understanding about different IPC mechanis... | I needed to use Named pipe for communicating with my Erlang Vitual Machine which was running as a daemon. I believe they are being slowly replaced by "socketpairs" as it offers bi-directional communication unlike pipes which is only unidirectional unless we create two different pipes.
Shared Memory are still in use in ... |
4,850,345 | 4,850,441 | What do the statements "#pragma managed(push, off)" and "#pragma managed(pop)" mean? | I am looking at some C++/CLI code and have seen a lot of such statements mostly around #includes. What do they mean? I know that they, according to MSDN, Enable function-level control for compiling functions as managed or unmanaged. But I am interested in their inner mechanics especially the push and pop semantics. If ... |
#pragma managed(push, off)
Sets managed compilation option to the code after this line to off, and pushes to the stack previously active managed option.
#pragma managed(pop)
Restores last managed state from the stack. Code between these two lines is compiled as unmanaged. Code after pop line is compiled with the s... |
4,850,384 | 4,851,588 | compare two images using OpenCV | I want to compare two images using OpenCV. Could I filter the nearest matching result among other training data set..?
Example : the Database containing training image which show number 5 in using one hand.
Is it possible to match someone else ,same sign with that training image..?
Using OpenCV. Please help me.
| Like sinelaw said, there is no straightforward, easy solution in general.
However, I can think of one simple way that would work for your specific example.
Detect areas corresponding to human skin in the image. This is assuming the person isn't wearing gloves (if they are, knowing the color of the gloves will help). ... |
4,850,530 | 4,850,546 | Dynamic allocation in C++ using 'new' | Bit confused about usage of new to allocate memory dynamically.
e.g. If I need to allocate memory for 100 ints(assuming int is 4 bytes), should I say :
int *ptr = new int[100];
or
int *ptr = new int[100*4]; //assuming int is 4 bytes.
Basially new operator allocates memory in bytes or that many bytes of type T used w... | The size given to new is the number of items, not the memory size. However, consider using std::vector instead.
For example, new int[100] allocates at least 100 * sizeof(int) bytes (which is 400 when sizeof(int) is 4); any more it allocates will be due to implementation and runtime details which you (except for very r... |
4,850,555 | 4,850,594 | iostreams slow. Is there a way to speed them up? | I've been hacking at a problem on and off for several days now that lists filenames that exceed the Windows MAX_PATH limit.
I'm using Visual Studio 2008 with all the patches I can find. The timing is done with QueryPerformanceCounter and company.
The latest issue occurs in the following code:
start = getTime();
... | It is very likely that the std::endl line terminator is causing the performance bottleneck, since it flushes the stream after putting the newline. Exchange it with '\n' and a std::wcout << std::flush at the end of all output.
start = getTime();
for( vector<wstring>::iterator it = files.begin(); it != files.end(); ++it ... |
4,850,578 | 4,850,882 | Making sure same configuration is used for library and executable | let's say I am distributing a library as binary. It is shipped in two versions, debug and release. Debug and release are incompatible with each other, so if e.g. the user builds a release executable, he/she must link with release library.
If there is a mismatch between library and executable versions, currently there w... | I'm going to assume that you are using a static library and by binary you mean a .lib that will be linked at compile time (as opposed to a dll or the like that might be mismatched at run-time).
Seems to me the easiest way is to have this sort of a construct in your .h file
#ifdef _RELEASE //or whatever your compiler us... |
4,850,674 | 4,850,759 | is it possible to restrict class instances to be used only as temporaries? | is it possible to restrict class instances to be used only as rvalues (e.g. temporaries)?
for example, I have class Wrapper whose constructor takes A const& and saves this reference in its member. It's a dangerous because lifetime of Wrapper instance cannot be longer than lifetime of A instance, but it's fine if Wrapp... | I don't think it would be safe:
const A &a = YourClass( tmp );
YourClass in this case is the class you're looking for which only allow temporary instances, tmp is the temporary value you pass to the constructor.
It's possible (ie: safe, defined behavior) to have a constant reference to a temporary (ie: a), but the tem... |
4,850,794 | 4,862,426 | Is it necessary to destroy a tooltip? | In my application I am handling the WM_HELP message and then creating a tooltip for a control using this method:
Taken from: http://msdn.microsoft.com/en-us/library/bb760252(v=vs.85).aspx
HWND CreateToolTip(int toolID, HWND hDlg, PTSTR pszText)
{
if (!toolID || !hDlg || !pszText)
{
return FALSE;
}
... | It's been a while since I've done any WinAPI programming but if my memory serves me...
The call to CreateWindowEx passes the hDlg as the hWndParent parameter meaning the dialog window is now the parent of the tooltip.
From the MSDN documentation on the DestroyWindow function it says:
If the specified window is a paren... |
4,851,001 | 4,851,154 | boost asio async_read_until: how to raise error from a custom MatchCondition? | I am trying to optimize an application layer protocol that has a mixed mode protocol ( line protocol for meta info, handshake, acknowledgement, etc. and binary for data ). In a state where the client is waiting for an ACK, I do
async_read_until(socket, buffer, untill_crlf_maxbytes_1024_match_condition, handler);
Wher... | By raise error, do you mean throw exception? If so, it's a bad idea because most functions of boost asio have two versions: throwing exceptions and returning error codes. Error codes are very useful for asynchronous nature of boost asio.
You can return true from your match condition for all cases, including errors. Jus... |
4,851,075 | 4,851,173 | Universally compiler independent way of implementing an UNUSED macro in C/C++ | When implementing stubs etc. you want to avoid "unused variable" warnings. I've come across a few alternatives of UNUSED() macros over the years, but never one which either is proven to work for "all" compilers, or one which by standard is air tight.
Or are we stuck with #ifdef blocks for each build platform?
EDIT: Due... | According to this answer by user GMan the typical way is to cast to void:
#define UNUSED(x) (void)(x)
but if x is marked as volatile that would enforce reading from the variable and thus have a side effect and so the actual way to almost guarantee a no-op and suppress the compiler warning is the following:
// use expr... |
4,851,234 | 4,851,326 | Difference between int* and int[] in C++ | Context: C++
Consider the example below
class TestClass
{
private:
int A[];
int *B;
public:
TestClass();
};
TestClass::TestClass()
{
A = 0; // Fails due to error: incompatible types in assignment of `int' to `int[0u]'
B = 0; // Passes
}
A = 0 fails but B = 0 succeeds. What's the catch? What exact... | The only difference between them is that int A[] in a class would not compile, and should not compile!
Comeau C++ compiler gives this error:
"ComeauTest.c", line 4: error:
incomplete type is not allowed
int A[];
^
Wikipedia says,
Comeau C/C++ has been regarded as the
most standards-conformant ... |
4,851,810 | 4,851,838 | Are C++ enums slower to use than integers? | It's really a simple problem :
I'm programming a Go program. Should I represent the board with a QVector<int> or a QVector<Player> where
enum Player
{
EMPTY = 0,
BLACK = 1,
WHITE = 2
};
I guess that of course, using Player instead of integers will be slower. But I wonder how much more, because I believe t... | Enums are completely resolved at compile time (enum constants as integer literals, enum variables as integer variables), there's no speed penalty in using them.
In general the average enumeration won't have an underlying type bigger than int (unless you put in it very big constants); in facts, at §7.2 ¶ 5 it's explicit... |
4,851,858 | 4,852,081 | Error when running OpenGL project under Ubuntu 10.10 | I had OpenGL project for finding a convex hull written in Windows.
Now i'm using Ubuntu 10.10 and i tried to port the code (It's C++ code) and run it.
I saw that, it should be compiled this way :
g++ convex.cpp -lm -lglut -lGLU -o convex_hull_project
It compiles the file, but when i run the file ./convex_hull_project ... | You have to call glutCreateWindow before you set windows's properties. Your code, fixed (I've replaced width and height constants with 300 just to get it to compile and commented out mouse handler registration):
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <GL/glut.h>
#include <GL... |
4,851,995 | 4,852,070 | Serialize a struct and send it via socket with C++ | i would send a struct via C++ sockets. This is an example struct:
struct PIPPO
{
int x;
int y;
};
that i use with:
PIPPO test2;
test2.x = 10;
test2.y = 20;
and I have the code above to serialize and send it via socket. The problem is that if I try to get the HEX value of the test variable i only see 0A and infact on ... | Sending a raw binary representation over the wire can cause you problem, specially when you have an heterogeneous network or applications. Have a look to protobuf which might be best suited for this.
|
4,852,249 | 4,942,423 | What is the preferred way in C++ for converting a builtin type (int) to bool? | When programming with Visual C++, I think every developer is used to see the warning
warning C4800: 'BOOL' : forcing value to bool 'true' or 'false'
from time to time. The reason obviously is that BOOL is defined as int and directly assigning any of the built-in numerical types to bool is considered a bad idea.
So my ... | There is no preferred way in C++, since the C++ Std simply allows the integral conversion from int to bool. (So the preferred way wrt the Std would be bool b = i;.)
That said, judging from the other answers, there does not even seem to be an accepted way to do it in Visual C++ (MS) although the MSDN page states
... I... |
4,852,533 | 4,853,594 | Efficient implementation of a threaded console window | I have a Win32 application that consists of two components: A main window that acts as the app's interface and a secondary modeless dialog that functions as a console. The application generates copious amounts of debug text during certain (regular) operations.
Having to update the console's edit control during every de... | I tried using a timer in the main thread and it worked well enough for me. My thanks to the posters!
|
4,852,658 | 4,852,859 | polymorphic iterators in C++ | I'm trying to implement a polymorphic iterator in C++. Basically, I need this to be able to apply a filter, so that the iterator would skip some items depending on the associated condition. So I made a GoF-like iterator with an abstract interface, this allows me to derive a filtered iterator from it and implement the r... | The usual approach is to use compile-time polymorphism instead of runtime polymorphism; this allows the compiler many more opportunities to optimize code using the iterator and generally is more idiomatic in modern C++.
If you do need runtime polymorphic behavior, it's probably easiest to encapsulate the polymorphism w... |
4,852,706 | 4,852,724 | Embedding Lua: how to programatically save a script to a folder, how to compile a script? | I am embedding Lua in a C++ application, and I am using luaL_dofile to load a script
However, I cannot seem to find documentation on the functions to use to:
Compile a script (and save byte stream to a specified folder)
Save a script to a specified folder
last but not the least, when I use luaL_dofile to load a scrip... | Look up luaL_loadfile and lua_dump. See also test/luac.lua.
|
4,852,954 | 4,855,593 | In C++, how to compute the mean of a vector of integers using a vector view and gsl_stats_mean? | my program manipulates STL vectors of integers but, from time to time, I need to calculate a few statistics on them. Therefore I use the GSL functions. To avoid copying the STL vector into a GSL vector, I create a GSL vector view, and give it to the GSL functions, as in this piece of code:
#include <iostream>
#include ... | Use the integer statistics functions:
cout << "mean=" << gsl_stats_int_mean( gsl_v.vector.data, 1, stl_v.size() ) << endl;
Note the gsl_stats_int_mean instead of gsl_stats_mean.
|
4,853,037 | 4,853,111 | how to create taskbar button w/o any window? | I have simple no-UI application that will be then converted to windows service. but for testing it would be useful to see when it's running. so I'd like to create a taskbar button as other applications with UI have. is it possible with reasonable effort?
| No, it's not possible. Buttons on the taskbar represent windows. You can't have a button without a window, and that window needs to be visible. (The window can have coordinates that place it off the screen(s), and it can have zero dimensions, but it needs to have the WS_VISIBLE style.)
Another option is to create a not... |
4,853,263 | 4,853,298 | Why so many errors here in typedef? | from this:
// parts of c++0x std
#include <boost/bind.hpp>
#include <boost/function.hpp>
#ifndef _IGraphElement_h_
#define _IGraphElement_h_
using namespace std ;
template <typename DataType >
class IGraphElement : public IGraphElementBase{
typedef boost::function<void(DataTy... | typedef FunctionSequence::iterator FunctionIterator; // (line **)
This should be written as,
typedef typename FunctionSequence::iterator FunctionIterator;
Since iterator is a dependent name, so typename is required!
Read about dependent name here:
Name binding and dependent names (C++ only)
Dependent Names (scroll ... |
4,853,360 | 4,853,473 | Comparing arrays of different size | I am implementing my own boost::array variant for fun and education, and I was just wondering: should comparing two arrays of different size yield false, or should it be a type error?
array<int, 3> a = {1, 2, 3};
array<int, 5> b = {1, 2, 3, 4, 5};
a == b // <--- false or type error?
| In the language, the different template instantiations are unrelated types. That means that technically, the simplest thing to do is what boost::array does: ignore the problem, the compiler will yell if you try to compare different sizes.
I was inclined to answer that this depends on the domain that you are modeling, b... |
4,853,375 | 4,854,159 | Compiler Error doesn't make sense (error is missing parameter to function) | I am getting a compiler error of:
error: no matching function for call to buildTransFunc(<unresloved overloaded function type>, boost::function<EnumType(short int)>, EnumTypeToStringTranslator&)
The declaration for buildTransFunc is as follows:
template<typename RT, typename func, typename... Args>
RT buildTransFunc(fu... | I guess the moral of this question is don't try to be too fancy... as this works by
plainly calling boost::bind with the parameters, instead of forwarding them though a seprate function.
so instead of this:
toASCIITranslator temp = buildTansFunc<.....>(....);
just do the call like this:
toASCIITranslator temp = boost:... |
4,853,384 | 4,853,407 | What is the purpose of the returning of a value from main() in C/C++? |
Possible Duplicates:
main() functions return value?
What should main() return in C/C++?
What is the purpose of the returning of a value from main() in the languages C and C++?
How the return value helps us?
Can the return value be used to achieve anything important?
| It's the exit status. It's typically used to signal to the OS whether the process was successful or not in whatever it was doing.
|
4,853,542 | 4,853,578 | Boost/std bind how to solve such errors? (binding function from one class to another class) | So I am triing to create a simple graph connecting one class to another...
#include "IGraphElement.h"
#include <boost/bind.hpp>
class simpleRendererGraphElement : public IGraphElementBase, public simpleRendererLibAPI
{
public:
IGraphElement<ExtendedCharPtr>* charGenerator;
// we owerrite init
void Init(I... | If you are using boost::bind you need to use boost::placeholders. You can't mix-and-match.
(Visual C++ 2008 doesn't even include std::placeholders, though; the TR1 service pack includes std::tr1::placeholders, but the C++0x std::placeholders wasn't introduced until Visual C++ 2010.)
|
4,853,550 | 4,854,072 | Import Existing C++ Source Code into Visual Studio | I am trying to import an existing c++ application's source into visual studio to take advantage of some specific MS tools. However, after searching online and playing with visual studio, I cannot seem to find an easy way to import existing c++ source code into visual studio and keep it structurally intact.
The impor... | I am not aware of any general solution under the constraints given - specifically having to create many projects from a source tree.
The best option I see is actually creating the project files by some script.
Creating a single project manually (create empty project, then add the files),
Configure it as close as pos... |
4,853,611 | 4,853,682 | How can I extend a compiler generated copy constructor | I frequently run into the problem, that I must extend a compiler generated copy constructor. Example:
class xyz;
class C
{
...
int a, b, c;
std::set<int> mySet;
xyz *some_private_ptr;
};
Assume, that some_private_ptr should only be copied under certain conditions. For other conditions it should be res... | the moment you define your own copy ctor, the compiler does not bother generating one for you. Unfortunately this means you have to do all the leg work yourself! You could group the members into some sort of impl_ structure within your class, and then rely on the copy ctor for that.
for example:
class xyz;
class C
{
... |
4,853,627 | 4,853,814 | Stopping a Timer With Virtual Keys | I've created a basic window which handles virtual keys. The case VK_UP initializes a timer which is counting from 9 backwards. The timer can be stopped if either 0 is reached or VK_DOWN is pressed. The problem is, when I initialize the timer with VK_UP the program stops until the timer has reached 0. How can I interrup... | Use a real timer, not a counting loop. Review SetTimer(). Understanding the event driven programming model for Windows is pretty important, it is well covered by any book about Windows programming, like Petzold's.
|
4,853,847 | 4,858,212 | passing argument/arguments signal to callback on GTK+ in C | Here is my code:
#include <gtk/gtk.h>
G_MODULE_EXPORT void waka(GtkWidget *button, GtkWidget* entry1)
{
printf("%s",gtk_entry_get_text(GTK_ENTRY(entry1)));
}
int main(int argc, char * argv[])
{
GtkWidget *window, *button, *entry;
gtk_init(&argc,&argv);
window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
button = gtk_bu... | the problem is that you're trying to use pointer to entry before initializing it. I've changed a bit your code to fix this, see if it will work for you:
#include <gtk/gtk.h>
void waka(GtkWidget *button, GtkWidget* entry1)
{
g_print("entry: %s\n", gtk_entry_get_text(GTK_ENTRY(entry1)));
}
int main(int argc, char * ar... |
4,853,851 | 4,854,160 | Get compression ratio of image | I use LibJPEG to read JPEG compressed images. Is there a way to get the current compression ratio of the unchanged image?
| Do you mean the encoding quality, usually a number 0-100?
That isn't stored - it's used as a guide for the image encode as to how accurate the waves should be, and it's then discarded. There's no field for it in any of the JFIF header structures. As far as I can see there's no formal definition of what this number mean... |
4,854,284 | 4,854,499 | How do I resolve an IP into host using c-ares? | This is what I've done so far. It compiles, but it segfaults when I try to run it.
#include <iostream>
#include <netdb.h>
#include <arpa/inet.h>
#include <ares.h>
void dns_callback (void* arg, int status, int timeouts, struct hostent* host)
{
std::cout << host->h_name << "\n";
}
int main(int argc, char **argv... | You atleast have to initialize the ares_channel before you use it
if(ares_init(&channel) != ARES_SUCCESS) {
//handle error
}
You also need an event loop to process events on the ares file descriptors and call ares_process to handle those events (more commonly, you'd integrate this in the event loop of your appli... |
4,854,447 | 4,906,826 | If I want to develop Layered Service Provider to support all Windows OS's, what problems should I expect? | I want to develop simple HTTP filter (transparent proxy).
I want it to support all versions of Windows including XP and above.
From the folks that have experience with this, what problems should iIexpect when installing the service?
| There are some that I could quickly think of on top of my head:
-You should be aware that you have to cover all browsers or at least major ones like IE, firefox, chrome, safari and opera. The ways they use Winsock are different, eg overlapped vs. non-overlapped IO.
-Installation/Uninstallation is challenging as it's v... |
4,854,503 | 4,854,610 | C++ Variables - declare and define. Inheritance | Let's have a C++ object A. There are two variables (VAR1 and VAR2) in A accessible to its children.
Object B extends A and has one private variable VAR3 it can also access VAR1 and VAR2. Each instance of A/B has its own variables.
Would this be the right way of declaring and defining the variables?
A.h
class A {
prote... |
Each instance of A/B has its own variables.
Would this be the right way of declaring and defining the variables?
No. You've declared A's members as static which means they are class-variables, not instance-variables. Each instance doesn't get it's own copy. Instead, they all share the same instance.
Make then non-... |
4,854,554 | 4,854,664 | Gui library for game | I'm making a game with OpenGL render api. Now I need in level editor. It should consist of lots of widgets parents/children etc, so it's hard to write need widgets by hands.
Any ideas about good gui-system which can be easilly connected with opengl? The most important part is gui editing. I really need some editing-too... | You should have a look to http://qt.nokia.com/ .
It is very easy to inject the OpenGL rendering into Qt widgets.
To easily edit your GUI, you can use Qt Creator ( http://qt.nokia.com/products/developer-tools ).
|
4,854,567 | 4,857,677 | can I combine clr-based targets in MSBuild for c++ file? | Is it possible to call all types of targets in an MSBuild project file that starts as a C++ project file?
Perhaps that question is not quite accurate, but my intention is to use targets from the MSBuild extention pack along with the new C++ targets for VS 2010.
I'm guessing the need for the new C++ targets is to have s... | You should be able to import and utilize the functionality provided by the MSBuild Extension Pack just fine -- it does not matter what language the tasks were written in or what language source code other tasks in your MSBuild project file are compiling. They're all just MSBuild tasks.
|
4,854,584 | 4,854,802 | glTexImage2D multiple images | I'm drawing an image from openCV full screen, this is a large image at 60fps so I needed a faster way than the openCV gui.
Using OpenGL I do:
void paintGL() {
glClear (GL_COLOR_BUFFER_BIT);
glClearColor (0.0,0.0,0.0,1.0);
glDisable(GL_DEPTH_TEST);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
... | The reason why you cannot see how to add another texture is because you are missing two critical functions in the code that you posted: glGenTextures and glBindTexture. The first will generate texture objects in the OpenGL context (places for textures to exist on the graphics hardware). The second "selects" one of thos... |
4,854,678 | 4,854,734 | Android C++ Native Code | I am a new Android developer and I would like to create an application using only C/C++ code for Android but I have found the documentation to be very limited. I can create an Android C/C++ project in eclipse, but it uses a lot of java code.
I'm using NativeActivity (new to 2.3) and I need help setting up my project. D... | Just remove all of the generated Java code. You don't need it if you want a purely native activity. The only thing you need to do is to set up the Android Manifest file as shown in the documentation. In particular, you'll need:
<!-- Tell NativeActivity the name of or .so -->
<meta-data android:name="and... |
4,854,774 | 4,855,925 | C++0x (C++11) as functional language? | i'm wondering if C++0x (C++11) (with lambdas and perfect forwarding) is (a superset of) a functional language.
is there any feature of functional languages, that C++ doesn't have?
| The functional programming paradigm models computation as a relation between sets, and is thus inherently declarative. However, in practice, we often think of functions as imperative, ie you put in an input value and get out an output value, same as with a procedure. From this point of view, the characteristic property... |
4,854,886 | 4,855,060 | Convert from int to int32 | I have a bunch of int's in my c++ code that I need to change to int32's. Same with my bool's. What header do I need to include in order to use int32's and bool32's. Also how do I declare these once I make them. Am I able to just replace the int's with int32's?
For example:
int x;
Becomes
int32 x;
I am getting lots of... | On windows you should be able to use the built in type __int32. I've never hear of a 32 bit bool, but you can just use typedef for that one.
|
4,855,073 | 4,855,090 | std::string s = (std::string)"a" + "b" + "c"; OK? | It works, no crashes. Is it OK?
edit: the reason I ask is that std::string s = "a" + "b" + "c"; produces a compiler error, and (std::string)"a" just tells the compiler, "Just presume what "a" is pointing at is an std::string". And I didn't actually know how std::string is implemented.
Thanks for the feedback from ever... | Yes. + is left-associative, so it's equivalent to ((std::string)"a" + "b") + "c". std::string::operator+ is overloaded to take a const char * as the argument.
|
4,855,219 | 4,868,535 | Binding class member function to c-function | Below I have a concept of binding class member function to a global function. The main purpose of this is using C++ for C-style callback function implementation. Can this be done in a better way (for example, without final macro or typeof, or using C++0x features)?
#include <iostream>
using namespace std;
template<ty... | I think that the only technique which will work perfectly is to write a C wrapper function for each member function that you wish to invoke within a C callback; i.e.:
extern "C" void Foo_x(Foo *foo)
{
foo->x();
}
extern "C" void Foo_x1(Foo *foo, int i)
{
foo->x1(i);
}
You could also use lambda expressions of ... |
4,855,389 | 4,856,884 | Using Strncmp with a string from a file | Goodnight to everyone, I'm trying to parse an .h file so I can have a small console frontend to change its values, but when I try to use strncmp with a string read from a file and a string defined in code to compare with the file string I get a strange error from the compiler that I cant resolve, here is my source code... | the problem is that strncmp() function overloaded for strncmp(const char*, const char*, int)
but you want to call it by strncmp(string, string, size_t)
you must convert string to const char* with
c_str()
for example
string str = "Hello";
char * arr = str.c_str().
you get it?
|
4,855,422 | 4,855,490 | C++ classes (public, private, and protected) | How can classes in C++ be declared public, private, or protected?
| In C++ there is no notion of an entire class having an access specifier the way that there is in Java or C#. If a piece of code has visibility of a class, it can reference the name of that class and manipulate it. That said, there are a few restrictions on this. Just because you can reference a class doesn't mean yo... |
4,855,475 | 4,855,870 | Boost Spirit v2 gcc compilation error which does not show up using msvc | I recently wrote some spirit parsing code in windows, which I recently have tried to get build on an ubuntu box and have ran into a compilation error that I am struggling with.
After some hacking and slashing, I have managed to come up with this example code snippet which exhibits the same behavior:
struct FooParser
: ... | I think the problem here is the begin() and end() of std::string, try this:
std::string::const_iterator begin = txt.begin();
std::string::const_iterator end = txt.end();
then pass that in:
phrase_parse(begin, end, foobar, space, result)
The problem I believe is that everywhere else you are using the type const_iterat... |
4,855,544 | 4,855,624 | Using winsock on an AIX system - possible? | Is it possible to use winsock on an AIX system?
If not, is there any native support in C++ for unix based machines and e-mail support, without importing 3rd party libraries?
Thanks in advance
| Winsock's analog in AIX is the use of the BSD sockets API, which is what Winsock is based on.
There will be some differences, but if you have email code written in Winsock, you should be able to translate it to BSD API.
Here's a tutorial/guide: http://beej.us/guide/bgnet/
Here's AIX 6.1's sockets guide: http://publib.... |
4,855,597 | 4,855,651 | How do I create a timer? (Do something every X seconds/minutes/hours) | I need to do something in my program every 10 seconds and I don't know how to do it in C++ Console Application. In C# I could just create a timer but I'm struggling here now...
sleep(); is not an option because as far as I know it makes your program inactive for X seconds, I need my app to be active and working, calcul... | Boost has a timer library.
http://www.boost.org/doc/libs/1_45_0/libs/timer/index.html
In fact, if you haven't come across Boost already, I'm sure you'll find it very useful.
To do an event based timer, you should look at this answer.
|
4,855,844 | 4,855,938 | SDL_Surface pointer passing between two classes | If I declare a SDL_Surface pointer in a class, can i share it with another class to draw on it in somehow?
class foo{
private:
SDL_Surface* mainScreen;
public:
foo() {
mainScreen = SDL_SetVideoMode(400,300,32, SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_OPENGL);
}
~foo() {
SDL_FreeSurfa... | Screen is black probably because you're using double buffering and never flip the buffer (call SDL_Flip(a.getSurf()) after b.draw).
|
4,856,348 | 4,856,411 | Multi-threading jobs that need to maintain order | I have a c/c++ process that has a long queue and every element in this queue needs to be
sent to a multiple (TCP) servers. The single thread is an option that works, however it is slow.
I need to implement a multithreaded solution. My process does not know in advance the number
of servers. The first idea is to create o... | Have you looked at boost asio? It supports the concept of a "thread pool", so rather than a single thread per server (that is synchronous), you can have a pool of threads handling a large number of connections asynchronously. Performance isn't too bad either...
|
4,856,396 | 4,856,537 | When creating a "Handler Registration" type architecture, how should I pass handlers? | I am for learning purposes writing a UDP client/server protocol in c++, where the communication from the server component of my application to the rest of the application is achieved using handlers.
For example, I might register an Authorization component against the value 1, and an TextMessage component against value ... | When in doubt, share with a shared_ptr. That's self-documenting and almost always works, at the expense of some pointer indirection and one/two memory allocations.
|
4,856,736 | 4,856,795 | Calling managed delegate from unmanaged code using COM interop | I'm working on a hobby project where I need to call a managed delegate from unmanaged C++. Due to external constraints I also need to pass the delegate from managed code to unmanaged code at runtime.
Ideally, what I would want to do is to simply call the delegate as I would in C# (by invoking the delegate using the sam... | Just export a function that accepts a function pointer. The C# code can call it, passing a delegate object. The pinvoke marshaller does the heavy lifting, same thing as Marshal.GetFunctionPointerForDelegate(). Which creates a stub that stores the delegate's Target and Method. The function pointer you'll get points ... |
4,856,753 | 4,857,155 | Speed of HTTP GET Method in C++ | I have been using certain libraries in a C++ program to connect and fetch different websites. Mainly I used Chillkat and Curl. However, recently I started programming my own HTTP fetcher, using the help of MSDN and the Winsocket2 library.
I programmed my software to open a socket with SOCKET_STREAM type and for Ipv4,
... | If you are seeing performance differences on a modern machine with low volumes, the most likely problem is that you have forgotten to turn off the Nagle algorithm. Use setsockopt() to set TCP_NODELAY to 1. HTTP is not Telnet.
I wouldn't worry about explicit flushing or buffer management or anything like that until you ... |
4,856,951 | 4,903,317 | Where can I find "C/C++ Users Journal" code archive? | The articles can be found from Dr. Dobb's web site, but I can't find the links to the source code anywhere. I'm looking at this article in particular (http://www.drdobbs.com/cpp/184403758). Googling around seems to suggest that the source code used to be at http://www.cuj.com/code/archive.htm or ftp.cuj.com/pub/ but ne... | DDJ and CUJ source code are archived here:
http://www.drdobbs.com/sourcecode/index.jhtml
|
4,856,993 | 4,860,025 | private vs public ports | I am having a tough time with private and public udp ports. I am doing a client-server VoIP program and have some questions.
1) the private port is the one you use in bind() right?
2) the public port is assigned by the firewall right? as it is the port visible outside my local network.
3) When I am debugging between t... |
1) the private port is the one you use
in bind() right?
Right.
2) the public port is assigned by the
firewall right? as it is the port
visible outside my local network.
Well, yes, but it's not exactly the firewall. It's the NAT. Of course, NAT could be (and most often is) implemented in the firewall, but ther... |
4,857,001 | 4,857,034 | what will be the official name of c++0x? | as I know standard should be accepted this year. So, will it be c++11?
| [ED: Since this question was asked the C++ Standard has been published. In my answer I have changed past tense to present tense and elaborated a bit on things that have clarified since release.]
The name of the language according to the Standard is C++. In order to distinguish it from other versions of the Standard ... |
4,857,049 | 4,857,108 | Syntax for default template template parameter | I have written a list-like template class sll (Single Linked List). Now, I am trying to plugin an allocator to it. I have the default allocator, allocator, and a pool based allocator, pool_allocator. These are designed after STL allocator interface, but I need to add the number of elements that the allocator would hand... | You have to write:
template<typename T,
typename Allocator = allocator<T, Default_3> >
class sll { ... };
|
4,857,087 | 4,857,116 | Creating a static array on the heap? | I need to create a very large array. Let us say 50 megabytes.
Can I be safe to create it as a normal static array? Will the compiler put it on the stack (possibly causing a stack overflow), or will it be smart enough to put it on the heap?
If there is no way to do so, is there an easy way to do it with malloc or "new" ... | As I understand it, static variables don't live on the stack. If they did, where would they go when you pop the stack frame they live in? Static function variables need to keep their state between calls, so logically, the static data should be kept on the heap.
Also, when the program ends, everything is automatically d... |
4,857,180 | 4,858,673 | A QLineEdit with a QCompleter won't show the QCompleter's popup menu with an empty text field | I have a QLineEdit, with a QCompleter object associated to it. If the user enters at least one character, the popup menu from the QCompleter is shown, but when the user deletes the last character (thus leaving the field empty) the popup disappears. Is there any way to make it show even when the QLineEdit's text is empt... | you should be able to force completer's popup window to get shown once your line edit text is erased by using QCompleter::complete slot:
lineEdit->completer()->complete();
Here's how you can do it:
define textChanged slot for your lineedit;
override customEvent method for your window;
in the textChanged slot send use... |
4,857,188 | 4,857,397 | Clearing a Layout in Qt | I'm creating an application in Qt that allows users to drag around various "modules" in a QGraphicsView. Whenever one of these modules is selected, it emits a signal which is then picked up by a "ConfigurationWidget" which is a side-panel which should display all of the relevant parameters of the selected module:
cla... | It looks like the best way to do this is to use a QStackedLayout, as hinted at by armonge:
void ConfigurationWidget::moduleSelectedSlot(Module* m)
{
QStackedLayout *stackedLayout = qobject_cast<QStackedLayout*>(layout());
QWidget *layoutWidget = new QWidget(this);
QFormLayout *formLayout = new QFormLayout(layout... |
4,857,225 | 4,857,346 | deriving from std::exception | i want to derive from std::exception to add specific information to my log files, but i cant figure how to access the .what() from the std::exception.
furthermore, i know that it is unsafe to create a string in my exception handler, but i'm not an expert on this topic, so what are some safer alternatives?
struct Except... | EDIT: Since writing this answer, I've stumbled upon the Error and Exception Handling section in the Boost document. I would recommend that document over this answer.
First off, making your exception not-copyable is a bad idea. When you write something such as
// could be any exception, doesn't matter.
throw Exception... |
4,857,563 | 4,857,653 | correct format for reading and writing binary strings using ifstream | I'm trying to read back a string that I wrote into a binary file, but it's giving me problems and I don't know what's going on. I open and read my file using the code below:
ifstream input([filePath UTF8String], ios::in | ios::binary);
int numStringBytes;
input.read((char*)&numStringBytes, 4);
char *names;
input.read((... | names needs to be allocated.
You can use something like:
char *names = new char[ numStringBytes ];
input.read((char*)names, numStringBytes);
...
delete[] names; // don't forget to dealocate
or, better yet, use a std::vector:
std::vector<char> names( numStringBytes, 0 ); // construct a big enough vector
input.read((cha... |
4,857,629 | 4,857,681 | 2d QList Memory Leak | I created this 2D Qlist. Code "works" but when I consider a bit deeper the syntax it leaves me wondering whether this code leads to memory leak.
I would be great if someone could shed some light on whether this code leads to a mem leak or not. If it does, WHY and how to fix?
My Specific concerns are question marke... | I would suggest checking for memory leaks using something similar to valgrind or other.
However, when memory "leaks," it means that that memory was simply not freed after use and all access has been removed. This essentially means that there is memory allocated on the heap, for example, but nothing has access to it so... |
4,857,678 | 4,858,769 | Android C++ NDK Sample not updating | I got the hello-jni sample to run on my emulator and it will say "Hello from JNI !" via hell-jni.c. However when I change
return (*env)->NewStringUTF(env, "Hello from JNI !");
to
return (*env)->NewStringUTF(env, "Hello from TEST !");
Then I close my emulator, open it back up I will not see the string update. I tried... | You have changed the native code. So just by clean and run you will not get the effect.
If you change the native code you need to build the native library again. Need to make the make the native library using NDK
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.