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 rece... | 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 ... |
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 st... | 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:... |
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,
destroye... | 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*si... |
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 comp... | 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 v... | 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&)'
coll... | 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 ... |
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... | 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 ta... |
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... |
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 ot... | 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 acceptab... |
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 f... | 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); ... |
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, ... |
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... | 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 cod... |
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 o... | 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.... |
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 wi... | 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'... | 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 functi... |
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... | 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... |
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 res... | 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"
... | 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 nev... |
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... | 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... | 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 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 th... |
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 w... | 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() {
... | 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, whi... | 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 i... |
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;... |
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 doe... |
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':
... | 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.setAct... |
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... | (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 b... |
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.dwMajorVer... | 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!... |
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*, i... | 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 n... |
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 mi... | 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[] =... | 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
... |
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, Everyo... | 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... | 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 b... |
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 ... |
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, ... |
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:... | 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... |
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... | 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. ... |
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 pos... | 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 lin... |
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... | 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 cra... | 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... |
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));
} ;
... | 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;
... |
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 th... | 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 &... | 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 ... | 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 ... |
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... | 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 th... |
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 (re... | 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 w... |
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.... |
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 ... | 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 ... |
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 ... |
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/bette... | 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 abstra... |
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... |
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 expre... | 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 t... | 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... |
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\micr... |
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 T... |
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 stud... | 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, siz... | 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... |
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 rig... | 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] +
//...
!... |
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 ha... | 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-En... |
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 wit... | 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 bef... |
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(m... | 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_iterato... |
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 ... |
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 ... | 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.... |
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 pe... | 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 i... |
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_fu... | 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 ra... |
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
... | 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 ... |
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].g... | 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 yours... |
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,
ba... | 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 dec... | 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 dynam... | 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 them... |
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. ... | 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 tha... |
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::i... | 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. ... | 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 initi... |
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:
"myT... | 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 ... |
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 t... | 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 li... |
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 servi... | 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 consta... | 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... |
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':
te... | 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 s... |
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 gai... | 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... |
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... |
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 shar... | 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 ... | 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 ... |
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 Addre... | 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.