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,468,811 | 2,468,961 | Load NSImage into QPixmap or QImage | I have an NSImage pointer from a platform SDK, and I need to load it into Qt's QImage class. To make things easier, I can create a QImage from a CGImageRef by using QPixmap as an intermediate format, like this:
CGImageRef myImage = // ... get a CGImageRef somehow.
QImage img = QPixmap::fromMacCGImageRef(myImage).toImag... | NSImage is a high level image wrapper that might contain more than one image (thumbnails, different resolutions, vector representations, ...) and does a lot of caching magic. A CGImage on the other hand is one plain bitmap image. Since NSImage is a so much richer object, there’s no easy way of converting in between the... |
2,468,853 | 2,468,913 | Freeing memory twice | In C and C++, Freeing a NULL pointer will result in nothing done.
Still, I see people saying that memory corruption can occur if you "free memory twice".
Is this true? What is going on under the hood when you free memory twice?
| int *p = malloc(sizeof(int));
//value of p is now lets say 0x12345678
*p = 2;
free(p); //memory pointer is freed, but still value of p is 0x12345678
//now, if you free again, you get a crash or undefined behavior.
So, after free ing the first time, you should do p = NULL , so if (by any chance), free(p) is c... |
2,468,857 | 2,468,871 | Are +=, |=, &= etc atomic? | Are the "modify" operators like +=, |=, &= etc atomic?
I know ++ is atomic (if you perform x++; in two different threads "simultaneously", you will always end up with x increased by 2, as opposed to x=x+1 with optimization switched off.)
What I wonder is whether variable |= constant, and the likes are thread-safe or do... | You are wrong. There is no guarantee that ++ is atomic and neither is there for the compound assignment operators, or indeed for any C++ operation.
|
2,469,015 | 2,469,021 | Copying pointers in C++ | I have a class A containing two pointers to objects of another class B. I want to initialize one pointer or the other depending on which one is passed to init(), which also takes other parameters. My situation is thus the following:
class A {
public:
A();
init(int parameter, int otherParameter, B* toBeInitiali... | Yes, change to
void init( int parameter, int otherParameter, B*& toBeInitialized ) {
toBeInitialized = someConstructorFunction(parameter, otherParameter);
}
In your original code toBeInitialized is passed by value and only the local copy of the variable will be modified.
|
2,469,160 | 2,469,217 | comparison between string literal | This very simple code:
#include <iostream>
using namespace std;
void exec(char* option)
{
cout << "option is " << option << endl;
if (option == "foo")
cout << "option foo";
else if (option == "bar")
cout << "opzion bar";
else
cout << "???";
cout << endl;
}
int main()
{
... | char arrays or char pointers aren't really the same thing as string class objects in C++, so this
if (option == "foo")
Doesn't compare the string option to the string literal "foo" it compares the address of option with the address of the string literal "foo". You need to use one of the many string comparison functio... |
2,469,303 | 2,469,338 | How should platform specific lib files be named? | I'm working on a C++ project that produces a lib that other teams use. It's being produced in a few different flavours:
Win32 Debug Dynamic
Win32 Debug Static
Win32 Release Dynamic
Win32 Release Static
x64 Debug Dynamic
x64 Debug Static
x64 Release Dynamic
x64 Release Static
I'm wondering what the best wisdom is on h... | I output all the different flavours into the same directory, using a naming convention to disambiguate. By having them in the same directory, the linker directories don't have to change between flavour. The libraries then get linked using a set preprocessor directives that select the #pragma (lib,...) directive for the... |
2,469,393 | 2,469,951 | Problem with FtpFindFirstFile | I want to download all file from ftp directory i want use for that FtpFindFirstFile and FtpGetFile;
LPWIN32_FIND_DATA FileData;
TCHAR* APP_NAME = TEXT("ftpcli");
TCHAR* PATH_FTP = TEXT("ftp://127.0.01");
TCHAR* ADR_FTP = TEXT("127.0.0.1");
TCHAR* LC_FILE = TEXT("C:\\!");
TCHAR* PATH_FILE = TEXT("/Soft/DVD_Players/Win... | You've declared a pointer to WIN32_FIND_DATA, you need a concrete instance of that structure. Fix:
WIN32_FIND_DATA FileData; // NOTE: not LP
|
2,469,531 | 2,469,697 | Reading and writing C++ vector to a file | For some graphics work I need to read in a large amount of data as quickly as possible and would ideally like to directly read and write the data structures to disk. Basically I have a load of 3d models in various file formats which take too long to load so I want to write them out in their "prepared" format as a cache... | As Laurynas says, std::vector is guaranteed to be contiguous, so that should work, but it is potentially non-portable.
On most systems, sizeof(Vertex) will be 12, but it's not uncommon for the struct to be padded, so that sizeof(Vertex) == 16. If you were to write the data on one system and then read that file in on an... |
2,469,858 | 2,469,930 | How to access C arrays from assembler for Windows x64? | I've written an assembler function to speed up a few things for image processing (images are created with CreateDIBSection).
For Win32 the assembler code works without problems, but for Win64 I get a crash as soon as I try to access my array data.
I put the relevant info in a struct and my assembler function gets a poi... | Quite probably, the pData field is at [rbx + 8], not [rbx + 4]. The compiler inserts some extra space ("padding") between ulParam1 and pData so that pData is 8-byte aligned (which makes accesses faster).
|
2,469,861 | 2,477,451 | Parsing string, with Boost Spirit 2, to fill data in user defined struct | I'm using Boost.Spirit which was distributed with Boost-1.42.0 with VS2005. My problem is like this.
I've this string which was delimted with commas. The first 3 fields of it are strings and rest are numbers. like this.
String1,String2,String3,12.0,12.1,13.0,13.1,12.4
My rule is like this
qi::rule<string::iterator, qi... | qi::skip_type is not something you could use a skipper. qi::skip_type is the type of the placeholder qi::skip, which is applicable for the skip[] directive only (to enable skipping inside a lexeme[] or to change skipper in use) and which is not a parser component matching any input on its own. You need to specify your ... |
2,469,931 | 2,469,967 | How to check if a pointer is null in C++ Visual 2010 | I am having problems here if I want to check if eerste points to nothing I get
Blockquote
Unhandled exception at 0x003921c6 in
Bank.exe: 0xC0000005: Access violation
reading location 0xccccccd0.
and I am kinda wondering why he justs skips the if statement or doens't stop when the object eerste points to nothing
... | I think you have to change
Bank::Bank()
{
eerste = NULL;
laatste = NULL;
}
because they are probably declared in your class as member variables and you're declaring them as local variables.
As Fred Larson proposed, you can also use initialization lists.
Bank::Bank() : eerste(NULL), laatste(NULL)
{
//whatev... |
2,470,255 | 2,470,834 | C++ - Difference between (*). and ->? | Is there any difference in performance - or otherwise - between:
ptr->a();
and
(*ptr).a();
?
| Since you are asking for it in the comments. What you are probably looking for can be found in the Standard (5.2.5 Class member access):
3 If E1 has the type “pointer to class
X,” then the expression E1->E2 is
converted to the equivalent form
(*(E1)).E2;
The compiler will produce the exact same instructions ... |
2,470,286 | 2,471,067 | PHP's preg_match() equivalent in C++? | My question is simple.
Is there a PHP's preg_match() function equivalent in the C++ STL?
If not, can you tell me an alternative?
Thanks.
| preg_match() calls code from libPCRE. If you want the equivalent of preg_match(), then you must use that library.
Alternatively, if you just need the feature of regular expression matching (PCRE or not), there is also the Boost::regex library mentioned in another answer.
If your compiler supports the new versions of th... |
2,470,487 | 2,472,299 | Call c++ function pointer from c# | Is it possible to call a c(++) static function pointer (not a delegate) like this
typedef int (*MyCppFunc)(void* SomeObject);
from c#?
void CallFromCSharp(MyCppFunc funcptr, IntPtr param)
{
funcptr(param);
}
I need to be able to callback from c# into some old c++ classes. C++ is managed, but the classes are not ref... | dtb is right. Here a more detailed example for Marshal.GetDelegateForFunctionPointer. It should work for you.
In C++:
static int __stdcall SomeFunction(void* someObject, void* someParam)
{
CSomeClass* o = (CSomeClass*)someObject;
return o->MemberFunction(someParam);
}
int main()
{
CSomeClass o;
void* p = 0;
... |
2,470,539 | 2,470,578 | c++ simple conditional logging | Disclaimer: I'm not a c++ developer, I can only do basic things. (I understand pointers, just my knowledge is so rusty, I haven't touch c/c++ for about 20 years :) )
The setup: I have an Outlook addin, written in C#/.Net 1.1. It uses a c++ shim to load.
Usually, this works pretty well, and I use in my c# code nlog for ... | The loading of the logging dll's seams like a complicated way of handling the configuration issue. Why not use the registry. If you use conditional loading on dlls you will be using LoadLibrary and GetProceAddress and as you said your not really a c++ coder so why introduce the complexity. Also there have to be n+1 ... |
2,470,737 | 2,470,840 | Why can't initialize the static member in a class in the body or in the header file? | Could any body offer me any reason about that?
If we do it like that, what's the outcome? Compile error?
| The problem is that static initialization isnt just initialization, it is also definition. Take for example:
hacks.h :
class Foo
{
public:
static std::string bar_;
};
std::string Foo::bar_ = "Hello";
std::string GimmeFoo();
main.cpp :
#include <string>
#include <sstream>
#include <iostream>
#include "hacks.h"
... |
2,471,001 | 2,471,076 | LNK2001 error in code | I am getting LNK2001 error. The code has been included below. Can someone please help me out?
Error 3 error LNK2001: unresolved external symbol "private: static class std::vector<struct _UpdateAction,class std::allocator<struct _UpdateAction> > InstrumentCache::actionTaken" (?actionTaken@InstrumentCache@@0V?$vect... | It seems that you are missing the definition of actionTaken (the declaration in the class is not enough). Does adding
ActionTakenVector InstrumentCache::actionTaken;
in PerformanceTest.cpp help?
|
2,471,249 | 2,471,424 | Linux network programming. What can I start with? | I've recently got interested in Linux network programming and read quite a bit (Beej's Guide to Network Programming). But now I'm confused. I would like to write something to have some practice, but I don't know what exactly. Could please recommend me a couple of projects to start with?
Thanks.
| I'm not sure how in-depth you want to start your Linux Network Programming career, but if you want to just get started with dealing with sockets, probably the easiest examples are a Producer/Consumer pairing or an Echo Server. Another good source would be looking at some of the examples/assignments from any number of ... |
2,471,251 | 2,471,402 | Visual Studio C++ multi-project solution | I have created an C++ solution in VS2008. The first project contains the model. The second projects is the view. The problem is that i don't get make references to my model classes defined in the first project. The message error is :
Error 1 fatal error C1083: Cannot open include file: 'utils/GeradorSistematicoDeA... | First of all I find this approach for the MVC pattern quite strange. But if you really want to do it like that you have to link the resulting DLL/LIB from your model project to your view project (go to the project properties, then Configuration Properties/Linker/Input/Additional Dependencies; you may need to set the ri... |
2,471,339 | 2,475,757 | Generic calls to OnResetDevice() and OnLostDevice() | This is kind of a COM question to do with DirectX.
So, both ID3DXSprite and ID3DXFont and a bunch of the other ID3DX* objects require you to call OnLostDevice() when the d3d device is lost AND OnResetDevice() when the device is reset.
What I want to do is maintain an array of all ID3DX* objects and simply call OnResetD... | There isn't a common base class, sorry.
You could use multiple inheritance and templates to sort of achive what you want. Something like this (untested but hopefully you'll get the idea)...
#include <d3dx9.h>
#include <vector>
using namespace std;
class DeviceLostInterface
{
public:
virtual void onLost() = 0;
... |
2,471,430 | 2,471,550 | How to set maximum read length for a stream in C++? | I'm reading data from a stream into a char array of a given length, and I'd like to make the maximum width of read to be large enough to fit in that char array.
The reason I use a char array is that part of my specification is that the length of any individual token cannot exceed a certain value, so I'm saving myself ... | char x[4];
cin.width(4);
cin >> x;
cout << x;
Input: "abcdef"
Output: "abc"
(x[3] is null terminating char)
Width works fine in this case.
Note: Empirical testing indicates that the cin.width call only lasts for one stream operation. It may be more convenient to use cin >> setw(4) >> x; instead, though this requires ... |
2,471,529 | 2,471,563 | How to implement generic callbacks in C++ | Forgive my ignorance in asking this basic question but I've become so used to using Python where this sort of thing is trivial that I've completely forgotten how I would attempt this in C++.
I want to be able to pass a callback to a function that performs a slow process in the background, and have it called later when ... | The callback should be stored as a boost::function<void, std::string>. Then you can use boost::bind to "convert" any other function signature to such an object, by binding the other parameters.
Example
I've not tried to compile this, but it should show the general idea anyways
void DoLongOperation(boost::function<void,... |
2,471,591 | 2,481,740 | How can I detect message boxes popping up in another process? | I'd like to execute some code whenever a (any!) message box (as spawned by the MessageBox Function) is shown in another process. I didn't start the process I'm monitoring.
I can think of three approaches:
Install a global CBT Hook procedure which tells me whenever a window is created on the desktop. Then, check whethe... | I can't think of any efficient solution that doesn't involve injecting code into the other process (this is basically what many types of hooks do by the way). But if you are willing to go down that path, you can intercept calls to MessageBox.
Spend some time stepping through into a call to MessageBox in the debugger ... |
2,471,892 | 2,472,442 | Setting custom header values in an IIS ISAPI filter | I have an ISAPI filter that I am using to do URL rewriting for my CMS. I am processing SF_NOTIFY_PREPROC_HEADERS notifications, and trying to do this:
DWORD ProcessHeader(HTTP_FILTER_CONTEXT *con, HTTP_FILTER_PREPROC_HEADERS *head)
{
head->SetHeader(con, "test1", "aaa");
con->AddResponseHeaders(con, "test2:bbb\... | I finally figured it out, I was missing a ':' in the header name:
DWORD ProcessHeader(HTTP_FILTER_CONTEXT *con, HTTP_FILTER_PREPROC_HEADERS *head)
{
head->SetHeader(con, "test1:", "aaa");
return SF_STATUS_REQ_NEXT_NOTIFICATION;
}
This now creates a server variable called "HTTP_TEST1".
|
2,472,568 | 2,472,974 | Visual C++ 9.0 (2008) Static Lib + Boost Library = Large .lib File | I have a Visual Studio 2008 C++ project that outputs a static library and uses some functionality of the Boost Library. When I build the project in Debug configuration, the .lib file is 7.84 MB. When I build the project in Release configuration, the .lib file is 23.5 MB. !!!!
The only Boost headers I include are:
b... | Project + Properties, C/C++, Optimization, Whole Program Optimization = No. That at least ought to keep your Release build size from blowing up. I can't repro the debug library size, just the headers gives me a 111KB .lib.
|
2,472,601 | 2,472,725 | Numerical precision of double type in Visual C++ 2008 Express debugger | I'm using Visual C++ 2008 Express Edition and when i debug code:
double x = 0.2;
I see in debugging tooltip on x 0.20000000000000001
but:
typedef numeric_limits< double > double_limit;
int a = double_limit::digits10
gives me: a = 15
Why results in debugger are longer than normal c++ precision?
What is this strange p... | What you are seeing is caused by the fact that real numbers (read floating-point) cannot be expressed with perfect precision and accuracy in binary computers. This is a fact of life. Instead, computers approximate the value and store it in memory in a defined format.
In the case of most modern machines (including any... |
2,472,773 | 2,476,965 | Instruction for installing an environment with Qt and Qt integration with Visual Studio 2008 | I want to use Qt lib but I don't know how to install Visual Studio 2008+Qt+Qtintegration. I have read some forums, that step by step tell what to download, where to download from, and then what to do. But that was for old versions of mentiond products.
I ask to Qt developers tell me the way to install these items on Wi... | To get QT working with dev studio you need to install two things.
First, a copy of the QT Visual Studio Libraries.
And the QT Visual Studio Addin.
http://qt.nokia.com/downloads/windows-cpp-vs2008
http://qt.nokia.com/downloads/visual-studio-add-in
Download the QT sdk, and install it. It usually installs into a folder... |
2,472,868 | 2,472,902 | I just learned about C++ functions; can I use if statements on function return values? | What I am confused on is about the isNumPalindrome() function. It returns a boolean value of either true or false. How am I suppose to use that so I can display if it's a palindrome or not. For ex. if (isNumPalindrome == true) cout << "Your number is a palindrome"; else cout << "your number is not a palindrome.";
#inc... | The return value for a function can be used just like a variable of the same type.
Your main program should look something like this:
int main()
{
int num=askNumber();
bool isPal=isNumPalindrome(num);
if (isPal)
{
//do something
}
else
{
//do something else
}
return 0;
}
or you could be even... |
2,472,924 | 2,473,242 | Linking to MSVC DLL from MinGW | I'm trying to link the LizardTech GeoExpress DSDK into my own application. I use gcc so that we can compile on for platforms. On Linux and Mac this works easily: they provide a static library (libltidsdk.a) and headers and all that we have to do is use them.
Compiling for windows isn't so easy. They've built the lib... | You can't do this. They have exported C++ classes from their dll, rather than C-functions. The difference is, c++ functions are always exported with names in a mangled form that is specific to a particular version of the compiler.
Their dll is usable by msvc only in that form, and will probably not even work between di... |
2,472,944 | 2,472,968 | Good C++ array class for dealing with large arrays of data in a fast and memory efficient way? | Following on from a previous question relating to heap usage restrictions, I'm looking for a good standard C++ class for dealing with big arrays of data in a way that is both memory efficient and speed efficient. I had been allocating the array using a single malloc/HealAlloc but after multiple trys using various call... | Have you tried using an std::deque? Unlike a std::vector, which uses one huge heap allocation, deque usually allocates in small chunks, but still provides amortised constant time indexing via operator[].
|
2,473,087 | 2,473,143 | I want to extend std::string, but not for the reason you might think | I have a method that effectively takes a string. However, there is a very limited subset of strings I want to use. I was thinking of typedef'ing std::string as some class, and call the functions explicit. I'm not sure that would work, however. Ideas?
| The usual rule still applies: the class isn't designed to be inherited from, and its destructor isn't virtual, so if you ever upcast to the std::string base class, and let the object be destroyed, your derived class' destructor won't be called.
If you can guarantee that this will never happen, go ahead.
Otherwise, you ... |
2,473,300 | 2,473,395 | Overloading the QDataStream << and >> operators for a user-defined type | I have a an object I'd like to be able to read and write to/from a QDataStream. The header is as follows:
class Compound
{
public:
Compound(QString, QPixmap*, Ui::MainWindow*);
void saveCurrentInfo();
void restoreSavedInfo(QGraphicsScene*);
void setImage(QPixmap*);
QString getName();
private:
... | I think you've answered your own question! The stream operator
QDataStream& operator<<( QDataStream&, const Compound& )
will work fine. In the implementation you just use the existing stream operators on QDataStream to serialise the individual bits of your Compound. Some Qt classes define non-member QDataStream operat... |
2,473,538 | 2,473,606 | C++ Macro Arithmetric | I have to do with Macros (it's macros calling macros; so templates are out of the question).
Here's what I want:
foo(3, a, b1, c1) --> foo1(a, b1, c1);
foo(5, a, b1, c1, b2, c2) -> foo2(a, b1, c1, b2, c2);
foo(7, a, b1, c1, b2, c2, b3, c3) -> foo3(a, b1, c1, b2, c2, b3, c3);
So basically, what I want is to be able to ... | I haven't tested this, but should work:
#define SUBSTFOO3( a, b1, c1 ) foo1(a, b1, c1)
#define SUBSTFOO5( a, b1, c1, b2, c2 ) foo2(a, b1, c1, b2, c2)
/* ad nauseam */
#define foo( N, ... ) SUBSTFOO ## N ( __VA_ARGS__ )
This might also work:
#define SUBSTFOO3 foo1 /* no arguments needed */
#define SUBSTFOO5 foo2 /* "(... |
2,473,628 | 2,473,648 | C++: can't static_cast from double* to int* | When I try to use a static_cast to cast a double* to an int*, I get the following error:
invalid static_cast from type ‘double*’ to type ‘int*’
Here is the code:
#include <iostream>
int main()
{
double* p = new double(2);
int* r;
r=static_cast<int*>(p);
std::cout << *r << std::endl;
}... | Aside from being pointers, double* and int* have nothing in common. You could say the same thing for Foo* and Bar* pointer types to any dissimilar structures.
static_cast means that a pointer of the source type can be used as a pointer of the destination type, which requires a subtype relationship.
|
2,473,665 | 2,473,722 | window c++ : how to timeout receiveFrom function in a udp based conversation | I am trying to create a reliable service on top of UDP.
Here i need to timeout receiveFrom function of window c++ if not packet arrives
in specified time.
In java i do this DatagramSocket.setSoTimeout but i dont know how to achieve this in windows c++.
thanks
| Take a look at setsockopt() specifically SO_RCVTIMEO.
|
2,473,799 | 2,473,857 | GDI+ double buffering in C++ | I haven't written anything with GDI for a while now (and never with GDI+), and I'm just working on a fun project, but for the life of me, I can't figure out how to double buffer GDI+
void DrawStuff(HWND hWnd) {
HDC hdc;
HDC hdcBuffer;
PAINTSTRUCT ps;
hdc = BeginPaint(hWnd, &ps);
h... | CreateCompatibleDC(hdc) creates a DC with a 1x1 pixel monochrome bitmap as its drawing surface. You need to also CreateCompatibleBitmap and select that bitmap into the hdcBuffer if you want a drawing surface larger than that.
Edit:
the flickering is being caused by WM_ERASEBKGND, when you do this
hdc = BeginPaint(hWnd,... |
2,474,006 | 2,474,013 | new[n] and delete every location with delete instead the whole chunk with delete[] | Is this valid C++ (e.g. not invoking UB) and does it achieve what I want without leaking memory? valgrinds complains about mismatching free and delete but says "no leaks are possible" in the end.
int main() {
int* a = new int[5];
for(int i = 0; i < 5; ++i)
a[i] = i;
for(int i = 0; i < 5; ++i)
delete &a[... | No way. You cannot call delete on what was not allocated by new or you get heap corruption.
You see, that array created by new[] didn't allocate n individual objects, but one array. The second object of the array is in the middle of the allocation block.
|
2,474,018 | 2,474,021 | When does invoking a member function on a null instance result in undefined behavior? | Consider the following code:
#include <iostream>
struct foo
{
// (a):
void bar() { std::cout << "gman was here" << std::endl; }
// (b):
void baz() { x = 5; }
int x;
};
int main()
{
foo* f = 0;
f->bar(); // (a)
f->baz(); // (b)
}
We expect (b) to crash, because there is no correspon... | Both (a) and (b) result in undefined behavior. It's always undefined behavior to call a member function through a null pointer. If the function is static, it's technically undefined as well, but there's some dispute.
The first thing to understand is why it's undefined behavior to dereference a null pointer. In C++03, ... |
2,474,091 | 2,474,113 | Why can I set an anonymous enum equal to another in C but not C++? | I have the following code snippet:
enum { one } x;
enum { two } y;
x = y;
That will compile in C, but in C++, I get the following error:
test.c:6: error: cannot convert ‘main()::<anonymous enum>’ to ‘main()::<anonymous enum>’ in assignment
Can someone explain to me why this is happening? I would prefer an answer with... | Converting from one enum type to another goes via an integer type (probably the underlying type of the source, not sure).
An implicit conversion from enum to an integer type is allowed in both C and C++. An implicit conversion from an integer type to enum is allowed in C, but not in C++.
Basically, C++ is being more ty... |
2,474,121 | 2,474,142 | Is it possible to use the .NET version of TeeChart with C++? | TeeChart .NET is a 100% managed C#.NET Charting Control. Would it still be possible to use the .NET version of the charting control with Visual C++?
I'm contemplating changing IDEs from Codegear to Visual Studio, so the legacy C++ code is obviously not C++/CLI
| Visual C++/CLI ?
Create a DLL on VC++/CLI and link dynamically with your main VC++/non-CLI project
|
2,474,190 | 2,474,264 | C++ find method is not const? | I've written a method that I'd like to declare as const, but the compiler complains. I traced through and found that this part of the method was causing the difficulty:
bool ClassA::MethodA(int x)
{
bool y = false;
if(find(myList.begin(), myList.end(), x) != myList.end())
{
y = true;
}
retur... | If myList is an object of a custom container type, you could have a problem if its begin() and end() methods don't have a const overload. Also, assuming perhaps the type of x isn't really int in your code, are you sure there's an equality operator that can operate on a const member of that type?
|
2,474,282 | 2,474,299 | C++ a class with an array of structs, without knowing how large an array I need | I have a class with fields like firstname, age, school etc. I need to be able to store other information like for instance, where they have travelled, and what year it was in. I cannot declare another class specifically to hold travelDestination and what year, so I think a struct might be best. This is just an example:... | You could try associating a std::vector with each person, with each entry in the vector containing a struct:
typedef struct travel {
string travelDest;
string year;
} travelRecord;
std::vector<travelRecord> travelInfo;
You can then add items to the vector as you see fit:
travelRecord newRecord1 = {"Jamaica", ... |
2,474,384 | 2,474,403 | C++ typename of member variable | Is it possible to get typename of a member variable? For example:
struct C { int value ; };
typedef typeof(C::value) type; // something like that?
Thanks
| Not in C++03. C++0x introduces decltype:
typedef decltype(C::value) type;
Some compilers have a typeof extension, though:
typedef typeof(C::value) type; // gcc
If you're okay with Boost, they have a library for it:
typedef BOOST_TYPEOF(C::value) type;
|
2,474,429 | 2,474,436 | Does throw inside a catch ellipsis (...) rethrow the original error in C++? | If in my code I have the following snippet:
try {
doSomething();
} catch (...) {
doSomethingElse();
throw;
}
Will the throw rethrow the specific exception caught by the default ellipsis handler?
| Yes. The exception is active until it's caught, where it becomes inactive. But it lives until the scope of the handler ends. From the standard, emphasis mine:
§15.1/4: The memory for the temporary copy of the exception being thrown is allocated in an unspecified way, except as noted in 3.7.4.1. The temporary persists ... |
2,474,432 | 2,474,558 | System of linear equations in C++? | I need to solve a system of linear equations in my program. Is there a simple linear algebra library for C++, preferably comprised of no more than a few headers? I've been looking for nearly an hour, and all the ones I found require messing around with Linux, compiling DLLs in MinGW, etc. etc. etc. (I'm using Visual St... | I think Eigen is what you're looking for.
http://eigen.tuxfamily.org/index.php?title=Main_Page
It is a headers only library and compiles on many compilers. It even uses exotic assembly for faster math.
This is the page that shows off the linear solver api.
http://eigen.tuxfamily.org/dox-2.0/TutorialAdvancedLinearAlgeb... |
2,474,434 | 2,474,452 | What are the main benefits of implementing a virtual machine as part of an application? | Several databases I've been looking at recently implement a virtual machine internally to perform the respective data reads and writes. For an example, check out this article on SQLite's virtual machine they call the 'VDBE'. I'm curious as to what the benefits of such an architecture are. I would assume performance is ... | They do their stuff at the "assembly-like" level, where you gain acceptable speed without losing portability. I think they provide a virtual machine so they get a balanced trade off. Either you execute the high level code(SQL code**) as a high level language and you lose speed but you gain convenience. The other way is... |
2,474,548 | 2,474,631 | Why does my finite state machine take so long to execute? | I'm working on a state machine which is supposed to extract function calls of the form
/* I am a comment */
//I am a comment
pref("this.is.a.string.which\"can have QUOTES\"", 123456);
where the extracted data would be pref("this.is.a.string.which\"can have QUOTES\"", 123456);
from a file. Currently, to process a 41kb ... | Unless your 41 kb file is mostly comments or prefs, it's going to spend most of its time in state 0. And for each character in state 0, you make a minimum of two function calls.
if (boost::starts_with(boost::make_iterator_range(begin, end), "pref(")) {
You can speed this up by pre-testing to see if the current chara... |
2,474,608 | 2,474,649 | Asynchronous Completion Routines I/O, Pointer to routine encapsulated in class | I was wondering if there was anyway to use functions like ReadFileEx that require a pointer to a function in a class WITHOUT marking the function as static? Thanks in advance. SBP.
| No, non-static class functions have an implied first argument (this) which is incompatible with their use as a callback for ReadFileEx etc.
|
2,474,756 | 2,474,770 | Is It Safe to Cast Away volatile? | Most of the time, I am doing this way.
class a {
public:
~ a() {
i = 100; // OK
delete (int *)j; // Compiler happy. But, is it safe?
// The following code will lead compilation error : delete j;
}
private:
volatile int i;
volatile int *j;
};
int main... | Nothing. If you don't access the volatile memory, the semantics of volatile are unaffected. If you accessed volatile memory through a casted non-volatile pointer, the compiler might optimize the reference away. If the value had changed, you'd have the wrong value. For some value of wrong. ;-)
The delete doesn't access ... |
2,474,994 | 2,475,219 | C++ in embedded software programming | Is there significant problem, if I write the code for embedded linux system using C++ language programming ?.
Actually, I have intention to port some code to arm linux, with arm-uclibc compiler.
Thanks
| Are you asking about plain C++ or embedded C++? As I understand it, embedded C++ is pretty much dead. You can program in C++, but, depending on your requirements, there may be some constructs that you will want to avoid using. For example, if you don't have much space, you may want to avoid templates as much as possibl... |
2,475,138 | 2,475,621 | right usage of std::uncaught_exception in a destructor | There are some articles concluding "never throw an exception from a destructor", and "std::uncaught_exception() is not useful", for example:
http://www.gotw.ca/gotw/047.htm (written by Herb Sutter)
But it seems that I am not getting the point. So I wrote a small testing example (see below).
Since everything is fine w... | There's nothing technically wrong with your code. It's perfectly safe in that you will never accidentally terminate because you threw an exception when it was not safe to. The issue is that it also is not useful, in that it will occasionally also not throw an exception when it is safe to. Your destructor's documenta... |
2,475,614 | 2,477,203 | VC++ libcurl .lib size | I'm having an issue with the size of the .lib when I compile libcurl. It's 1.6 MB and the sample program they have is alround 300 KB.
I downloaded the latest version (curl-7.20.0) and opened the project file from the lib directory in visual studio 2008. In the project properties I set /MT and compiled a release build.... | Turn off Whole Program Optimization to keep the size reasonable. Project + Properties, C/C++, Optimization.
|
2,475,642 | 2,475,677 | How to achieve the following C++ output formatting? | I wish to print out double as the following rules :
1) No scietific notation
2) Maximum decimal point is 3
3) No trailing 0.
For example :
0.01 formated to "0.01"
2.123411 formatted to "2.123"
2.11 formatted to "2.11"
2.1 formatted to "2.1"
0 formatted to "0"
By using .precision(3)... | You cannot do this with the iostream library's built-in formatting.
Additionally, you don't need to apply fixed on every output because it is not reset.
You can write your own manipulator to do it:
struct MyFormatter {
int precision;
double value;
MyFormatter(int precision, double value) : precision(precision), v... |
2,475,657 | 2,475,688 | Overloaded function called with one parameter, but I thought I'd passed two | I recently refactored code like this (MyClass to MyClassR).
#include <iostream>
class SomeMember
{
public:
double m_value;
SomeMember() : m_value(0) {}
SomeMember(int a) : m_value(a) {}
SomeMember(int a, int b)
: m_value(static_cast<double>(a) / 3.14159 +
static_cast<double>(b) / 2.71828)
{}
}... | I’m not sure what exactly you expect but let’s start …
First off, ditch VC6. Seriously. Using it is a huge problem since it’s just not standards conforming and precludes a lot of options. Using it correctly is like playing Russian roulette.
Your constructor of m_third doesn’t do what you think it does. You cannot writ... |
2,475,686 | 2,475,724 | Accessing program information that gdb sees in C++ | I have a program written in C++, on Linux, compiled with -g.
When I run it under gdb, I can
1) set breakpoints
2) at those breakpoints, print out variables
3) see the stackframe
4) given a variable that's a structure, print out parts of the structure (i.e. how ddd displays information).
Now, given that my program is c... | The debugging format is called dwarf. This should give you hint where to search further.
Library to read ELF file DWARF debug information
|
2,475,794 | 2,476,875 | Symbol exporting problem using __declspec(dllexport) | I use __declspec(dllexport) with several methods in a library. But one of the symbols do not get exported properly. The value in question is called "restart". I've given the output from dumpbin.exe, below:
1 0 0002DB27 ev_err = @ILT+2850(_ev_err)
2 1 0002DADC m_foutput = @ILT+2775(_m_foutput)
... | It is because your "restart" identifier is data, not code. It probably should have been named "restart_state". Exporting data from a DLL is a supported scenario but a good way to blow your foot off. The client code has to have strict binary compatibility with the DLL code. That's a very questionable proposition for... |
2,475,818 | 2,476,176 | How to generate boost uuid from string at compile time | is there a way to generate a boost uuid from a string like 988A00C4-79F3-46f9-98CD-D5AD4AA2A0FE at compile time?
| No, because there is no processing of string literals at compile time in C++.
Depending on what you need and where you get the string from, you could use a pre-build-step that directly puts it into some aggregate initializer form or something that you can process at compile time (i.e. compile-time lists of characters).... |
2,475,870 | 2,475,905 | Misunderstanding function pointer - passing it as an argument | I want to pass a member function of class A to class B via a function pointer as argument. Please advise whether this road is leading somewhere and help me fill the pothole.
#include <iostream>
using namespace std;
class A{
public:
int dosomeA(int x){
cout<< "doing some A to "<<x <<endl;
return(0);
}
};
c... | Pointers to members are different from normal function pointers. As the compiler error indicates the type of &A::dosomeA is actually int (A::*)(int) and not int (*)(int).
Inside B's constructor you need an instance of A to call the member on using one the .* or ->* operators.
E.g'
B(int(A::*ptr)(int))
{
A atmp;
... |
2,475,938 | 4,639,714 | Accessing Firefox tab element in nsIWebProgressListener::OnStateChange using C++ | I am developing extension for Firefox 3.0-3.5 versions using VS2008.
I want to set attribute to a tab once the document load request completes within that tab window.
So in OnStateChange method, I am checking for document load.
I have used STATE_STOP & STATE_IS_DOCUMENT for it.
I want to determine which tab window has ... | IF I understood the question correctly and you want a for a content window, you probably need https://developer.mozilla.org/en/Working_with_windows_in_chrome_code#Accessing_the_elements_of_the_top-level_document_from_a_child_window to get the chrome window, then run the implementation of gBrowser.getBrowserForDocument... |
2,475,973 | 2,476,001 | how to implement code completion in qt | i am writing an ide using qt (on c++) and i need to add auto completion feature to it
so i want to know :
how to do that (i am using qtPlainTextEdit) ?
what the data structure i should use ?
| I think you should take a look at this:
http://qt-project.org/doc/qt-4.8/tools-customcompleter.html
I used this example to understand CodeCompletion and I think it is fine :)
[edit]
Qt has a own class for such purpose called QCompleter: http://qt-project.org/doc/qt-4.8/qcompleter.html
|
2,476,031 | 2,476,517 | How to test COM object integrity automatically? | Every COM object must have integrity. In simplified terms this means that if an object implements 3 interfaces - A, B and C and I have A* pointer to the object I must be able to successfully QueryInterface() both B and C and having B I must be able to retrieve A and C and having C I must be able to retrieve A and B.
No... | I don't see the problem. If you implement A, B and C then interface A must QI properly for A, B, C and IUnknown. Including itself. The test is the same for all interfaces, you need only one small function that takes an IUnknown* argument.
|
2,476,205 | 2,476,222 | Will the Windows service be 64-bit if installed from 64-bit process? | Just wondering, if I install a Windows service from 64-bit process (service code embedded in the process), is the service itself Win32 service or can services be 64-bit as well?
I need to know this since my service would inject code (DLL-injection) to Win32-process, so due to WOW64 restrictions the service-process itse... | 64 bit. See... if the exe of the service is 32 bit, the service is 32 bit. if the exe of the service is 64 bit, the service runs 64 bit.
|
2,476,235 | 2,476,820 | What are common uses of condition variables in C++? | I'm trying to learn about condition variables. I would like to know what are the common situations where condition variables are used.
One example is in a blocking queue, where two threads access the queue - the producer thread pushes an item into the queue, while the consumer thread pops an item from the queue. If the... | One use of condition variables that's a bit more complicated than just a message queue, is to "share a lock", where different threads are waiting for subtly different conditions of the same basic nature. For instance, you have a (very shonky, simplified) web cache. Each entry in the cache has three possible states: not... |
2,476,381 | 2,476,426 | C++ Constructor initialization list strangeness | I have always been a good boy when writing my classes, prefixing all member variables with m_:
class Test {
int m_int1;
int m_int2;
public:
Test(int int1, int int2) : m_int1(int1), m_int2(int2) {}
};
int main() {
Test t(10, 20); // Just an example
}
However, recently I forgot to do that and ended up w... | Yes, it's valid. The names in the member initializer list are looked up in the context of the constructor's class so int1 finds the name of member variable.
The initializer expression is looked up in the context of the constructor itself so int1 finds the parameter which masks the member variables.
|
2,476,425 | 2,477,023 | C++/STL: std::transform with given stride? | I have a 1d array containing Nd data, I would like to effectively traverse on it with std::transform or std::for_each.
unigned int nelems;
unsigned int stride=3;// we are going to have 3D points
float *pP;// this will keep xyzxyzxyz...
Load(pP);
std::transform(pP, pP+nelems, strMover<float>(pP, stride));//How to define... | Well, I have decided to use for_each instead of transform any other decisions are welcome:
generator<unsigned int> gen(0, 1);
vector<unsigned int> idx(m_nelem);//make an index
std::generate(idx.begin(), idx.end(),gen);
std::for_each(idx.begin(), idx.end(), strMover<float>(&pPOS[0],&m... |
2,476,432 | 2,477,389 | Storing expression template functors | at the moment I'm really interested in expression templates and want to code a library for writing and differentiating mathematical functions with a lambda-style syntax. At the moment, I'm able to write (_x * _x)(2); and get the correct result 4. But I would really like to do something like MathFunction f = _x * _x; f(... | As I'm a newbie to this site, I have found this not until I submitted this question. Thanks for your answers, but this is what I was really looking for.
|
2,476,724 | 2,476,777 | Any implementations of C++0x out there? | Other than Microsoft's upcoming VC10?
| here is a good breakdown of c++0x support in several major compilers
|
2,476,748 | 2,476,806 | Writing 'bits' to C++ file streams | How can I write 'one bit' into a file stream or file structure each time?
Is it possible to write to a queue and then flush it?
Is it possible with C# or Java?
This was needed when trying to implement an instance of Huffman coding. I can't write bits into files, so write them to a bitset and then (when compression was ... | Buffering the individual bits until you've accumulated a whole byte seems like a good idea:
byte b;
int s;
void WriteBit(bool x)
{
b |= (x ? 1 : 0) << s;
s++;
if (s == 8)
{
WriteByte(b);
b = 0;
s = 0;
}
}
You just have to deal with the case when the number of bits to be wr... |
2,477,053 | 2,477,116 | How do I get an Iterator over a vector of objects from a Template? | I'm busy implementing a Graph ADT in C++. I have templates for the Edges and the Vertices. At each Vertex I have a vector containing pointers to the Edges that are incident to it. Now I'm trying to get an iterator over those edges. These are the lines of code:
vector<Edge<edgeDecor, vertexDecor, dir>*> edges = this->in... | If that snippet comes from a template, you have probably run into the problem of dependent names - use typename:
typename vector<Edge<edgeDecor, vertexDecor, dir>*>::const_iterator i;
typename tells the compiler that you are referring to a type. Without it, dependent names are assumed to not be types or templates.
F... |
2,477,160 | 2,477,189 | storing an integer constant other than zero in a pointer variable | int main()
{
int *d=0;
printf("%d\n",*d);
return 0;
}
this works fine.
>cc legal.c
> ./a.out
0
if i change the statement int *d=0; to int *d=1;
i see the error.
cc: "legal.c", line 6: error 1522: Cannot initialize a pointer with an integer constant other than zero.
so its obvious that it will allow only zero.i wan... | I'm surprised that you didn't get a SEGFAULT when you ran your code. The *d in the printf statement is dereferencing the pointer. To answer your question, though, C++ allows 0 to be given as a default initializer for any object, which is why it can be used to initialize the pointer to null (0 and null are identical). ... |
2,477,162 | 2,477,175 | std::map and behavior of already inserted data | Does std::map move around already inserted values when inserting new data ?
| The map is implemented as a tree, and when you insert a new element, the tree may need to be rebalanced.
This does not invalidate any iterators or references to elements in the tree. This balancing is done via the manipulation of pointers, so you have nothing to worry about; the nodes themselves stay put.
Balancing inv... |
2,477,459 | 2,477,474 | Segmentation fault before return | Why does the following code seg fault before returning:
int main()
{
char iD[20];
memset (iD, 0, 20);
char* prefix;
srand (time(NULL) );
int iPrefix = rand()%1000000;
sprintf(prefix, "%i", iPrefix);
int len = strlen(prefix);
char* staticChar = "123456789";
//set prefix into ID
memcpy(iD, prefix, len);
// append sta... | You need to allocate memory for prefix before calling this:
sprintf(prefix, "%i", iPrefix);
or you could refactor the code e.g.,
snprintf(iD, sizeof(iD), "%i%s", iPrefix, staticChar);
|
2,477,461 | 2,477,487 | is const (c++) optional? | according to some tutorials i read a while back, the "const" declaration makes a variable "constant" ie it cannot change later.
But i find this const declaration abit inconveniencing since the compiler sometimes gives errors like
"cannot convert const int to int"
or something like that.
and i find myself cheating by ... | Are you serious? Why would you want to give up on such a useful feature just because you make a mistake sometimes? Better try and learn to avoid mistakes with const and you benefit from the great assistance it adds to ensure correctnes with your code.
Of course, you can say goodbye to all the help the language provide... |
2,477,486 | 2,492,813 | How to manipulate a header and then continue with it in C#? | I want to replace an old ISAPI filter that ran on IIS6. This filter checks if the request is of a special kind, then manipulates the header and continues with the request. Two headers are added in the manipulating method that I need for calling another special ISAPI module.
So I have ISAPI C++ code like:
DWORD OnPrePro... | I finally found it. As I stated in the comments I add two headers to the request that are needed by my DLL that finally handles the request. The url header contains the path to the DLL. So I have to do a redirect to that DLL.
This is done with the following code:
private void OnMapRequestHandler(HttpContext context)
{
... |
2,477,570 | 2,477,702 | How to load an RSA key from binary data to an RSA structure using the OpenSSL C Library? | Currently I have my private key saved in a file, private.key, and I use the following function to load it:
RSA *r = PEM_read_RSAPrivateKey("private.key", NULL, NULL, NULL);
This works perfectly but I'm not happy with the file-based format; I want to save my key in pure binary form (ie, no base64 or similar) in a char* ... | Use d2i_RSAPrivateKey to load directly from a buffer containing binary DER format:
const unsigned char *p = key;
RSA *r = d2i_RSAPrivateKey(NULL, &p, keylen);
|
2,477,850 | 2,477,864 | How to use string.substr() function? | I want to make a program that will read some number in string format and output it like this: if the number is 12345 it should then output 12 23 34 45 . I tried using the substr() function from the c++ string library, but it gives me strange results - it outputs 1 23 345 45 instead of the expected result. Why ?
#includ... | If I am correct, the second parameter of substr() should be the length of the substring. How about
b = a.substr(i,2);
?
|
2,477,951 | 2,478,045 | Win32 API - Create Button help | I try to create 2 buttons inside my app
case WM_CREATE:{
hWnd =CreateWindowEx(NULL,
L"BUTTON",
L"Giai PTB2",
WS_TABSTOP|WS_VISIBLE|
WS_CHILD|BS_DEFPUSHBUTTON,
100,
100,
100,
24,
hWnd,
(HMENU)IDC_... | check hWnd .. you are changing is value by the first create
the side effect is that you are passing the first button as parent of the second ...
|
2,478,143 | 2,478,364 | How can I find out how much memory an instance of a C++ class consumes? | I am developing a Graph-class, based on boost-graph-library.
A Graph-object contains a boost-graph, so to say an adjacency_list, and a map.
When monitoring the total memory usage of my program, it consumes quite a lot (checked with pmap).
Now, I would like to know, how much of the memory is exactly consumed by a filled... | I have never used adjacency_list so this is just an idea which although works with STL containers.
So using adjacency_list says BGL uses containers from the STL such as std::vector, std::list, and std::set to represent the set of vertices and the adjacency structure. OK, then you just have to give your adjacent list s... |
2,478,151 | 2,478,167 | Why is 'volatile' parasitic in C++? | Consider the following code:
int main()
{
int i;
volatile int* p = &i; ... | If you mean that the pointer should be volatile, rather than the object it points to, then declare it as
int* volatile p;
|
2,478,397 | 2,478,746 | Atomic swap in GNU C++ | I want to verify that my understanding is correct. This kind of thing is tricky so I'm almost sure I am missing something. I have a program consisting of a real-time thread and a non-real-time thread. I want the non-RT thread to be able to swap a pointer to memory that is used by the RT thread.
From the docs, my und... | Generally don't use volatile when writing concurrent code in C/C++. The semantics of volatile are so close to what you want that it is tempting but in the end volatile is not enough. Unfortunately Java/C# volatile != C/C++ volatile. Herb Sutter has a great article explaining the confusing mess.
What you really want ... |
2,478,717 | 2,478,732 | Is it good practice to generally make heavyweight classes non-copyable? | I have a Shape class containing potentially many vertices, and I was contemplating making copy-constructor/copy-assignment private to prevent accidental needless copying of my heavyweight class (for example, passing by value instead of by reference).
To make a copy of Shape, one would have to deliberately call a "clone... | Restricting your users isn't always a good idea. Just documenting that copying may be expensive is enough. If a user really wants to copy, then using the native syntax of C++ by providing a copy constructor is a much cleaner approach.
Therefore, I think the real answer depends on the context. Perhaps the real class you... |
2,478,881 | 2,478,898 | reading a file of unknown length with a function | I'm trying to write a short function that will let me quickly read in a file of unknown size and return pointer to the array of data and the length of that array but it seems my code isn't working. What am i doing wrong?
int readIn(int* pointer, param parameters, string description)
{
string fileName = parameters.f... | You aren't returning anything in your pointer variable after the function call.
You can fill a variable so it's value remains changed after the function call by dereferencing it's address.
Example:
void fillX(int *p)
{
//p holds a memory address, go to that memory address and change its value
*p = 4;
}
void ma... |
2,478,928 | 2,479,000 | RAII: Initializing data member in const method | In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member.
Example: Loading from a data base
struct MyClass
{
int get_value(void) const;
private:
void load_from_database(voi... | This is not RAII. In RAII you would initialize it in the constructor, which would solve your problems.
So, what you are using here is Lazy. Be it lazy initialization or lazy computation.
If you don't use mutable, you are in for a world of hurt.
Of course you could use a const_cast, but what if someone does:
static cons... |
2,478,933 | 2,478,951 | Compilation failing - no #include - boost | I'm trying to compile a third-party library, but g++ is complaining about the following line:
typedef boost::shared_ptr<MessageConsumer> MessageConsumerPtr;
The strange thing is, there is no #include directive in the file - and it is clearly supposed to be this way; there are about 60 files with the same (or very simi... | You can use the -include command line option:
g++ -include boost/shared_ptr.hpp ...
From the man page:
-include file
Process file as if "#include "file"" appeared as the first line of
the primary source file. However, the first directory searched for
file is the preprocessor's ... |
2,479,067 | 2,479,202 | Why is the volatile qualifier used through out std::atomic? | From what I've read from Herb Sutter and others you would think that volatile and concurrent programming were completely orthogonal concepts, at least as far as C/C++ are concerned.
However, in GCC implementation all of std::atomic's member functions have the volatile qualifier. The same is true in Anthony Williams's ... | Why is the volatile qualifier used throughout std::atomic?
So that volatile objects can also be atomic. See here:
The relevant quote is
The functions and operations are defined to work with volatile objects, so that variables that should be volatile can also be atomic. The volatile qualifier, however, is not required ... |
2,479,253 | 2,479,269 | Which namespace does operator<< (stream) go to? | If I have have some overloaded ostream operators, defined for library local objects, is its okay for them to go to std namespace? If I do not declare them in std namespace, then I must use using ns:: operator <<.
As a possible follow-up question, are there any operators which should go to standard or global namespace?
| According to Koenig Lookup (C++ Standard 3.4.2) operator<< will be searched in namespaces of arguments. No need to declare it in std namespace.
|
2,479,393 | 2,495,733 | MAPI_E_NOT_FOUND on OpenMsgStore | I'm trying to open the MessageStore of a user using MAPI. The weird thing is, when I run this a console application, while I'm logged with the user, everything works fine.
But when I run this as a Windows Service I get MAPI_E_NOT_FOUND when trying to open the MessageStore.
I already configured the service to run as the... | Is that an Exchange profile? Are you sure you are opening the primary mailbox rather than the PF store?
Dmitry Streblechenko (MVP)
http://www.dimastr.com/
OutlookSpy - Outlook, CDO
and MAPI Developer Tool
|
2,479,459 | 2,587,331 | Maximum length of a std::basic_string<_CharT> string | I was wondering how one can fix an upper limit for the length of a string (in C++) for a given platform.
I scrutinized a lot of libraries, and most of them define it arbitrarily. The GNU C++ STL (the one with experimental C++0x features) has quite a definition:
size_t npos = size_t(-1); /*!< The maximum value that can ... | The comments in basic_string.h from GCC 4.3.4 state:
// The maximum number of individual char_type elements of an
// individual string is determined by _S_max_size. This is the
// value that will be returned by max_size(). (Whereas npos
// is the maximum number of bytes the allocator can allocate.)
... |
2,479,576 | 2,479,618 | What kind of bad things would happen if you write the whole class in a single file in C++? | In C# or Java, classes are declared and defined at the same time. In C++, the norm is to do that separately. What if we write the whole class in one , say .cpp, file and include that in files that references to it, what kinds of bad thing technically would happen besides a lengthened compilation process?
| If your implementation of MyClass is all in the header file MyClass.h then any file you needed to implement MyClass will be included whenever someone includes MyClass.h.
If you change any part of MyClass.h, even if it's trivial (such as adding a comment or even a space) then all files that include it will have to recom... |
2,479,591 | 2,487,915 | What's the recommended implementation for hashing OLE Variants? | OLE Variants, as used by older versions of Visual Basic and pervasively in COM Automation, can store lots of different types: basic types like integers and floats, more complicated types like strings and arrays, and all the way up to IDispatch implementations and pointers in the form of ByRef variants.
Variants are als... | Hash codes of VARIANTS that are equal should be equal.
Without knowing the equality and coercion rules that are used for testing equality, it is hard to come up with a proper implementation.
|
2,479,746 | 2,479,762 | Loop on enumeration values | How awful is it - or is it perfectly acceptable - to index a loop on an enumeration?
I have an enumeration defined. The values of the literals are default values. The assigned values do not have any significance, will not have any significance, and the values of any literals added in the future will also not have any s... | As far as I'm concerned, that's just fine. I'm sure some purist out there somewhere will freak out, but as far as the language spec is concerned, that code will work correctly, so you should feel free to go for it if it makes your life easier.
|
2,479,784 | 2,479,944 | Exporting static data in a DLL | I have a DLL which contains a class with static members. I use __declspec(dllexport) in order to make use of this class's methods. But when I link it to another project and try to compile it, I get "unresolved external symbol" errors for the static data.
e.g.
In DLL, Test.h
class __declspec(dllexport) Test{
protected:
... | In this thread at cprogramming.com it is suggested that a static variable is local to the dll and not exported.
Summary of discussion below
The static member is not accessed directly by code in the calling application, only through member functions of the class in the dll. However there are several inline functions acc... |
2,479,846 | 2,479,899 | No "redefinition of default parameter error" for class template member function? | Why does the following give no compilation error?:
// T.h
template<class T> class X
{
public:
void foo(int a = 42);
};
// Main.cpp
#include "T.h"
#include <iostream>
template<class T> void X<T>::foo(int a = 13)
{
std::cout << a << std::endl;
}
int main()
{
X<int> x;
x.foo(); // prints 42
}
It... |
8.3.6 §6 The default arguments in a member function definition that
appears outside of the class
definition are added to the set of
default arguments provided by the
member function declaration in the
class definition.
[Example:
class C {
void f(int i = 3);
void g(int i, int j = 99);
};
void C::f(int i ... |
2,479,983 | 2,480,027 | What elegant solution exists for this pattern? Multi-Level Searching | Assume that we have multiple arrays of integers. You can consider each array as a level. We try to find a sequence of elements, exactly one element from each array, and proceed to the next array with the same predicate. For example, we have v1, v2, v3 as the arrays:
v1 | v2 | v3
-----------------
1 | 4 | 16
2 |... | If you order your arrays beforehand, the search can be done much faster. You could start on your smaller array, then binary-search for expected numbers on each of them. This would be O(nklogM), n being the size of the smallest array, k being the numbers of arrays, M being the size of larger array
This could be done eve... |
2,480,074 | 2,480,089 | What's the boost way to create a functor that binds out an argument | I have need for a function pointer that takes two arguments and returns a string.
I would like to pass an adapter that wraps a function that takes one argument, and returns the string (i.e. discard one of the arguments).
I can trivially build my own adapter, that takes the 2 arguments, calls the wrapped function passin... | By only providing _1, it will ignore the 2nd parameter given to m_callback and call MyCtrl::GetRowText with one int parameter.
void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _1); }
On the other hand,
void UseRowText() { m_callback = boost::bind(&MyCtrl::GetRowText, this, _2); }
is also valid,... |
2,480,322 | 2,480,582 | nasm/yasm arguments, linkage to C++ | I've got a question concerning nasm and its linkage to C++. I declare a litte test function as
extern "C" void __cdecl myTest( byte i1, byte i2, int stride, int *width );
and I call it like this:
byte i1 = 1, i2 = 2;
int stride = 3, width = 4;
myTest( i1, i2, stride, &width );
the method only serves to debug assembly ... | Well, it seems that I have to preserve ebx via push/pop.
|
2,480,338 | 2,480,353 | Purpose of front() and back() in assigning values in a Queue? (C++) | I have declared:
queue<int, list<int> > Q
After a series of calls:
Q.push(37);
Q.pop();
Q.push(19);
Q.push(3);
Q.push(13);
Q.front();
Q.push(22);
Q.push(8);
Q.back();
I get:
19->3->13->22->8->NULL
What I don't get is what the calls to Q.front() and Q.back() do. From what I understand, they return a reference to t... | They give you a reference but if you want to do something with it then you have to use that reference.
e.g.
Q.push(37);
Q.push(19);
Q.front() = 8;
Then you should have...
8,19
Merely calling Q.front() or Q.back() on their own line has no effect. These are generally referred to as accessor functions, they give you ac... |
2,480,502 | 2,480,515 | C++ read registry string value in char* | I'm reading a registry value like this:
char mydata[2048];
DWORD dataLength = sizeof(mydata);
DWORD dwType = REG_SZ;
..... open key, etc
ReqQueryValueEx(hKey, keyName, 0, &dwType, (BYTE*)mydata, &dataLength);
My problem is, that after this, mydata content looks like: [63, 00, 3A, 00, 5C, 00...], i.e. this looks like ... | Look at WideCharToMultiByte().
|
2,480,632 | 2,480,640 | When virtual destructor is not needed even there is a virtual function, Why? | It says that if there is a virtual function, it is a good practice to have a virtual destructor. However, if the object is created on the stack but not on heap, do we still need to do that?
Regards,
| Strictly speaking no - the virtual destructor is only necessary if the object will be destroyed via a pointer to reference to a base object.
If the static type at destruction time is the actual type of the object, then the correct dtor will be called regardless of whether it's virtual or not.
But if a class has virtual... |
2,480,659 | 2,480,694 | Why does defined(X) not work in a preprocessor definition without a space? | A preprocessor definition that includes defined(X) will never evaluate to true, but (defined X) will. This occurs in MSVC9; I have not tested other preprocessors. A simple example:
#define FEATURE0 1
#define FEATURE1 0
#define FEATURE2 1
#define FEATURE3 (FEATURE0 && !FEATURE1 && (defined(FEATURE2)))
#define FEATURE4 ... | defined is specific to #if and #elif. When using it through macro expansion the behavior is undefined.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.