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 |
|---|---|---|---|---|
873,978 | 873,986 | C++ - Simple server which sends simple HTML to clients | Now, I'm just fooling around with this and I'm not sure as to why this isn't working.
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include <cassert>
const char html[] = "HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Content-type: text/html\r\n"
"\r\n"
"<html>\r\n"
"<head>\r\n"
"<title>Hello, world!... | You need to send back the status line:
HTTP/1.1 200 OK
preceding your response headers.
See Fiddler (www.fiddler2.com) to get a better idea of what proper HTTP responses look like.
Regarding your later edit, all browsers wait for a certain amount of data before starting rendering; Chrome's limit is different than Fir... |
873,993 | 874,000 | VS rand() problem with pthread-win32 | I come into a strange problem in pthread programming
I've compiled the following code in vs2005 with pthread-w32
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <pthread.h>
#include <windows.h>
pthread_mutex_t lock;
void* thread1(void *) {
int r1;
while(true) {
pthread_mutex_lock(&lock); // ran... | rand is only pseudo-random, and will return the same sequence each time. srand only works on the current thread, so calling it in your main thread won't affect your worker threads.
You need to call srand from within each thread, with a value that's different for each thread - for instance, within your thread1 and thre... |
874,052 | 902,449 | Properties file library for C (or C++) | The title is pretty self-explanatory: does anyone know of a (good) properties file reader library for C or, if not, C++?
Edit: To be specific, I want a library which handles the .properties file format used in Java: http://en.wikipedia.org/wiki/.properties
| STLSoft's 1.10 alpha contains a platformstl::properties_file class. It can be used to read from a file:
using platformstl::properties_file;
properties_file properties("stuff.properties");
properties_file::value_type value = properties["name"];
or from memory:
properties_file properties(
"name0=value1\n name1 ... |
874,169 | 874,171 | How to get the size of an Array? | In C# I use the Length property embedded to the array I'd like to get the size of.
How to do that in C++?
| Arrays in C/C++ do not store their lengths in memory, so it is impossible to find their size purely given a pointer to an array. Any code using arrays in those languages relies on a constant known size, or a separate variable being passed around that specifies their size.
A common solution to this, if it does present a... |
874,298 | 874,337 | C++ templates that accept only certain types | In Java you can define generic class that accept only types that extends class of your choice, eg:
public class ObservableList<T extends List> {
...
}
This is done using "extends" keyword.
Is there some simple equivalent to this keyword in C++?
| I suggest using Boost's static assert feature in concert with is_base_of from the Boost Type Traits library:
template<typename T>
class ObservableList {
BOOST_STATIC_ASSERT((is_base_of<List, T>::value)); //Yes, the double parentheses are needed, otherwise the comma will be seen as macro argument separator
...
}... |
874,408 | 874,429 | Getting the name of a DLL from within the dll | If I have a dll called "foo.dll" and the end user renames it to "bar.dll". After calling to a LoadLibrary, how can I get the name "bar.dll" from inside my dll?
Is it GetModuleFileName(hModule, buffer); ?
| yes, you need to store hModule in DllMain
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
hModule = hinstDLL;
break;
}
}
|
874,433 | 874,455 | C++ std::string conversion problem on Windows | This is my procedure:
bool Open(std::string filename)
{
...
HANDLE hFile = CreateFile(filename.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
...
}
Error:'CreateFileW' : cannot convert parameter 1 from 'const char *' to 'LPCWSTR'
Types pointed to are unrelated; conversion re... | A std::string consists of an array of char's, and so the c_str function returns a const char*.
A LPCWSTR is a Long Pointer to a Constant Wide String, or in other words, const wchar_t*.
So you have a couple of options. Either get the filename as a wide string (std::wstring), or specify that you want the non-wide version... |
874,719 | 874,740 | Return value optimization in VC2008 | Is there other technique like RVO (return value optimization) or NRVO (named return value optimization) that can be use with VC2008?
| Maybe this may help you.
But typically it's the compiler who does such kind of optimization, not you.
|
874,824 | 907,286 | Contiguous VirtualAlloc behaviour on Windows Mobile | I have been optimising memory performance on a Windows Mobile application and have encountered some differences in behaviour between VirtualAlloc on Win32 and Windows CE.
Consider the following test:
// Allocate 64k of memory
BYTE *a = (BYTE*)VirtualAlloc(0, 65536,
MEM_RESERVE|MEM_C... | No, it's not possible.
|
875,050 | 875,068 | How to copy a byte[] into a char*? | All I need this for is strcpy().
I want to see whether the first three bytes of a buffer(byte array) are "JMX" as string.
This is what I did so far:
char * ddj;
strcpy( ddj, buffer ); //buffer is BYTE[]
if ( strcmp( "JMX", ddj ) == 0 ) //check first three chars are "JMX"
{
buffer += 20; //increase the index with ... | Tho things go wrong here:
ddj does not point to any actual memory. Hence the copy will have undefined behavior
The copying is not necessary in the first place.
This is what you can do:
if(strncmp("JMX", buffer, 3) == 0) {
buffer += 20;
size -= 20;
}
This uses strncmp instead of strcmp, thus ensuring that no more... |
875,103 | 875,109 | How do I erase an element from std::vector<> by index? | I have a std::vector<int>, and I want to delete the n'th element. How do I do that?
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
vec.erase(???);
| To delete a single element, you could do:
std::vector<int> vec;
vec.push_back(6);
vec.push_back(-17);
vec.push_back(12);
// Deletes the second element (vec[1])
vec.erase(std::next(vec.begin()));
Or, to delete more than one element at once:
// Deletes the second through third elements (vec[1], vec[2])
vec.erase(std::... |
875,249 | 875,264 | How to get Current Directory? | I want to create a file in the current directory (where the executable is running).
My code:
LPTSTR NPath = NULL;
DWORD a = GetCurrentDirectory(MAX_PATH,NPath);
HANDLE hNewFile = CreateFile(NPath,GENERIC_WRITE,0,NULL,CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL);
I get exception at GetCurrentDirectory().
Why am I getting ... | I would recommend reading a book on C++ before you go any further, as it would be helpful to get a firmer footing. Accelerated C++ by Koenig and Moo is excellent.
To get the executable path use GetModuleFileName:
TCHAR buffer[MAX_PATH] = { 0 };
GetModuleFileName( NULL, buffer, MAX_PATH );
Here's a C++ function that ge... |
875,479 | 875,489 | What is the difference between a .cpp file and a .h file? | Because I've made .cpp files and then transferred them into .h files, the only difference I can find is that you can't #include .cpp files. Is there any difference that I am missing?
| The C++ build system (compiler) knows no difference, so it's all one of conventions.
The convention is that .h files are declarations, and .cpp files are definitions.
That's why .h files are #included -- we include the declarations.
|
875,553 | 875,565 | What happens if more than one .cpp file is #included? | Becase I've seen (and used) situations like this:
In header.h:
class point
{
public:
point(xpos, ypos);
int x;
int y;
};
In def.cpp:
#include"header.h"
point::point(xpos, ypos)
{
x = xpos;
y = ypos;
}
In main.cpp:
#include"header.h"
int main()
{
point p1(5,6);
return 0;
}
I know the progr... | The compiler doesn't care - it compiles each .cpp file into .obj file, and the .obj files each contain a list of missing symbols. So in this case, main.obj says "I'm missing point::point".
It's then the linker's job to take all the .obj files, combine them together into an executable, and make sure that each .obj file... |
875,578 | 875,583 | How to refer to an "owner class" in C++? | I have code that looks like this:
template<class T>
class list
{
public:
class iterator;
};
template<class T>
class list::iterator
{
public:
iterator();
protected:
list* lstptr;
};
list<T>::iterator::iterator()
{
//???
}
I want to make the constructor of list::iterator to make iterator::lstptr point ... | You can pass the list to the constructor of iterator:
list xlst;
list::iterator xitr(xlst);
Or, you could make an iterator factory function:
list xlst;
list::iterator xitr = xlst.create_iter();
In the factory function case, the create_iter() function can use this to refer to the enclosing list.
|
875,685 | 876,025 | Simplifying algorithm testing for researchers. | I work in a group that does a large mix of research development and full shipping code.
Half the time I develop processes that run on our real time system ( somewhere between soft real-time & hard real-time, medium real-time? )
The other half I write or optimize processes for our researchers who don't necessarily care... | If you can change enough of the program through a script to be useful, without a full recompile, maybe you should think about breaking the system up into smaller parts. You could have a "server" that handles data loading etc and then the client code that does the actual processing. Each time the system loads new data, ... |
875,686 | 875,895 | Advice for C++ GUI programming | I have been writing C++ Console/CMD-line applications for about a year now and would like to get into windows GUI apps. For those of you who have taken this road before, what advice/tips can you give me. Ex: good readings, tutorials, approach tactics, etc...
I know this is a really broad question, but i really don't ... | I highly recommend the use of the Qt Libraries for several reasons:
The Framework is freely available for Windows, Linux, MacOS X, and a couple of mobile systems. Since version 4.5 the license is LGPL, which basically means that you can use Qt even in commercial applications.
The design of Qt is out-standing, e.g. the... |
875,743 | 875,769 | Signal to a calling thread that a resource is already in use | Question slightly in the abstract...
We have a situation where we have a struct that can be accessed by 2 or 3 threads concurrently.
We wish to signal to a thread that tries to modify the struct if it is already being modified.
e.g. The code at the moment:
thread0: struct->modify(var SomeNewState)
thread1: struct->mo... | Are you using Windows?
TryEnterCriticalSection
[Edit: fixed link]
|
875,950 | 875,993 | Filtering Windows Messages in a Hook Filter Function | I am trying to retrieve messages for another application with a Windows hook. I have setup a WH_GETMESSAGE hook with SetWindowsHookEx. This is done via a DLL. In my GetMsgProc function (that should be called whenever the target application receives a message) I want to take action based on the type of message. Howe... | Are you sure that you're hooking the correct window or the correct message, respectively? Under some circumstances WM_SYSCOMMAND or WM_MENUCOMMAND is generated instead of WM_COMMAND.
Your code looks fine, have you also tried dumping the incoming messages into console?
|
876,155 | 876,197 | Getting Started on Driver Development | Does anyone have any books/tutorials which may be useful in getting started in Windows device driver development?
For plain Win32/GUI development, Petzold's book seems to be the essential reference. Does such exist for drivers?
I would like to note that I'm not actually talking to hardware -- I actually want to emulate... | One thing to beware of is the device driver development (architecture and tools) changes more than Win32 development ... so while Petzold's book from the 1990s is fine for Win32 and may be considered a timeless classic, the architecture for many kinds of drivers (printer drivers, network drivers, etc.) has varied in va... |
876,301 | 878,594 | Is there any way to use SMO in c++ other than Managed Code? | Is there any way to use SQLSERVER SMO(sqlserver management Objects) in c++ other than Managed Code?
Help me in this regard...
I sincerely request dont give the comment as duplicate still i am not getting Clear answer
| As you pointed out. This question has already been asked without a satisfactory answer.
SMO is strictly manage code. The previous version, DMO, could be used in unmanaged code. If you need to use SMO, you have to use either C++/CLI or create wrappers for COM.
From the MSDN Documentation on SMO:
The SMO object model su... |
876,497 | 877,307 | How to modify source files in Pre-Build... without modifying source files? | so I'm using Visual Studio 2005 and for my current project I'm building a C# Add-In to handle the weaving of aspects for AspectC++. It's simple enough to gather the aspect and source files and feed them into the aspect compiler, but this generates new (modified) source files. I'm trying to emulate the standard Aspect... | It sounds like you want to modify the source code just before or after the preprocessor. In this case you should use the #line directive, to tell the compiler what file and line it is really processing. This is how the preprocessor works, it includes all your header files into one massive file, this file contains #li... |
876,776 | 876,801 | Calling a class inside a class | I'm trying to write a class that when asked on, will call on a class and make it into a class member. Here's a quick example of what I mean:
class foo{
myClass Class;
foo();
};
foo::foo()
{
//Create the class and set it as the foo::Class variable
}
I'm sure this is actually an easy thing to do. Any help would b... | There is no need to do anything. Assuming that myClass has a default constructor, it will be used to construct the Class (you could use better names here, you know) instance for you. If you need to pass parameters to the constructor, use an initialisation list:
foo :: foo() : Class( "data" ) {
}
|
876,901 | 876,970 | calculating execution time in c++ | I have written a c++ program , I want to know how to calculate the time taken for execution so I won't exceed the time limit.
#include<iostream>
using namespace std;
int main ()
{
int st[10000],d[10000],p[10000],n,k,km,r,t,ym[10000];
k=0;
km=0;
r=0;
scanf("%d",&t);
for(int y=0;y<t;y++)
{
... | If you have cygwin installed, from it's bash shell, run your executable, say MyProgram, using the time utility, like so:
/usr/bin/time ./MyProgram
This will report how long the execution of your program took -- the output would look something like the following:
real 0m0.792s
user 0m0.046s
sys 0m0.218s
You ... |
877,107 | 877,156 | C++ error - "member initializer expression list treated as compound expression" | I'm getting a C++ compiler error which I'm not familiar with. Probably a really stupid mistake, but I can't quite put my finger on it.
Error:
test.cpp:27: error: member initializer expression list treated as compound expression
test.cpp:27: warning: left-hand operand of comma has no effect
test.cpp:27: error: invalid i... | m_bar is a reference, so you can't construct one.
As others have noted, you can initialise references with the object it refers to, but you can't construct one like you're trying to do.
Change line 30 to
const Bar m_bar
and it'll compile / run properly.
|
877,117 | 877,142 | How to model an OO style interface for C functions? | I have a C module which is created by the Real-time Workshop based on a Simulink Model.
This modules provides three public functions:
int init();
int calc(double *inputarray, double *outputarray);
int term();
Based on the contents of the outputarray, I can model a class called OutputThing.
I want to integrate those fu... | If you are able to also abstract inputarray to an InputThing class I'd suggest the following. This also better encapsulates the initialisation/termination using C++ construction/destruction.
class WrapperModule {
public:
// Calls init()
WrapperModule();
// Calls term()
~WrapperModule();
// Calls c... |
877,193 | 877,327 | Port Delphi to C++ gradually | I have a large application written in Delphi. I want to renew it, starting with the user interface. I thought about using the new Qt. During the process of renewing it, I want to change to C++ as the programming language.
Is there a way to gradually rewrite the application (starting with the UI) to change to C++?
Thank... | The best course of action highly depends on the C++ development environment.
If it is C++ Builder you have two possibilities:
Use runtime packages instead of normal DLLs. This will spare you much headaches when it comes to string marshalling and mapping class hierarchies to flat DLL functions.
Use mixed code. You can ... |
877,523 | 877,538 | error: request for member '..' in '..' which is of non-class type | I have a class with two constructors, one that takes no arguments and one that takes one argument.
Creating objects using the constructor that takes one argument works as expected. However, if I create objects using the constructor that takes no arguments, I get an error.
For instance, if I compile this code (using g++... | Foo foo2();
change to
Foo foo2;
You get the error because compiler thinks of
Foo foo2()
as of function declaration with name 'foo2' and the return type 'Foo'.
But in that case If we change to Foo foo2 , the compiler might show the error " call of overloaded ‘Foo()’ is ambiguous".
|
877,577 | 878,228 | Is there a difference between Boost's scoped mutex and WinAPi's critical section? | In Windows environment, is Boost's scoped mutex using WinAPI's critical sections, or something else?
| The current version of boost::mutex uses neither a Win32 CRITICAL_SECTION, nor a Win32 Mutex. Instead, it uses atomic operations and a Win32 Event for blocking waits.
Older versions (boost 1.34.1 and prior) were a wrapper around CRITICAL_SECTION on Windows.
Incidentally, the mutex itself is not scoped. The boost::mutex... |
877,652 | 62,037,090 | Copy a streambuf's contents to a string | Apparently boost::asio::async_read doesn't like strings, as the only overload of boost::asio::buffer allows me to create const_buffers, so I'm stuck with reading everything into a streambuf.
Now I want to copy the contents of the streambuf into a string, but it apparently only supports writing to char* (sgetn()), creat... | I mostly don't like answers that say "You don't want X, you want Y instead and here's how to do Y" but in this instance I'm pretty sure I know what tstenner wanted.
In Boost 1.66, the dynamic string buffer type was added so async_read can directly resize and write to a string buffer.
|
877,699 | 877,707 | Default construction of elements in a vector | While reading the answers to this question I got a doubt regarding the default construction of the objects in the vector. To test it I wrote the following test code:
struct Test
{
int m_n;
Test();
Test(const Test& t);
Test& operator=(const Test& t);
};
Test::Test() : m_n(0)
{
}
Test::Test(const Te... | It uses the equivalent of the default constructor for ints, which is to zero initialise them. You can do it explicitly:
int n = int();
will set n to zero.
Note that default construction is only used and required if the vector is given an initial size. If you said:
vector <X> v;
there is no requirement that X have a d... |
877,758 | 877,834 | compare buffer with const char* in C++ | What is the correct C++ way of comparing a memory buffer with a constant string - strcmp(buf, "sometext") ? I want to avoid unnecessary memory copying as the result of creating temporary std::string objects.
Thanks.
| If you're just checking for equality, you may be able to use std::equal
#include <algorithms>
const char* text = "sometext";
const int len = 8; // length of text
if (std::equal(text, text+len, buf)) ...
of course this will need additional logic if your buffer can be smaller than the text
|
877,888 | 878,230 | How to create a .dll in Visual Studio 2008 for use in a C# App? | I have a C++ class I'd like to access from a C# application. I'll need to access the constructor and a single member function. Currently the app accepts data in the form of stl::vectors but I can do some conversion if that's not likely to work?
I've found a few articles online which describe how to call C++ DLLs and so... | The easiest way to interoperate between C++ and C# is by using managed C++, or C++/CLI as it is called. In VisualStudio, create a new C++ project of type "CLR Class Library". There is some new syntax for the parts that you want to make available to C#, but you can use regular C++ as usual.
In this example, I'm using st... |
877,896 | 877,918 | Count Processors using C++ under Windows | Using unmanaged C++ on a Windows platform, is there a simple way to detect the number of processor cores my host machine has?
| You can use GetLogicalProcessorInformation to get the info you need.
ETA:
As mentioned in the question a commenter linked to, another (easier) way to do it would be via GetSystemInfo:
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );
numCPU = sysinfo.dwNumberOfProcessors;
Seems like GetLogicalProcessorInformation would... |
878,057 | 878,135 | Delete a registry key recursively | I need to remove a subtree in the Windows registry under Windows Mobile 6. The RegDeleteTree function is not available, and SHDeleteKey is (apparently) not available in any static library under the WM6 SDK, though the declaration is available in shlwapi.h.
I tried to get it from shlwapi.dll, like
typedef DWORD (__s... | I guess I found the answer myself in MSDN. It puzzles me that the functionality is not available through the SDK, though...
I put the code from MSDN here as well, just for the record:
//*************************************************************
//
// RegDelnodeRecurse()
//
// Purpose: Deletes a registry key and... |
878,166 | 878,298 | Is there C++ lazy pointer? | I need a shared_ptr like object, but which automatically creates a real object when I try to access its members.
For example, I have:
class Box
{
public:
unsigned int width;
unsigned int height;
Box(): width(50), height(100){}
};
std::vector< lazy<Box> > boxes;
boxes.resize(100);
// at this point boxes co... | It's very little effort to roll your own.
template<typename T>
class lazy {
public:
lazy() : child(0) {}
~lazy() { delete child; }
T &operator*() {
if (!child) child = new T;
return *child;
}
// might dereference NULL pointer if unset...
// but if this is const, what else can be ... |
878,172 | 884,124 | Find unused function in vc2008? | how to find unused functions in a c++ project vc2008
| I always use "/OPT:REF" when creating release versions. This flag removes all unreferenced functions and will reduce the final binary substantially if there are many functions not being used (in our case we have a kernel with loads of methods used differently from different customized applications).
The "/VERBOSE" will... |
878,627 | 878,709 | Get the domain name of a computer from Windows API | In my application I need to know if the computer is the primary domain controller of a domain, so I need to know the domain of the computer to call NetGetDCName function.
Thanks.
EDIT: The problem is related with the DCOM authentication so I need to know the domain to use the DOMAIN\USERNAME in case of a PDC or COMPUTE... | I would consider using NetWkstaGetInfo() and pass the local computer name is that first parameter.
#include <Lmwksta.h>
#include <StrSafe.h>
WCHAR domain_name[256];
WKSTA_INFO_100 info = {0};
if (NERR_Success == NetWkstaGetInfo(L"THIS-COMPUTER", 100, &info) &&
SUCCEEDED(StringCchCopy(domain_name, ARRAYSIZE(domain... |
879,375 | 879,617 | How can I remove the leading zeroes from an integer generated by a loop and store it as an array? | I have a for loop generating integers.
For instance:
for (int i=300; i>200; i--)
{(somefunction)*i=n;
cout<<n;
}
This produces an output on the screen like this:
f=00000000000100023;
I want to store the 100023 part of this number (i.e just ignore all the zeros before the non zero numbers start but then k... | This is a mish-mash of answers, because they are all there, I just don't think you're seeing the solution.
First off, if they are integers Bill's answer along with the other answers are great, save some of them skip out on the "store in array" part. Also, as pointed out in a comment on your question, this part is a dup... |
879,408 | 879,570 | C++: Function wrapper that behaves just like the function itself | How can I write a wrapper that can wrap any function and can be called just like the function itself?
The reason I need this: I want a Timer object that can wrap a function and behave just like the function itself, plus it logs the accumulated time of all its calls.
The scenario would look like this:
// a function who... | Here is an easy way to wrap functions.
template<typename T>
class Functor {
T f;
public:
Functor(T t){
f = t;
}
T& operator()(){
return f;
}
};
int add(int a, int b)
{
return a+b;
}
void testing()
{
Functor<int (*)(int, int)> f(add);
cout << f()(2,3);
}
|
879,530 | 879,572 | How do I monitor the lock on a file to see when it is released? [C++] | I am looking for a way to create a program in unmanaged c++ that waits until a file is unlocked (as in it is no longer in use) and than does something. I have had no luck locating how to do this, any help would be appreciated!
UPDATE: I may have answered my own question, see below and tell me what you think..
UPDATE: ... | Here is one possible solution to my problem, does anyone see a problem with this?
#include <iostream>
#include <fstream>
#include <windows.h>
using namespace std;
void main(int argc, char ** argv) {
if (argc < 2 || argc > 2) {
return;
}
ofstream myfile;
myfile.open(argv[1], ios_base::app);
... |
879,535 | 879,793 | What is the difference between a template class and a class template? | What is the difference between a template class and a class template?
| This is a common point of confusion for many (including the Generic Programming page on Wikipedia, some C++ tutorials, and other answers on this page). As far as C++ is concerned, there is no such thing as a "template class," there is only a "class template." The way to read that phrase is "a template for a class," a... |
879,603 | 879,666 | Remove an array element and shift the remaining ones | How do I remove an element of an array and shift the remaining elements down. So, if I have an array,
array[]={1,2,3,4,5}
and want to delete 3 and shift the rest so I have,
array[]={1,2,4,5}
How would I go about this in the least amount of code?
| You just need to overwrite what you're deleting with the next value in the array, propagate that change, and then keep in mind where the new end is:
int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
// delete 3 (index 2)
for (int i = 2; i < 8; ++i)
array[i] = array[i + 1]; // copy next element left
Now your array is {1,... |
879,664 | 879,756 | is there a difference between a struct in c++ and a struct in c#? | is there a difference between a struct in c++ and a struct in c#?
| In C# you use structs to define value types (as opposed to reference types declared by classes).
In C++, a struct is the same thing as a class with a default accessibility level of public.
So the question should be: are structs in C# different from classes in C++ and, yes, they are: You cannot derive from C# structs, y... |
879,896 | 879,995 | C++: How to implement a timeout for an arbitrary function call? | I need to call a library function that sometimes won't terminate within a given time, unfortunately. Is there a way to call the function but abort it if it doesn't terminate within n seconds?
I cannot modify the function, so I cannot put the abort condition into it directly. I have to add a timeout to the function exte... | You could spawn a boost::thread to call the API:
boost::thread api_caller(::api_function, arg1, arg2);
if (api_caller.timed_join(boost::posix_time::milliseconds(500)))
{
// API call returned within 500ms
}
else
{
// API call timed out
}
Boost doesn't allow you to kill the worker thread, though. In this example... |
879,966 | 879,980 | How to tell if stderr is directing output to a file? | Is there a way I can tell whether stderr is outputting to a file or the terminal within a C/C++ program? I need to output different error message depending on whether the program is invoked as:
./program
or like:
./program 2>> file
| Try using isatty() on the file descriptor:
The isatty() function determines if
the file descriptor fd refers to a
valid terminal type device.
The function fileno() examines the
argument stream and returns its
integer descriptor.
Note that stderr is always on file descriptor 2, so you don't really need fileno(... |
880,269 | 880,292 | how do clean up deleted objects in C++ | Is it possible to zero out the memory of deleted objects in C++? I want to do this to reproduce a coredump in unit test:
//Some member variable of object-b is passed-by-pointer to object-a
//When object-b is deleted, that member variable is also deleted
//In my unit test code, I want to reproduce this
//even if I expl... | You probably should override the delete operator.
Example for the given class B:
class B
{
public:
// your code
...
// override delete
void operator delete(void * p, size_t s)
{
::memset(p, 0, s);
::operator delete(p, s);
}
};
EDIT: Thanks litb for pointing this out.
|
880,495 | 880,502 | C++ Interface Compiling | EDIT:
I figured out the solution. I was not adding -combine to my compile instructions and that was generating the errors.
I'm in the process of working through the Deitel and Deitel book C++ How to Program and have hit a problem with building and compiling a C++ interface using g++. The problem is, I've declared the... | Looks like you just need to link in the GradeBook.cpp object file to your final executable. Care to post your makefile or the way you are building it?
|
880,528 | 881,511 | UDP Client - Release version not working in VS 2005 only | I have a simple UDP client/server program that that sends (server) a text string and receives (client) that text string to display on the dialog box. This is a MFC C++ program and I have it working properly in Visual Studio 6.0, Visual Studio 2003 in both the debug and release versions. I am trying to get the same co... | You should never need to add casts to message map entries.
For an ON_MESSAGE handler, the type of the function must be afx_msg LRESULT (CWnd::*)(WPARAM, LPARAM), so you should change your readData function from this:
LRESULT CUDPClientDlg::readData() {
...
}
to this:
LRESULT CUDPClientDlg::readData(WPARAM wParam,... |
880,570 | 880,651 | Question about server socket programming model | Over the last couple of months I've been working on some implementations of sockets servers in C++ and Java. I wrote a small server in Java that would handle & process input from a flash application hosted on a website and I managed to successfully write a server that handles input from a 2D game client with multiple p... | Sounds like you have a couple of questions here. I'll do my best to answer what I can see.
1. How should I handle threading in my network server?
I would take a good look at what kind of work you're doing on the worker threads that are being spawned by your server. Spawning a new thread for each request isn't a good id... |
880,600 | 880,738 | warning: declaration does not declare anything | I'm getting this warning all over the place in some perfectly well functioning objective-c code within XCode. My google-fu has failed me... others have run into this but I could not find an explanation on what exactly is causing it or how it can be fixed.
| Found the problem and fixed it. I had this:
enum eventType { singleTouch };
enum eventType type;
... and changed it to:
enum eventType { singleTouch } type;
|
880,603 | 880,643 | Using C++ in an embedded environment | Today I got into a very interesting conversation with a coworker, of which one subject got me thinking and googling this evening. Using C++ (as opposed to C) in an embedded environment. Looking around, there seems to be some good trades for and against the features C++ provides, but others Meyers clearly support it. So... | It sort of depends on the particular nature of your embedded system and which features of C++ you use. The language itself doesn't necessarily generate bulkier code than C.
For example, if memory is your tightest constraint, you can just use C++ like "C with classes" -- that is, only using direct member functions, di... |
880,639 | 880,857 | cxxTestgen.py throw a syntax error | I've follow the tutorial on cxxtest Visual Studio Integration and I've looked on google but found nothing.
When I try to lunch a basic test with cxxtest and visual studio I get this error :
1>Generating main code for test suite
1> File "C:/cxxtest/cxxtestgen.py", line 60
1> print usageString()
1> ... | You appear to be using Python 3.0 on a body of code which is not ready for python 3.0 - your best bet is to downgrade to python 2.6 until cxxtestgen.py works with python 3.0.
See http://docs.python.org/3.0/whatsnew/3.0.html#print-is-a-function for details
|
880,803 | 900,869 | Running small C++ programs in Visual Studio without creating projects | Is there any way to build/run small C++ programs, in Visual Studio without creating projects?
For example, if I have a file hello.cpp, can I compile it to hello.exe without a project?
| GMan's idea of having a 'sandbox' project is a good one, as it allows for easily trying out multi-file tests. I call mine "cppTest".
However, if you just want to be able to compile whatever C or C++ file you happen to have open, just create a simple "External Tool". Actually, it's not as simple as it probably should b... |
880,882 | 880,924 | optimizing boost unordered map and sets, C++ | I will be parsing 60GB of text and doing a lot of insert and lookups in maps.
I just started using boost::unordered_set and boost::unordered_map
As my program starts filling in these containers they start growing bigger and bigger and i was wondering if this would be a good idea to pre allocate memory for these contai... | I would try it both ways, which will let you generate hard data showing whether one method works better than the other. We can speculate all day about which method will be optimal, but as with most performance questions, the best thing to do is try it out and see what happens (and then fix the parts that actually need ... |
881,053 | 881,157 | What is the most violent way that an application can terminate itself (linux) | I'd like to emulate violent system shutdown, i.e. to get as close as possible to power outage on an application level. We are talking about c/c++ application on Linux. I need the application to terminate itself.
Currently i see several options:
call exit()
call _exit()
call abort()
do division by zero or dereference N... | At the application level, the most violent you can get is _exit(). Division by zero, segfaults, etc are all signals, which can be trapped - if untrapped, they're basically the same as _exit(), but may leave a coredump depending on the signal.
If you truly want a hard shutdown, the best bet is to cut power in the most v... |
881,064 | 881,100 | Top down and Bottom up programming | Why do we say languages such as C are top-down while OOP languages like Java or C++ are bottom-up? Does this classification have any importance in software development?
| The "top down" approach takes a high level definition of the problem and subdivides it into subproblems, which you then do recursively until you're down to pieces that are obvious and easy to code. This is often associated with the "functional decomposition" style of programming, but needn't be.
In "bottom up" program... |
881,119 | 881,135 | Dealing with lazy computation in C++ classes | Let's say I have a class:
class NumberCollection
{
public:
typedef std::set<int> SetType;
typedef SetType::iterator iterator;
void insert(int n);
iterator begin();
iterator end();
size_t size() const;
iterator difficultBegin();
iterator difficultEnd();
size_t difficultSize() const;... | That's totally the way to do it. Const can mean binary const, or it can mean conceptually const. Using mutable means you're doing the later, which is fine.
|
881,667 | 881,716 | Allocation of managed objects in Managed C++ | Is it necessary to check for nullptr after allocating an object using gcnew?
| No, you'll get a OutOfMemoryException in the object can't be allocated by the GC.
|
881,957 | 884,122 | Methodology for upgrading OS Kernel | I am looking to get into operating system kernel development and figured my contribution would be to extend the SANOS operating system in order to support JDK 1.6 and 1.7. I have been reading books on operating systems (Tannenbaum) as well as studying how BSD and Linux have tackled this challenge but still am stuck on ... | The minimum number of system calls any reasonable *nix style OS should have are (IMHO):
open
close
read
write
fork
exec
waitpid
the first 4 allow you to both provide input to a program and get its output. (Remember on *nix like operating systems stdout is just another file handle as far as the OS is concerned).
The o... |
881,964 | 882,208 | Adding Blue Screen of Death to Non-Windows OS | I am looking to get into operating system kernel development and figured and have been reading books on operating systems (Tannenbaum) as well as studying how BSD and Linux have tackled this challenge but still am stuck on several concepts.
If I wanted to mimic the Windows Blue Screen of Death on an operating system, ... | I'm not exactly sure where to look in the source but you might want to look into ReactOS, an open source Windows clone which has BSOD already.
|
881,966 | 881,971 | Constructor access rules | if I compile (under G++) and run the following code it prints "Foo::Foo(int)". However after making copy constructor and assignment operators private, it fails to compile with the following error: "error: ‘Foo::Foo(const Foo&)’ is private". How comes it needs a copy constructor if it only calls standard constructor at ... | The copy constructor is used here:
Foo f = Foo(3);
This is equivalent to:
Foo f( Foo(3) );
where the first set of parens a re a call to the copy constructor. You can avoid this by saying:
Foo f(3);
Note that the compiler may choose to optimise away the copy constructor call, but the copy constructor must still be av... |
881,974 | 882,247 | False Alarm: SqlCommand, SqlParameter and single quotes | I'm trying to fix single quote bug in the code:
std::string Index;
connection->Open();
String^ sTableName = gcnew String(TableName.c_str());
String^ insertstring = String::Format("INSERT INTO {0} (idx, rec, date) VALUES (@idx, @rec, getdate())", sTableName);
SqlCommand^ command = gcnew SqlCommand(insertstring, conn... | I suspect the problem is either a quote getting in your table name, or that idx sounds more like the name of a number type than a character type.
Based on your update, I suggest you check for extra constraints on the table in management studio.
|
882,249 | 882,279 | Is it legal to switch on a constant in C++? | I was just made aware of a bug I introduced, the thing that surprised me is that it compiled, is it legal to switch on a constant?
Visual Studio 8 and Comeau both accept it (with no warnings).
switch(42) { // simplified version, this wasn't a literal in real life
case 1:
std::cout << "This is of course, i... | It's not impossible that switching on a constant makes sense. Consider:
void f( const int x ) {
switch( x ) {
...
}
}
Switching on a literal constant would rarely make sense, however. But it is legal.
Edit: Thinking about it, there is case where switching on a literal makes
perfect sense:
int main() {
... |
882,478 | 882,587 | C++ Partial Specialization ( Function Pointers ) | Can any one please tell, whether below is legal c++ or not ?
template < typename s , s & (*fn) ( s * ) >
class c {};
// partial specialization
template < typename s , s & (*fn) ( s * ) >
class c < s*, s* & (*fn)(s**) {};
g++ ( 4.2.4) error: a function call
cannot appear in a constant-expression
error: templat... | I think you mean
template < typename s , s & (*fn) ( s * ) >
class c {};
// partial specialization
template < typename s , s & (*fn) ( s * ) >
class c < s*, fn > {};
|
882,764 | 890,318 | Embedding Rake in a C++ app? Or is there a Lake for LUA? | I've found a couple of questions about embedding Ruby in a C++ app. Almost all of the top-voted answers suggest using Lua instead.
Given that a project I have in mind would be better served by the grammar already expressed in Rake (it's a rules engine), is there any easy way to embed Rake in a C++ app, or is there a Ra... | There are a number of build systems that can use Lua, based strongly on Lua or even implemented in Lua. Some of them are listed at the Lua User's Wiki.
Of the ones listed at the wiki, Bou was explicitly inspired by Rake. Its author observed that the name "lake" was already in use for another build system at the time th... |
882,855 | 883,002 | What is the difference between iterators in Java and C++? | How is the implementation of Iterator in Java different from that in C++?
| In the current C++ (98) standard library (in particular the portion formerly known as STL) defines a form of iterators that are very close to C pointers (including arithmetic). As such they just point somewhere. To be useful, you generally need two pointers so that you can iterate between them. I understand C++0x intro... |
883,109 | 885,296 | What are C++ non-template members as used in the Barton-Nackman trick? | From wikipedia:
// A class template to express an equality comparison interface.
template<typename T> class equal_comparable
{
friend bool operator==(T const &a, T const &b) { return a.equal_to(b); }
friend bool operator!=(T const &a, T const &b) { return !a.equal_to(b); }
};
class value_type
// Class value_t... | The rules of the language have changed since the pattern was invented, although care was taken not to break it. In other words, as far as I can tell, it still works but for different reasons than it originally did. I don't think I would base an attempt at dimensional analysis on this pattern as I think there are better... |
883,156 | 883,372 | tidy code for asynchronous IO | Whilst asynchronous IO (non-blocking descriptors with select/poll/epoll/kqueue etc) is not the most documented thing on the web, there are a handful of good examples.
However, all these examples, having determined the handles that are returned by the call, just have a 'do_some_io(fd)' stub. They don't really explain h... | I suggest take a look on: http://www.kegel.com/c10k.html, second take a look on existing libraries like libevent, Boost.Asio that already do the job and see how they work.
The point is that the approach may be different for each type of system call:
select is simple reactor
epoll have both edge or level triggered inte... |
883,332 | 883,441 | "CruiseControl" Automation for C++ projects? | We've got a C++ Project that currently uses Make on Linux to build. I'd like to automate it similar to a Java Project under CruiseControl.
1) Is there a project similar to CruiseControl for C++ projects?
OR
2) Is there a good "how-to" on using CruiseControl for C++ Projects?
| I've been looking at setting up CruiseControl for C++ projects on Linux but came across Hudson. It has a one file/one command line setup and you're up and running. The management access is via nice web interface. I highly recommend it.
Hudson compared to CC seems easier to setup and manage plus you have access to build... |
883,536 | 884,739 | How to get the minimize and maximize buttons to appear on a wxDialog object | I've run into an issue using a wxDialog object on Linux In the construtor for the object I pass the relevant style flags (wxCAPTION|wxMINIMIZE_BOX|wxMAXIMIZE_BOX|wxCLOSE_BOX|wx_RESIZE_BORDER) but the buttons don't show up. When I was designing the class in wxformbuilder they would appear on the displayed design but d... | If you create a dialog on wxGTK then during construction
gtk_window_set_type_hint(GTK_WINDOW(m_widget), GDK_WINDOW_TYPE_HINT_DIALOG);
is called, which leaves it up to the window manager what decoration is shown for this window. So if you give it the style but no buttons are shown, then there's nothing you can do. In a... |
883,632 | 883,671 | How do I pass a Generic::List by reference? | In an attempt to wrap some unmanaged code in a managed .dll I'm trying to convert a Generic::List of data points into a std::vector. Here's a snippet of what I'm trying to do:
namespace ManagedDLL
{
public ref class CppClass
{
void ListToStdVec( const List<double>& input_list, std::vector<double>& outpu... | As List<T> is a managed .NET class, it's passed by managed GC-Handle denoted by ^ and not by C++-reference.
Ex:
void ListToVec(List<double>^ input_list, std::vector<double>& out)
You don't need additional const here. The notation List<T>^% creates a tracking reference (comparable to C++-pointers) rather than a call by... |
883,644 | 883,764 | Educational IDE to start programming in C++? | I'am aware there has been a generic question about a "best IDE in C++" but I would like to stress I'm a new to C++ and programming in general. This means I have the needs of a student:
relatively easy and unbloated working environment
things just work, focus on the code
color coding to show the different language fea... | If you are using both windows and linux (as your comment indicates), I'd recommend Qt Creator. Qt is cross platform so your apps will work on linux, windows, and mac. Qt has excellent documentation, too, so it's very newbie friendly. Signals and Slots take a bit of getting used to, but IMO it's worth it.
|
883,682 | 883,801 | Why is this C++ class not equivalent to this template? | Can somebody explain to me why the following works:
template<class T> class MyTemplateClass {
public:
T * ptr;
};
int main(int argc, char** argv) {
MyTemplateClass<double[5]> a;
a.ptr = new double[10][5];
a.ptr[2][3] = 7;
printf("%g\n", a.ptr[2][3]);
return 0;
}
But this doesn't:
class MyClass... | The difference lies in the C++ grammar. A simple-declaration is formed like this:
declaration-specifier-seq init-declarator-list
Where declaration-specifier-seq is a sequence of declaration specifiers:
simple-type-specifier: int, bool, unsigned, typedef-name, class-name ...
class-specifiers: class X { ... }
type-quali... |
883,999 | 884,006 | Why does g++ complain when using templated typedefs in graph_traits<>? | When I try to compile this code:
struct BasicVertexProperties
{
Vect3Df position;
};
struct BasicEdgeProperties
{
};
template < typename VERTEXPROPERTIES, typename EDGEPROPERTIES >
class Graph
{
typedef adjacency_list<
setS, // disallow parallel edges
vecS, // vertex container
bidirect... | These lines:
typedef graph_traits<GraphContainer>::vertex_descriptor Vertex;
typedef graph_traits<GraphContainer>::edge_descriptor Edge;
should be:
typedef typename graph_traits<GraphContainer>::vertex_descriptor Vertex;
typedef typename graph_traits<GraphContainer>::edge_descriptor Edge;
The reason b... |
884,435 | 884,473 | Pass variables between C++ and Lua via Swig | I'm working on a C++ project with a large number of classes (150+), each of which has anywhere from 10 to 300 fields or so. I would really like to be able to provide a scripting interface for testing purposes so that I can code callbacks that don't require any re-compilation. I'd like to do this in Lua since I'm more f... | As long as you wrap your user-defined types using Swig interfaces (see here for documentation on Swig-Lua API), the interaction should be seamless. The provided Swig wrappers will allow you to instantiate new objects, pass them along to C++ and vice-versa.
I do not believe that Swig-Lua wrapping supports director class... |
885,069 | 885,207 | Where can I find documentation for publishing data to perfmon in C++? | Years ago I wrote some code to "publish" data for perfmon to consume. Using those counters is pretty well documented, but I found it challenging to find (at the time) good documentation and sample code to publish the data for perfmon.
Does anyone know where I can get this documentation? I also seem to recall some class... | You're bringing back old memories!
From 1998, Jeffrey Richter wrote an article in Microsoft Systems Journal describing how to create your own perfmon counters, its very easy (after cutting and pasting his template code just add shared-memory variables in a dll, and update them as needed).
|
885,136 | 885,163 | Members vs method arguments access in C++ | Can I have a method which takes arguments that are denoted with the same names as the members of the holding class? I tried to use this:
class Foo {
public:
int x, y;
void set_values(int x, int y)
{
x = x;
y = y;
};
};
... ... | It's generally a good idea to avoid this kind of confusion by using a naming convention for member variables. For example, camelCaseWithUnderScore_ is quite common. That way you would end up with x_ = x;, which is still a bit funny to read out loud, but is fairly unambiguous on the screen.
If you absolutely need to h... |
885,166 | 904,084 | postgresql libpq inserting empty row for no reason | I'm using the libpq library in C for accessing my Postgresql database. The application inserts a piece of data fed from a queue. When there is a lot of data and it's inserting very quickly it randomly inserts and empty row into the table. Before I even perform the insert I check to make sure that the length of the text... | See Milen A. Radev's comment. It should have been an answer. You should not allow empty rows.
Surely at least one column can have a constraint that would cause the insert to fail. Then your app can print/log the error with enough diagnostics for you to figure out what's going on, and under what conditions.
Without ret... |
885,609 | 886,756 | how to best deal with a bunch of references in a class | I have a class that references a bunch of other classes. I want to be able to add these references incrementally (i.e. not all at the same time on the constructor), and I want to disallow the ability to delete the object underlying these references from my class, also I want to test for NULL-ness on these references s... | I agree with other comments that you should use boost::shared_ptr.
However if you don't want the class holding these references to part-control the lifetime of the objects it references you should consider using boost::weak_ptr to hold the references then turn this into a shared_ptr when you want to us it. This will... |
885,623 | 885,645 | Get window handle of last activated window | I am developing an application that sits in the system tray and can perform actions on the active window. But when the icon in the system tray is clicked, GetForegroundWindow() returns the taskbar. I need to get the window that was active before the taskbar was.
I've tried enumerating the desktop window with EnumWindow... | I think the only way to get that info is by installing a system wide hook (SetWindowsHookEx) on WH_CALLWNDPROC and capturing all WM_ACTIVATEAPP. This will even enable you to track the full history of which window was active when.
|
885,711 | 885,714 | Are there any good custom allocators for C++ that maximize locality of reference? | I am running a simulation with a lot if bunch of initial memory allocations per object. The simulation has to run as quickly as possible, but the speed of allocation is not important. I am not concerned with deallocation.
Ideally, the allocator will place everything in a contiguous block of memory. (I think this is ... | Just make your own.
See an old question of mine to see how you can start:
Improvements for this C++ stack allocator?
|
885,819 | 885,981 | "Fun" C++ library that interprets ASCII figures in code - what is it called? ("Multi-Dimensional Analog Literals") | A while ago I stumbled upon a C++ gem, a set of classes that through operator overloading and possibly some preprocessor tricks, let you define variables using in-code ASCII art:
Line x = |-----|; //x is 5
Line y = |---|; //y is 3
Rectangle r = +---+
| |
+---+; //r is 3 by 1
and ... | I believe you are after Multi-Dimensional Analog Literals
http://www.eelis.net/C++/analogliterals.xhtml
|
885,908 | 885,951 | while (1) Vs. for (;;) Is there a speed difference? | Long version...
A co-worker asserted today after seeing my use of while (1) in a Perl script that for (;;) is faster. I argued that they should be the same hoping that the interpreter would optimize out any differences. I set up a script that would run 1,000,000,000 for loop iterations and the same number of while loo... | In perl, they result in the same opcodes:
$ perl -MO=Concise -e 'for(;;) { print "foo\n" }'
a <@> leave[1 ref] vKP/REFC ->(end)
1 <0> enter ->2
2 <;> nextstate(main 2 -e:1) v ->3
9 <2> leaveloop vK/2 ->a
3 <{> enterloop(next->8 last->9 redo->4) v ->4
- <@> lineseq vK ->9
4 <;> nexts... |
886,076 | 886,112 | How can I intercept all key events, including ctrl+alt+del and ctrl+tab? | I'm writing a screen saver type app that needs to stop the user from accessing the system without typing a password. I want to catch/supress the various methods a user might try to exit the application, but all research I do seems to point me to "you can't".
Anything in C# or C++ would be great.
I've thought of disab... | To add to what Shog9 said, if your application could intercept ctrl+alt+del, then your application would be able to pretend to be the Windows Login dialog, and by doing so trick the end-user into typing their credentials into your application.
If you do want to replace the Windows Login dialog, see Winlogon and GINA (b... |
886,178 | 886,203 | Merging 8 sorted lists in c++, which algorithm should I use | I have 8 sorted lists that I need to merge into 1 sorted list. I don't know the best way to do this. I was thinking of the following:
void merge_lists_inplace(list<int>& l1, const list<int>& l2)
{
list<int>::iterator end_it = l1.end();
--end_it;
copy(l2.begin(), l2.end(), back_inserter(l1));
++end_it;
... | A simple extension of merge sort's merge phase can do this in O(n lg m) time (where n = total number of items and m = number of lists), using a priority queue (eg, a heap). Pseudocode:
Let P = a priority queue of the sorted lists, sorted by the smallest element in each list
Let O = an empty output list
While P is not e... |
886,206 | 886,337 | Out of declaration template definitions for template method in template class | Does anyone know the syntax for an out-of-declaration template method in a template class.
for instance:
template<class TYPE>
class thing
{
public :
void do_very_little();
template<class INNER_TYPE>
INNER_TYPE do_stuff();
};
The first method is defined:
template<class TYPE>
void thing<TYPE>::do_very_little()
{
... | template<class TYPE>
template<class INNER_TYPE>
INNER_TYPE thing<TYPE>::do_stuff()
{
return INNER_TYPE();
}
See this page:
http://msdn.microsoft.com/en-us/library/swta9c6e(VS.80).aspx
|
886,296 | 886,310 | C++: When is it acceptable to have code in the header file? | I've been taught to keep class definitions and code separate.
However, I've seen situations where people would often include some bits of code in the header, e.g. simple access methods which returns a reference of a variable.
Where do you draw the line?
| Generally speaking, things you want the compiler to inline, or templated code. In either case, the code must be available to the compiler everywhere it's used, so you have no choice.
However, note that the more code you put in a header file, the longer it will take to compile - and the more often you'll end up touching... |
886,683 | 886,693 | How does using arrays in C++ result in security problems | I was told that the optimal way to program in C++ is to use STL and string rather than arrays and character arrays.
i.e.,
vector<int> myInt;
rather than
int myInt[20]
However, I don't understand the rational behind why it would result in security problems.
| I suggest you read up on buffer overruns, then. It's much more likely that a programmer creates or risks buffer overruns when using raw arrays, since they give you less protection and don't offer an API. Sure, it's possible to shoot yourself in the foot using STL too, but at least it's harder.
|
886,703 | 886,740 | Will adding data members (at the end) of an exportable struct cause problems? | An exportable function has a struct as a one of the parameters. This DLL is used by many Exes
One of the EXEs needs to send some additional data, so we have added one member at the end of the struct and distributed the DLL.
Now my question is, if we put the new DLL in other EXEs which are not aware of the extra member,... | If other functions accept the struct by value, i.e. not by taking a pointer to it, then yes, there very likely will be problems. Your calling code will place a larger struct on the stack than the receiving function will remove, causing net stack growth and general badness.
|
886,729 | 886,774 | How to best convert VARIANT_BOOL to C++ bool? | When using COM boolean values are to be passed as VARIANT_BOOL which is declared in wtypes.h as short. There are also predefined values for true and false:
#define VARIANT_TRUE ((VARIANT_BOOL)-1)
#define VARIANT_FALSE ((VARIANT_BOOL)0)
Which is the best way to convert from VARIANT_BOOL to C++ bool type? Obvious varian... | Compare to VARIANT_FALSE. There is a lot of buggy code out there that mistakenly passes in the C++ bool true value (cast to the integer value 1) to a function expecting VARIANT_BOOL. If you compare to VARIANT_FALSE, you will still get the correct expected value.
|
887,163 | 887,324 | Integrating external applications with my applications | I have 2 desktop applications that I wish to integrate with external applications. One of the applications is extended with plugins which are developed by me, to provide specific features which are not common for all distributions. The situation can be described in the following diagram:
alt text http://img32.imageshac... | I agree with the commenter, COM seems like a good strategy.
Your support dlls get registered when they are installed, then your core app can look for plugins, something like:
hr = CLSIDFromProgID(L"Wakko.1.0", &clsid);
hr = GetActiveObject(clsid, NULL, &punk);
or
hr = CoCreateInstance(clsid, ...,..., IID_IWAKKO, .... |
887,509 | 887,558 | When to use -O2 flag for gcc? | If I use "-O2" flag, the performance improves, but the compilation time gets longer.
How can I decide, whether to use it or not?
Maybe O2 makes the most difference in some certain types of code (e.g. math calculations?), and I should use it only for those parts of the project?
EDIT: I want to emphasize the fact that ... | I would recommend using -O2 most of the time, benefits include:
Usually reduces size of generated code (unlike -O3).
More warnings (some warnings require analysis that is only done during optimization)
Often measurably improved performance (which may not matter).
If release-level code will have optimization enabled, ... |
887,524 | 887,541 | convert pointer to shared_ptr | I have some library code (I cannot not change the source code) that returns a pointer to an object (B). I would like to store this pointer as shared_ptr under a class with this type of constructor:
class A
{
public:
A(boost::shared_ptr<B> val);
...
private:
boost::shared_ptr<B> _val;
...
};
int main()... | As you say, you have to copy them not just copy a pointer. So either B already has implemented 'clone' method or you have to implement some external B* copy(B* b) which will create new B with same state.
In case B has implemented copy constructor you can implement copy as just
B* copyOf(B* b)
{
return new B(*b);
}... |
887,689 | 887,700 | Write a circular file in c++ | I need to write a circular file in c++. The program has to write lines in a file and when the code reaches a maximum number of lines, it must overwrite the lines in the beginning of the file.
Anyone have any idea?
| Unfortunately you can't truncate/overwrite lines at the beginning of a file without rewriting the entire thing.
New Suggestion
I've just thought of a new approach that might do the trick for you...
You could include a small header to your file that has the following structure.
Edit: Rubbish, I've just described a varia... |
887,966 | 887,992 | Is there a handy way of finding largest element in container using STL? | Is there a way finding largest container inside a container using STL? ATM, I have this
rather naïve way of doing it:
int main()
{
std::vector<std::vector<int> > v;
...
unsigned int h = 0;
for (std::vector<std::vector<int> >::iterator i = v.begin(); i != v.end(); ++i) {
... | You can always use std::max_element and pass a custom comparator that compares the size of two std::vector<int> as arguments.
|
888,085 | 995,596 | How to add files to Eclipse CDT project with CMake? | I'm having problem getting the source and header files added into my Eclipse CDT project with CMake. In my test project (which generates and builds fine) I have the following CMakeLists.txt:
cmake_minimum_required(VERSION 2.6)
project(WINCA)
file(GLOB WINCA_SRC_BASE "${WINCA_SOURCE_DIR}/src/*.cpp")
file(GLOB WINCA_SR... | The problem I had was I made an "in-source" build instead of an "out-of-source" build. Now it works fine, and it was actually lots of info on this on the Wiki but somehow I misunderstood it.
|
888,235 | 888,313 | Overriding a Base's Overloaded Function in C++ |
Possible Duplicate:
C++ overload resolution
I ran into a problem where after my class overrode a function of its base class, all of the overloaded versions of the functions were then hidden. Is this by design or am I just doing something wrong?
Ex.
class foo
{
public:
foo(void);
~foo(void);
virtual vo... | In class bar, add
using foo::a;
This is a common 'gotcha' in C++. Once a name match is found in the a class scope, it doesn't look further up the inheritance tree for overloads. By specifying the 'using' declaration, you bring all of the overloads of 'a' from 'foo' into the scope of 'bar'. Then overloading works pr... |
888,531 | 888,596 | Enumerate members of a structure? | Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to... | To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).
If you have control over your data structure, you could try a std::vector<boost::any> or a std::map<std::string, boost::any> then add all your member variables to the vector/map.
Of course, th... |
888,611 | 888,637 | Is it possible to use a custom class in place of std::pair in an STL map? | Is this possible?
#include <map>
class Example {
private:
std::map<std::string, std::string, less<std::string>,
std::allocator< CustomPair<std::string, std::string> > > myMap;
};
In the example above, CustomPair would be a template class holding a key and value. If this is possible, is it that simple or is t... | One can only speculate what your real intent is here, so I assume you already have a class that contains both key and value. In that case std::set with a custom comparison may be a better choice than a std::map.
You then need to provide a comparison that will only compare the key part of your class and the key part mus... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.