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,661,685 | 2,662,053 | CAsyncSocket and ThreadPool problem | I have a server application with such structure:
There is one object, call him Server, that in endless cycle listens and accepts connections.
I have descendant class from CAsyncSocket, that has overriden event OnReceive, call him ProxySocket.
Also I have a thread pool with early created threads.
When connection is received by server object he accepts the new connection on the new object ProxySocket.
When data arrives to the ProxySocket, he creates a command object and gives it to thread pool. In this command object I giving the socket handle of a ProxySocket. When new object of command is creating - I creating a new Socket in working thread and attach handle to it.
My issue is next:
When command ends, socket doesn't close, I just detach handle it and set CSocket handle to INVALID_SOCKET value, as planned. But my first ProxySocket object doesn't receives messages of new data receiving after that. How can I solve this?
| I don't think you can use CAsyncSocket objects (or their descendants) in a thread pool secenario. CAsyncSockets are implemented on top of WSASsyncSelect - which tells the winsock to send notifcations to a window handle.
Because windows have thread affinity, one can never "move" the CAsyncSocket handling to a different thread.
|
2,662,102 | 2,662,112 | Import a shared object and call its functions in C++ | Is it possible to import a shared object (without linking the program with it) and call any function?
| Yes it is possible.
Windows: use LoadLibrary and GetProcAddress.
POSIX: use dlopen and dlsym.
There is a mini tutorial here.
|
2,662,146 | 2,662,152 | Problem with array of elements of a structure type | I'm writing an app in Visual Studio C++ and I have problem with assigning values to the elements of the array, which is array of elements of structure type. Compiler is reporting syntax error for the assigning part of the code. Is it possible in anyway to assign elements of array which are of structure type?
typedef struct {
CString x;
double y;
} Point;
Point p[3];
p[0] = {"first", 10.0};
p[1] = {"second", 20.0};
p[2] = {"third", 30.0};
| Give your struct a constructor:
struct Point {
CString x;
double y;
Point( const CString & s = "" , double ay = 0.0 ) : x(s), y(ay) {}
};
You can then say:
Point p[3];
p[0] = Point( "first", 10.0 );
|
2,662,370 | 2,665,074 | Formatting time in milliseconds using boost::date_time library | I have a time duration in milliseconds which I ideally would like to format using the formatting functionality present in the boost::date_time library. However, after creating a boost::posix_time::time_duration I can't seem to find a way to actually apply the formatting string to it.
| You need to add the duration to a time object first, and then output it like this:
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet("%Y%m%d %H:%M:%S.%f");
std::stringstream date_stream;
date_stream.imbue(std::locale(date_stream.getloc(), facet));
date_stream << boost::posix_time::microsec_clock::universal_time();
output:
20100326 12:02:08.024820
Tested with boost 1.41
|
2,662,417 | 2,662,523 | C++ Suppress Automatic Initialization and Destruction | How does one suppress the automatic initialization and destruction of a type? While it is wonderful that T buffer[100] automatically initializes all the elements of buffer, and destroys them when they fall out of scope, this is not the behavior I want.
#include <iostream>
static int created = 0,
destroyed = 0;
struct S
{
S()
{
++created;
}
~S()
{
++destroyed;
}
};
template <typename T, size_t KCount>
class fixed_vector
{
private:
T m_buffer[KCount];
public:
fixed_vector()
{
// some way to suppress the automatic initialization of m_buffer
}
~fixed_vector()
{
// some way to suppress the automatic destruction of m_buffer
}
};
int main()
{
{
fixed_vector<S, 100> arr;
}
std::cout << "Created:\t" << created << std::endl;
std::cout << "Destroyed:\t" << destroyed << std::endl;
return 0;
}
The output of this program is:
Created: 100
Destroyed: 100
I would like it to be:
Created: 0
Destroyed: 0
My only idea is to make m_buffer some trivially constructed and destructed type like char and then rely on operator[] to wrap the pointer math for me, although this seems like a horribly hacked solution. Another solution would be to use malloc and free, but that gives a level of indirection that I do not want.
The reason why I want this is because I am making a container and I do not want to pay for the initialization overhead of things that I will not use. For example, if my main function was:
int main()
{
{
std::vector<S> vec;
vec.reserve(50);
}
std::cout << "Created:\t" << created << std::endl;
std::cout << "Destroyed:\t" << destroyed << std::endl;
return 0;
}
The output would be correct:
Created: 0
Destroyed: 0
| You can create the array as array of chars and then use placement new to create the elements when needed.
template <typename T, size_t KCount>
class Array
{
private:
char m_buffer[KCount*sizeof(T)]; // TODO make sure it's aligned correctly
T operator[](int i) {
return reinterpret_cast<T&>(m_buffer[i*sizeof(T)]);
}
After re-reading your question it seems that you want a sparse array, this sometimes goes by the name of map ;o) (of course the performance characteristics are different...)
template <typename T, size_t KCount>
class SparseArray {
std::map<size_t, T> m_map;
public:
T& operator[](size_t i) {
if (i > KCount)
throw "out of bounds";
return m_map[i];
}
|
2,662,430 | 2,662,448 | Combining several static archives into a new one | I'm making a game engine for mobile devices. I want to compile my code, link it against a few static libraries and then combine my compiled code with those static libraries to form a new static library. However, my Google Fu is abandoning me.
Suppose I have static libraries a.a, b.a and c.a and my code. I want to compile all that into awesome.a.
How can I do that?
I'm using CodeSourcery's arm-none-linux-gnueabi-ar by the way.
Thanks in advance.
| Assuming that a.a, b.a, and c.a are in the CWD, something like:
mkdir a-objs && ( cd a-objs && ar -x ../a.a )
mkdir b-objs && ( cd b-objs && ar -x ../b.a )
mkdir c-objs && ( cd c-objs && ar -x ../c.a )
rm -f awesome.a && ar -r awesome.a a-objs/* b-objs/* c-objs/* && ranlib awesome.a
should work.
|
2,662,442 | 2,662,460 | C++ Function pointers vs Switch |
What is faster: Function pointers or switch?
The switch statement would have around 30 cases, consisting of enumarated unsigned ints from 0 to 30.
I could do the following:
class myType
{
FunctionEnum func;
string argv[123];
int someOtherValue;
};
// In another file:
myType current;
// Iterate through a vector containing lots of myTypes
// ... for ( i=0; i < myVecSize; i ++ )
switch ( current.func )
{
case 1:
//...
break;
// ........
case 30:
// blah
break;
}
And go trough the switch with func every time. The good thing about switch would also be that my code is more organized than with 30 functions.
Or I could do that (not so sure with that):
class myType
{
myReturnType (*func)(int all, int of, int my, int args );
string argv[123];
int someOtherValue;
};
I'd have 30 different functions then, at the beginning a pointer to one of them is assigned to myType.
What is probably faster: Switch statement or function pointer?
Calls per second: Around 10 million.
I can't just test it out - that would require me to rewrite the whole thing. Currently using switch.
I'm building an interpreter which I want to be faster than Python & Ruby - every clock cycle matters!
| Switch statements are typically implemented with a jump table. I think the assembly can go down to a single instruction, which would make it pretty fast.
The only way to be sure is to try it both ways. If you can't modify your existing code, why not just make a test app and try it there?
|
2,662,487 | 2,662,493 | What am I doing wrong?, linking in C++ | I'm trying to code a simple base64 encoder/decoder (to test my programming skill).
I can compile it, but it doesn't link, I've this message error:
C:\Documents and Settings\Facon\Escritorio>g++ base64.o main.o -o prueba.exe
main.o:main.cpp:(.text+0x24a): undefined reference to `Base64Encode(std::vector > const&)'
collect2: ld returned 1 exit status
Compiler & Linker: Mingw32 3.4.5
SO: Windows XP
This is my source code:
base64.h:
#ifndef BASE64_H
#define BASE64_H
#include <iostream>
#include <vector>
typedef unsigned char byte;
std::string Base64Encode(const std::vector<byte> &array);
std::vector<byte> Base64Decode(const std::string &array);
#endif
base64.cpp:
#include "base64.h"
std::string Base64Encode(std::vector<byte> &array)
{
const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const unsigned int size = array.size();
std::string output;
for (unsigned int i = 0; (i < size); i++)
{
if ((size - i) > 3)
{
output.push_back(static_cast<char>(base64_table[array[i] >> 2]));
output.push_back(static_cast<char>(base64_table[((array[i++] & 0x03) << 4) | ((array[i] & 0xF0) >> 4)]));
output.push_back(static_cast<char>(base64_table[((array[i++] & 0x0F) << 2) | ((array[i] & 0xC0) >> 4)]));
output.push_back(static_cast<char>(base64_table[array[i] & 0x3F]));
}
else if ((size - i) == 3)
{
output.push_back(static_cast<char>(base64_table[array[i] >> 2]));
output.push_back(static_cast<char>(base64_table[((array[i++] & 0x03) << 4) | ((array[i] & 0xF0) >> 4)]));
output.push_back(static_cast<char>(base64_table[(array[i] & 0x0F) << 2]));
output.push_back(static_cast<char>('='));
}
else if ((size - i) == 2)
{
output.push_back(static_cast<char>(base64_table[array[i] >> 2]));
output.push_back(static_cast<char>(base64_table[(array[i] & 0x03) << 4]));
output.push_back('=');
output.push_back('=');
}
}
return output;
}
std::vector<byte> Base64Decode(const std::string &array) // TODO
{
const char *base64_table = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
}
main.cpp:
#include <iostream>
#include <vector>
#include "base64.h"
using namespace std;
int main(int argc, char *argv[])
{
const char* prueba = "sure.";
vector<byte> texto;
string codificado;
for (unsigned int i = 0; (prueba[i] != 0); i++)
{
texto.push_back(prueba[i]);
}
codificado = Base64Encode(texto);
cout << codificado;
return 0;
}
PD: Sorry for my bad knowledge of English :P
| You're missing a const in the implementation of Base64Encode, it's declared as:
std::string Base64Encode(const std::vector<byte> &array);
But implemented as
std::string Base64Encode(std::vector<byte> &array) { ... }
The compiler thinks that you've overloaded the function (for const and non-const vectors) and thinks the implementation of the const version is missing.
|
2,662,554 | 2,662,564 | C++ Interpreter: How to emit error messages? | I want to emit dynamic error messages like all interpreters do nowadays, for example:
Name error: Undefined variable
would be constant, however what I want to reach is:
Name error: Undefined variable 'X', in line 1
Okay. The line number was really no problem: Every error message must have a line number, so I added it to the error emitter function:
Error( ErrType type, string msg, int line );
So where is my problem?
How do I get the 'X' into Undefined variable *?
I can't use sprintf as it doesn't support strings yet I use them everywhere
I can't simply use cout and connect everything as I want error messages to be supressable
I'd like to get everything into one function like above, Error()
How do I put together dynamic error messages?
For example: Error( Name, sprintf("Undefined variable %s", myVariableName ), lineNum );
(But myVariableName is a string and sprintf will mess things up)
| You can get a null-terminated C string out of myVariableName by calling c_str:
myVariableName.c_str()
Note that your use of sprintf is incorrect; the first parameter of sprintf takes the buffer into which to place the formatted string. If you are using std::string in your program, why use sprintf at all? If Error takes a std::string then you can just use string concatenation:
Error(Name, "Undefined variable " + myVariableName, lineNum);
|
2,662,843 | 2,662,848 | C++ can local class reference be passed to a function? | I would like to know if the following is allowed:
template < class C >
void function(C&);
void function() {
class {} local;
function(local);
}
thanks
| It's not allowed right now. But it's supported in C++0x. The current Standard says at 14.3.1/2
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
That said, if the function is also local, there's no problem
void f() {
class L {} local;
struct C {
static void function(L &l) {
// ...
}
};
C::function(local);
}
|
2,662,881 | 2,663,143 | What are useful functions for drawing text (MFC)? | I'm creating a line chart control, and I need to write (or better say draw) the axis names and axis values.
I found DrawText and TextOut functions, but the text they show is flickering and don't know how to set the font and text orientation (I will need vertical text orientation as well as horizontal).
Are there any other functions you could recommend or how to use these stated above and get the results I need?
| I doubt the flickering is caused by DrawText or TextOut, but rather your paint method. If you are redrawing the entire window on the paint event it is likely to flcker as you erase the whole window, and then there is a perceptible delay before all elements are redrawn.
It may be possible to reduce the flicker acceptably by only painting the invalidated region; however this can become complex. A simpler method is to use double buffering; where you draw to a non-visible memory context, and then switch it to visible context.
Try Google'ing "MFC double buffering" for plenty of examples.
|
2,662,896 | 2,662,936 | Stack and queue operations on the same array | I've been thinking about a program logic, but I cannot draw a conclusion to my problem.
Here, I've implemented stack and queue operations to a fixed array.
int A[1000];
int size=1000;
int top;
int front;
int rear;
bool StackIsEmpty()
{
return (top==0);
}
bool StackPush( int x )
{
if ( top >= size ) return false;
A[top++] = x;
return true;
}
int StackTop( )
{
return A[top-1];
}
bool StackPop()
{
if ( top <= 0 ) return false;
A[--top] = 0;
return true;
}
bool QueueIsEmpty()
{
return (front==rear);
}
bool QueuePush( int x )
{
if ( rear >= size ) return false;
A[rear++] = x;
return true;
}
int QueueFront( )
{
return A[front];
}
bool QueuePop()
{
if ( front >= rear ) return false;
A[front++] = 0;
return true;
}
It is presumed(or obvious) that the bottom of the stack and the front of the queue is pointing at the same location, and vice versa(top of the stack points the same location as rear of the queue).
For example, integer 1 and 2 is inside an array in order of writing. And if I call StackPop(), the integer 2 will be popped out, and if I call QueuePop(), the integer 1 will be popped out.
My problem is that I don't know what happens if I do both stack and queue operations on the same array. The example above is easy to work out, because there are only two values involved. But what if there are more than 2 values involved?
For example, if I call
StackPush(1);
QueuePush(2);
QueuePush(4);
StackPop();
StackPush(5);
QueuePop();
what values will be returned in the order of bottom(front) from the final array?
I know that if I code a program, I would receive a quick answer. But the reason I'm asking this is because I want to hear a logical explanations from a human being, not a computer.
ADDED:
For the second example, I have 4 candidates.
25
12
24
45
or no answer from here at all.
| In the case of your code, it will probably not do what you expect since the stack routines and the queue routines maintain different variables for where to push to.
StackPush(1); // place 1 at position 0; increase top of stack to 1
QueuePush(2); // place 2 at position 0; increase rear of queue to 1
QueuePush(4); // place 4 at position 1; increase rear of queue to 2
StackPop(); // get value(2) from position 0; decrease top of stack to 0
StackPush(5); // place 5 at position 0; increase top of stack to 1
QueuePop(); // get value(5) from position 0; increase front of queue to 1
If you instead wrote the code so that the stack use rear instead of top, then you would see these results.
StackPush(1); // place 1 at position 0; increase rear to 1
QueuePush(2); // place 2 at position 1; increase rear to 2
QueuePush(4); // place 4 at position 2; increase rear to 3
StackPop(); // get value(4) from position 2; decrease rear to 2
StackPush(5); // place 5 at position 2; increase rear to 3
QueuePop(); // get value(1) from position 0; increase front to 1
|
2,662,963 | 2,662,982 | C++ static variables dynamic | Is it possible or makes sense to have static dynamic variables on a class, initialized with new operator?
| Do you mean the following? Yes, it's allowed.
class Class {
static Base *b;
};
Base *Class::b = new Derived();
Use smart pointers if you need it to be destroyed when the program exits
class Class {
static boost::scoped_ptr<Base> b;
};
boost::scoped_ptr<Base> Class::b(new Derived());
|
2,663,170 | 2,663,189 | std::vector capacity after copying |
Does vector::operator= change vector capacity? If so, how?
Does vector's copy constructor copy capacity?
I looked through documentation but could not find a specific answer. Is it implementation dependent?
| All you're guaranteed is that:
The vector has enough capacity to store its elements. (Obviously.)
The vector won't get a new capacity until it's current capacity is full.*
So how much extra or little an implementation wants to put is up to the implementation. I think most will make capacity match size, when copying, but it cannot lower capacity. (Because of number 2 above; reallocating while there's enough room is not allowed.)
* Mostly. See Charles' comments below.
|
2,663,288 | 2,664,358 | Learning to write organized and modular programs | I'm a computer science student, and I'm just starting to write relatively larger programs for my coursework (between 750 - 1500 lines). Up until now, it's been possible to get by with any reasonable level of modularization and object oriented design. However, now that I'm writing more complex code for my assignments I'd like to learn to write better code.
Can anyone point me in the direction of some resources for learning about what sort of things to look for when designing your program's architecture so that you can make it as modularized as possible?
| refactoring by martin fowler is the book that has helped me most among the 20 or so books that I have read on oo, patterns, test driven development and general software engineering over the last two years.
particularly the section on smells can help you see what you need to avoid as you are developing more complex code.
|
2,663,702 | 2,663,773 | While using #ifndef, .h file being added multiple times | I am trying to use following pattern.
#ifndef TRACER_H
#include "Tracer.h"
#endif
This is statement is added to each file in the code such that tracer.h is added only once.
Still I am getting an error saying multiple objects.
Also Tracer.h contains
#ifndef TRACER_H
#define TRACER_H
Here is the error;
i tried pragma once as well:
1>Generating Code...
1>Linking...
1>LINK : \\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Debug\Project3.exe not found or not built by the last incremental link; performing full link
1>SemiExpression.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class tracer &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVtracer@@@Z) already defined in main.obj
1>SemiExpression.obj : error LNK2005: "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > tracer::log" (?log@tracer@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in main.obj
1>Tokenizer.obj : error LNK2005: "class std::basic_ostream<char,struct std::char_traits<char> > & __cdecl operator<<(class std::basic_ostream<char,struct std::char_traits<char> > &,class tracer &)" (??6@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@std@@AAV01@AAVtracer@@@Z) already defined in main.obj
1>Tokenizer.obj : error LNK2005: "private: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > tracer::log" (?log@tracer@@0V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A) already defined in main.obj
1>\\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Debug\Project3.exe : fatal error LNK1169: one or more multiply defined symbols found
1>Build log was saved at "file://\\stu05-fsrv.ad.syr.edu\akbhat$\Visual Studio 2008\Projects\Project3\Project3\Debug\BuildLog.htm"
| Firstly, header guards go inside the file. It makes it much easier:
// some_header.h
#ifndef SOME_HEADER_INCLUDED_H
#define SOME_HEADER_INCLUDED_H
// ...
#endif
Secondly, these guards only protect from multiple includes per-translation-unit. If you have main.cpp and foo.cpp, and each contains:
#include "some_header.h"
#include "some_header.h" // again
// ...
The contents in-between the include guards will be included only once per-unit, but will be defined twice, one in each unit.
When link time comes, you'll get multiple-definition errors. You need to have those static variables defined in one source file, and only declare it in the header.
|
2,663,775 | 2,663,787 | C++ boost thread id and Singleton | Sorry to flood so many questions this week.
I assume thread index returned by thread.get_id is implementation specific.
In case of the pthreads, is index reused? IE, if thread 0 runs and joins, is thread launched afterwords going to have a different ID?
the reason I ask this is a need to implement Singleton pattern with a twist: each thread gets its own instance. I know it sounds very crazy, but threads control hardware (cuda) which does not permit device memory sharing, even at thread level.
What is a good way to implement such pattern?
| For a global (singleton) where each thread gets its own instance, use thread local storage. Boost has thread_specific_ptr for this.
|
2,663,788 | 2,663,794 | What is the purpose of using a reference to a reference in C++? | In my adventures studying the boost libraries, I've come across function signatures that have parameters which are a reference to a reference to an object.
Example:
void function(int && i);
What is the purpose/benefit of doing it this way rather than simply taking a reference to an object? I assume there is one if it's in boost.
| This is not a reference to a reference; there is no such thing.
What you're seeing is a C++0x rvalue reference, denoted by double ampersands, &&. It means that the argument i to the function is a temporary, so the function is allowed to clobber its data without causing problems in the calling code.
Example:
void function(int &i); // A
void function(int &&i); // B
int foo();
int main() {
int x = foo();
function(x); // calls A
function(foo()); // calls B, because the return value is a temporary
}
This rarely useful with plain ints, but very useful when defining move constructors, for example. A move constructor is like a copy constructor, except that it can safely 'steal' the internal data from the original object, because it's a temporary that will cease to exist after the move constructor returns.
|
2,663,814 | 2,663,824 | How do I initialize the vector I have defined in my header file? | I have the following in my Puzzle.h
class Puzzle
{
private:
vector<int> puzzle;
public:
Puzzle() : puzzle (16) {}
bool isSolved();
void shuffle(vector<int>& );
};
and then my Puzzle.cpp looks like:
Puzzle::Puzzle()
{
// Initialize the puzzle (0,1,2,3,...,14,15)
for(int i = 0; i <= puzzle.size(); i++)
{
puzzle[i] = i;
}
}
// ... other methods
Am I using the initializer list wrong in my header file? I would like to define a vector of ints and initialize its size to that of 16. How should I do this?
G++ Output:
Puzzle.cpp:16: error: expected unqualified-id before ')' token
Puzzle.cpp: In constructor `Puzzle::Puzzle()':
Puzzle.cpp:16: error: expected `)' at end of input
Puzzle.cpp:16: error: expected `{' at end of input
Puzzle.cpp: At global scope:
Puzzle.cpp:24: error: redefinition of `Puzzle::Puzzle()'
Puzzle.cpp:16: error: `Puzzle::Puzzle()' previously defined here
| The problem is that you have defined Puzzle::Puzzle() in both the header and the .cpp file, so it has two definitions.
The initializer list can go along with the constructor definition in the .cpp file:
Puzzle::Puzzle()
: puzzle (16)
{
// ...
}
and remove the definition from the header:
Puzzle(); // I'm just a declaration now, not a definition
|
2,663,834 | 2,817,627 | What C++ library to use to write a cross-platform service/daemon? | I wonder what library would ease the development of a cross-platform service/daemon ? (C/C++)
I'm targeting: Windows, Linux and OS X.
Requirements: network operations and serial port communication.
Also it would be nice to have a basic sample service application.
| When it comes to Qt you might try qt-service.
|
2,664,031 | 2,664,042 | Shortest and best way to "reinitialize"/clean a class instance | I will keep it short and just show you a code example:
class myClass
{
public:
myClass();
int a;
int b;
int c;
}
// In the myClass.cpp or whatever
myClass::myClass( )
{
a = 0;
b = 0;
c = 0;
}
Okay. If I know have an instance of myClass and set some random garbage to a, b and c.
What is the best way to reset them all to the state after the class constructor was called, so: 0, 0 and 0?
I came up with this way:
myClass emptyInstance;
myUsedInstance = emptyInstance; // Ewww.. code smell?
Or..
myUsedInstance.a = 0; myUsedInstance.c = 0; myUsedInstance.c = 0;
I think you know what I want, is there any better way to achieve this?
| myUsedInstance = myClass();
C++11 is very efficient if you use this form; the move assignment operator will take care of manually cleaning each member.
|
2,664,051 | 2,664,094 | Why is shrink_to_fit non-binding? | The C++0x FCD states in 23.3.6.2 vector capacity:
void shrink_to_fit();
Remarks: shrink_to_fit is a non-binding request to reduce capacity() to size(). [Note: The request is non-binding to allow latitude for implementation-specific optimizations. —end note]
What optimizations are intended to be allowed?
| This is quite a strained out, but:
Consider vector's allocator that could only allocate memory with, say, 4 KB granularity. Then it wouldn't make sense to reallocate memory if a vector had capacity of 4096 and size of 4095 as this wouldn't conserve memory, yet waste some CPU time for copying elements.
|
2,664,162 | 2,664,207 | PCRE multi line matche problem | i have this C++ program (actually it's just a snippet) :
#include <iostream>
#include <pcre.h>
#include <string>
using namespace std;
int main(){
string pattern = "<a\\s+href\\s*=\\s*\"([^\"]+)\"",
html = "<html>\n"
"<body>\n"
"<a href=\"example_link_1\"/>\n"
"<a href=\"example_link_2\"/>\n"
"<a href=\"example_link_3\"/>\n"
"</body>\n"
"</html>";
int i, ccount, rc,
*offsets,
eoffset;
const char *error;
pcre *compiled;
compiled = pcre_compile( pattern.c_str(), PCRE_CASELESS | PCRE_MULTILINE, &error, &eoffset, 0 );
if( !compiled ){
cerr << "Error compiling the regexp!!" << endl;
return 0;
}
rc = pcre_fullinfo( compiled, 0, PCRE_INFO_CAPTURECOUNT, &ccount );
offsets = new int[ 3 * (ccount + 1) ];
rc = pcre_exec( compiled, 0, html.c_str(), html.length(), 0, 0, offsets, 3 * (ccount + 1) );
if( rc >= 0 ){
for( i = 1; i < rc; ++i ){
cout << "Match : " << html.substr( offsets[2*i], offsets[2*i+1] - offsets[2*i] ) << endl;
}
}
else{
cout << "Sorry, no matches!" << endl;
}
delete [] offsets;
return 0;
}
As you can see, i'm trying to match html links inside a buffer with the given regular expression (the \\s is \s escaped for C/C++ strings).
But, even if in the buffer there are 3 links and the regexp is compiled with the PCRE_CASELESS and PCRE_MULTILINE flags, i match only one element :
Match : example_link_1
Note: I start the loop fro index 1 because the pcre library returns the string that matched (not the match itself) as the first element, and the matches follows.
What's wrong with this code? The regexp itself i think it's correct (tried in PHP for instance).
| Well, it's not supposed to return all matches. Just think of it, you ask for capturecount, which is something like one or two (that is, either the whole match and one subexpression, or just subexpression, I don't remember, I'd guess two). And how would you expect it to know how many matches are in the string you've never passed to it? And you don't expect the thing to return three matches in the array, do you? And if you've had three thousands?
It's been a while since I dealt with pcre api, but I would think you need to loop and match against the rest of the string again.
|
2,664,208 | 2,664,214 | How to disable WinMain entry point for a MFC application? | I understand that is not possible to have applications with multiple entry points under Windows.
I have a MFC application and I added code for making it running as a service (main() entry point and other required stuff) but it looks that Windows will always run the WinMain() from MFC instead of my main.
The question is how can I disable the WinMain() from MFC in order to be able to run my own main().
Probably the same problem would apply if you want to run the same application as a console application.
What do I have to change in project properties in order to build it as a console application (main instead of WinMain)?
Is commenting my CWinApp the only solution?
| If you look at the linker settings you can change the entry point. This is where you want to be looking.
|
2,664,225 | 2,668,109 | g++ and c++0x specification support | although it's been said that the support for c++0x new features in g++ are in experimental mode, many gcc developer claimed that you can use most of the new features in your codes and get the program to work.
but when I try to compile this simple program it results in segmentation fault. Why?
#include <thread>
#include <iostream>
void my_thread_func()
{
std::cout<<"hello"<<std::endl;
}
int main()
{
std::thread t(my_thread_func);
t.join();
}
g++ -std=c++0x -Wall -o run main.cc
| I linked the executable with pthread library and it worked! I did not see any missing shared library dependency (ldd), but seems like std C++ library implementation on Linux uses pthread internally.
g++ thread.cpp -o thread -Wall -std=c++0x -lpthread
|
2,664,296 | 2,664,490 | Managed DirectX as a starting point | I know the difference between manage and unmanaged DirectX. My question is if I decided to do managed directX as a starting point, would it help me to better understand unmanaged DirectX. Honestly, the only thing I see different about the 2 is how you initiate and access resources. Matrix Math is Matrix no matter what so If I learn it in managed, then I should be fine in unmanaged
| So long as you stick with Managed DirectX (or SlimDX) and not one of the newer frameworks like XNA then the API translates fairly directly from managed to unmanaged.
I'd recommend using SlimDX as it is a very thin wrapper over the DirectX API. And it is up to date unlike Managed DirectX.
|
2,664,369 | 3,438,852 | How to add a wrapper to the MFC WinMain? | I want to add a wrapper to the MFC WinMain in order to be able to make a MFC application be able run as GUI application or as a service.
Can I add a wrapper to WinMail from MFC without modifying MFC source code?
| It is possible, just check the command line parameters in order to change the behavior. Check http://msdn.microsoft.com/en-us/library/ms687414(VS.85).aspx
In case you will want to make it work as console remember that it is not possible to make an application that is running as both console and GUI on Windows. Still there is not limitation for services, a service application can be a GUI one or a command line one.
|
2,664,395 | 2,664,411 | can't find what's wrong with my code :( | the point of my code is for me to press f1 and it will scan 500 pixels down and 500 pixels and put them in a array (it just takes a box that is 500 by 500 of the screen). then after that when i hit end it will click on only on the color black or... what i set it to.
anyway it has been doing odd stuff and i can't find why:
#include <iostream>
#include <windows.h>
using namespace std;
COLORREF rgb[499][499];
HDC hDC = GetDC(HWND_DESKTOP);
POINT main_coner;
BYTE rVal;
BYTE gVal;
BYTE bVal;
int red;
int green;
int blue;
int ff = 0;
int main()
{
for(;;)
{
if(GetAsyncKeyState(VK_F1))
{
cout << "started";
int a1 = 0;
int a2 = 0;
GetCursorPos(&main_coner);
int x = main_coner.x;
int y = main_coner.y;
for(;;)
{
//cout << a1 << "___" << a2 << "\n";
rgb[a1][a2] = GetPixel(hDC, x, y);
a1++;
x++;
if(x > main_coner.x + 499)
{
y++;
x = main_coner.x;
a1 = 0;
a2++;
}
if(y > main_coner.y + 499)
{
ff = 1;
break;
}
}
cout << "done";
break;
}
if(ff == 1)
break;
}
for(;;)
{
if(GetAsyncKeyState(VK_END))
{
GetCursorPos(&main_coner);
int x = main_coner.x;
int y = main_coner.y;
int a1 = -1;
int a2 = -1;
for(;;)
{
x++;
a1++;
rVal = GetRValue(rgb[a1][a2]);
gVal = GetGValue(rgb[a1][a2]);
bVal = GetBValue(rgb[a1][a2]);
red = (int)rVal; // get the colors into __int8
green = (int)gVal; // get the colors into __int8
blue = (int)bVal; // get the colors into __int8
if(red == 0 && green == 0 && blue == 0)
{
SetCursorPos(main_coner.x + x, main_coner.y + y);
mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
Sleep(10);
mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
Sleep(100);
}
if(x > main_coner.x + 499)
{
a1 = 0;
a2++;
}
if(y > main_coner.y + 499)
{
Sleep(100000000000);
break;
}
if(GetAsyncKeyState(VK_CONTROL))
{
Sleep(100000);
break;
}
}
}
}
for(;;)
{
if(GetAsyncKeyState(VK_END))
{
break;
}
}
return 0;
}
anyone see what's wrong with my code :(
(feel free to add tags)
| If you want your rgb array to have 500x500 entries (numbered [0][0] to [499][499]), you'll need to declare it as COLORREF rgb[500][500];
Also, make sure you don't try to access rgb[a1][a2] where a2 == -1
|
2,664,579 | 2,664,591 | UnitTest++ constructing fixtures multiple times? | I'm writing some unit tests in UnitTest++ and want to write a bunch of tests which share some common resources. I thought that this should work via their TEST_FIXTURE setup, but it seems to be constructing a new fixture for every test. Sample code:
#include <UnitTest++.h>
struct SomeFixture {
SomeFixture() {
// this line is hit twice
}
};
TEST_FIXTURE(SomeFixture, FirstTest) {
}
TEST_FIXTURE(SomeFixture, SecondTest) {
}
I feel like I must be doing something wrong; I had thought that the whole point of having the fixture was so that the setup/teardown code only happens once. Am I wrong on this? Is there something else I have to do to make it work that way?
| The point of a test fixture is to not have to write the same setup/teardown code in every single test, not to share state. If you want to share state, then you can simply reference a class with static fields and static functions in your tests, and then you can use the standard TEST macro instead of TEST_FIXTURE.
|
2,664,607 | 2,664,627 | Issue using Visual Studio 2010 compiled C++ DLL in Windows 2000 | I have a very simple DLL written in unmanaged C++ that I access from my application. I recently switch to Visual Studio 2010, and the DLL went from 55k down to 35k with no code changes, and now it will no longer load in Windows 2000. I didn't change any code or compiler settings. I have my defines setup for 0x0500, which should include Windows 2000 support. Has anyone else run into this, or have any ideas of what I can do?
| Visual Studio 2010 cannot build binaries that run on Windows 2000. It's actually even worse than that, they won't run on Windows XP RTM or Windows XP Service Pack 1 either. This is because VS2010's C runtime library requires the EncodePointer API which is not available until SP2.
It appears you're stuck building with installing VS2008 if you want to support earlier versions of Windows. You can either move your entire project to Visual Studio 2008 or you can target the vc90 (Visual Studio 2008) toolset from within your Visual Studio 2010 projects. For more details on the latter method, see this anwser to my related question here.
|
2,664,624 | 2,664,653 | 2d array, using calloc in C | I'm trying to create a 2D array of chars to storage lines of chars. For Example:
lines[0]="Hello";
lines[1]="Your Back";
lines[2]="Bye";
Since lines has to be dynamically cause i don't know how many lines i need at first. Here is the code i have:
int i;
char **lines= (char**) calloc(size, sizeof(char*));
for ( i = 0; i < size; i++ ){
lines[i] = (char*) calloc(200, sizeof(char));
}
for ( i = 0; i < size; i++ ){
free(lines[i]);
}
free(lines);
I know that each line can't go over 200 chars. I keep getting errors like "error C2059: syntax error : 'for'" and such. Any ideas of what i did wrong?
|
No the code is not in a function.
You can't just put arbitrary statements outside of functions in C and C++. What you can do though is use a function to initialize the variable:
char** init_lines() {
char** ln = /* ... */;
// your allocations etc. here
return ln;
}
char** lines = init_lines();
|
2,664,662 | 2,668,358 | Set all outgoing network traffic to go through a certain proxy | I think I know how to do this in windows with registry entry. Any cleaner ways with .NET?
Anyway to do this in Qt, so for Macs as well?
| No, there is no such way on Windows. For starters, the most common way to do so only works for outgoing HTTP traffic. FTP, NNTP, or Doom 2 will not be affected. Secondly, most webbrowsers copy the proxy information from WinInet/Internet Explorer (which you happen to assume is in the registry). Changing the original doesn't update those copies. Furthermore, quite often in companies the proxy will depend on the destination (google "proxy.pac" for details)
|
2,664,739 | 2,664,759 | Getting bizarre "expected primary-expression" error | I'm getting a really strange error when making a method call:
/* input.cpp */
#include <ncurses/ncurses.h>
#include "input.h"
#include "command.h"
Input::Input ()
{
raw ();
noecho ();
}
Command Input::next ()
{
char input = getch ();
Command nextCommand;
switch (input)
{
case 'h':
nextCommand.setAction (ACTION_MOVELEFT);
break;
case 'j':
nextCommand.setAction (ACTION_MOVEDOWN);
break;
case 'k':
nextCommand.setAction (ACTION_MOVEUP);
break;
case 'l':
nextCommand.setAction (ACTION_MOVERIGHT);
break;
case 'y':
nextCommand.setAction (ACTION_MOVEUPLEFT);
break;
case 'u':
nextCommand.setAction (ACTION_MOVEUPRIGHT);
break;
case 'n':
nextCommand.setAction (ACTION_MOVEDOWNLEFT);
break;
case 'm':
nextCommand.setAction (ACTION_MOVEDOWNRIGHT);
break;
case '.':
nextCommand.setAction (ACTION_WAIT);
break;
}
return nextCommand;
}
and the error:
Administrator@RHYS ~/code/rogue2
$ make
g++ -c -Wall -pedantic -g3 -O0 input.cpp
input.cpp: In member function `Command Input::next()':
input.cpp:21: error: expected primary-expression before '=' token
input.cpp:24: error: expected primary-expression before '=' token
input.cpp:27: error: expected primary-expression before '=' token
input.cpp:30: error: expected primary-expression before '=' token
input.cpp:33: error: expected primary-expression before '=' token
input.cpp:36: error: expected primary-expression before '=' token
input.cpp:39: error: expected primary-expression before '=' token
input.cpp:42: error: expected primary-expression before '=' token
input.cpp:45: error: expected primary-expression before '=' token
make: *** [input.o] Error 1
Sorry about the lack of linenumbers, the errors occur on the lines "nextCommand.setAction(...)", which is totally bizarre considering that they don't contain a '='.
Any ideas?
Thanks,
Rhys
| Here's the only thing I can think of (without seeing more code) that would cause this:
Your identifiers in all-caps are macros, defined something like this:
#define ACTION_MOVELEFT = 1
#define ACTION_MOVEDOWN = 2
and so on. When the macros are then expanded, you end up with code like:
case 'h':
nextCommand.setAction (= 1);
break;
The = is not used to define a macro; for object-like macros, everything following the macro name until the newline ending the macro definition is part of the replacement list. So, the macros should be defined as follows:
#define ACTION_MOVELEFT 1
#define ACTION_MOVEDOWN 2
and so on.
However, you should consider using an enumeration to enforce type safety and to avoid using the preprocessor when it doesn't need to be used:
enum ActionType
{
ActionMoveLeft,
ActionMoveDown
};
Or, at the very least, use const ints rather than #defines.
|
2,664,778 | 2,664,901 | How can I get bitfields to arrange my bits in the right order? | To begin with, the application in question is always going to be on the same processor, and the compiler is always gcc, so I'm not concerned about bitfields not being portable.
gcc lays out bitfields such that the first listed field corresponds to least significant bit of a byte. So the following structure, with a=0, b=1, c=1, d=1, you get a byte of value e0.
struct Bits {
unsigned int a:5;
unsigned int b:1;
unsigned int c:1;
unsigned int d:1;
} __attribute__((__packed__));
(Actually, this is C++, so I'm talking about g++.)
Now let's say I'd like a to be a six bit integer.
Now, I can see why this won't work, but I coded the following structure:
struct Bits2 {
unsigned int a:6;
unsigned int b:1;
unsigned int c:1;
unsigned int d:1;
} __attribute__((__packed__));
Setting b, c, and d to 1, and a to 0 results in the following two bytes:
c0 01
This isn't what I wanted. I was hoping to see this:
e0 00
Is there any way to specify a structure that has three bits in the most significant bits of the first byte and six bits spanning the five least significant bits of the first byte and the most significant bit of the second?
Please be aware that I have no control over where these bits are supposed to be laid out: it's a layout of bits that are defined by someone else's interface.
| (Note that all of this is gcc-specific commentary - I'm well aware that the layout of bitfields is implementation-defined).
Not on a little-endian machine: The problem is that on a little-endian machine, the most significant bit of the second byte isn't considered "adjacent" to the least significant bits of the first byte.
You can, however, combine the bitfields with the ntohs() function:
union u_Bits2{
struct Bits2 {
uint16_t _padding:7;
uint16_t a:6;
uint16_t b:1;
uint16_t c:1;
uint16_t d:1;
} bits __attribute__((__packed__));
uint16_t word;
}
union u_Bits2 flags;
flags.word = ntohs(flag_bytes_from_network);
However, I strongly recommend you avoid bitfields and instead use shifting and masks.
|
2,664,809 | 2,664,832 | Construct a LPCWSTR on WinCE in C++ (Zune/ZDK) | What's a good way to construct an LPCWSTR on WinCE 6? I'd like to find something similar to String.Format() in C#. My attempt is:
OSVERSIONINFO vi;
memset (&vi, 0, sizeof vi);
vi.dwOSVersionInfoSize = sizeof vi;
GetVersionEx (&vi);
char buffer[50];
int n = sprintf(buffer, "The OS version is: %d.%d", vi.dwMajorVersion, vi.dwMinorVersion);
ZDKSystem_ShowMessageBox(buffer, MESSAGEBOX_TYPE_OK);
That ZDKSystem_ShowMessageBox refers to the ZDK for hacked Zunes available at:
http://zunedevwiki.org
This line of code works well with the message box call:
ZDKSystem_ShowMessageBox(L"Hello Zune", MESSAGEBOX_TYPE_OK);
My basic goal is to look at the exact version of WinCE running on a Zune HD to see which features are available (i.e. is it R2 or earlier?).
Also I haven't seen any tags for the ZDK so please edit if something is more fitting!
| sprintf is for narrow strings. LPCWSTR is a const WCHAR *, so you need wide characters, and the right function.
E.g.
WCHAR buf[100];
StringCchPrintfW(buf, _countof(buf), L"Hello, world!");
or using generic text functions, and compiling with UNICODE,
TCHAR buf[100];
StringCchPrintf(buf, _countof(buf), _T("Hello, world!"));
(There are other functions you could use, such as _stprintf_s, swprintf_s, etc)
|
2,664,837 | 2,664,848 | Make Map Key Sorted According To Insert Sequence | Without help from additional container (like vector), is it possible that I can make map's key sorted same sequence as insertion sequence?
#include <map>
#include <iostream>
using namespace std;
int main()
{
map<const char*, int> m;
m["c"] = 2;
m["b"] = 2;
m["a"] = 2;
m["d"] = 2;
for (map<const char*, int>::iterator begin = m.begin(); begin != m.end(); begin++) {
// How can I get the loop sequence same as my insert sequence.
// c, b, a, d
std::cout << begin->first << std::endl;
}
getchar();
}
| No. A std::map is a sorted container; the insertion order is not maintained. There are a number of solutions using a second container to maintain insertion order in response to another, related question.
That said, you should use std::string as your key. Using a const char* as a map key is A Bad Idea: it makes it near impossible to access or search for an element by its key because only the pointers will be compared, not the strings themselves.
|
2,664,913 | 2,664,929 | Is there a C++ cross platform "named event like the "CreateEvent()" in Win32? | I am looking for something analogous to CreateEvent(), SetEvent() and WaitForMultipleObjects() from the Win32 world.
Specifically this has to be accessible across processes on the same machine.
We are already using Poco for some cross platform stuff, but I don't see that the Poco::Event is what I want. perhaps i am missing something.
EDIT:
To explain what I want to do:
I want process B to know when something happens in process A. This is trivial in win32 - Each process/thread calls CreateEvent() with a name for the event. Process B calls waitForXObject() and Process A calls SetEvent() when something happens. B is signaled.
Again, this is trivial in win32, but how to do it cross-platform.
| There is no built in way in C++ to do named events. But you can use boost to do it.
You're looking for boost::condition and boost::named_condition
As you also mentioned there exists: Poco.NamedEvent
|
2,665,112 | 2,665,123 | Undefined symbols for C++0x lambdas? | I was just poking around into some new stuff in C++0x, when I hit a stumbling block:
#include <list>
#include <cstdio>
using namespace std;
template <typename T,typename F>
void ForEach (list<T> l, F f) {
for (typename list<T>::iterator it=l.begin();it!=l.end();++it)
f(*it);
}
int main() {
int arr[] = {1,2,3,4,5,6};
list<int> l (arr,arr+6);
ForEach(l,[](int x){printf("%d\n",x);});
}
does not compile. I get a load of undefined symbol errors. Here's make's output:
i386-apple-darwin9-gcc-4.5.0 -std=c++0x -I/usr/local/include -o func main.cpp
Undefined symbols:
"___cxa_rethrow", referenced from:
std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o
"operator new(unsigned long)", referenced from:
__gnu_cxx::new_allocator<std::_List_node<int> >::allocate(unsigned long, void const*) in ccPxxPwU.o
"___gxx_personality_v0", referenced from:
___gxx_personality_v0$non_lazy_ptr in ccPxxPwU.o
"___cxa_begin_catch", referenced from:
std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o
"operator delete(void*)", referenced from:
__gnu_cxx::new_allocator<std::_List_node<int> >::deallocate(std::_List_node<int>*, unsigned long) in ccPxxPwU.o
"___cxa_end_catch", referenced from:
std::_List_node<int>* std::list<int, std::allocator<int> >::_M_create_node<int const&>(int const&&&) in ccPxxPwU.o
"std::__throw_bad_alloc()", referenced from:
__gnu_cxx::new_allocator<std::_List_node<int> >::allocate(unsigned long, void const*) in ccPxxPwU.o
"std::_List_node_base::_M_hook(std::_List_node_base*)", referenced from:
void std::list<int, std::allocator<int> >::_M_insert<int const&>(std::_List_iterator<int>, int const&&&) in ccPxxPwU.o
ld: symbol(s) not found
collect2: ld returned 1 exit status
make: *** [func] Error 1
Why is this not working?
| Those are link errors. Are you missing a C++ library? What if you used i386-apple-darwin9-g++-4.5.0?
P.S. I can't test this, as I have gcc 4.2.1 (i686-apple-darwin10-gcc-4.2.1) on my Mac and get:
cc1plus: error: unrecognized command line option "-std=c++0x"
|
2,665,142 | 2,665,157 | C++: Saving the class object in archived format which is having char * attributes and read it back from file | Assume I have a class
class A
{
char *attr1,*attr2;
public:
. . .
};
How to save the object of this class to file in a binary format and read it back?
Thanks.
| Read about serialization. For example the Boost serialization library. They have a nice definition:
Here, we use the term "serialization"
to mean the reversible deconstruction
of an arbitrary set of C++ data
structures to a sequence of bytes.
Such a system can be used to
reconstitute an equivalent structure
in another program context. Depending
on the context, this might used
implement object persistence, remote
parameter passing or other facility.
In this system we use the term
"archive" to refer to a specific
rendering of this stream of bytes.
This could be a file of binary data,
text data, XML, or some other created
by the user of this library.
That said, such a solution is the 5-kg hammer that solves most serialization problems. It may be the case that you need something far simpler. For example, if you object only consists of a few char* attributes you can save it in a simpler way. A general solution, however, would allow you flexibility in case your object gets more complex in the future.
|
2,665,738 | 10,924,218 | Why does the token returned by LogonUser() in Win x64 not belong to LOCAL group? | I have a piece of code that calls LogonUser() followed by CreateProcessAsUser(). In Win32, the resulting process belongs to a user (say, TESTDOMAIN\user1) who belongs to the LOCAL group. However, in x64, the process owner does not belong to LOCAL. The owner still belongs to all other groups (Authenticated Users, Everyone, etc.)
Does anyone know if this is a documented behavior change? Or am I supposed to put some special flag in x64 when calling LogonUser()?
Thanks.
| I confirmed this behavior with MSDN support. They cited security reasons for the behavior change.
|
2,665,755 | 2,665,803 | How to get installed Windows SDK version? | How can I determine what version of the Windows SDK is installed on my computer?
I'm asking so I can install the latest version if it isn't installed already.
| On English locale at least:
dir "%ProgramFiles%\Microsoft SDKs\Windows"
should work. It is quite likely that there will be multiple versions installed, which is the right one for an one build can only be specified by that project.
|
2,665,909 | 2,665,925 | Random numbers from -10 to 10 in C++ | How does one make random numbers in the interval -10 to 10 in C++ ?
srand(int(time(0)));//seed
for(int i = 0; i < size; i++){
myArray[i] = 1 + rand() % 20 - 10;//this will give from -9 to 10
myArray2[i] =rand() % 20 - 10;//and this will -10 to 9
}
| You need a range of 21, not 20, so do something like this:
x = rand() % 21 - 10;
|
2,665,931 | 2,665,959 | Why am I getting 'Heap Corruption'? | Please don't crucify me for this one. I decided it might be good to use a char* because the string I intended to build was of a known size. I am also aware that if timeinfo->tm_hour returns something other than 2 digits, things are going to go badly wrong. That said, when this function returns VIsual Studio goes ape at me about HEAP CORRUPTION. What's going wrong? (Also, should I just use a stringbuilder?)
void cLogger::_writelogmessage(std::string Message)
{
time_t rawtime;
struct tm* timeinfo = 0;
time(&rawtime);
timeinfo = localtime(&rawtime);
char* MessageBuffer = new char[Message.length()+11];
char* msgptr = MessageBuffer;
_itoa(timeinfo->tm_hour, msgptr, 10);
msgptr+=2;
strcpy(msgptr, "::");
msgptr+=2;
_itoa(timeinfo->tm_min, msgptr, 10);
msgptr+=2;
strcpy(msgptr, "::");
msgptr+=2;
_itoa(timeinfo->tm_sec, msgptr, 10);
msgptr+=2;
strcpy(msgptr, " ");
msgptr+=1;
strcpy(msgptr, Message.c_str());
_file << MessageBuffer;
delete[] MessageBuffer;
}
| You need to allocate one more byte, since .length of a string returns its length without the terminating NUL, for which you also need space in the char*.
I.e. suppose Message.length() returns 10. You allocate 21 bytes. Copy 11 bytes into the buffer, then copy the message, which needs 10 bytes + one for NUL. Total: 22 bytes, and you only have 21 allocated.
|
2,665,936 | 2,665,965 | Is there a way to specify the dimensions of a nested STL vector C++? | I know vectors can be constructed to a predefined size
vector<int> foo(4);
But is there a way to specify the dimensions of nested vectors?
vector< vector<int> > bar(4);
Lets say I wanted a vector of size 4 containing vector's of size 4... like a 4x4 multidimensional array of ints?
| The second argument to that constructor is the value to initialize with. Right now you're getting 4 default-constructed vectors. To clarify with a simpler 1D example:
// 4 ints initialized to 0
vector<int> v1(4);
// *exactly* the same as above, this is what the compiler ends up generating
vector<int> v2(4, 0);
// 4 ints initialized to 10
vector<int> v3(4, 10);
So you want:
vector< vector<int> > bar(4, vector<int>(4));
// this many ^ of these ^
This creates a vector of vectors of ints, initialized to contain 4 vectors that are initialized to contain 4 ints, initialized to 0. (You could specify a default value for the int to, if desired.)
A mouth-full, but not too hard. :)
For a pair:
typedef std::pair<int, int> pair_type; // be liberal in your use of typedef
typedef std::vector<pair_type> inner_vec;
typedef std::vector<inner_vec> outer_vec;
outer_vec v(5, inner_vec(5, pair_type(1, 1)); // 5x5 of pairs equal to (1, 1)
// this many ^ of these ^
//this many ^ of these ^
|
2,666,300 | 2,666,307 | Conversion char[] to char* | may be this is a sizzle question but please help
void Temp1::caller()
{
char *cc=Called();
printf("sdfasfasfas");
printf("%s",cc);
}
char *Temp1::Called()
{
char a[6]="Hello";
return &a;
}
Here how to print Hello using printf("%s",cc);
| 2 things
You need %s, the string format specifier to print strings.
You are returning the address of a local array variable a[6], it will be destroyed after the function returns. The program should be giving you a segmentation fault. You should be getting a crash. If you are on a linux machine do ulimit -c unlimited, and then run the program. You should see a core dump.
|
2,666,301 | 2,666,385 | how to know location of return address on stack c/c++ | i have been reading about a function that can overwrite its return address.
void foo(const char* input)
{
char buf[10];
//What? No extra arguments supplied to printf?
//It's a cheap trick to view the stack 8-)
//We'll see this trick again when we look at format strings.
printf("My stack looks like:\n%p\n%p\n%p\n%p\n%p\n% p\n\n"); //%p ie expect pointers
//Pass the user input straight to secure code public enemy #1.
strcpy(buf, input);
printf("%s\n", buf);
printf("Now the stack looks like:\n%p\n%p\n%p\n%p\n%p\n%p\n\n");
}
It was sugggested that this is how the stack would look like
Address of foo = 00401000
My stack looks like:
00000000
00000000
7FFDF000
0012FF80
0040108A <-- We want to overwrite the return address for foo.
00410EDE
Question:
-. Why did the author arbitrarily choose the second last value as the return address of foo()?
-. Are values added to the stack from the bottom or from the top?
apart from the function return address, what are the other values i apparently see on the stack? ie why isn't it filled with zeros
Thanks.
| The one above it is the previous EBP (0012FF80). The value above the prev-EBP is always the return address.
(This obviously assumes a non-FPO binary and 32bit Windows)1.
If you recall, the prologue looks like:
push ebp ; back up the previous ebp on the stack
mov ebp, esp ; set up the new frame pointer
and when a function is called, e.g.
call 0x00401000
The current EIP is pushed on the stack (used as the return address), so the stack after the prologue looks like:
[ebp+0xc] ; contains parameter 1, etc
[ebp+0x8] ; contains parameter 0
[ebp+0x4] ; contains return address
[ebp] ; contains prev-EBP
So for each %p, printf uses the next 4 bytes starting from [ebp+0xc] (the first %p parameter). Eventually you hit the previous EBP value stored on the stack, which is (0012FF80) and then the next one is the Return Address.
Note these addresses must 'make sense', which they clearly do here (though it may not be 'clear' for all).
Re Q2) The stack grows down. So when you push eax, 4 is subtracted from esp, then the value of eax is moved to [esp], equivalently in code:
push eax
; <=>
sub esp, 4
mov [esp], eax
The book is Writing Secure Code, yes?
|
2,666,325 | 2,666,349 | Finding character in String in Vector | Judging from the title, I kinda did my program in a fairly complicated way. BUT! I might as well ask anyway xD
This is a simple program I did in response to question 3-3 of Accelerated C++, which is an awesome book in my opinion.
I created a vector:
vector<string> countEm;
That accepts all valid strings. Therefore, I have a vector that contains elements of strings.
Next, I created a function
int toLowerWords( vector<string> &vec )
{
for( int loop = 0; loop < vec.size(); loop++ )
transform( vec[loop].begin(), vec[loop].end(),
vec[loop].begin(), ::tolower );
that splits the input into all lowercase characters for easier counting. So far, so good.
I created a third and final function to actually count the words, and that's where I'm stuck.
int counter( vector<string> &vec )
{
for( int loop = 0; loop < vec.size(); loop++ )
for( int secLoop = 0; secLoop < vec[loop].size(); secLoop++ )
{
if( vec[loop][secLoop] == ' ' )
That just looks ridiculous. Using a two-dimensional array to call on the characters of the vector until I find a space. Ridiculous. I don't believe that this is an elegant or even viable solution. If it was a viable solution, I would then backtrack from the space and copy all characters I've found in a separate vector and count those.
My question then is. How can I dissect a vector of strings into separate words so that I can actually count them? I thought about using strchr, but it didn't give me any epiphanies.
Solution via Neil:
stringstream ss( input );
while( ss >> buffer )
countEm.push_back( buffer );
From that I could easily count the (recurring) words.
Then I did a solution via Wilhelm that I will post once I re-write it since I accidentally deleted that solution! Stupid of me, but I will post that once I have it written again ^^
I want to thank all of you for your input! The solutions have worked and I became a little better programmer. If I could vote up your stuff, then I would :P Once I can, I will! And thanks again!
| If the words are always space separated, the easiest way to split them is to use a stringstream:
string words = .... // populat
istringstream is( words );
string word;
while( is >> word ) {
cout << "word is " << word << endl;
}
You'd want to write a function to do this, of course, and apply it to your strings. Or it may be better not to store the strings at allm but to split into words on initial input.
|
2,666,447 | 2,666,513 | C++ memory leak detecting method | I'm working on a project using many external library on windows.
I got problem with memory leak: i detected many memory leaks by overriding operator new/new[] and delete/delete[]. The problem is i know how many memory blocks are leaked, but don't know where to find them, in overrided functions, i could log size and position of allocated mem block, without stack trace.
So to deal with it, i guess i need to log stack trace too (but how?), or is there any way to find which code caused memory leaked?
Thanks a lot for any help.
| I use the following approach to supply new with info on which file and line that allocates each memory block:
void operator delete(void *p, const char* filename, int line);
void operator delete(void *p, const char* filename, int line, const std::nothrow_t&);
void operator delete[](void *p, const char* filename, int line);
void operator delete[](void *p, const char* filename, int line, const std::nothrow_t&);
void *operator new(std::size_t n, const char* filename, int line);
void *operator new(std::size_t n, const std::nothrow_t&, const char* filename, int line);
void *operator new[](std::size_t n, const char* filename, int line);
void *operator new[](std::size_t n, const std::nothrow_t&, const char* filename, int line);
#define new foo_new
#define foo_new new(__FILE__, __LINE__)
|
2,666,641 | 2,666,712 | Why do I have to specify pure virtual functions in the declaration of a derived class in Visual C++? | Given the base class A and the derived class B:
class A {
public:
virtual void f() = 0;
};
class B : public A {
public:
void g();
};
void B::g() {
cout << "Yay!";
}
void B::f() {
cout << "Argh!";
}
I get errors saying that f() is not declared in B while trying do define void B::f(). Do I have to declare f() explicitly in B? I think that if the interface changes I shouldn't have to correct the declarations in every single class deriving from it. Is there no way for B to get all the virtual functions' declarations from A automatically?
EDIT: I found an article that says the inheritance of pure virtual functions is dependent on the compiler:
http://www.objectmentor.com/resources/articles/abcpvf.pdf
I'm using VC++2008, wonder if there's an option for this.
| Yes, in C++ you have to explicitly clarify your intention to override the behavior of a base class method by declaring (and defining) it in the derived class. If you try to provide a new implementation in derived class without declaring it in class definition it will be a compiler error.
|
2,667,086 | 2,668,224 | Information about PTE's (Page Table Entries) in Windows | In order to find more easily buffer overflows I am changing our custom memory allocator so that it allocates a full 4KB page instead of only the wanted number of bytes. Then I change the page protection and size so that if the caller writes before or after its allocated piece of memory, the application immediately crashes.
Problem is that although I have enough memory, the application never starts up completely because it runs out of memory. This has two causes:
since every allocation needs 4 KB, we probably reach the 2 GB limit very soon. This problem could be solved if I would make a 64-bit executable (didn't try it yet).
even when I only need a few hundreds of megabytes, the allocations fail at a certain moment.
The second problem is the biggest one, and I think it's related to the maximum number of PTE's (page table entries, which store information on how Virtual Memory is mapped to physical memory, and whether pages should be read-only or not) you can have in a process.
My questions (or a cry-for-tips):
Where can I find information about the maximum number of PTE's in a process?
Is this different (higher) for 64-bit systems/applications or not?
Can the number of PTE's be configured in the application or in Windows?
Thanks,
Patrick
PS. note for those who will try to argument that you shouldn't write your own memory manager:
My application is rather specific so I really want full control over memory management (can't give any more details)
Last week we had a memory overwrite which we couldn't find using the standard C++ allocator and the debugging functionality of the C/C++ run time (it only said "block corrupt" minutes after the actual corruption")
We also tried standard Windows utilities (like GFLAGS, ...) but they slowed down the application by a factor of 100, and couldn't find the exact position of the overwrite either
We also tried the "Full Page Heap" functionality of Application Verifier, but then the application doesn't start up either (probably also running out of PTE's)
| A shotgun approach is to allocate those isolated 4KB entries at random. This means that you will need to rerun the same tests, with the same input repeatedly. Sometimes it will catch the error, if you're lucky.
A slightly smarter approach is to use another algorithm than just random - e.g. make it dependent on the call stack whether an allocation is isolated. Do you trust std::string users, for instance, and suspect raw malloc use?
|
2,667,225 | 2,670,149 | Endianness conversion and g++ warnings | I've got the following C++ code :
template <int isBigEndian, typename val>
struct EndiannessConv
{
inline static val fromLittleEndianToHost( val v )
{
union
{
val outVal __attribute__ ((used));
uint8_t bytes[ sizeof( val ) ] __attribute__ ((used));
} ;
outVal = v;
std::reverse( &bytes[0], &bytes[ sizeof(val) ] );
return outVal;
}
inline static void convertArray( val v[], uint32_t size )
{
// TODO : find a way to map the array for (uint32_t i = 0; i < size; i++)
for (uint32_t i = 0; i < size; i++)
v[i] = fromLittleEndianToHost( v[i] );
}
};
Which work and has been tested (without the used attributes). When compiling I obtain the following errors from g++ (version 4.4.1)
|| g++ -Wall -Wextra -O3 -o t t.cc
|| t.cc: In static member function 'static val EndiannessConv<isBigEndian, val>::fromLittleEndianToHost(val)':
t.cc|98| warning: 'used' attribute ignored
t.cc|99| warning: 'used' attribute ignored
|| t.cc: In static member function 'static val EndiannessConv<isBigEndian, val>::fromLittleEndianToHost(val) [with int isBigEndian = 1, val = double]':
t.cc|148| instantiated from here
t.cc|100| warning: unused variable 'outVal'
t.cc|100| warning: unused variable 'bytes'
I've tried to use the following code :
template <int size, typename valType>
struct EndianInverser { /* should not compile */ };
template <typename valType>
struct EndianInverser<4, valType>
{
static inline valType reverseEndianness( const valType &val )
{
uint32_t castedVal =
*reinterpret_cast<const uint32_t*>( &val );
castedVal = (castedVal & 0x000000FF << (3 * 8))
| (castedVal & 0x0000FF00 << (1 * 8))
| (castedVal & 0x00FF0000 >> (1 * 8))
| (castedVal & 0xFF000000 >> (3 * 8));
return *reinterpret_cast<valType*>( &castedVal );
}
};
but it break when enabling optimizations due to the type punning.
So, why does my used attribute got ignored?
Is there a workaround to convert endianness (I rely on the enum to avoid type punning) in templates?
| I only have gcc 4.2.1 but if I get rid of the attribute ((used)) and give the union a name it compiles without warnings for me.
inline static val fromLittleEndianToHost( val v )
{
union
{
val outVal ;
uint8_t bytes[ sizeof( val ) ] ;
} u;
u.outVal = v;
std::reverse( &u.bytes[0], &u.bytes[ sizeof(val) ] );
return u.outVal;
}
From what I've read the 'union' technique works on gcc but is not guaranteed in the standard, the other 'reinterpret_cast' method is wrong (because of type aliasing). However I think this applies to C, not sure about C++. Hope that helps.
|
2,667,355 | 2,667,376 | map<int,int> default values | std::map<int,int> mapy;
++mapy[5];
Is it safe to assume that mapy[5] will always be 1? I mean, will mapy[5] always get the default value of 0 before '++', even if not explicitly declared, as in my code?
| As soon as you access the map with the [] operator, if the key doesn't exist it gets added. The int gets "value initialization" invoked - so it will get a value of 0.
|
2,667,377 | 2,667,407 | typedef declaration syntax | Some days ago I looked at boost sources and found interesting typedef.
There is a code from "boost\detail\none_t.hpp":
namespace boost {
namespace detail {
struct none_helper{};
typedef int none_helper::*none_t ;
} // namespace detail
} // namespace boost
I didn't see syntax like that earlier and can't explain the sense of that.
This typedef introduces name "none_t" as pointer to int in boost::detail namespace.
What the syntax is?
And what difference between "typedef int none_helper::*none_t" and for example "typedef int *none_t" ?
| The syntax is for a pointer to member - here it typedefs none_t as a pointer to an int data member of none_helper.
The syntax can be used e.g. this way:
struct X { int i; };
typedef int X::*PI;
PI pi = &X::i;
X* x = foo();
x->*pi = 42;
InformIT has an article on member pointers, containing more details.
|
2,667,420 | 2,667,434 | I just don't get the C++ Pointer/Reference system | I've never had problems with references as in Python (implicit) or PHP (explicit &). In PHP you write $p = &$myvar; and you have $p as a reference pointing to $myVar.
So I know in C++ you can do this:
void setToSomething( int& var )
{
var = 123;
}
int myInt;
setToSomething( myInt );
myInt is now 123, why?
Doesn't & mean "memory address of" x in C++? What do I do then if var is only the address to myInt and not a pointer?
void setToSomething( int* var )
{
*var = 123;
}
int myInt;
int* myIntPtr = &myInt;
setToSomething( myIntPtr );
Does the above work as expected?
I don't understand the difference between * and & in C++ fully. They tell you & is used to get the address of a variable, but why does that help you in functions etc. Like in the first example?
| In the first example, & is used to declare a reference type.
It's not the same thing as the & operator which is used to get an object's address.
You can view a reference type as a type which uses under the covers a pointer which can never be NULL.
|
2,667,500 | 2,667,543 | Including a C header which declares a variable called "new"? | I'm trying to use the OpenCA (libPKI) library in a C++ application. However, when including the file pki_x509_data_st.h the following code fragment is encountered:
typedef struct pki_x509_callbacks_st {
/* ---------------- Memory Management -------------------- */
void * (*new) (void );
void (*free) (void *x );
void * (*dup) (void *x );
This won't compile because of the "new" pointer declaration.
How can I make it work?
Update
After renaming the "new" variable I've encountered some new problems ("using typedef name after struct" etc.. ). I want to avoid changing too much of the old C code (modifying library headers somehow makes me feel nervous) so I decided just create a minimal isolation layer instead.
| If you can get away with it, rename it to something that's not a reserved word in C++. Chances that that you might end up having to rebuild the whole library and apply your "fix" there as well.
I'd be looking into constructing an isolation layer between your C++ code and the C library, potentially a bit of C code that only exposes the functions you need to use and completely isolate you from the rest.
Oh, and by the way - that's a function pointer declaration, not a variable declaration. Just to clear this up...
|
2,667,514 | 2,683,383 | OpenSSL: SessionTicket TLS extension problem | I'm using an application which uses OpenSSL for client TLS side.
We upgrade the OpenSSL version from 0.9.8e to 0.9.8k.
And then TLS doesn't work...
Wireshark shows that the new version (with OpenSSL 0.9.8k) sends the client hello packet with a SessionTicket extension - and the server side responds with a fatal internal error.
The previous version sends an almost identical hello packet, but without the SessionTicket ext.
When I replaced TLSv1_client_method with SSLv23_client_method, everything worked fine - the sent client hello packet was a SSLv2 one (In the sniffer) without any extension (as it wasn't TLS but SSL?)
Is there a better way to disable this extension or to solve the problem in another way?
Thanks in advance,
rursw1
| Quote from RFC 5077:
“Note that the encoding of an empty SessionTicket extension was
ambiguous in RFC 4507. An RFC 4507 implementation may have encoded
it as:
00 23 Extension type 35
00 02 Length of extension contents
00 00 Length of ticket
or it may have encoded it the same way as this update:
00 23 Extension type 35
00 00 Length of extension contents
A server wishing to support RFC 4507 clients should respond to an
empty SessionTicket extension encoded the same way as it received it.
“
So the server I worked with supports RFC 4507 and not the newer 5077.
Removing it 'normally' using SSL_CTX_set_options with SSL_OP_NO_TICKET solved the problem.
Hope this will help someone...
EDIT:
Well, this can be done also with the configuration flag -no-tlsext. (When running the perl Configure script).
But, pay attention that in OpenSSL 0.9.8n and OpenSSL 1.0.0, you will need to comment out some parts of the source code or it won't compile - as the secure renegotiation (which is considered to be unsafe by itself) requires it.
|
2,667,574 | 2,667,670 | List iterator not dereferencable? | I get the error "list iterator not dereferencable" when using the following code:
bool done = false;
while (!_list_of_messages.empty() && !done) {
// request the next message to create a frame
// DEBUG ERROR WHEN NEXT LINE IS EXECUTED:
Counted_message_reader reader = *(_list_of_messages.begin());
if (reader.has_more_data()) {
_list_of_frames.push_back(new Dlp_data_frame(reader, _send_compressed_frames));
done = true;
} else {
_list_of_messages.pop_front();
}
}
(The line beginning with "Counted_message_reader..." is the one giving the problem)
Note that the error doesn't always occur but seemingly at random times (usually when there's lots of buffered data).
_list_of_messages is declared as follows:
std::list<Counted_message_reader> _list_of_messages;
In the surrounding code we could do pop_front, push_front and size, empty or end checks on _list_of_messages but no erase calls.
I've studied the STL documentation and can't see any glaring problems. Is there something wrong with the above code or do I have a memory leak somewhere?
Thanks! Appreciated!
| Could you have a race-condition?
If the list were empty, then I'd expect a problem when trying to dereference begin(), but you check for empty. Do you have another thread adding or removing items from list in parallel?
Your code snippets works for me on VS 2008 (assuming I typedef Counted_message_reader to int).
|
2,667,648 | 2,667,681 | What does it mean to be "terminated by a zero"? | I am getting into C/C++ and a lot of terms are popping up unfamiliar to me. One of them is a variable or pointer that is terminated by a zero. What does it mean for a space in memory to be terminated by a zero?
| Take the string Hi in ASCII. Its simplest representation in memory is two bytes:
0x48
0x69
But where does that piece of memory end? Unless you're also prepared to pass around the number of bytes in the string, you don't know - pieces of memory don't intrinsically have a length.
So C has a standard that strings end with a zero byte, also known as a NUL character:
0x48
0x69
0x00
The string is now unambiguously two characters long, because there are two characters before the NUL.
|
2,667,675 | 2,667,721 | Data structures with different sized bit fields | If I have a requirement to create a data structure that has the following fields:
16-bit Size field
3-bit Version field
1-bit CRC field
How would I code this struct? I know the Size field would be an unsigned short type, but what about the other two fields?
| First, unsigned short isn't guaranteed to be only 16 bits, just at least 16 bits.
You could do this:
struct Data
{
unsigned short size : 16;
unsigned char version : 3;
unsigned char crc : 1;
};
Assuming you want no padding between the fields, you'll have to issue the appropriate instructions to your compiler. With gcc, you can decorate the structure with __attribute__((packed)):
struct Data
{
// ...
} __attribute__((packed));
In Visual C++, you can use #pragma pack:
#pragma pack(push, 0)
struct Data
{
// ...
};
#pragma pack(pop)
|
2,667,826 | 2,667,842 | Where is the code generated for sqrt and __CIsqrt? | I set VC++ to generate ASM for a method which calls sqrt, to see if it's generating FPU or SSE instructions. However when sqrt is called, I don't see the ASM. I only see a call to some function __CIsqrt, which I assume is some system sqrt function. I can't see any ASM for that to know what it is doing?
| That's because the compiler isn't generating the code - the code already exists in the library. If you want to see it, the easiest method is often to trace into the library function call in the debugger in assembler mode.
|
2,667,925 | 2,668,951 | Pass a Delphi class to a C++ function/method that expects a class with __thiscall methods | I have some MSVC++ compiled DLL's for which I have created COM-like (lite) interfaces (abstract Delphi classes). Some of those classes have methods that need pointers to objects. These C++ methods are declared with the __thiscall calling convention (which I cannot change), which is just like __stdcall, except a this pointer is passed on the ECX register.
I create the class instance in Delphi, then pass it on to the C++ method. I can set breakpoints in Delphi and see it hitting the exposed __stdcall methods in my Delphi class, but soon I get a STATUS_STACK_BUFFER_OVERRUN and the app has to exit. Is it possible to emulate/deal with __thiscall on the Delphi side of things? If I pass an object instantiated by the C++ system then all is good, and that object's methods are called (as would be expected), but this is useless - I need to pass Delphi objects.
Edit 2010-04-19 18:12 This is what happens in more detail: The first
method called (setLabel) exits with no
error (though its a stub method). The
second method called (init), enters
then dies when it attempts to read the
vol parameter.
C++ Side
#define SHAPES_EXPORT __declspec(dllexport) // just to show the value
class SHAPES_EXPORT CBox
{
public:
virtual ~CBox() {}
virtual void init(double volume) = 0;
virtual void grow(double amount) = 0;
virtual void shrink(double amount) = 0;
virtual void setID(int ID = 0) = 0;
virtual void setLabel(const char* text) = 0;
};
Delphi Side
IBox = class
public
procedure destroyBox; virtual; stdcall; abstract;
procedure init(vol: Double); virtual; stdcall; abstract;
procedure grow(amount: Double); virtual; stdcall; abstract;
procedure shrink(amount: Double); virtual; stdcall; abstract;
procedure setID(val: Integer); virtual; stdcall; abstract;
procedure setLabel(text: PChar); virtual; stdcall; abstract;
end;
TMyBox = class(IBox)
protected
FVolume: Double;
FID: Integer;
FLabel: String; //
public
constructor Create;
destructor Destroy; override;
// BEGIN Virtual Method implementation
procedure destroyBox; override; stdcall; // empty - Dont need/want C++ to manage my Delphi objects, just call their methods
procedure init(vol: Double); override; stdcall; // FVolume := vol;
procedure grow(amount: Double); override; stdcall; // Inc(FVolume, amount);
procedure shrink(amount: Double); override; stdcall; // Dec(FVolume, amount);
procedure setID(val: Integer); override; stdcall; // FID := val;
procedure setLabel(text: PChar); override; stdcall; // Stub method; empty.
// END Virtual Method implementation
property Volume: Double read FVolume;
property ID: Integer read FID;
property Label: String read FLabel;
end;
I would have half expected using stdcall alone to work, but something is messing up, not sure what, perhaps something to do with the ECX register being used? Help would be greatly appreciated.
Edit 2010-04-19 17:42 Could it be that the ECX register needs to be
preserved on entry and restored once
the function exits? Is the this
pointer required by C++? I'm probably
just reaching at the moment based on
some intense Google searches. I
found something related, but it
seems to be dealing with the reverse
of this issue.
| Let us assume that you have created a MSVC++ class with VMT that maps perfectly into the VMT of a Delphi class (I have never done it, I just believe you that is possible). Now you can call the virtual methods of a Delphi class from MSVC++ code, the only problem is __thiscall calling convention. Since __thiscall is not supported in Delphi, the possible solution is to use proxy virtual methods on Delphi side:
UPDATED
type
TTest = class
procedure ECXCaller(AValue: Integer);
procedure ProcProxy(AValue: Integer); virtual; stdcall;
procedure Proc(AValue: Integer); stdcall;
end;
implementation
{ TTest }
procedure TTest.ECXCaller(AValue: Integer);
asm
mov ecx,eax
push AValue
call ProcProxy
end;
procedure TTest.Proc(AValue: Integer);
begin
ShowMessage(IntToStr(AValue));
end;
procedure TTest.ProcProxy(AValue: Integer);
asm
pop ebp // !!! because of hidden delphi prologue code
mov eax,[esp] // return address
push eax
mov [esp+4],ecx // "this" argument
jmp Proc
end;
|
2,668,075 | 2,668,098 | Will exit() or an exception prevent an end-of-scope destructor from being called? | Let's say I have the following code:
struct mytype
{
~mytype() { /* do something like call Mix_CloseAudio etc */ }
};
int main()
{
mytype instant;
init_stuff();
start();
return 0;
}
Is that destructor guaranteed to be called even if exit() is used from somewhere inside start() ?
| If you call exit, the destructor will not be called.
From the C++ standard (§3.6.1/4):
Calling the function
void exit(int);
declared in <cstdlib> (18.3) terminates the program without leaving the current block and hence without destroying any objects with automatic storage duration (12.4). If exit is called to end a program during the destruction of an object with static storage duration, the program has undefined behavior.
|
2,668,104 | 2,668,184 | What does it mean "regular file" according to S_ISREG C/C++? | Let's consider the following 3 code lines:
struct stat buffer;
status = lstat(file.c_str(), &buffer);
bool Flag = S_ISREG(buffer.st_mode)
When S_ISREG() returns true it tells you that the file is a regular file
What does regular means exactly ?
Thanks
| It is non-standard, you should check the documentation for your CRT implementation. But it ought to mean that the name refers to a regular file, instead of a pipe, stream, symbolic link, directory or device.
|
2,668,133 | 2,668,162 | Opinions regarding C++ programming practice | I have a program that I am writing, not too big. Apart from the main function, it has about 15 other functions that called for various tasks at various times. The code works just fine all in one file, and as it is right now.
However, I was wondering if anyone had any advice on whether it is smarter/more efficient/better programming to put those functions in a separate file different from where main is, or whether it even matters at all. If yes, why? If no, why not?
I am not new at C++, but definitely not an expert either, so if you think this question is stupid, feel free to tell me so.
Thanks for your time!
| Depends on how big those functions are. If your source file starts to get over several hundred lines of code in length, there is reason to extract part of the functionality into one (or more) separate file(s).
If you can group the functions into distinct sets based on their responsibilities and/or their level of abstraction, you may prefer separating them into distinct physical files (and classes of course) along those lines. E.g. some functions may work with file I/O while others do some computation. Or some functions do low level bit flipping chores within file I/O, while others build on the former to implement some more abstract functionality.
Another reason to partition your code would be if some of the functions were used by more than one client, but this apparently does not apply to your case. (However, this is probably going to change if / as your app is further developed and extended in the future...)
|
2,668,144 | 2,668,247 | placement new to defer to a different constructor | Is this safe? I'm not using any virtual functions in my actual implementation, but I'm tempted to believe that even if I was, it would still be safe.
class Foo
{
Foo()
{
// initialize things
}
Foo( int )
{
new ( this ) Foo();
}
}
| By the time you enter the open curly brace of the Foo(int) constructor, all class members have had their constructor called. If you then force a call to another constructor with placement new, you're overwriting the current state of the class. This basically means all members have their constructors called twice - if something does new in its constructor, you leak that content, and you will really, really mess things up! You're effectively constructing two objects, and the destructors for the members of the first object are never called, since the second object overwrites the memory of the first object.
In other words it's BAD! Don't do it!!
The most common workaround is to use some kind of initialisation function, and call that from both constructors. This won't let you initialize const members and others that must be in the initializer list, though.
|
2,668,240 | 2,668,315 | C++: parsing with simple regular expression or shoud I use sscanf? | I need to parse a string like func1(arg1, arg2); func2(arg3, arg4);. It's not a very complex parsing problem, so I would prefer to avoid resorting to flex/bison or similar utilities.
My first approch was to try to use POSIX C regcomp/regexec or Boost implementation of C++ std::regex. I wrote the following regular expression, which does not work (I'll explain why further on).
"^"
"[ ;\t\n]*"
"(" // (1) identifier
"[a-zA-Z_][a-zA-Z0-9_]*"
")"
"[ \t\n]*"
"(" // (2) non-marking
"\["
"(" // (3) non-marking
"[ \t]*"
"(" // (4..n-1) argument
"[a-zA-Z0-9_]+"
")"
"[ \t\n]*"
","
")*"
"[ \t\n]*"
"(" // (n) last argument
"[a-zA-Z0-9_]+"
")"
"]"
")?"
"[ \t\n]*"
";"
Note that the group 1 captures the identifier and groups 4..n-1 are intended to capture arguments except the last, which is captured by group n.
When I apply this regex to, say func(arg1, arg2, arg3) the result I get is an array {func, arg2, arg3}. This is wrong because arg1 is not in it!
The problem is that in the standard regex libraries, submarkings only capture the last match. In other words, if you have for instance the regex "((a*|b*))*" applied on "babb", the results of the inner match will be bb and all previous captures will have been forgotten.
Another thing that annoys me here is that in case of error there is no way to know which character was not recognized as these functions provide very little information about the state of the parser when the input is rejected.
So I don't know if I'm missing something here... In this case should I use sscanf or similar instead?
Note that I prefer to use C/C++ standard libraries (and maybe boost).
| If you want to use Regex, would it be simpler to split it into 2 steps. In step 1 you find
func1(stuff);
and turn it into func1 and stuff
In the next step, you parse 'stuff' to find all the separate args for the function.
|
2,668,430 | 2,668,477 | In C++, how can I make typedefs visible to every file in my project? | I have a typedef
typedef unsigned int my_type;
used in a file. I would like to make it visible across all my files, without
putting it in a header file included by everything. I don't want to go the header file
route because as it stands this will be the only declaration in the header file
(and it seems unnecessary to add a file just for this).
Is there a way to do this?
If instead I had:
typedef X my_type;
where X was a class, would I need to include X.h everywhere and have the typedef at the end
of X.h ?
| I don't want to go the header file route because as it stands this will be the only declaration in the header file (and it seems unnecessary to add a file just for this).
What's the problem with that? It seems just as unnecessary to avoid creating a file at all costs.
Is there a way to do this?
Not as far as I am aware.
would I need to include X.h everywhere and have the typedef at the end of X.h ?
No, but that's probably the best thing. The only reason you should be doing that is if X is a template, and you need templates to be in headers anyway.
|
2,668,738 | 2,822,866 | C++ Code Analysis - how to add custom dictionary? | ;) Yeah. I also have C++ in my solution.
How do I add a custom dictionary there? There is no tool for an includes file, as well as no way to tell it the type is CustomDictionary.
THe advice and approach shown in http://msdn.microsoft.com/en-us/library/bb514188(v=VS.100).aspx is not usable for C++ projects.
| For VS2010, you can set the dictionary by editing your .vcxproj file and pasting this:
<ItemGroup>
<CodeAnalysisDictionary Include="c:\temp\mydictionary.xml" />
</ItemGroup>
Modify the path to your dictionary.
To make this a permanent setting for all your C++ projects, navigate to c:\program files\msbuild\microsoft.cpp\v4.0 and edit Microsoft.Cpp.props, pasting the above (make a backup please).
To verify that the change is effective, use Tools + Options, Projects and Solutions, Build and Run, MSBuild project build log file verbosity = Diagnostic. Rebuild your project, look in the .log file and verify that fxcopcmd.exe got started with the /dictionary option.
Both approaches worked well on my machine.
|
2,668,851 | 2,669,481 | How do I detect that my application is running as service or in an interactive session? | I'm writing an application that is able to run as a service or standalone but I want to detect if the application was executed as a service or in a normal user session.
| I think you can query the process token for membership in the Interactive group.
From http://support.microsoft.com/kb/243330:
SID: S-1-5-4
Name: Interactive
Description: A group that includes all users that have logged on interactively. Membership is controlled by the operating system.
Call GetTokenInformation with TokenGroups to get the groups associated with the account under which the process is running, then iterate over the sids looking for the Interactive sid.
I found a nice chunk of code at http://marc.info/?l=openssl-dev&m=104401851331452&w=2
|
2,669,042 | 2,669,391 | How do I set the QT debugger to give more meaningful messages? | I'm currently learning the QT framework. I need to know if it's possible to set the debugger to give meaningful messages as opposed to what it gives me right now, which is the failed step in the build process (usually the '.o' file) I need to know if it's possible to set it to giving meaningful message like Visual studio
| The debugger is not involved in the build process. Those errors messages come either from the compiler or the linker, or the moc compiler.
You can try qmake -d to make it extra verbose. That might help you understand the nature of the problem.
|
2,669,056 | 2,669,150 | Regarding two dimensional array | I have some problems using two dimensional array.
static const int PATTERNS[20][4];
static void init_PATTERN()
{
// problem #1
int (&patterns)[20][4] = const_cast<int[20][4]>(PATTERNS);
...
}
extern void UsePattern(int a, const int** patterns, int patterns_size);
// problem #2
UsePattern(10, PATTERNS, sizeof(PATTERNS)/sizeof(PATTERNS[0]));
In the first statement, I need to cast the const off the two dimensional array PATTERNS. The reason for this is that the init function is called only once, and in the remaining code, PATTERNS is strictly read-only.
In the second statement, I need to pass PATTERNS array to the int** argument. Direct passing resulted a compile error.
I have solved the problem, just about the same time that @Andrey posted the answer. Yes int[][] can't be casted to int**.
It can be casted to int* through &(PATTERNS[0][0]), and the function prototype must be modified with row size (the number of elements in a row). The array can be const_cast away with reference syntax.
| Firstly, there's no such thing as cast to array type (or to function type) in C++. Yet this is what you are trying to do. If you want to cast away constness from something, you have to cast to either pointer or reference type. In your case you have a reference on the receiving end of the cast, so the cast itself has to be to reference type as well
int (&patterns)[20][4] = const_cast<int (&)[20][4]>(PATTERNS);
Of course, as Bill already noted, casting away constness from a constant object (and then attempting to modify the object) leads to undefined behavior.
Secondly, a two-dimensional array cannot be passed anywhere as an int ** pointer. If you want to pass your PATTERNS somewhere, you can pass it as const int (&)[20][4], const int (*)[20][4], const int [][4], const int (*)[4] or something similar to that, but not as int **. Do a search on SO and/or read some FAQ on arrays to understand why. This has been explained too many times to repeat it again.
|
2,669,191 | 2,669,474 | Strlen of MAX 16 chars string using bitwise operators | The challenge is to find the fastest way to determine in C/C++ the length of a c-string using bitwise operations in C.
char thestring[16];
The c-string has a max size of 16 chars and is inside a buffer
If the string is equal to 16 chars doesn't have the null byte at the end.
I am sure can be done but didn't got it right yet.
I am working on this at the moment, but assuming the string is memcpied on a zero-filled buffer.
len = buff[0] != 0x0 +
buff[1] != 0x0 +
buff[2] != 0x0 +
buff[3] != 0x0 +
buff[4] != 0x0 +
buff[5] != 0x0 +
buff[6] != 0x0 +
buff[7] != 0x0 +
buff[8] != 0x0 +
buff[9] != 0x0 +
buff[10] != 0x0 +
buff[11] != 0x0 +
buff[12] != 0x0 +
buff[13] != 0x0 +
buff[14] != 0x0 +
buff[15] != 0x0;
Note:
the buffer is zero-filled "\0123456789abcde" can't happen.
| This would work fine since buf is initialized with zero. Your solution has != which will use jump instruction. If the GPU has multiple XOR units, the following code can be pipelined quite nicely. On other hand, JUMP instruction would cause flushing of the pipeline.
len = !!buf[0] +
!!buf[1] +
//...
!!buf[15]
Update: The above code and OP's code produce the same assembly code when compiled by GCC with -O3 flags. (different if no optimization flags are provided)
|
2,669,208 | 2,669,264 | Qt Sockets and Endianness | I'm writing a program that uses QUdpSocket for transmitting data over the network. This is my first socket program, and I've come across an interesting problem called Endianness.
My actual question in, do I have to worry about Endianness when I'm using QNetwork as my sockets library? If I do have to worry, what do I have to do to properly avoid Endianness problems?
| Generally, you need to worry about endianness (byte-order) when you transfer integers larger than a single byte from one computer to another. In C/C++, this means that if you're sending something like a 16-bit, 32-bit or 64-bit integer, you need to first convert the integer to network byte order, (also known as Big-Endian). The computer on the receiving end must then convert the incoming integers to host byte order, which is whatever byte-order the host-machine uses natively. This is usually done using the htons and ntohs series of library functions, but with the Qt library you can also use the qToBigEndian and qFromBigEndian functions.
Note that you don't need to worry about endianness when sending ASCII or UTF-8 text, because these formats are composed of sequences of individual bytes, rather than multi-byte data types.
|
2,669,350 | 2,672,483 | New to C/C++ Using Android NDK to port Legacy code, getting compile errors | I have been trying to take some old Symbian C++ code over to Android today using the NDK.
I have little to no C or C++ knowledge so its been a chore, however has to be done.
My main issue is that I'm having trouble porting what I believe is Symbian specifi code to work using the small C/C++ subset that is available with the Android NDK.
Here is a picture of the compilation errors I'm getting using cygwin
I was wondering if anyone could point me in the right direction on how to deal with these errors? For instance is TBool/Int/TUint/RPointerArray/RSocket a Symbian primitive and thats why it wont compile or is it something else?
Also what is ISO C++?
Any tutorials, guides or tips and help would be greatly appreciated.
EDIT:
Here is a code snippet from the .h file I am trying to import followed by the output for the snippet from the compiler.
Could someone guide me on how I would port this Symbian specific code to normal C++?
If I got an idea of whats Symbian specific and how to change it I believe I could change then begin to port the rest myself
#ifndef __RTPSTREAM_H__
#define __RTPSTREAM_H__
class CRTPParser;
class MDataRecorderObserver
{
public:
virtual void DataRecorded(const TDesC8& aData, TUint aCodec, TUint aFramesizeMs)=0;
};
class MRTPStreamDataObserver
{
public:
virtual void AudioDataSent()=0;
virtual void DataReceived(const TDesC8& aData,TUint aCodec, TBool aMarker, TUint aSeq, TUint aTime)=0;
virtual void DataReceived(const TDesC8& aData)=0;
};
$ make APP=ndk-socket
Android NDK: Building for application 'ndk-socket'
Compile++ thumb: socket <= apps/ndk-socket/project/jni/rtpstream.cpp
In file included from apps/ndk-socket/project/jni/com_ciceronetworks_utils_RTPJn
i.h:2,
from apps/ndk-socket/project/jni/rtpstream.cpp:4:
build/platforms/android-3/arch-arm/usr/include/jni.h:489: note: the mangling of
'va_list' has changed in GCC 4.4
In file included from apps/ndk-socket/project/jni/rtpstream.cpp:11:
apps/ndk-socket/project/jni/rtp/RTPStream.h:15: error: ISO C++ forbids declarati
on of 'TDesC8' with no type
apps/ndk-socket/project/jni/rtp/RTPStream.h:15: error: expected ',' or '...' bef
ore '&' token
apps/ndk-socket/project/jni/rtp/RTPStream.h:23: error: ISO C++ forbids declarati
on of 'TDesC8' with no type
apps/ndk-socket/project/jni/rtp/RTPStream.h:23: error: expected ',' or '...' bef
ore '&' token
apps/ndk-socket/project/jni/rtp/RTPStream.h:24: error: ISO C++ forbids declarati
on of 'TDesC8' with no type
apps/ndk-socket/project/jni/rtp/RTPStream.h:24: error: expected ',' or '...' bef
ore '&' token
apps/ndk-socket/project/jni/rtp/RTPStream.h:24: error: 'virtual void MRTPStreamD
ataObserver::DataReceived(int)' cannot be overloaded
apps/ndk-socket/project/jni/rtp/RTPStream.h:23: error: with 'virtual void MRTPSt
reamDataObserver::DataReceived(int)'
apps/ndk-socket/project/jni/rtp/RTPStream.h:30: error: 'TInt' has not been deca
red
| By "ISO C++", the G++ compiler means "The C++ standard".
This looks like the usual G++ error spew when it gets confused. Typically only the top error message is meaningful, and then the rest is what the compiler prints out because it was confused. The odd thing is that the initial error about "expected class name before '<' token" is itself more typical of error spew than real errors. It's perhaps useful to have a look at that point in the code and see what it says and whether there's anything strange or compiler-specific there.
Also, from a Google-search, it looks like the initial note about va_name mangling is just informative and very unlikely to cause a problem in this case -- and, specifically, is certainly not going to cause the rest of these compiler errors.
Edit: Based on the revised error output and source code that you posted, it looks like the error is simply that this code is using the "TDesc8" data type without it first being declared, and the rest is likely to be followon from that. According to the information I could find online in the Symbian documentation, code that uses that type should have a #include <e32des8.h> line to include the relevant header. Does the code you are compiling include that header?
|
2,669,393 | 2,669,471 | Problem with Mergesort in C++ | vector<int>& mergesort(vector<int> &a) {
if (a.size() == 1) return a;
int middle = a.size() / 2;
vector<int>::const_iterator first = a.begin();
vector<int>::const_iterator mid = a.begin() + (middle - 1);
vector<int>::const_iterator last = a.end();
vector<int> ll(first, mid);
vector<int> rr(mid, last);
vector<int> l = mergesort(ll);
vector<int> r = mergesort(rr);
vector<int> result;
result.reserve(a.size());
int dp = 0, lp = 0, rp = 0;
while (dp < a.size()) {
if (lp == l.size()) {
result[dp] = (r[rp]);
rp++;
} else if (rp == r.size()) {
result[dp] = (l[lp]);
lp++;
} else if (l[lp] < r[rp]) {
result[dp] = (l[lp]);
lp++;
} else {
result[dp] = (r[rp]);
rp++;
}
dp++;
}
a = result;
return a;
}
It compiles correctly but while execution, I am getting:
This application has requested the
runtime to end it in an unusual way.
This is a weird error.
Is there something that is fundamentally wrong with the code?
| One problem is with the usage of reserve() (either use resize() or append items with push_back() instead of accessing the index).
if (a.size() == 1) return a;
int middle = a.size() / 2;
vector<int>::const_iterator first = a.begin();
vector<int>::const_iterator mid = a.begin() + (middle - 1);
vector<int>::const_iterator last = a.end();
vector<int> ll(first, mid);
vector<int> rr(mid, last);
This could be another problem. If the size is 2, then ll would end up being an empty vector, and this function doesn't appear to handle this. There doesn't seem to be much reason to subtract 1 from middle anyway.
It is also possible that you are copying things around far more than needed: you shouldn't need the l and r vectors (because they will just be copies of ll and rr), similarly I don't think you need the result vector, since you could just write the merged results right back to a.
|
2,669,534 | 2,669,599 | Set designed Tframe on some Tpanel | I am totally novice in C++ Builder.
Never tried working with VCL frames.
So, i have some Tform with Tpanel and two frames designed.
How can i display designed frames on my forms panel?
Tired searching similar examples.
| I don't know C++ builder, but I've heard it uses the exact same Form Designer that Delphi has. In Delphi, to place a frame on the form, you need to create the frame first and have it in your project. Then go to the component palette and find the "Frames" option under the Standard group. Select it and it'll give you a dialog box containing all the frames in your project. Pick which one from there and you've got an instance of the frame on your form, which you can manipulate just like any other control.
|
2,669,577 | 2,669,665 | Why aren't operator conversions implicitly called for templated functions? (C++) | I have the following code:
template <class T>
struct pointer
{
operator pointer<const T>() const;
};
void f(pointer<const float>);
template <typename U>
void tf(pointer<const U>);
void g()
{
pointer<float> ptr;
f(ptr);
tf(ptr);
}
When I compile the code with gcc 4.3.3 I get a message (aaa.cc:17: error: no matching function for call to ‘tf(pointer<float>&)’) indicating that the compiler called 'operator pointer<const T>' for the non-templated function f(), but didn't for the templated function tf(). Why and is there any workaround short of overloading tf() with a const and non-const version?
Thanks in advance for any help.
| The reason is that you don't get implicit type conversions during template deduction, it never gets to that point.
Consider:
template <typename T>
struct foo {};
template <typename U>
void bar(foo<U>)
{}
foo<int> f;
bar(f);
For that call to bar, the compiler can deduce that U is an int, and instantiate the function. However, consider:
template <typename U>
void bar(foo<const U>)
{} // note ^^^^
foo<int> f;
bar(f);
There is no U the compiler can deduce such that the type of foo matches the type of the parameter. Ergo, template instantiation fails. There is no chance for the conversion to happen.
|
2,669,681 | 2,670,232 | Behavior of virtual function in C++ | I have a question, here are two classes below:
class Base{
public:
virtual void toString(); // generic implementation
}
class Derive : public Base{
public:
( virtual ) void toString(); // specific implementation
}
The question is:
If I wanna subclass of class Derive perform polymophism using a pointer of type Base, is keyword virtual in the bracket necessary?
If the answer is no, what's the difference between member function toString of class Derive with and without virtual?
| C++03 §10.3/2:
If a virtual member function vf is
declared in a class Base and in a
class Derived, derived directly or
indirectly from Base, a member
function vf with the same name and
same parameter list as Base::vf is
declared, then Derived::vf is also
virtual (whether or not it is so
declared) and it overrides
Base::vf.
|
2,669,770 | 2,669,909 | Composite key syntax in Boost MultiIndex | Even after studying the examples, I'm having trouble figuring out how to extract ranges using a composite key on a MultiIndex container.
typedef multi_index_container<
boost::shared_ptr< Host >,
indexed_by<
hashed_unique< const_mem_fun<Host,int,&Host::getID> >, // ID index
ordered_non_unique< const_mem_fun<Host,int,&Host::getAgeInY> >, // Age index
ordered_non_unique< const_mem_fun<Host,int,&Host::getHousehold> >, // Household index
ordered_non_unique< // Age & eligibility status index
composite_key<
Host,
const_mem_fun<Host,int,&Host::getAgeInY>,
const_mem_fun<Host,bool,&Host::isPaired>
>
>
> // end indexed_by
> HostContainer;
My goal is to get an iterator pointing to the first of the subset of elements in HostContainer hmap that has age partnerAge and returns false to Host::isPaired():
std::pair< hmap::iterator,hmap::iterator > pit = hmap.equal_range(boost::make_tuple( partnerAge, false ) );
I think this is very wrong.
How/Where do I specify the iterator index (which should be 3 for age & eligibility)? I will include other composite keys in the future.
What exactly are the two iterators in std::pair? (I'm copying syntax from an example that I don't understand.)
I would ideally use std::count to calculate the number of elements of age partnerAge that are eligible (return false to Host::isPaired()). What is the syntax for extracting the sorted index that meets these requirements?
I'm obviously still learning C++ syntax. Thanks in advance for any help.
| To get access to N-th index you could use function get as follows:
std::pair< hmap::nth_index<3>::type::const_iterator,
hmap::nth_index<3>::type::const_iterator > pit =
hmap.get<3>().equal_range(boost::make_tuple( partnerAge, false ) );
equal_range returns pair of iterators of N-th index. You will get range of elements that are satisfy the specified condition since your composite key is not unique. To iterate through that range you could use loop from the first iterator to the second iterator.
Consider using named indexes to use them as get<index_name>(), because specifying actual number is not very readable.
count has syntax similar to equal_range:
size_t cnt = hmap.get<3>().count(boost::make_tuple( partnerAge, false ) );
|
2,669,888 | 2,669,911 | Initialization Order of Class Data Members | In the following code, when the ctor of X is called will the ctor of A or B be called first? Does the order in which they are placed in the body of the class control this? If somebody can provide a snippet of text from the C++ standard that talks about this issue, that would be perfect.
class A {};
class B {};
class X
{
A a;
B b;
};
| The order is the order they appear in the class definition - this is from section 12.6.2 of the C++ Standard:
5 Initialization shall proceed in the
following order:
— First, and only for
the constructor of the most derived
class as described below, virtual base
classes shall be initialized in the
order they appear on a depth-first
left-to-right traversal of the
directed acyclic graph of base
classes, where “left-to-right” is the
order of appearance of the base class
names in the derived class
base-specifier-list.
— Then, direct
base classes shall be initialized in
declaration order as they appear in
the base-specifier-list (regardless of
the order of the mem-initializers).
— Then, nonstatic data members shall be
initialized in the order they were
declared in the class definition
(again regardless of the order of the
mem-initializers).
— Finally, the body
of the constructor is executed. [Note:
the declaration order is mandated to
ensure that base and member subobjects
are destroyed in the reverse order of
initialization. ]
|
2,669,915 | 2,669,923 | How to make this C++ code more DRY? | I have these two methods on a class that differ only in one method call. Obviously, this is very un-DRY, especially as both use the same formula.
int PlayerCharacter::getAttack() {
int attack;
attack = 1 + this->level;
for(int i = 0; i < this->current_equipment; i++) {
attack += this->equipment[i].getAttack();
}
attack *= sqrt(this->level);
return attack;
}
int PlayerCharacter::getDefense() {
int defense;
defense = 1 + this->level;
for(int i = 0; i < this->current_equipment; i++) {
defense += this->equipment[i].getDefense();
}
defense *= sqrt(this->level);
return defense;
}
How can I tidy this up in C++?
| In my opinion, what you have is fine, as it will allow you to tweak attack/defense more than if you represented both of them with one function. Once you start testing your game, you'll begin balancing attack/defense formulas, so having separate functions for them is fine.
The whole concept of DRY [don't repeat yourself] is [hopefully] to prevent your code from becoming a huge copy & paste fest. In your situation, the defense/attack formulas will change over time [for example, what if characters have buffs/status-ailment? A specific status ailment might cut defense in half, while increasing attack by 2 (Berserk, FF reference, heh)]
|
2,670,219 | 2,670,253 | C++ standard thread class? | I have come across many ad hoc implementations of thread class in C++, but why is there no standard library thread class like the one in Java? The one that I generally use in C++ is http://www.linuxdocs.org/HOWTOs/C++Programming-HOWTO-24.html
| std::thread will be standardized in C++0x, and many compilers already support it.
It is perhaps more ambitious than your cited example as construction/destruction signifies initiation/joining of thread execution.
Here's another article.
|
2,670,491 | 2,670,621 | detect if extended desktop is to the left or to the right | So, I have a screen capture utility (it takes full screen shots and saves it to png files) I've written, and it uses SM_CXVIRTUALSCREEN and SM_CYVIRTUALSCREEN to determine the width and height of the desktop.
I then get the desktop DC and copy out the bits and save them as png.
BitBlt(
backDC, 0, 0,
backBufferCX, backBufferCX,
desktopDC, X_SRC, 0, SRCCOPY );
Here X_SRC is usually 0, UNLESS THE DESKTOP HAS BEEN EXTENDED "TO THE LEFT". In that case it needs to be -1280px, for example, if the left monitor measures 1280px.
How can I determine if the desktop's starting point is negative (if the user has extended his desktop to the left?)
| You can obtain the positioning information for all of the monitors via the EnumDisplayMonitors method.
Or, if you only care about the corners of the virtual screen, you can pass SM_XVIRTUALSCREEN and SM_YVIRTUALSCREEN into the GetSystemMetrics method.
|
2,670,501 | 2,670,578 | How to pass non static member function into glutDisplayFunc | I have a class which has functionality to initialise opengl and run it in separate thread.
My problem is: openGL callbacks such as glutDisplayFunc, glutMotionFunc etc accepts
void (*f) void, and I cannot pass class member function.
ways around.
1) I can declare member function as static, but in this case I need to declare all used member variables as static, and end up declaring a whole class as a static.
2) I can use some stand alone function and declare my object as global, but its too bad.
I wonder if there are some ways around so I dont need to make my opengl class static ?? (using c++)
| You'll need to create a "thunk" or "trampoline": C API function callbacks into C++ member function code
|
2,670,558 | 2,670,576 | deleting dynamically allocated object that contains vector in C++ STL | I have a class
class ChartLine{
protected:
vector<Point> line; // points connecting the line
CString name; //line name for legend
CPen pen; //color, size and style properties of the line
};
where Point is a structure
struct Point{
CString x;
double y;
};
In main() I dynamically allocate objects of type ChartLine with new operator.
If I use delete afterwards, will default destructor ~ChartLine() properly dealocate (or clear) member ChartLine::line(which is vector btw) or I would have to clear that vector in ~ChartLine() manually?
Thanks in advance.
Cheers.
| The implicitly created destructor will call the destructor of all the members (in the reverse order they are declared in the class.) The vector will clean up after itself. You don't need to define a destructor yourself.
This is why you should prefer automatic allocation in combination with RAII. When objects clean themselves, your code as safer and easier. Hint: Don't use new and delete, put it in a smart pointer!
std::auto_ptr<int> p(new int(5));
boost::shared_ptr<int> p = boost::make_shared<int>(5);
Both of those will delete automatically, and now you're exception safe as well. (Note, the two above do not do the same thing. There are more types of smart pointers as well.)
|
2,670,727 | 2,670,808 | particle system: particle generation | I have a system that generates particles from sources and updates their positions. Currently, I have written a program in OpenGL which calls my GenerateParticles(...) and UpdateParticles(...) and displays my output. One functionality that I would like my system to have is being able to generate n particles per second. In my GenerateParticles(...) and UpdateParticles(...) functions, I accept 2 important parameters: current_time and delta_time. In UpdateParticles(...), I update the position of my particle according to the following formula: new_pos = curr_pos + delta_time*particle_vector. How can I use these parameters and global variables (or other mechanisms) to produce n particles per second?
| You need to be careful, the naive way of creating particles will have you creating fractional particles for low values of n (probably not what you want). Instead create an accumulator variable that gets summed with your delta_time values each frame. Each frame check it to see how many particles you need to create that frame and subtract the appropriate amounts:
void GenerateParticles(double delta_time) {
accumulator += delta_time;
while (accumulator > 1.0 / particles_per_second) {
CreateParticle(...);
accumulator -= 1.0 / particles_per_second;
}
}
Make sure you put some limiting in so that if the time delta is large you don't create a million particles all at once.
|
2,670,738 | 2,670,778 | staying within boundaries of image? | So I am to loop through copyFrom.pixelData and copy it into pixelData.
I realize that I need to check the conditions of i and j, and have them not copy past the boundaries of pixelData[x][y],
I need another 2 loops for that? I tried this, but was getting segmentation fault..
Is this the right approach?
void Image::insert(int xoff, int yoff, const Image& copyFrom, Color notCopy)
{
for (int x = xoff; x < xoff+copyFrom.width; x++) {
for (int y = yoff; y < yoff+copyFrom.height; y++) {
for (int i = 0; i<width; i++) {
for (int j = 0; j<height; j++) {
if (copyFrom.pixelData[i][j].colorDistance(notCopy) > 20)
pixelData[x][y]=copyFrom.pixelData[i][j];
}
}
}
}
}
}
| No, you don't need more loops for that.
Instead try:
int copywidth = std::min(width, copyFrom.width-xoff);
// likewise copyheight = ...
for( int x = 0; x < copywidth; x++ ) {
// likewise for( int y ...
pixelData[x][y] = copyFrom.pixelData[x+xoff][y+yoff];
}
|
2,670,781 | 2,777,109 | Design: How to declare a specialized memory handler class | On an embedded type system, I have created a Small Object Allocator that piggy backs on top of a standard memory allocation system. This allocator is a Boost::simple_segregated_storage<> class and it does exactly what I need - O(1) alloc/dealloc time on small objects at the cost of a touch of internal fragmentation. My question is how best to declare it. Right now, it's scope static declared in our mem code module, which is probably fine, but it feels a bit exposed there and is also now linked to that module forever. Normally, I declare it as a monostate or a singleton, but this uses the dynamic memory allocator (where this is located.) Furthermore, our dynamic memory allocator is being initialized and used before static object initialization occurs on our system (as again, the memory manager is pretty much the most fundamental component of an engine.) To get around this catch 22, I added an extra 'if the small memory allocator exists' to see if the small object allocator exists yet. That if that now must be run on every small object allocation. In the scheme of things, this is nearly negligable, but it still bothers me.
So the question is, is there a better way to declare this portion of the memory manager that helps decouple it from the memory module and perhaps not costing that extra isinitialized() if statement? If this method uses dynamic memory, please explain how to get around lack of initialization of the small object portion of the manager.
| A good guideline is: say what you mean, unless there is good reason to do otherwise. This allocator is a global static object, and should be declared as such. Now if its state needs initializing, I would do that in the code that initializes the dynamic memory allocator -- since this is in fact part of the work of initializing the memory allocation system, this again falls under the heading of saying what you mean. That would avoid the inelegant conditional check on every call.
|
2,670,816 | 2,670,919 | How can I use the compile time constant __LINE__ in a string? | I can use __LINE__ as a method parameter just fine, but I would like an easy way to use it in a function that uses strings.
For instance say I have this:
11 string myTest()
12 {
13 if(!testCondition)
14 return logError("testcondition failed");
15 }
And I want the result of the function to be:
"myTest line 14: testcondition failed"
How can I write logError? Does it have to be some monstrosity of a macro?
| Why do you even need it as a string? What's wrong with an integer? Here are two ways you could write logError():
#define logError(str) fprintf(stderr, "%s line %d: %s\n", __FILE__, __LINE__, str)
// Or, forward to a more powerful function
#define logError(str) logError2(__FILE__, __LINE__, str)
void logError2(const char *file, int line, const char *str);
If you really need the line as a string, you can use the stringizing operator #, but because of the way macros work, you'll need to wrap it in two macros:
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#define LINE_STRING STRINGIZE(__LINE__)
And now LINE_STRING is a macro that will expand to a string containing the current line number wherever it is expanded. If you only had one level of macros (i.e. if you had #define STRINGIZE(x) #x), then you would get the literal string "__LINE__" every time you expanded it, which is not what you want.
|
2,670,849 | 2,670,890 | Returning pointers in a thread-safe way | Assume I have a thread-safe collection of Things (call it a ThingList), and I want to add the following function.
Thing * ThingList::findByName(string name)
{
return &item[name]; // or something similar..
}
But by doing this, I've delegated the responsibility for thread safety to the calling code, which would have to do something like this:
try
{
list.lock(); // NEEDED FOR THREAD SAFETY
Thing *foo = list.findByName("wibble");
foo->Bar = 123;
list.unlock();
}
catch (...)
{
list.unlock();
throw;
}
Obviously a RAII lock/unlock object would simplify/remove the try/catch/unlocks, but it's still easy for the caller to forget.
There are a few alternatives I've looked at:
Return Thing by value, instead of a
pointer - fine unless you need to
modify the Thing
Add function ThingList::setItemBar(string name, int value) - fine, but these tend to
proliferate
Return a pointerlike object which locks the list on creation and unlocks it again on destruction. Not sure if this is good/bad practice...
What's the right approach to dealing with this?
| There is no one "right approach"; it depends on the needs of your application.
If at all possible, return things by value, or return a copy that the caller can do whatever they want with.
A variant of the above is to return a modifiable copy, and then provide a way to atomically merge a modified object back into the list. Something like:
Thing t = myThingList.getThing(key);
t.setFoo(f);
t.setBar(b);
myThingList.merge(t); // ThingList atomically updates the appropriate element
However, that can cause problems if multiple threads try to update the same object.
The "pointerlike object" idea sounds cool, but I suspect it would lead to hard-to-find bugs when some lock isn't getting released somewhere.
I'd try to keep all the locking/unlocking code within ThingList, so the ThingList::set... functions are probably what I would do.
|
2,670,868 | 2,678,470 | PCAP Web Service Usage Logging for Dummies | I've been assigned the task (for work) of working with PCAP for the first time in my life. I've read through the tutorials and have hacked together a real simple capture program which, it turns out, isn't that hard. However, making use of the data is more difficult. My goal is to log incomming and outgoing web service requests. Are there libraries (C or C++) that stitch together the packets from PCAP that would make reporting on this simple (that is Layer 7 reporting)? Baring that is there something short of reading all of the RFC's from soup to nuts that will allow me to have an "ah-ha!" moment (all of the tutorials seem to stop at the raw packet level which isn't useful for me)?
It looks like PERL has a library that may do this and I may eventually attempt a reverse engineer from PERL.
NOTE BENE: Web Server logs aren't acceptable here as I will be intercepting on a routing device. If I had access to those I'd be done and happy...I don't.
NOTE BENE: I do not have access to anything but what my application will install on this black box so script languages are out
| As this point I'm looking into OpenDPI. I'm not sure if its a tight fit and will respond back here once I know but it does seem that it will cover my needs and won't require reverse engineering:
http://code.google.com/p/opendpi/
EDIT: Yep. OpenDPI works for my needs.
|
2,670,999 | 2,671,026 | How can I work around the fact that in C++, sin(M_PI) is not 0? | In C++,
const double Pi = 3.14159265;
cout << sin(Pi); // displays: 3.58979e-009
it SHOULD display the number zero
I understand this is because Pi is being approximated, but is there any way I can have a value of Pi hardcoded into my program that will return 0 for sin(Pi)? (a different constant maybe?)
In case you're wondering what I'm trying to do: I'm converting polar to rectangular, and while there are some printf() tricks I can do to print it as "0.00", it still doesn't consistently return decent values (in some cases I get "-0.00")
The lines that require sin and cosine are:
x = r*sin(theta);
y = r*cos(theta);
BTW: My Rectangular -> Polar is working fine... it's just the Polar -> Rectangular
Thanks!
edit: I'm looking for a workaround so that I can print sin(some multiple of Pi) as a nice round number to the console (ideally without a thousand if-statements)
| What Every Computer Scientist Should Know About Floating-Point Arithmetic (edit: also got linked in a comment) is pretty hardcore reading (I can't claim to have read all of it), but the crux of it is this: you'll never get perfectly accurate floating point calculations. From the article:
Squeezing infinitely many real numbers into a finite number of bits requires an approximate representation.
Don't let your program depend on exact results from floating point calculations - always allow a tolerance range. FYI 3.58979e-009 is about 0.0000000036. That's well within any reasonable tolerance range you choose!
|
2,671,044 | 2,671,333 | templates and casting operators | This code compiles in CodeGear 2009 and Visual Studio 2010 but not gcc. Why?
class Foo
{
public:
operator int() const;
template <typename T> T get() const { return this->operator T(); }
};
Foo::operator int() const
{
return 5;
}
The error message is:
test.cpp: In member function `T Foo::get() const':
test.cpp:6: error: 'const class Foo' has no member named 'operator T'
| It's a bug in G++. operator T is an unqualified dependent name (because it has T in it and lookup will thus be different depending on its type). As such it has to be looked up when instantiating. The Standard rules
Two names are the same if
...
they are the names of user-defined conversion functions formed with the same type.
Thus the type name specified after the operator keyword doesn't have to match lexically in any way. You can apply the following work-around to force GCC treating it as a dependent name
template<typename T, typename>
struct identity { typedef T type; };
class Foo
{
public:
operator int() const;
template <typename T> T get() const {
return this->identity<Foo, T>::type::operator T();
}
};
|
2,671,046 | 2,671,096 | Does Microsoft make available the .obj files for its CRT versions to enable whole program optimization on CRT codepaths? | Given the potential performance improvements from LTCG (link time code generation, or whole program optimization), which requires the availability of .obj files, does Microsoft make available the .obj files for the various flavors of its MSVCRT releases? One would think this would be a good place for some potential gain. Not sure what they have to lose since the IL that is generated in the .obj files is not documented and processor specific.
| A static library is basically just a collection of .obj files mushed (that's a technical term) together into a single file, with a directory added so the linker can find each on easily. If you use the static library, it should be able to include them in the global optimization phase.
|
2,671,056 | 2,671,136 | Want to store profiles in Qt, use SQLite or something else? | I want to store some settings for different profiles of what a "task" does.
I know in .NET there's a nice ORM is there something like that or an Active Record or whatever? I know writing a bunch of SQL will be fun
| I'm going to agree with Micheal E and say that you can use QJson, but no you don't have to manage serialization. QJson has a QObject->QJson serializer/deserialzer. So as long as all your relevant data is exposed via Q_PROPERTY QJson can grab it and write/read it to/from the disk.
Examples here: http://qjson.sourceforge.net/usage.html
From there you can simply dump the data into a file.
|
2,671,323 | 2,671,422 | How do I change properties of buttons within button boxes in Qt Designer? | I have been searching online to no avail. Does anyone know how to access a button in a button box (created using the "Dialog with Buttons Right" template)?
| In Designer, select the OK or Cancel button. Then open the property editor and scroll down to the QDialogButtonBox section. You can then expand the standardButtons item to see the various buttons that are available. Other properties, such as the centerButtons property, are also available.
However, designer gives you very little control over the button box.
In code, you can do many other things, such as change the text that appears on the "standard buttons." From the documentation:
findButton = new QPushButton(tr("&Find"));
findButton->setDefault(true);
moreButton = new QPushButton(tr("&More"));
moreButton->setCheckable(true);
moreButton->setAutoDefault(false);
buttonBox = new QDialogButtonBox(Qt::Vertical);
buttonBox->addButton(findButton, QDialogButtonBox::ActionRole);
buttonBox->addButton(moreButton, QDialogButtonBox::ActionRole);
As long as you give the button box a name in designer, you can set these properties in code.
|
2,671,380 | 2,671,461 | how to cast c++ smart pointer up and down | two clients communicate to each other on top of a message layer
in the message body, I need include a field pointing to any data type
From client A, I send the field as a shared_ptr<TYPEA> to the message layer.
I define this field as a shared_ptr<void> in the message layer.
But how can I convert this field back to shared_ptr<TYPEA> in client B?
Or should I define shared_ptr<void> in message layer as something else?
Thanks
| If you're using boost::shared_ptr then you can use the various XXX_ptr_cast<>() functions (static_ptr_cast, dynamic_ptr_cast...).
If you're using the MSVC 2010 version I haven't been able to find an implementation of these functions. They may not be part of the standard.
|
2,671,448 | 2,671,472 | Access specifier while overriding methods | Assume you have a class that defines virtual methods with the access specifier public.
Can you change the access specifier on your overriden methods?
I am assuming no.
Looking for an explanation.
| Yes you can, but it "doesn't grok".
Take a look at Overriding public virtual functions with private functions in C++
|
2,671,460 | 2,671,483 | How does make_pair know the types of its args? | The definition for make_pair in the MSVC++ "utility" header is:
template<class _Ty1,
class _Ty2> inline
pair<_Ty1, _Ty2> make_pair(_Ty1 _Val1, _Ty2 _Val2)
{ // return pair composed from arguments
return (pair<_Ty1, _Ty2>(_Val1, _Val2));
}
I use make_pair all the time though without putting the argument types in angle brackets:
map<string,int> theMap ;
theMap.insert( make_pair( "string", 5 ) ) ;
Shouldn't I have to tell make_pair that the first argument is std::string and not char* ?
How does it know?
| Function template calls can usually avoid explicit template arguments (ie make_pair<…>) by argument deduction, which is defined by C++03 §14.8.2. Excerpt:
When a function template
specialization is referenced, all of
the template arguments must have
values. The values can be either
explicitly specified or, in some
cases, deduced from the use.
The specific rules are a bit complicated, but typically it "just works" as long as you have only one specialization which is generally qualified enough.
Your example uses two steps of deduction and one implicit conversion.
make_pair returns a pair<char const*, int>,
then template<class U, classV> pair<string,int>::pair( pair<U,V> const & ) kicks in with U = char*, V = int and performs member-wise initialization,
invoking string::string(char*).
|
2,671,498 | 2,688,227 | nslookup for C# and C++ to resolve a host using a specific Server | I need to resolve a hostname using a specific DNS server like you would in nslookup
C:\>nslookup hotname 192.100.10.10
Server: UnKnown
Address: 192.100.10.10
Name: hostname.host
Address: 192.100.10.14
But of course in return I don't just want the address I want all the values for Server, Address, Name and Address
I have looked at the System.Net.Dns Class but that only gives me the Resolved IP Address and doesn't let me select the DNS Server of my choosing
If any one has done this before and you can help me with this.
Edit:
Found One for C# : http://www.simpledns.com/dns-client-lib.aspx
Here is a snippet of my code just for some entertainment
//Buy him Cookies and Strippers
using JHSoftware;
| I still dont have an answer for C++ but here is the one for C#
var Options = new JHSoftware.DnsClient.RequestOptions();
Options.DnsServers = new System.Net.IPAddress[] {
System.Net.IPAddress.Parse("1.1.1.1"),
System.Net.IPAddress.Parse("2.2.2.2") };
var IPs = JHSoftware.DnsClient.LookupHost("www.simpledns.com",
JHSoftware.DnsClient.IPVersion.IPv4,
Options);
foreach(var IP in IPs)
{
Console.WriteLine(IP.ToString());
}
The above is using JHSoftware.dll and the code is copied from there to help others, the link is as below:
http://www.simpledns.com/dns-client-lib.aspx
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.