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,089,545 | 2,089,572 | Fine to have variables in a namespace? | I have a set of functions that work on a file. Originally I made it into a class, with the only private member being a static const std::string which was the name of the file. The user used these functions by creating an object and calling functions from it. However, I think I'm going to switch to using a namespace, si... | You can do similar things but they will have different semantics.
In a class, a static variable is a declaration, not a definition, it still requires a definition outside of the class; a variable declaration in a namespace is a definition unless you mark in as extern and don't provide an initializer.
In your case it do... |
2,089,619 | 2,089,900 | How do you create a freestanding C++ program? | I'm just wondering how you create a freestanding program in C++?
Edit: By freestanding I mean a program that doesn't run in a hosted envrioment (eg. OS). I want my program to be the first program the computer loads, instead of the OS.
| Have a look at this article:
http://www.codeproject.com/KB/tips/boot-loader.aspx
You would need a little assembly start-up code to get you as far as main() but then you could write the rest in C++. You'd have to write your own heap manager (new/delete) if you wanted to create objects at runtime and your own scheduler i... |
2,090,021 | 2,090,198 | Interview test for applied scientific computing job | Do you know a good and objective question/test to examine applicants for a scientific computing job?
(In fact, this test comes after the candidate passed an interview.)
1st) They need to be intelligent. (Edit, thanks for the words from Trent)
2nd) They would have to deal mostly with programming (C++ and Python, using s... | Well, an easy problem is to ask someone to solve a simple ODE system using whatever libraries they wish to use. None of the libraries that I know of are straightforward enough that they can be learnt during the test. For example, solve this system for x=1:10: dx/dt = -k (x^2/x).
A tougher one is to ask someone to solv... |
2,090,392 | 2,090,407 | Are Constants Really Appropriate Here, Or Is There Another Approach? - C++ | I'm a programming student in my 2nd OOP course, which is taught in C++. I know that it is generally bad practice to use magic numbers in code, so here's my question:
In the next program I have to write for this class, there is over 120 numbers given to us in tax tables, and we need to use them to compute tax and other ... | Constants would be more appropriate than magic numbers -
However, with that many "constants", and something that changes over time (tax tables), I personally would load these via a configuration file, and use some type of dictionary lookup for the individual values. This would make it much easier to adjust to new tax ... |
2,090,393 | 2,090,409 | Storage of a high score table, what kind of container? | Say I have a high score table structured like
name score
name score
....
I need to do some file operations and manipulate certain areas of the file, and I thought the best way to do this would be to store it in a container that preserved the order of the file, do the data manipulation with the container, then output b... | Use the
std::vector< std::pair< std::string, int > >
solution.
Or even better, do a HighScoreEntry class, and have a std::vector< HighScoreEntry > -- then you'll be able to add additional data to it later, and embed score handling code in the class.
To add an entry, push the entry to the end of the vector, and run std... |
2,090,442 | 2,090,698 | Producer/Consumer For Talking to Devices Serially | Here is my problem: I have to be able to send and receive to a device over serial. This has to be done in a multi-threaded fashion. The flow is as follows:
Wait for device to send me something - or if idle, then query status to see if online with device
If device sends me something, then process message, acknowledge, ... | What resources are you sharing that you think you need to synchronize?
If you have something like a queue in between the two threads then that is a pretty classic producer/consumer model. E.G. If you just have one thread reading and then putting commands in a queue while another thread extracts from the queue, process... |
2,090,619 | 2,090,796 | Dual purpose code commenting(users & maintainers)...HOW? | I am writing a C++ static library and I have been commenting with doxygen comments in the implementation files. I have never really had to care very much about documentation but I am working on something now that needs to be documented well for the users and also I am trying to replace my previous bad habit of just wa... | I generally believe that comments for users should not be inline in the code, as doxygen comments or anything like that. It should be a separate document, in prose form. As a user of the library, I don't need to, or want to, know what each parameter for a function means. Hopefully, that's obvious. I need to know what t... |
2,090,651 | 2,093,010 | DLL EXE Hybrid C++ Windows | I am currently working with DLL injection and need to have a single hybrid binary that could act as both an executable and a DLL. I thought of maybe writing a DllMain and WinMain function and then compiling it as an executable but I don't know what would happen if I did that. I know that it is posssible to combine a dl... | No.
Both a DLL and an EXE have a PE (Portable Executable) header. That header has a field IMAGE_FILE_HEADER::Characteristics. Bit 14 of that field is either 0 (for an EXE) or 1 (for a DLL).
|
2,090,661 | 2,090,700 | protected inheritance | Why protected and private inheritance are defined and proposed? I understand some cases private inheritance could be used but it is not recommended. How about protected inheritance?
Can anyone offer me an situation in which protected inheritance is a choice?
I rarely see this.
Thanks so much!
| Private inheritance is usually used for mixins---where people inherit to get functionality from the base class, rather than because of "is-a" inheritance.
Protected inheritance can also be used for mixins, where the mixed-in functionality is to be available to downstream classes too.
|
2,090,754 | 2,090,935 | What datatype to use for image data to avoid std:bad_alloc? | I'm developping an imaging library and I'm struggling with the image data datatype
Since images can have variable datatypes (8 bits per pixel, 16 bits per pixel) I thought of implementing my image data pointer to
void* pimage_data;
however void* leads to all kind of nastiness including ugly pointer arithmetics such a... | bad_alloc can mean you are out of free memory (since you say sizeof(CImage) == 28, you would most likely be doing it in a tight or infinite loop). It can also mean you have corrupted the freestore though previous naughty memory behavior and it just caught it on the next allocation/release cycle. A good debugging sessio... |
2,090,974 | 2,091,186 | How to separate CUDA code into multiple files | I am trying separate a CUDA program into two separate .cu files in effort to edge closer to writing a real app in C++. I have a simple little program that:
Allocates a memory on the host and the device.
Initializes the host array to a series of numbers.
Copies the host array to a device array
Finds the square of all t... | You are including mykernel.cu in kernelsupport.cu, when you try to link the compiler sees mykernel.cu twice. You'll have to create a header defining TestDevice and include that instead.
re comment:
Something like this should work
// MyKernel.h
#ifndef mykernel_h
#define mykernel_h
__global__ void TestDevice(int* device... |
2,091,136 | 2,092,136 | Unhandled exception: 0x80000001: Not implemented. (VC++) | I am using MS Visual Studio 2005 (C++)..
Could anyone tell me what could cause a runtime exception like so..?
Unhandled exception at 0x07ed0027 (xxx.dll) in yyy.exe: 0x80000001: Not implemented.
xxx.dll is a dll i am working on and yyy.exe is an exe that is calling that dll.. When the undhandled exception comes up wh... | Like the more familiar 0xC0000005, 0x80000001 is the code of an exception that's being raised. You can look them up in winnt.h. In this case, I've found #define STATUS_GUARD_PAGE_VIOLATION ((DWORD )0x80000001L)
Guard pages are used for stack growth. The first page after the top of the stack is marked as a guard ... |
2,091,426 | 2,091,633 | Why can't we create objects for an abstract class in C++? | I know it is not allowed in C++, but why? What if it was allowed, what would the problems be?
| Judging by your other question, it seems you don't understand how classes operate. Classes are a collection of functions which operate on data.
Functions themselves contain no memory in a class. The following class:
struct dumb_class
{
void foo(){}
void bar(){}
void baz(){}
// .. for all eternity
i... |
2,091,495 | 2,091,503 | Does new() allocate memory for the functions of a class also? | class Animal
{
public:
int a;
double d;
int f(){ return 25;}
};
Suppose for the code above, I try to initialize an object, by saying new Animal(), does this new() also allocate memory for the function f()?
In other words, what is the difference in memory allocation terms if I had this class instead and did a ne... | No. Functions exist in the text page and so no space is allocated for them.
|
2,091,499 | 2,091,505 | Why are global and static variables initialized to their default values? | In C/C++, why are globals and static variables initialized to default values?
Why not leave it with just garbage values? Are there any special
reasons for this?
|
Security: leaving memory alone would leak information from other processes or the kernel.
Efficiency: the values are useless until initialized to something, and it's more efficient to zero them in a block with unrolled loops. The OS can even zero freelist pages when the system is otherwise idle, rather than when some ... |
2,091,500 | 2,091,581 | Maintaining a std::set<boost::shared_ptr> | I'm writing a game and an accompanying engine in C++. The engine relies heavily on automation using a simple embedded scripting language. Scripts can create object classes, define event listeners on them, and produce instances from them. At present, an instance must be bound to a script-global identifier in order to pr... | You could add a static method to Instance that you then use to create new objects and that also does the administrative stuff like adding it to the set:
static Instance* create(int something) {
boost::shared_ptr<Instance> sptr(new Instance(something));
instanceset.insert(sptr);
return sptr.get();
}
If you want t... |
2,091,717 | 2,092,936 | Basic C++ program crashes VS 2008 | I'm following this tutorial on wrapping a .lib in a C++ DLL.
Right after I use the VS wizard to generate a Win32 DLL project, everything compiles just fine.
Then, following the tutorial, I substitute this VS-generated code:
DEMODLL_API int fnDemoDll(void)
{
return 42;
}
for this code:
DEMODLL_API int fnDemoDll(int... | The exact code is probably irrelevant. It's the IDE, not the compiler that crashes. Can you start the build in another way?
|
2,091,788 | 2,091,811 | How to make a PInvoke friendly native-API? | How to make a native API to be PInvoke friendly?
there are some tips on how to modify native-programs to be used with P/Invoke here. But before I even write a native programs, what are the things I should look out to make my programs/library PInvoke friendly?
using C or C++ are fine.
update:
if I write a C API, what a... | By definition every native function can be p/invoked from managed code. But in order to be p/invoke friendly a function should have as few parameters as possible which should be of native types (int, char*, float, ...). Also if a function allocates memory on some pointer that is returned to managed code, make sure you ... |
2,091,813 | 2,102,976 | Embedded Assembly Files in Visual Studio | I'll make this short and to the point. The _asm block has been completely stripped when creating 64 bit code in Visual Studio. My question is, where can I find some information on how to use assembly in some code that I can call from my project. Like an assembly file I suppose that has some "optimized" function in whic... | One approach is to write a C template for your assembler function, then use /FAs to generate assembler source for that function template. You should then be able to use the generated assembler source in place of the C template source and build from there. That way you take care of all the messy error-prone ABI stuff au... |
2,091,824 | 2,092,679 | C++ syntax to call templated inner class static member function? | I have some template code which compiles fine in VC9 (Microsoft Visual C++ 2008) but won't compile in GCC 4.2 (on Mac). I'm wondering if there's some syntactical magic that I'm missing.
Below I have a stripped-down example which demonstrates my error. Sorry if this example seems meaningless, I removed as much as I co... | Having use both Visual Studio and gcc, it's a known issue :) And I used VS2003 and gcc 3.4.2 so it's been like that for a while.
If I remember correctly, the problem is due to the way templates are parsed on these compilers.
gcc behaves as stated by the standard, and performs 2 parses:
the first when encountering the ... |
2,091,833 | 2,091,877 | C++: making shallow copy of an object a) syntax b) do i need to delete it | I have a class MyClassA. In its constructur, I am passing the pointer to instance of class B. I have some very basic questions related to this.
(1) First thing , is the following code correct? ( the code that makes a shallow copy and the code in methodA())
MyClassA::MyClassA(B *b){
this.b = b;
}
void MyClassA::me... | 1)
this.b = b;
Here you pass a pointer to an instance of B. As Mac notes, this should be:
this->b = b;
b.getFooValue();
This should be b->getFooValue(), because MyClassA::b is a pointer to B.
2) This depends of how you define what MyClassA::b is. If you specify (in code comments) that MyClassA takes over ownership... |
2,092,045 | 2,092,686 | Creating Java object with boost::posix_time::ptime serialized XML representation | I have following XML generated by serializing a boost::posix_time::ptime structure. I want to create a Java Date object with this XML.
<timeStamp class_id="0" tracking_level="0" version="0">
<ptime_date class_id="1" tracking_level="0" version="0">
<date>20100119</date>
</ptime_date>
<ptime_time_dura... | As you don't want to use a String (though I urge you to reconsider, after all that's what it is and easier to parse too), I guess you can do regular old division to extract parts. i.e.
int tmp = date; // unboxing
int year = tmp / 10000;
int month = (tmp % 10000) / 100;
int day = tmp % 100;
That's not very elegant eith... |
2,092,141 | 2,092,224 | PDB file from different versions of Visual Studio | I have an old DLL file which was built with VC++ 6. Now I need to investigate the dump file but I don't have its PDB available. The stacktrace reported by WinDbg is also inaccurate.
Is it possible to rebuild the project with later versions of Visual Studio i.e. 2003, 2005, 2008, have the PDB generated, and use this to... | I'm afraid I think the answer is no: you'll need to try and rebuild it with the same tool-chain exactly as the binary that generated the dump file you have.
VS is really fussy about how it matches dump files to pdb files in my experience: the only luck I've ever had in these situations is with WinDbg (but you've trie... |
2,092,244 | 2,092,293 | g++ and file read, weird behaviour with Xcode/Snow Leopard | I am writing a program that reads a file, whose first two lines are:
Field of space: 0.4
226981 20
Then I want to pass 226981 and 20 to integer variables. So I do:
ifstream vfile(file_name, ios::in);
vfile.getline(header,FILENAME); // Read the header-line
vfile >> nTot >> file_size;
If I compile the p... | This might be the _GLIBCXX_DEBUG issue - make sure you have the latest Xcode installed, that _GLIBCXX_DEBUG is set the same for all your code and libraries, and you might also want to check the xcode-users mailing list.
|
2,092,283 | 2,092,419 | How functions are resolved by compiler? | How it is determined whether the below call is bound at compile time or at runtime?
object.member_fn;//object is either base class or derived class object
p->member_fn;//p is either base class or derived class pointer
EDITED:
#include <iostream>
using namespace std;
class Base
{
public:
Base(){ cout<<... | If the method is not virtual, both calls will be resolved at compile time. If the method is virtual then the first call in your question (obj.method()) will be resolved at compile time for an object, but at runtime for a reference. The second call (objp->method()) will be resolved at runtime. You can also force at comp... |
2,092,378 | 2,164,689 | MacOSX: How to collect dependencies into a local bundle? | I am creating a plugin application (dylib) that depends on several other libraries. These other libraries are installed on my system, but are not guaranteed to be installed on any user's system. So I need to find a way bundle the dependencies along with my application.
I found that I can use otool to list or change the... | Use relative paths in your dylib using install_name_tool. That way you can set them once, and install that directory anywhere without needing to modify your libraries at install time.
You should place all of your dylib dependencies into one folder, then use install_name_tool to set the relative location of the other d... |
2,092,640 | 2,092,670 | What's the difference between ON_NOTIFY, ON_CONTROL, ON_CONTROL_REFLECT? | I always struggle to keep all these macros straight in my head. Is there an easy way to remember them, and which to use in a given scenario?
Specifically, does one of these allow a dialog to intercept/detect messages to child control windows? e.g Can the dialog register an interest when IDC_MY_CONTROL gets a WM_PAINT m... | ON_NOTIFY handles WM_NOTIFY messages. ON_CONTROL handles WM_COMMAND messages from controls. ON_CONTROL_REFLECT is for handling messages sent to a parent from the child class.
|
2,092,728 | 2,092,755 | Find address of variables in main? | Recently while surfing some C++ blogs, I came across a small C teaser program in one of them.
#include<stdio.h>
int find_addr()
{
/*fill your code here*/
}
int main()
{
int i,j;
clrscr();
find_addr();
return 0;
}
The question is to find the address of variables i & j without touching the main function. I haven't bee... | I think I found where you read the puzzles. Most of the programs use typeless main(), or worse, void main(). They assume a lot of system- and/or compiler-specific things. The programs on the page are not very good quality, and make for a bad tutorial. Please stay away from it.
For example, this is the first program... |
2,093,039 | 2,093,097 | Math question in regards to functions in the form (1) / ( b ^ c ) | I've found functions which follow the pattern of 1 / bc produce nice curves which can be coupled with interpolation functions really nicely.
The way I use the function is by treating 'c' as the changing value, i.e. the interpolation value between 0 and 1, while varying b for 'sharpness'. I use it to work out an interpo... | For interpolation the approach offering the most flexibility is using splines, in your case quadratic splines would seem sufficient. The wikipedia page is math heavy, but you can find adapted desciptions on google.
|
2,093,057 | 2,093,065 | Using wmemset in c++ | While using wmemset api (http://msdn.microsoft.com/en-us/library/1fdeehz6(VS.80).aspx) for the count parameter should I have to multiply the length of the target string by 2 and provide or will wmemset will itself take care of the conversion?
| The answer is no. They have an example on the page you linked to:
#include <wchar.h>
#include <stdio.h>
int main( void )
{
wchar_t buffer[] = L"This is a test of the wmemset function";
wprintf( L"Before: %s\n", buffer );
wmemset( buffer, '*', 4 );
wprintf( L"After: %s\n", buffer );
}
Output:
Before... |
2,093,175 | 2,093,225 | Using a STL container to store Treeview data | i'm looking for a C++ STL container class to keep the treeview parent/child node strings but when a node is deleted from tree control, do i have iterate through all the container class elements to find that selected one and then delete it? what's the best to keep the data updated in container?
| use STL set, which is efficient in operations like insert and delete in O(log n) time.
e.g.
set<TreeNode> a;
a.insert(aTreeNode); // insert
a.erase(aTreeNode); // delete
|
2,093,212 | 2,093,265 | Using templates to make items of varying length stay on stack? | The situation is that I have an array of items, and the items have an array inside. However, I want to make the array inside of variable length at declaration time, yet resizable at compile time.
So I would want something like:
class2<16>[] = new class2<16>[2048*1024];
Or whatever. Hopefully you get the idea.
Obviousl... | You can create a template parameter for your internal array-size. For example:-
template<int siz>
class Item{
int arr[siz];
};
int main() {
Item<15> items[10];
return 0;
}
|
2,093,409 | 2,096,440 | How to insert data into a TdxMemData in Borland Builder | I'm struggling to insert data into a TdxMemData which is linked to a grid by a TDataSourse.
The MemData -called PurchaseData- has 3 columns: Date (date), Place (string) and Value (currency).
I have a button that does the following:
PurchaseData->Insert();
PurchaseData->FieldByName("Date")->Value = TDateTime::CurrentDat... | I had mapped the event OnSelectionChanged of the grid and read the data in the newly selected row. Unfortunately when PurchaseData->Insert() is called, the SelectionChanged event is fired right away. before the new row's data is set by the next lines. I got Null from the data read and did Bad Things with it like settin... |
2,093,467 | 2,097,548 | Treeview selected item index | is there anyway to get the index of selected tree view node or do they even have one?
| Since you're asking for "index" only to be able to find data associated with this item you should know that tree control can hold your data. Every item (TVITEM struct) has a lParam member that you can use for this.
If you really need a container do as avakar suggested. Use HTREEITEM as key.
|
2,093,672 | 2,093,706 | Can I prevent object assignment? | I want to ensure that the following type of call is illegal:
MyClass me;
MyClass you;
me = you; // how to make this illegal?
Is it possible?
| Declare the assignment operator private:
class A {
private:
void operator=(const A&);
...
};
but don't provide an implementation - you will get a compile or link-time error if you try to perform an assignment to A.
I prefer to use a macro to do this. This also prevents copying, by making the copy constructo... |
2,093,740 | 2,093,815 | My wxFrame has a small thin 1 px border around it even though I asked for no border. Why? | Using wxwidgets. I want a window without a border. I pass the follwoing flags to the frame wxFRAME_NO_TASKBAR | wxSTAY_ON_TOP but it still draws a black outline 1 px wide around the window. Is this a bug or something?
| You must also set wxBORDER_NONE.
|
2,094,032 | 2,100,744 | Configure .NET-Based Components for Registration-Free Activation | I've been trying to get a registration-free .NET based COM DLL to work, but without success.
In Visual Studio 2008 I added a new C# class library.
I enabled the 'make assembly COM-visible' and 'register for COM interop' options.
I added a public interface and class with some functions.
I added a manifest dependency to... | I found the steps needed to get registration-free .NET COM interop working myself :-)
Run: mt -managedassemblyname:"myDll.dll" -out:"myDll.manifest"
Clean manifest (see format at http://msdn.microsoft.com/en-us/library/eew13bza.aspx). Mainly I needed to remove all tags except for assemblyIdentity, clrClass and file (a... |
2,094,072 | 2,094,214 | Nested unnamed namespace? | When using an unnamed namespace are there any issues if it is nested within another namespace? For example, is there any real difference between Foo1.cpp and Foo2.cpp in the following code:
// Foo.h
namespace Foo
{
void fooFunc();
}
// Foo1.cpp
namespace Foo
{
namespace
{
void privateFunction()
... | Unnamed namespace could be considered as a normal namespace with unique name which you do not know. According to C++ Standard 7.3.1.1:
An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
where all ... |
2,094,154 | 2,094,300 | referenced argument to a function with default value in C++ |
Possible Duplicate:
Default value to a parameter while passing by reference in C++
Is it possible to do something like this:
// definition
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble = 0.0);
Then the function can be called either like this:
MyFun(nMyInt, szMyChar, nMyReferencedDouble);
or li... | You could overload the function instead.
// Definition
bool MyFun(int nMyInt, char* szMyChar, double& nMyReferencedDouble);
// Overload
bool MyFun(int nMyInt, char* szMyChar)
{
double nMyReferencedDouble = 0.0;
MyFun( nMyInt, szMyChar, nMyReferencedDouble );
}
This is how you get around the current limitation... |
2,094,253 | 2,102,708 | Editing PDF with XPDF (or with something else) | I would like to ask if it is possible to edit PDF files using the xpdf library and if yes how? I guess this is possible but i could not find any tutorial nor documentation for xpdf so i have realy no idea :( . I'm also open for using another library if any other has support for pdf editing. My only requirement for such... | Just so you understand the scope of what you're getting into, "basic editing" of PDF content is nearly always non-trivial.
Page content in PDF is represented by short RPN programs that paint on the page. It's a small language similar to PostScript in semantics, but without looping structures or function definitions (s... |
2,094,366 | 2,094,412 | C++: Printing ASCII Heart and Diamonds With Platform Independent | I'm developing a card playing game and would like to print out the symbol for hearts, diamonds, spades and clubs. My target platform will be Linux.
In Windows, I know how to print out these symbols. For example, to print out a heart (in ASCII) I wrote...
// in Windows, print a ASCII Heart
#include <iostream>
using ... | If you want a portable way, then you should use the Unicode code points (which have defined glyphs associated to them):
♠ U+2660 Black Spade Suit
♡ U+2661 White Heart Suit
♢ U+2662 White Diamond Suit
♣ U+2663 Black Club Suit
♤ U+2664 White Spade Suit
♥ U+2665 Black Heart Suit
♦ U+2666 Black Diamond Suit
♧ U+2667 White ... |
2,094,427 | 2,095,209 | DLL : export as a C/C++ function? | I generated a DLL in Visual from a C++ code. Dependency Walker sees 3 functions exported as C functions.
I made an SCons project to do the generate the DLL, and 2 of the 3 functions are not seen as C functions.
What makes a function seen as a or C++ function, without modifying the code ? It must be in the compilation/l... |
What makes a function seen as a or C++ function, without modifying the code ?
A function compiled by a C++ compiler is automatically a 'C++-function' and name-mangling occurs to resolve C++ features such as namespaces and overloading.
In order to get 'C' export names, one must use the aforementioned extern "C" qual... |
2,094,717 | 2,094,743 | Do these two classes violate encapsulation? | class X
{
protected:
void protectedFunction() { cout << "I am protected" ; }
};
class Y : public X
{
public:
using X::protectedFunction;
};
int main()
{
Y y1;
y1.protectedFunction();
}
This way I am able to expose one of the functions of the base class.
Doesn't this violate the encapsulation princip... | Yes it does and that's why protected has received a fair share of criticism.
Bjarne Stroustrup, the creator of C++, regrets this in his excellent book The Design and Evolution of C++:
One of my concerns about protected is
exactly that it makes it too easy to
use a common base the way one might
sloppily have used... |
2,094,776 | 2,094,791 | Is It Possible To Do The Following In A Switch Statement - C++? | I am a programming student in my second OOP class, and I have a simple question that I have not been able to find the answer to on the internet, if it's out there, I apologize.
My question is this:
Is it possible have Boolean conditions in switch statements?
Example:
switch(userInputtedInt)
{
case >= someNum && <= ... | No this is not possible in C++. Switch statements only support integers and characters (they will be replaced by their ASCII values) for matches. If you need a complex boolean condition then you should use an if / else block
|
2,095,223 | 2,095,401 | Better C++ syntax for template base class typedefs and functions? | I have code that compiles fine with VC9 (Microsoft Visual C++ 2008 SP1) but not with GCC 4.2 (on Mac, if that matters). If I pile on enough qualifiers and keywords I can force it to work in GCC but this doesn't seem right.
Here's a minimal code sample exhibiting my problems:
template< typename N >
struct B {
typed... |
Am I wrong to expect a template class derived from another template class to be able to use inherited typedefs and functions directly?
Yes, this will not generally work as you expect it. The C++ name lookup rules specify that a name is only searched in a templated base classes if it depends on a template parameter (i... |
2,095,277 | 2,095,368 | Difference between C++ and Java compilation process |
Possible Duplicate:
Why does C++ compilation take so long?
Hi,
I searched in google for the differences between C++ and Java compilation process, but C++ and Java language features and their differences are returned.
I am proficient in Java, but not in C++. But I fixed few bugs in C++. From my experience, I noticed... | There are a few high-level differences that come to my mind. Some of those are generalizations and should be prefixed with "Often ..." or "Some compilers ...", but for the sake of readability I'll leave that out.
C/C++ compilation doesn't read any information from binary files, but reads method/type definitions only f... |
2,095,363 | 2,095,820 | C++ application - should I use static or dynamic linking for the libraries? | I am going to start a new C++ project that will rely on a series of libraries, including part of the Boost libraries, the log4cxx or the google logging library - and as the project evolves other ones as well (which I can not yet anticipate).
It will have to run on both 32 and 64 bit systems, most probably in a quite di... | Static linking has a bad rap. We have huge hard drives these days, and extraordinarily fat pipes. Many of the old arguments in favor of dynamic linking are way less important now.
Plus, there is one really good reason to prefer static linking on Linux: The plethora of platform configurations out there make it almost im... |
2,095,398 | 2,095,433 | C++ passing arrays to a method problem | Hey there I have this function:
void vdCleanTheArray(int (*Gen_Clean)[25])
{
}
I wanted to know what kind of array does it accepts and clear it.
Sorry, I have a little knowledge in c++, someone just asked me.
Thanks!
| It accepts an array declared as
int array[25];
which should be passed "by pointer", i.e. by applying the & operator to the array
vdCleanTheArray(&array);
As for how to clean it... As I understand, it is the above function that should clean it and you are supposed to write it, right? Well, inside the function you acce... |
2,095,465 | 2,095,603 | Calling managed c++ directly from C# failed | Having A.dll which is a managed c++ project (no other dependencies)
From B.dll which is a C# project where A.dll is referenced having a Nunit method foo().
If calling the managed c++ code from foo() I got FileNotFoundException:The specified module could not be found. (Exception from HRESULT: 0x8007007E).
I tried to cha... | This is not a managed DLL loading error, you can't see it in Fuslogvw.exe. I'd guess at an unmanaged DLL dependency for C++/CLI assembly that cannot be located. You'll be able to see Windows searching for the DLL with SysInternals' ProcMon utility.
|
2,095,759 | 2,095,782 | C++: Constructor versus initializer list in struct/class | An object of a struct/class (that has no constructor) can be created using an initializer list. Why is this not allowed on struct/class with constructor?
struct r { int a; };
struct s { int a; s() : a(0) {} };
r = { 1 }; // works
s = { 1 }; // does not work
| No, an object with a constructor is no longer considered a POD (plain old data). Objects must only contain other POD types as non-static members (including basic types). A POD can have static functions and static complex data members.
Note that the upcoming C++ standard will allow you to define initializer lists, which... |
2,095,977 | 2,095,994 | To Mutex or Not To Mutex? | Do I need a mutex if I have only one reader and one writer? The reader takes the next command (food.front()) from the queue and executes a task based on the command. After the command is executed, it pops off the command. The writer to the queue pushes commands onto the queue (food.push()).
Do I need a mutex? My reader... | A mutex is used in multi-threaded environments. I don't see mention of threads in your question, so I don't see a need for a mutex.
However, if we assume by reader and writer you mean you have two threads, you need to protect mutual data with a mutex (or other multi-threaded protection scheme.)
What happens when the qu... |
2,096,084 | 2,096,128 | Designing Thread Class | I have a design question. Is it better to define separate classes for SENDING and RECEIVING. Or, is it better to define a single Thread class? I like the idea of a single Thread class because it is easier to share a queue which can be locked by mutex.
Design Option #1 (Separate):
mySendThread = new SendThread(); // Hav... | I've designed a thread for communicating on the serial port (in Python, not C++, but it doesn't matter much) as follows:
There's a single thread and two queues - one for sent and one for received messages. The thread always listens (asynchronously) on both the serial port (for received data) and the sending queue (to s... |
2,096,381 | 2,096,403 | invalid conversion from 'int' to 'int*' | I was looking for solving a LCS problem (Longest common subsequence) and I tried to make my own code in c++ by referring to the explanation and the pascal code given at wikipedia.
My final result was this:
#include <iostream>
#include <algorithm>
using namespace std;
int LCS(int a[100], int b[100], int m, int n);
i... | Just pass the array name.
This
LCS(x, y, m, n);
not this
LCS(x[100], y[100], m, n);
|
2,096,450 | 2,096,531 | Putting a string or int back on the front of cin | I have a problem where I get an int as input at the wrong time in my c++ program, so I need to "put it back" on cin later. However the closest thing I can find to do this is the pushback function for istreams. This sadly is only for characters and using multiple characters seems to separate them. Is there a good way... | If you are using a seekable input (such as a file), you can use seekg. Unfortunately, this won't work for non-seekable streams (such as a pipe or human input).
|
2,096,596 | 2,096,697 | MFC dialog buttons show up as black boxes | I have an old MFC utility written with VS2008 project. We have used this utility for a few years now and I have never experienced this problem personalty but it is showing up more and more often on customers computers.
Sub dialogs launched from my main dialog will have their buttons blackened out. I have included a sc... | I've seen this when the machine was out of memory. It didn't have enough RAM left to load the button images.
|
2,096,668 | 2,097,348 | What was the most useful time you used a pointer-to-pointer and/or reference-to-pointer in a c/c++ project? | Pointers-to-pointers and references-to-pointers seem overly complicated at first, especially for newbies. What is the best and most useful reason you used one in a c/c++ project you worked on?
This can help people better understand pointers and how to use them effectively.
Edited: Included C as well as C++
| Since no one has mentioned this yet, they may be useful as iterators.
Assume you have a list of objects of some sort. And you need to traverse some of them in some specific order.
So you create an array holding pointers to the objects you need to traverse, and then you sort that array.
An iterator into that array is a ... |
2,096,709 | 2,097,305 | What's the best way to insert version and arch info into C++ sources? | I want my C++ program to include a "--version" option which causes it to print out:
Architecture it's compiled for
Version of the source (e.g., v0.1.0)
Name of the application
I'm also using autoconf/automake for the first time, and I notice that configure.ac has both the binary and the version. It doesn't currently ... | autoconf gives you a config.h, which provides string macros such as PACKAGE, PACKAGE_NAME, PACKAGE_STRING, PACKAGE_VERSION, and VERSION.
(When I use the Argp argument parser, I simply use
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <argp.h>
const char *argp_program_version = PACKAGE_STRING;
const char *ar... |
2,096,762 | 2,096,822 | What exactly is a PWSTR and why use this naming compared to char*, std::string, or CString in C++? | In various c++ code you often see different usage of strings: PWSTR, char*, std::string, CString, etc ...
When is the best time to use PWSTR as compared to any other string type?
| a PWSTR would be a wchar_t string pointer. That is a UNICODE (usually UCS2) string with each character taking 16 bits.
a char* would be a pointer 8 bits per character. this could be ASCII, ANSI, UTF8, or one of many hundreds of other encodings. Although you only need to worry about encodings if you need the string to... |
2,096,897 | 2,099,694 | Can Win32 "move" heap-allocated memory? | I have a .NET/native C++ application. Currently, the C++ code allocates memory on the default heap which persists for the life of the application. Basically, functions/commands are executed in the C++ which results in allocation/modification of the current persistent memory. I am investigating an approach for cancel... | Heap is a sort of big chunk of memory. It is a user-level memory manager. A heap is created by lower-level system memory calls (e.g., sbrk in Linux and VirtualAlloc in Windows). In a a heap, then you can request or return a small chunk of memory by malloc/new/free/delete. By default, a process has a single heap (unlike... |
2,097,418 | 2,097,448 | Pointers and Functions in C++ | From the lectures notes of a course at university, on "call-by-value":
void fun(int *ip)
{
*ip =100;
}
called by
int n=2;
int *np;
np = &n;
fun(np);
would change the value of n to 100.
When we say "int *ip", what exactly do we mean? A pointer of type integer? If so, when we call fun() with np as its argum... |
A pointer of type integer?
No, a pointer to an integer.
when we call fun() with np as its argument, shouldn't there be an error as np has the address of n, which is not an integer?
n is an integer so there’s no problem. &n, np and ip all have the same type in your code: int*.
And then, we change the value of ip to... |
2,097,705 | 2,097,734 | inside c++ thread, initializing reference | I've came across the following code, ok, not exactly but close.
The point of interest is the second line in the (heavily abbreviated code).
Why does one have to intialize someReference 'someReference' ? Other then be able to use . operator instead of -> ?
ptrThis is just as good, no? (it's inside the thread method, if ... | References always need to be initialized when they're declared (unless they're external). They remain bound to one object during their whole lifetime. This ensures that a reference, unlike a normal pointer, can (theoretically) never be NULL because it must refer to somebody. Assigning to a reference assigns to the refe... |
2,097,738 | 2,097,778 | how to pass a non static-member function as a callback? |
io_iterator_t enumerator;
kern_return_t result;
result = IOServiceAddMatchingNotification(
mNotifyPort,
kIOMatchedNotification,
IOServiceMatching( "IOFireWireLocalNode" ),
serviceMatchingCallback,
(void *)0x1234,
& enumerator );
servic... | You could keep it static, but use the userdata to store the this pointer in addition to whatever other userdata you want (by packing them into a structure, for example) and then call an object-specific callback from the static version by calling this->someCallback (where this is the pointer stored in the userdata, of c... |
2,097,811 | 2,114,807 | C++ syntax for explicit specialization of a template function in a template class? | I have code which works in VC9 (Microsoft Visual C++ 2008 SP1) but not in GCC 4.2 (on Mac):
struct tag {};
template< typename T >
struct C
{
template< typename Tag >
void f( T ); // declaration only
template<>
inline void f< tag >( T ) {} // ERROR: explicit specialization in
}; ... | You can't specialize a member function without explicitly specializing the containing class.
What you can do however is forward calls to a member function of a partially specialized type:
template<class T, class Tag>
struct helper {
static void f(T);
};
template<class T>
struct helper<T, tag1> {
static void... |
2,098,149 | 2,098,444 | What platforms have something other than 8-bit char? | Every now and then, someone on SO points out that char (aka 'byte') isn't necessarily 8 bits.
It seems that 8-bit char is almost universal. I would have thought that for mainstream platforms, it is necessary to have an 8-bit char to ensure its viability in the marketplace.
Both now and historically, what platforms use ... | char is also 16 bit on the Texas Instruments C54x DSPs, which turned up for example in OMAP2. There are other DSPs out there with 16 and 32 bit char. I think I even heard about a 24-bit DSP, but I can't remember what, so maybe I imagined it.
Another consideration is that POSIX mandates CHAR_BIT == 8. So if you're using... |
2,098,300 | 2,215,693 | A terminal-like window for wxWidgets? | I'm looking to add an element to my wxWidgets GUI that behaves like a terminal emulator. Not in terms of a shell which executes commands, but just the input-output setup of an application running in a terminal.
Basically, the requirements are:
Streaming input/output: When you enter a character, it is added to an input... | I know this is a couple weeks late, but hopefully it's still useful. I've got a project called Chameleon that uses a wxWidgets-based VT100 terminal widget, which was itself based off of a project called taTelnet. The Chameleon source is available from my website (download page here). Not sure if it's exactly what yo... |
2,098,319 | 2,098,416 | Calculating large factorials in C++ | I understand this is a classic programming problem and therefore I want to be clear I'm not looking for code as a solution, but would appreciate a push in the right direction. I'm learning C++ and as part of the learning process I'm attempting some programming problems. I'm attempting to write a program which deals w... | Skimmed this question, not sure if I really got it right but here's a deductive guess:
First question - how do you get a zero on the end of the number? By multiplying by 10.
How do you multiply by 10? either by multiplying by either a 10 or by 2 x 5...
So, for X! how many 10s and 2x5s do you have...?
(luckily 2 & 5 a... |
2,098,370 | 2,101,558 | How to launch short codes on mobile device? | Nokia has a long list of short codes on Symbian that can be applied to on-device data, such as
*#0000# - to check the phones software revision type,
*#7780# - to restore factory settings,
etc (the list is long)
If given a short code, how can I launch it? The program should not be aware of the functionality of the sho... | I don't think there is a generic way to do this.
From a pure Platform Security perspective, I expect only the phone manufacturer or operator to be able to give your application the capability to restore the handset factory settings.
As for the other short codes, your best bet is to find a single Symbian OS C++ API that... |
2,098,484 | 2,098,537 | Which of these statements about objects is true? | Given this:
struct { int x; } ix;
struct A { A() {}; int x; };
A ia;
Which of these is true?
a. ix is an object
b. ia is an object
c. both are objects
d. both are not objects.
| Many of these answers have ignored the C++ tag. In C++, "an object is a region of storage. [Note: a function is not an object, regardless of whether or not it occupies storage in the same way that objects do.]" (The C++ Standard, 1.8/1).
If the homework question is about C++, then no other definition of object is appli... |
2,098,685 | 2,103,731 | How does C++ builder stack up against other RAD IDEs? | It has been a few years since I did any development for PCs (I usually do embedded software).
At that time I was highly proficient with (Borland, now CodeGear) C++ Builder. Time has moved on, C++ Builder has become extremely expensive and there are alternatives (MSVC studio, NetBeans, QtCreator, maybe even Eclipse wi... | I never used C++ Builder but used to be a big fan/user of delphi. I normally work on server apps in c++, with some java. Reciently I started writing some small productivity apps for myself originally I used java, but then moved to Qt.
Now I love it. The library feels well designed just like vcl did in delphi. The... |
2,098,820 | 2,098,906 | reference to the pointed object | Dereferencing pointers can make the code very hard to read. What I usually do is putting a reference to the pointed object and working with the reference. Example:
shared_ptr<std::vector<int> > sp = get_sp_to_vector();
std::vector<int>& vec = *sp;
...
vec.push_back(5);
I wonder if it's a good practice. Does it have an... | Using local references is common, especially inside loop bodies, but there is one requirement: only do it when the reference will obviously live as long as the target object.
This usually isn't hard to guarantee, but here are some bad examples:
shared_ptr<X> p = get_p();
X& r = *p;
p.reset(); // might result in destroy... |
2,098,832 | 2,098,845 | Should I use "int" or "bool" as a return value in C++? | If I have a function that performs some procedure and then needs to return the truth value of something is there a compelling reason to use either a boolean variable, or an int variable, as the return type?
bool Foo()
{
...
...
return truthValue;
}
int Foo()
{
...
...
return truthValue;
}
Is there an ap... | If it's a genuine truth value, then you should use a bool as it makes it very clear to the caller what will be returned. When returning an int, it could be seen as a code/enum type value.
Code should be as clear and explicit as possible whether it be function names, parameter names and types, as well as the types of... |
2,098,901 | 2,098,984 | My version of C++ non-member getline(), that takes a FILE* (created by _wfopen()) instead of a stream, is too slow | In C++, you can use non-member getline() with a stream in a loop like this:
#include <string>
#include <fstream>
#include <cstdlib>
using namespace std;
int main() {
ifstream in("file.txt");
if (!in) {
return EXIT_FAILURE;
}
for (string line; getline(in, line); ) {
// Do stuff with each... | You should be using C++ I/O facilities if you're programming in C++. Having said that...
First, you are checking for newline by checking for 10 and 13. You should open your file in text mode, and check for '\n' instead. This method is portable, and works with different line-end conventions, as well as on non-ASCII s... |
2,099,120 | 2,099,148 | Why doesn't C++ implement construction + calling functions in same line? | I'm wondering why C++ (and possibly other languages, I'm not sure) doesn't allow statements like this.
MyObject foo.DoBar();
You would think that the language could understand to construct the object, then call the function. The only reason I can think of this not working is that if the construction of the object fail... | You can construct an object and immediately call a function on it, you just can't assign the object to a variable if you do so:
MyObject().DoBar();
A practical reason for this restriction is that the constructor creates the object and the function you're calling could also have a return value, so that you would end up... |
2,099,436 | 2,099,518 | A few sorting questions | I have found a way that improves (as far as I have tested) upon the quicksort algorithm beyond what has already been done. I am working on testing it and then I want to get the word out about it. However, I would appreciate some help with some things. So here are my questions. All of my code is in C++ by the way.
One... | If you have confidence in your work, definitely try to discuss it with someone knowledgeable at your university as soon as possible. It's not enough to show that your code runs faster than another procedure on your machine. You have to mathematically prove whatever performance gain you claim to have achieved through ... |
2,099,442 | 2,102,487 | Algorithm for allocating memory pages and page tables | I want to design an algorithm for allocating and freeing memory pages and page tables. What data structures would allow best performance and simplest implementation?
| Even though OS normally implement page tables, the simpler solution could be something like this.
Have a large contiguous memory as an array. When you allocate some memory, maintain that information in a linked list storing the index of the array and the length in the data part.
When you are building the linked list, m... |
2,099,540 | 2,099,590 | Defining custom hash function and equality function for unordered_map | I am trying to define a type of unordered_map that has a custom hash function and equality comparison function. The function prototypes of these functions are as follows:
//set<Vertex3DXT*> is the type of the key; Cell3DXT* is the type of the value
size_t VertexSetHashFunction(set<Vertex3DXT*> vertexSet); //hash functi... | Those functions should be declared as an operator () in a class, unfortunately. Like this:
class VertexSetHashFunction {
public:
::std::size_t operator ()(const ::std::set<Vertex3DXT*> &vertexSet) const;
};
class SetEqual {
public:
bool operator ()(const ::std::set<Vertex3DXT*> &a, const ::std::set<Vertex3... |
2,099,731 | 2,099,898 | Which one to use const char[] or const std::string? | Which is better for string literals,
standard string or character array?
I mean to say for constant strings, say
const char name[] = "so"; //or to use
const string name = "so";
| For string literals, and only for string constants that come from literals, I would use const char[]. The main advantage of std::string is that it has memory management for free, but that is not an issue with string literals.
It is the actual type of the literal anyway, and it can be directly used in any API that requi... |
2,099,743 | 2,110,613 | NPAPI plugin in QtWebKit | I know its possible to integrate NPAPI plugins with QtWebKit as its been supported since the release of Qt 4.5.
My question is, should I go and design my plugin according to the Mozilla/Gecko documentaion -Which is probably the only available/reliable documentation for NPAPI beside some really old book called "Programm... | Going with Mozillas and other documentation like colonelpanics tutorial will be fine. You might also want to take a look at FireBreaths source because we already solved some common issues there.
QtWebKit actually wraps WebKit and i don't recall there being any real differences between Mozilla and WebKit. Of course you ... |
2,099,804 | 2,099,902 | porting from 32 bit to 64 bit | I have windows application build using Visual C++. Its being build and run on 32 bit windows env. Now I need to make sure it works on windows vista / 7 64 bit env. What all things I need to consider for this porting process ??
| That's not porting from 32bit to 64, that's just running your 32bit code on a 64bit machine to make sure it still works.
The way to do that is to just test all the functionality on the 64-bit machine, just as you do every time you release a new version, right? :-)
If you really want to port it (i.e., compile it to a 64... |
2,099,830 | 2,099,873 | Unsigned keyword in C++ | Does the unsigned keyword default to a specific data type in C++? I am trying to write a function for a class for the prototype:
unsigned Rotate(unsigned object, int count)
But I don't really get what unsigned means. Shouldn't it be like unsigned int or something?
| From the link above:
Several of these types can be modified using the keywords signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed
This means that you can assume the author is using ints.
|
2,099,882 | 2,099,901 | Checking for a null object in C++ | I've mostly only worked with C and am running into some unfamiliar issues in C++.
Let's say that I have some function like this in C, which would be very typical:
int some_c_function(const char* var)
{
if (var == NULL) {
/* Exit early so we don't dereference a null pointer */
}
/* The rest of the co... |
Basically, all I'm trying to do is to
prevent the program from crashing when
some_cpp_function() is called with
NULL.
It is not possible to call the function with NULL. One of the purpose of having the reference, it will point to some object always as you have to initialize it when defining it. Do not think ref... |
2,100,012 | 2,100,107 | Object creation wrapper for a template class | Given a template class as such:
template <typename TYPE>
class SomeClass {
public:
typedef boost::intrusive_ptr<SomeClass<TYPE> > Client_t;
inline Client_t GetClient() { return Client_t(this); }
};
SomeClass is intended only to be used via pointer references returned by SomeClass::GetClient(). Which makes it natu... | SomeClass<int>::Client_t some_class = New_SomeClass<int>();
Because template parameters for New_SomeClass don't depend on a function parameter, you must specify them. The error message you reported is a little strange for this problem, however, so you might have something else going on.
Or, my preference instead of N... |
2,100,239 | 2,100,295 | C++ STL container and in-place construction | Please consider the following:
class CMyClass
{
public:
CMyClass()
{
printf( "Constructor\n" );
}
CMyClass( const CMyClass& )
{
printf( "Copy constructor\n" );
}
};
int main()
{
std::list<CMyClass> listMyClass;
listMyClass.resize( 1 );
return 0;
}
It produces the following output:
Constru... | By design, all the C++ Standard Library containers store copies. Therefore the call to the copy constructor cannot be avoided if you wish to store values in the container - the only way out is to store pointers instead. If you want to mitigate the overhead of copying, investigate the use of reference counting.
|
2,100,458 | 2,100,546 | Multiple writes in boost::asio to a single socket | I couldn't find any thing about what happens if you try to do a second write to a boost::asio socket before a previous one completed. This seems like something that could potentially happen in many asynchronous programs (since after doing the first write, the program will then continue before waiting for it to finish, ... | So, with normal non-blocking sockets, you can write some implementation-dependant amount of stuff to the socket, then eventually a write will return -EWOULDBLOCK and not do the write so you can retry later. Poking around in the source tells me that Boost wraps that, so that everything you write should get there eventu... |
2,100,486 | 2,100,576 | Advantages/disadvantages of auto pointers | What are the advantages and disadvantages of using auto pointers (auto_ptr), compared to ordinary pointers? I've heard it does automatic releasing of memory but how come it is not used often?
| The main drawback of std::auto_ptr is that it has the transfer-of-ownership semantic. That makes it impossible to store std::auto_ptr in STL containers because the containers use the copy constructor when you store or get an element.
Also, another important aspect that i have noticed about the std::auto_ptr is that the... |
2,100,644 | 2,100,685 | Will using delete with a base class pointer cause a memory leak? | Given two classes have only primitive data type and no custom destructor/deallocator.
Does C++ spec guarantee it will deallocate with correct size?
struct A { int foo; };
struct B: public A { int bar[100000]; };
A *a = (A*)new B;
delete a;
I want to know do I need to write an empty virtual dtor?
I have tried g++ and v... | Unless the base class destructor is virtual, it's undefined behaviour. See 5.3.5/4:
If the static type of the operand [of the delete operator] is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behaviour is ... |
2,100,776 | 2,100,990 | C++ app: modules design | My app contains several modules (big classes) like network io, data storage, controls, etc. Some of them can cooperate. What would be a good way of declaring and binding the modules? I see several possibilities:
1) All modules declared as global, so we have in main.cpp
#include ...
ModuleA a;
ModuleB b;
ModuleC c;
and... | From a computer science point of view, you ideally want to decrease the coupling as much as possible. From a general development point of view, you want to reduce the amount of code that is compiled when you make a change somewhere.
So, to address this, you'll want to use interfaces and the 'universe' class.
main ()
{
... |
2,101,041 | 2,105,624 | Capturing network status change event | I am trying to get events when the internet connection is reestablished after it is lost. It is for a data transfer software that I am developing. If I lose the network during data transfer, I would like to be notified when it is back and continue the transfer automatically.
I can of course create a separate thread and... | You might want to check out the System Event Notification Server (SENS) API http://msdn.microsoft.com/en-us/library/cc185680(VS.85).aspx
I have not actually used it, but it seems like it supplies the events your looking for.
EDIT:
WMI appears to have all the information you need about various network connectivity and ... |
2,101,078 | 2,101,135 | Redefine Virtual Functions between header files in C++ | I have one header file which uses a virtual function.
This is declared and defined:
#ifndef HeaderH
#define HeaderH
class Base {
<some code>
public:virtual int checkVal(int& val) { return val;}
};
#endif
I have another header file which declares some functions, and inherits from this base header.
Finally, I have t... | You have already provided the definition of checkval() inside your base class, so why are you redefining it? You can define it only once.If you want to give the implementation inside the .cpp file, just declare checkval() inside the base class, no need to define it there.
Your implementation of checkval() fails if you ... |
2,101,103 | 2,116,932 | Assembler task - min and max values of the array | I've encountered problems with assembler code. I'm a newbie to assembler, so it seems difficult for me to solve it myself.
The task is: "To find minimal and maximal elements of the array."
All I've already done is searching for maximal element. I can't find out, how to make check for the minimal element and where I sh... | If it's interesting to someone, here is the solution for my question(I found out it today with help of my tutor):
#include <conio.h>
#include <stdio.h>
#include <iostream.h>
void main() {
int N = 10, i;
clrscr();
int a[] = { 1, 4, -6, 12, -25, 10, 3, -4, 15, 7}, MAX, MIN, RESULT;
__asm{
mov cx, N
... |
2,101,362 | 2,101,592 | Why is QMutex unknown? | I've included the QMutex header and using it as seen below. But I get the following error:
error C2146: syntax error : missing > ';' before identifier > '_RecorderParamsMutex'
error C4430: missing type specifier
- int assumed. > Note: C++ does not support default-int
error C4430: missing type specifier -> int ass... | Looking at the header file, the class declarations are wrapped by an #ifdef. Try it like this:
#define QT_THREAD_SUPPORT
#include <qmutex.h>
This probably ought to be a project-level #define so other threading definitions are available as well.
|
2,101,390 | 2,101,464 | Will C++ exceptions safely propagate through C code? | I have a C++ application that calls SQLite's (SQLite is in C) sqlite3_exec() which in turn can call my callback function implemented in C++. SQLite is compiled into a static library.
If an exception escapes my callback will it propagate safely through the C code of SQLite to the C++ code calling sqlite3_exec()?
| My guess is that this is compiler dependent. However, throwing an exception in the callback would be a very bad idea. Either it will flat-out not work, or the C code in the SQLite library will be unable to handle it. Consider if this is some code in SQLite:
{
char * p = malloc( 1000 );
...
call_the_callback(); /... |
2,101,449 | 2,133,159 | Experience with IBPP interface for Firebird database | I'd like to the ask guys with experience in Firebird and IBPP (especially the latter). I found a lot of positive posts about Firebird but I'm having a problem to decide about IBPP. The interface itself is clean and simple but it seems that the project does not have much of activity going on (maybe because it's very sta... | In addition to the points Milan mentioned:
There is currently no way to use more than one client library when connecting to different databases, or even to specify which client library will be used. There is a certain hard-coded sequence of client library locations that are probed, and the first one that is found will... |
2,101,789 | 2,137,875 | Implementation of a work stealing queue in C/C++? | I'm looking for a proper implementation of a work stealing queue in C/CPP. I've looked around Google but haven't found anything useful.
Perhaps someone is familiar with a good open-source implementation? (I prefer not to implement the pseudo-code taken from the original academic papers).
| No free lunch.
Please take a look the original work stealing paper. This paper is hard to understand. I know that paper contains theoretical proof rather than pseudo code. However, there is simply no such much more simple version than TBB. If any, it won't give optimal performance. Work stealing itself incurs some amou... |
2,102,056 | 2,102,070 | Why can't for_each modify its functor argument? |
http://www.cplusplus.com/reference/algorithm/for_each/
Unary function taking an element in
the range as argument. This can either
be a pointer to a function or an
object whose class overloads
operator(). Its return value, if any,
is ignored.
According to this article, I expected that for_each actually mo... | The function object is taken by value. for_each returns the function object, so if you change it to:
multiply = std::for_each(vec.begin(),vec.end(),multiply);
you get the expected output.
|
2,102,151 | 2,104,955 | How to write a Cocoa OpenGL app in C++? | I'm writing an application that needs to use OpenGL, on the Mac, in C++.
Is there anyway I can get Cocoa to just give me an OpenGL context and let me do my work in C++? (I want my app to run on both Mac OS X and iPHone; but all the GUI is in OpenGL, I just need a OpenGL context).
Thanks!
| You cannot escape a minimal amount of objective-C code. However, if you rename the objective C files to .mm files, the objective C code will be able to call c++ class methods. This means you can hook the -drawRect (and other relevent NSOpenGLView messages) to your c++ OpenGL implementation. The NSOpenGLView has a -make... |
2,102,187 | 2,102,257 | Can a functor retain values when passed to std::for_each? | According to the first answer to this question, the functor below should be able to retain a value after being passed to foreach ( I couldn't get the struct Accumulator in the example to compile, so built a class).
class Accumulator
{
public:
Accumulator(): counter(0){}
int counter;
void ope... | This was just asked here.
The reason is that (as you guessed) std::for_each copies its functor, and calls on it. However, it also returns it, so as outlined in the answer linked to above, use the return value for for_each.
That said, you just need to use std::accumulate:
int counter = std::accumulate(_cards.begin(), _c... |
2,102,401 | 2,102,511 | Determine if O/S is Windows 7 | Working on a project and need to be able to determine whether the O/S is Windows 7, Vista or default to XP. I understand I could run into Win2K and earlier versions but let's just say that's not a concern as other code will catch that before it gets to this point. My application will be in C++ for the time being using ... | List of Windows Version, using GetVersionEx:
Version Number Description
6.1 Windows 7 / Windows 2008 R2
6.0 Windows Vista / Windows 2008
5.2 Windows 2003
5.1 Windows XP
5.0 Windows 2000
|
2,102,582 | 2,102,615 | (How) can I count the items in an enum? | This question came to my mind, when I had something like
enum Folders {FA, FB, FC};
and wanted to create an array of containers for each folder:
ContainerClass*m_containers[3];
....
m_containers[FA] = ...; // etc.
(Using maps it's much more elegant to use: std::map<Folders, ContainerClass*> m_containers;)
But to come... | There's not really a good way to do this, usually you see an extra item in the enum, i.e.
enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};
So then you can do:
int fuz[FOOBAR_NR_ITEMS];
Still not very nice though.
But of course you do realize that just the number of items in an enum is not safe, given e.g.
enum foob... |
2,102,907 | 2,102,943 | Which side (left or right) of && (and) operator evaluated in C++ | Which order is the and && operator evaluated
For example the following code
if (float alpha = value1-value2 && alpha > 0.001)
//do something
threw an exception that alpha is being used without being initiated.
I thought the expression left of the && would always initiate the value of alpha first, but it seems I ma... | This gets parsed as:
if (int alpha = (value1-value2 && (alpha > 0.001)))
... because && has a higher "parsing precedence" than = -- which is probably not what you want. Try:
int alpha = value1-value2;
if (alpha && (alpha > 0.001))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.