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 |
|---|---|---|---|---|
1,874,103 | 1,877,905 | negative color with glBlendFunc()? | i want my lines to be drawn with negative color (taken from the screen under the line), i just didnt understand how the blending works, looked at docs etc, tested 50 combinations and so on. started to think its not possible at all...
could someone just give the two values?
| You should use logic ops for that purpose. Not blend.
So all you have to do is to call:
glEnable(GL_COLOR_LOGIC_OP);
glLogicOp(GL_INVERT);
You can use GL_ XOR too, depending what you want to achieve. GL_ XOR is useful if you want to restore the frame buffer exactly in the state that it was before the line draw happene... |
1,874,205 | 1,875,157 | C/C++ J2ME interpreter | do anyone know some C or C++ interpreter for cell phones? I have Nokia 5310 and found some Basic interpreter (CellBasic) and want to develop in C or C++ on the go. Or, does anybody knows Scheme J2ME intepreter?
| You don't want to do a C interpreter in J2ME unless you first compile it to bytecode elsewhere: you'd waste a lot of space with the parser.
If you're interested, I have my own interpreter that's used by various people and companies called Hecl, at http://www.hecl.org
It's fairly simple, but has commands to access a var... |
1,874,208 | 1,874,417 | Problem using reinterpret_cast<> in c++ | I am trying to cast a datastream into a struct since the datastream consists of fixed-width messages and each message has fulle defined fixed width fields as well. I was planning on creating a struct and then using reinterpret_cast to cast pointer to the datastream to the struct to get the fields. I made some test code... | In order to be able to print an array of chars, and being able to distinguish it from a null-terminated string, you need other operator<< definitions:
template< size_t N >
std::ostream& operator<<( std::ostream& out, char (&array)[N] ) {
for( size_t i = 0; i != N; ++i ) out << array[i];
return out;
}
|
1,874,262 | 1,874,269 | C/C++/C# Force window to be on top | Is the there a way to force another window to be on top? Not the application's window, but another one, already running on the system. (Windows, C/C++/C#)
| You can use the Win32 API BringWindowToTop. It takes an HWND.
You could also use the Win32 API SetWindowPos which also allows you to do things like make the window a top-level window.
|
1,874,297 | 1,874,329 | C++ good coding style - always fully qualify library types? | What is generally considered good coding style in C++ where you use types from the standard library? For example, if I have a using namespace std; directive would you still expect to see library types fully qualified like so: std::string or is it acceptable to just use string as the type identifier?
If you do fully qua... | fully qualify in header files. import the namespace in the .cpp files.
keeps the global namespace from being cluttered by a simple #include
|
1,874,354 | 1,874,365 | A dynamic buffer type in C++? | I'm not exactly a C++ newbie, but I have had little serious dealings with it in the past, so my knowledge of its facilities is rather sketchy.
I'm writing a quick proof-of-concept program in C++ and I need a dynamically sizeable buffer of binary data. That is, I'm going to receive data from a network socket and I don't... | You want a std::vector:
std::vector<char> myData;
vector will automatically allocate and deallocate its memory for you. Use push_back to add new data (vector will resize for you if required), and the indexing operator [] to retrieve data.
If at any point you can guess how much memory you'll need, I suggest calling res... |
1,874,467 | 1,874,823 | What does this statement mean? "good C++ programming typically doesn't use pointers in complicated ways." | In this other question in the winning answer I read:
... good C++ programming typically
doesn't use pointers in complicated
ways.
What does it mean to not use pointers in complicated ways?
(I'm really hoping that this isn't a subjective question)
| As the guy who wrote that, I can at least tell you what I meant.
In a good C++ program, of the sorts I'm familiar with, pointers are used to indicate objects, mostly so they can be passed around and used polymorphically. They aren't used to pass by reference, because that's what references are for. There is NO pointe... |
1,874,578 | 1,874,625 | C/C++/C# SetWindowPos: Window on top of others | I would like someone to give a working example of SetWindowPos on how to make a window "topmost" (be on top and stay there) using either C/C++/C#. Thanks in advance!
| SetWindowPos with .NET
|
1,874,738 | 1,935,942 | How do I keep Eclipse from automatically deleting my exe file | I use Eclipse for Java development.
There is an *.exe file in a subdirectory of my workspace, which keeps getting deleted.
Specifically, one of the projects is dedicated to C++ development using MSVC; there is no Java there. The root of this project has cpp and h files, and I use MSVC to generate the exe under the /b... | The problem is you are storing your executable in /bin, which is an Eclipse output directory. This directory gets removed each time you do a clean build. Solution: store your executable elsewhere (i.e. /exe).
|
1,875,147 | 1,875,365 | Can you help with creating a zip archive with the LZMA (7zip) SDK? | I am trying to use the LZMA SDK to create a zip archive (either .zip or .7z format). I've downloaded and built the SDK and I just want to use the dll exports to compress or decompress a few files. When I use the LzamCompress method, it returns 0 (SZ_OK) as if it worked correctly. However, after I write the buffer to fi... | I do not know about LZMA specifically, but from what I know of compression in general, it looks like you are writing a compressed bit stream to a file without any header information that would let a decompression program know how the bit stream is compressed.
The LzmaCompress() function probably writes this information... |
1,875,167 | 1,876,431 | Performance profiling on Linux | What are the best tools for profiling C/C++ applications on *nix?
(I'm hoping to profile a server that is a mix of (blocking) file IO, epoll for network and fork()/execv() for some heavy lifting; but general help and more general tools are all also appreciated.)
Can you get the big system picture of RAM, CPU, network a... | I recommend taking stackshots, for which pstack is useful. Here's some more information:
Comments on gprof.
How stackshots work.
A blow-by-blow example.
A very short explanation.
If you want to spend money, Zoom looks like a pretty good tool.
|
1,875,228 | 1,875,439 | Practical and advanced C++ usage | I've studied C++ as a college course. And I have been working on it for last three years. So I kinda have a fairly good idea what is it about. But I believe to know a language is quite different from using it to full potential. My current job doesn't allow me to explore much.
I have seen you guys suggest studying a ope... | I was in the same situation 12 years ago when I got my first programming job out of college. I didn't do any open source but I managed to gain a lot of practical and advanced C++ knowledge by reading books (the dead tree kind).
In particular, there was an excellent series by Scott Meyers which I feel helped the most i... |
1,875,247 | 1,875,292 | Cross-compile from (open)Solaris to Windows? | Is there any way I can cross-compile C/C++ code for Windows (XP, Vista, Win7), ideally in 64-bit as well as 32-bit (for Vista and Win7), from a Solaris or OpenSolaris setup? My codebase is already cross-platform, I would like to cross-compile it (generate windows DLLs and EXEs) from Solaris or Linux as part of an autom... | I'm not sure if you want cross-compilation (creation of Windows EXE files on the the Solaris box) or cross-platform (code that compile on Solaris or Windows). The latter is easier, and to do it you should start by installing the MinGW version of the GCC compiler on your Windows box.
|
1,875,296 | 1,875,369 | Problem with class template specialisations | I'm trying to port some code from VC9 to G++, however Ive run into a problem with template specialisations apparently not being allowed for class members.
The following code is an example of these errors for the getValue specialisations of the class methods. In all cases the error is "error: explicit specialization in ... | You haven't shown the class definition enclosing these function-declarations. But i assume it's some class where these templates are declared in. You have to define the specializations outside:
struct SomeClass {
template<typename T> T getValue(const_iterator key)const
{
try{return boost::lexical_cast<T>... |
1,875,388 | 1,875,413 | Help on linking in gcc | In Microsoft visual c++ compiler, you can specify linker options using
#pragma comment(lib, "MSVCRT") //links with the MVCRT library
see this page
I find this feature very useful because linker errors are common and i want to just place all the linker options in my source code instead of specifying them to the comp... | GCC doesn't support this because to link correctly, the order in which you link your objects matters.
See also my answer and others in the question "#pragma comment(lib, “xxx.lib”) equivalent under Linux?"
|
1,875,425 | 1,875,448 | want to make a complex c++ gui simply | I want to make a nice simple gui using c++. which have drag and drop capabilities, must be light weight. Im thinking of a gui like utorrent client gui.Its light weight and simple.
please give me information about most easy to use libraries / ide /plugin (on windows platform may be good).
| Either use QT or wxWidgets. Both are free to use, but QT uses more advanced features of C++ and is used slightly more than wxWidgets (From what I have seen) and has the backing of Nokia.
Both have various gui editors. QT has a QT Creator and there is a list of tools on the wxWiki, which includes a lot of open source RA... |
1,875,542 | 1,877,527 | How do I overload the I/O operators C++ | I have created a class that allows the user to input their mailing address, order date, type of cookie ordered and the quantity. There were other errors, but I stayed late and with the assistance of my prof, I have fixed them. Now all that is left is that I need to be able to change code to overload the I/O stream oper... | Implement two functions:
basic_ostream & operator<< (basic_ostream& ostr, const CookieOrder& co)
basic_istream & operator>> (basic_istream& istr, CookieOrder& co)
the operator<<= function will be called when you use cout << order << endl; and the operator>> function will be called when you use the >> (stream extractio... |
1,875,609 | 1,875,728 | Better way to count things? | In one of my programs for school, I use the following function to count the frequency of identifiers in a string, separated by newlines and #:
Input:
dog
cat
mouse
#
rabbit
snake
#
Function:
//assume I have the proper includes, and am using namespace std
vector< pair<string,int> > getFreqcounts(string input) {
vec... | You can get rid of the first for loop by simply deleting it. It accomplishes nothing useful. When/if the subscript into the map creates a new item, that item will have the chosen key, and your associated int will be initialized to zero automatically.
Personally, I'd probably do things a bit differently, using a strings... |
1,875,695 | 1,875,737 | Constructor and variable names in C++ vs. Java | I'm learning C++ coming from a Java background (knowing a little C from many years ago)...
In Java, it's common practice to use "this" inside a constructor to distinguish the variable passed in as arguments to the constructor from the one declared in the class:
class Blabla {
private int a;
private int b;
... | Yes, you can use this to refer to member variables. That said, you'll often find that your code looks as follows in idiomatic C++:
class Blabla {
private:
int a_;
int b_;
public:
Blabla(int a, int b) : a_(a), b_(b) {}
};
As you can see, you normally do not apply the access control specifiers (public, ... |
1,875,727 | 1,875,924 | C# COM Server - Testing in C++ | I have some C# interfaces exposed to COM:
interface IMyInterface
{
IMyListObject[] MyList
{
get;
}
}
interface IMyListObject
{
//properties that don't matter
}
So far I'm testing how our assembly is exposed to COM from C++ and most is working just fine.
My current problem is at one point I have 2 instance... | Not sure if E_POINTER makes sense or why it would work in C#. It can't work, your MyList property doesn't have a property setter. It doesn't really need one, you don't have to change the array, only the array contents. Use the SafeArrayXxxx() functions, using the ATL CComSafeArray or MFC COleSafeArray wrappers makes... |
1,875,830 | 1,876,578 | How to implement collision effects in a game? | I building a game with QT. Every objects on my GraphicsScene inherits from GraphicsPixmapItem (Player, Obstacles, bombs...). I would like to implment collision effects. For example when the player gets hover a bonus he can pick it.
With the QT framework I can get the collidings items but I don't know which type they a... | Design considerations:
I can't recommend inheriting Game objects from their graphic representation. Why? You may want to have multiple graphic representations of one game object (like one in game view or another one in minimap, or whatever). The relation is "Player 'has-a' graphic representation" and not "Player 'is-a'... |
1,875,998 | 1,876,052 | Can POSIX message queues be used cross user on Linux? | I have implemented a POSIX message queue.
On the listener side, I am opening the queue like this:
mqdes = mq_open(s_mailbox_name.c_str(), O_RDONLY | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, NULL);
On the sender side, I am opening the queue like this:
mqdes = mq_open(m_s_mailbox_name.c_str(), O_WRONLY);
The string is the ... | Check umask.
From man mq_open: "The permissions settings are masked against the process umask."
|
1,876,051 | 1,876,694 | How can I change a module's checksum in a minidump? | The software that I write (and sell) is compressed and encrypted before I distribute it. Everytime I release a new build, I keep all the .map files and the generated binaries including the exe before it is compressed and encrypted.
When it crashes on a client's machine I get a minidump back. I open these minidumps in... | Without knowing how exactly you are compressing and encrypting your binaries, it's hard for me to be very specific.
This blog post by John Robbins points out that executable images are associated with their PDBs via a GUID that's embedded in the executable's PE header. You should be able to view it by running DUMPBIN /... |
1,876,150 | 1,876,178 | Simple, efficient weak pointer that is set to NULL when target memory is deallocated | Is there a simple, efficient weak/guarded pointer? I need multiple pointers to the same object that are all automatically set to NULL when the object is deleted. There is one "master" pointer that is always used to delete the object, but there can be several other pointers that reference the same object.
Here are some ... | You can use the lock() member of boost::weak_ptr to be able to test (then use) the value of the weak_ptr without dealing with exceptions.
|
1,876,179 | 5,611,886 | How to handle multiple collision type in c++? | I'm building a game in c++ using Qt. I got the collision detection right using GraphicsItem methods the thing is that I don't know how to deal with every different collision type as there is different objects with different behaviour.
| It's actually possible to know which kind of object participate in the collision, through custom type, see the documentation for more info http://doc.qt.io/qt-5/qgraphicsitem.html#type
|
1,876,433 | 1,876,512 | SSE2 - 16-byte aligned dynamic allocation of memory | EDIT:
This is a followup to SSE2 Compiler Error
This is the real bug I experienced before and have reproduced below by changing the _mm_malloc statement as Michael Burr suggested:
Unhandled exception at 0x00415116 in SO.exe: 0xC0000005: Access violation reading
location 0xffffffff.
At line label: movdqa xmm0, xmm... | I think the 2nd problem is that you're reading at an offset from the pointer variable (not an offset from what the pointer points to).
Change:
label: movdqa xmm0, xmmword ptr [t1+eax]
To something like:
mov ebx, [t1]
label: movdqa xmm0, xmmword ptr [ebx+eax]
And similarly for your accesses through the t2 pointer.
Thi... |
1,876,444 | 1,877,231 | Boost Unit Testing and Visual Studio 2005/Visual C++ and the BOOST_AUTO_TEST_SUITE(stringtest) namespace? | I'm reading this article on the Boost Unit Testing Framework.
However I'm having a bit of trouble with the first example, my guess is that they left something out (something that would be obvious to hardcore C++ coders) as IBM often does in their articles. Another possibility is that my Visual Studio 2005 C++ compiler... | Looks correct to me. My Boost.Test code looks the same way. I'm running VS2008, but I know it works in 2005 as well.
Seems like your problem lies elsewhere.
If you use precompiled headers (and why do you do that in such a small test program?), shouldn't stdafx.h be included as the very first thing in the file?
And what... |
1,876,474 | 1,892,029 | C++ Newbie needs helps for printing combinations of integers | Suppose I am given:
A range of integers iRange (i.e. from 1 up to iRange) and
A desired number of combinations
I want to find the number of all possible combinations and print out all these combinations.
For example:
Given: iRange = 5 and n = 3
Then the number of combinations is iRange! / ((iRange!-n!)*n!) = 5! / (5-... | Here is your code edited :D :D with a recursive solution:
#include <iostream>
int iRange=0;
int iN=0; //Number of items taken from iRange, for which u want to print out the combinations
int iTotalCombs=0;
int* pTheRange;
int* pTempRange;
int find_factorial(int n)
{
if ( n<1)
return 1;
els... |
1,876,708 | 1,876,748 | evaluate trig functions in degrees as opposed to radians | So I have a function in an app that needs to let the user calculate a trig function (sin,cos,tan) using radians OR degrees, and also to expect a returned value from inverse trig functions (asin,acos,atan) as either radians or degrees. is there any way to do this without building in a converter directly into the way th... | There isn't a way to change the way the functions operate.
A "solution" would be to re-make the interface, and do the conversions:
// for example
float sin(float pX)
{
return std::sinf(d2r(pX));
}
And use that interface instead. Put it in a math:: namespace.
|
1,876,844 | 1,876,870 | Segfault when assigning one pointer to another | My brain has never really quite grasped linked lists and the finer points of pointers but I'm trying to help out a friend with some C++ assignments. (And before I go any further, yes, there is std::list but I'm looking for an academic answer, and maybe something that will make linked lists more understandable to he and... | Looking at your class, there doesn't appear to be a place where the pointer emp is set to point at an actual object.
This line:
*emp = *newEmp;
assigns the value of the object pointed to by newEmp to the object pointed to by emp. Unless both pointers point at valid objects, the code will have undefined behaviour.
You ... |
1,877,427 | 1,877,855 | C++ implementing a regex map | I have multiple regex expressions, each mapped to a different object. After passing in a string, I want to loop through each regex expression until one evaluates to true, then I would like to return the mapped object.
What is the best way to implement this in C++? Is there a boost object available for this?
| The simplest approach is probably best.
vector<pair<regex,Object>> regexes;
Object* find_it( string looking_for )
{
auto found = find_if( regexes, [&]( const pair<regex,Object>& thing )
{
return get<0>(thing).match(looking_for);
}
if( found != regexes.end() ) return & get<1>(*found... |
1,877,439 | 1,877,496 | sqlite3_open - problems checking if a file is a sqlite3 database | I'm working with sqlite3 for the first time, and cannot get it to properly check a file before it opens it. So far, sqlite always returns OK on any file.
Also, the file name is a variable returned from the GTK file chooser. It returns an absolute path, I'm guessing this is not a problem.
Thanks for any help.
This is a ... | sqlite3_open doesn't actually read the file until the first non-pragma statement is prepared.
sqlite3_open_v2 provides other options.
|
1,877,500 | 1,877,522 | C++ stl stringstream direct buffer access | this should be pretty common yet I find it fascinating that I couldn't find any straight forward solution.
Basically I read in a file over the network into a stringstream. This is the declaration:
std::stringstream membuf(std::ios::in | std::ios::out | std::ios::binary);
Now I have some C library that wants direct acc... | You can call str() to get back a std::string. From there you can call c_str() on the std::string to get a char*. Note that c_str() isn't officially supported for this use, but everyone uses it this way :)
Edit
This is probably a better solution: std::istream::read. From the example on that page:
buffer = new char ... |
1,877,576 | 1,883,827 | C++ socket message contains extra ASCII 0 character | So this is a really strange problem. I have a Java app that acts as a server, listens for and accepts incoming client connections, and then read data (XML) off of the socket. Using my Java client driver, everything works great. I receive messages as expected. However, using my C++ client driver on the first message onl... | So, the encoding thing didn't work. In the end, I simply did a substring(startIndex) call on the incoming message using xmlMessage.indexOf("<") as the starting index. It may not be elegant, but it'll work. And the box, will remain a mystery. I appreciate the insight that you three provided.
|
1,877,579 | 1,877,665 | Dealing with char arrays in C++ | I have this C-styled piece of initialization code:
const char * const vlc_args[] =
{
"-I", "dummy",
"--ignore-config",
"--extraintf=logger",
"--verbose=2"
"--plugin-path=/usr/lib/vlc"
};
//tricky calculation of the char space used
libvlc_new(sizeof(vlc_args)/sizeof(vlc_args[0]), vlc_args, &exc);
Si... | I think Josef Grahn is right: the API wants an actual array of pointers.
If you don't need to add arguments programmatically, you can just go back to using an array:
std::string pluginpath = "test";
std::string pluginpath_arg = "--plugin-path=" + pluginpath;
const char *args[] = {
"-I", dummy, "--ignore-config", ..... |
1,877,743 | 1,877,767 | Will using new (std::nothrow) mask exceptions thrown from a constructor? | Assume the following code:
Foo* p = new (std::nothrow) Foo();
'p' will equal 0 if we are out of heap memory.
What happens if we are NOT out of memory but Foo's constructor throws? Will that exception be "masked" by the nothrow version of 'new' and 'p' set to 0?... Or will the exception thrown from Foo's constructor ma... | No, it won't be. The nothrow only applies to the call to new, not to the constructor.
|
1,877,816 | 1,878,092 | difference between -h <name> and -o <outputfile> options in cc (C++) | I am building .so library and was wondering - what is the difference b/w -h and -o cc complier option (using the Sun Studio C++) ?
Aren't they are referring to the same thing - the name of the output file?
| -o is the name of the file that will be written to disk by the compiler
-h is the name that will be recorded in ELF binaries that link against this file.
One common use is to provide library minor version numbers. For instance, if
you're creating the shared library libfoo, you might do:
cc -o libfoo.so.1.0 -h libfoo... |
1,877,823 | 1,878,184 | Most efficient tree structure for what I'm trying to do | I'm wondering what the most generally efficient tree structure would be for a collection that has the following requirements:
The tree will hold anywhere between 0 and 232 - 1 items.
Each item will be a simple structure, containing one 32-bit unsigned integer (the item's unique ID, which will be used as the tree value... | Have you considered something like a trie? Lookup is linear in key length, which in your case means essentially constant, and storage can be more compact due to nodes sharing common substrings.
Keep in mind, though, that if your data set is actually filling large amounts of your key space your bigger efficiency concern... |
1,878,001 | 40,441,240 | How do I check if a C++ std::string starts with a certain string, and convert a substring to an int? | How do I implement the following (Python pseudocode) in C++?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(For example, if argv[1] is --foo=98, then foo_value is 98.)
Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little comman... | Use rfind overload that takes the search position pos parameter, and pass zero for it:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}
Who needs anything else? Pure STL!
Many have misread this to mean "search backwards through the whole st... |
1,878,285 | 1,948,473 | Iterate Over Struct; Easily Display Struct Fields And Values In a RichEdit Box | Is there an easier way to display the struct fields and their corresponding values in RichEdit control?
This is what I am doing now:
AnsiString s;
s = IntToStr(wfc.fontColor);
RichEdit1->Lines->Append(s);
etc...
Is there an easier way than having to individually call each one? I want to read a binary file and then di... | BOOST_FUSION_ADAPT_STRUCT seems to fit well here. For example:
// Your existing struct
struct Foo
{
int i;
bool j;
char k[100];
};
// Generate an adapter allowing to view "Foo" as a Boost.Fusion sequence
BOOST_FUSION_ADAPT_STRUCT(
Foo,
(int, i)
(bool, j)
(char, k[100])
)
// The action we w... |
1,878,539 | 1,878,567 | Does the stack get unwound when a SIGABRT occurs? | Does the stack get unwound (destructors run) when a SIGABRT occurs in C++?
Thanks.
| This answer indicates that destructors aren't called.
|
1,878,645 | 1,878,678 | Where does the -DNDEBUG normally come from? | Our build system has somehow changed such that optimized builds are no longer getting the -DNDEBUG added to the compile line. I searched our makefiles and didn't find this.
Where does -DNDEBUG originate for most people and how might that have changed? Before we did have -DNDEBUG, and I don't think this was removed fr... | Since the compiler can't decide on its own when to add the NDEBUG define and when not to, the flag is always set by either the makefile or project file (depending on your build system).
|
1,879,287 | 1,913,051 | OpenDDS and notification of publisher presence | Problem: How can I get liveliness notifications of booth publisher connect and disconnect?
Background:
I'm working with a OpenDDS implementation where I have a publisher and a subscriber of a data type (dt), using the same topic, located on separate computers.
The reader on the subscriber side has overridden implementa... | Ok, guess there aren't many DDS users here.
After some research I found that a reader/writer match occurs only if this compatibility criterion is satisfied: offered lease_duration <= requested lease_duration
The solution was to set the writer QoS to offer the same liveliness. There is probably a way of checking if the ... |
1,879,388 | 1,879,411 | virtual functions in C++ | In my C++ program:
#include<iostream.h>
class A
{
public:
virtual void func()
{
cout<<"In A"<<endl;
}
};
class B:public A
{
public:
void func()
{
cout<<"In B"<<endl;
}
};
class C:public B
{
public:
void func()
{
cout<<"In C"<<endl;
}
};
int... | For the basics you should read C++ FAQ Lite on Virtual Functions.
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed... |
1,879,400 | 1,950,629 | How to prevent a globally overridden "new" operator from being linked in from external library | In our iPhone XCode 3.2.1 project, we're linking in 2 external static C++ libraries, libBlue.a and libGreen.a. libBlue.a globally overrides the "new" operator for it's own memory management. However, when we build our project, libGreen.a winds up using libBlue's new operator, which results in a crash (presumably becaus... | Perhaps you could investigate using GNU objcopy, something along the lines of objcopy --redefine-sym oldNew=newNew libBlue.a. The biggest problem I see with this is that Apple's developer tool suite doesn't seem to include objcopy. You can install objcopy from MacPorts (sudo port install binutils), but that objcopy p... |
1,879,421 | 1,879,753 | C++ text menu: writing, reading, and sorting data | So my assignment is to create multiple classes for a Person, Name, ID #, Address, and Phone #.
Name makes up: First, Middle, and Last name.
ID # makes up: 9 digits.
Address makes up: street, city, state, and 5 digit zip code.
Phone # makes up: 3 digit area code and 7 digit number.
Person makes up: a full Name (First, M... | the problem with your code are the first few lines.
int w;
Person * stuArrPtr2=new Person[w];
At program startup w is most probably initialized with 0. So you create an array of zero Persons.
The moment you call stuArrPtr2[i].InputPerson() which should be stuArrPtr2[i]->InputPerson() by the way, you try to access a me... |
1,879,431 | 1,879,448 | how to destruct an array | #include <cstdlib>
#include <iostream>
using namespace std;
const unsigned long MAX_SIZE = 20;
typedef int ItemType;
class Heap {
private:
ItemType array[MAX_SIZE];
int elements; //how many elements are in the heap
public:
Heap( )
~Heap( )
bool IsEmpty( ) const
bool IsFull( ... | array is not dynamically allocated, so the storage for it goes away when the object no longer exists in scope. In fact, you can't reassign to array; it's an error to do so.
|
1,879,527 | 1,879,557 | windows: is it possible to dump (direct) a text file into a named pipe | I have a setup where a program gets its input like so:
1) user enters a command in a command prompt
2) the text from the command prompt is written to a named pipe
3) a process on the other side of the pipe is reading the input parse and execute the command
I would like to have the ability to store a set of commands in... | If you use named pipe it might be possible,
if you take a look at this, you can see they use plain CreateFile to open the pipe, taking a look at that, it seems you cannot redirect but you have to read and write, at least with the API is the same ReadFile WriteFile.
void WriteToPipe(void)
// Read from a file and writ... |
1,879,768 | 1,880,000 | How do I replace __asm jno no_oflow with an intristic in a VS2008 64bit build? | I have this code:
__asm jno no_oflow
overflow = 1;
__asm no_oflow:
It produces this nice warning:
error C4235: nonstandard extension used : '__asm' keyword not supported on this architecture
What would be an equivalent/acceptable replacement for this code to check the overflow of a subtraction operation that happene... | First define the following:
#ifdef _M_IX86
typedef unsigned int READETYPE;
#else
typedef unsigned __int64 READETYPE;
#endif
extern "C"
{
READETYPE __readeflags();
}
#pragma intrinsic(__readeflags)
You can then check the eflags register as follows:
if ( (__readeflags() & 0x800))
{
overflow = 1;
}
|
1,879,883 | 1,879,898 | Template class method collides with overloaded method | I have a template class in C++ (somewhat simplified):
template<typename T>
struct C
{
T member;
void set(const &T x) { member = x; }
void set(int x) { member = x; }
};
As you can see the set() function can be called either with the type T, or with an int. This works fine unless T is an int, in which case I get a... | One way around this would be to provide a specialisation of the template for int that only has one set function. Otherwise you might want to have a look at the Boost libraries if something like enable_if in their template meta programming code would allow you to turn on the function set(int x)only when T is not of type... |
1,880,052 | 1,880,574 | C++: duplicated static member? | I have a class which needs to be a singleton. It implemented using a static member pointer:
class MySinglton
{
public:
static MySinglton& instance() { ... }
private:
static MySinglton* m_inst;
};
This class is compiled into a .lib which is used in multiple dlls in the same application. The problem is that each... | A solution could be transferring the instantiation to the application, and the DLLs will get reference to it during initialization.
It may not be as elegant as you'd like, but it would do it.
Need to know what's the REAL problem behind your question.
The answer may not be in the form you expect it. ;)
|
1,880,275 | 1,880,339 | Good Windows Registry Wrapper for C++ | Does anyone know of any good free/open source Windows Registry wrappers for VC++ which do not require MFC (i.e. can be run in a console app)?
| ATL comes with a basic CRegKey wrapper that might suit your needs and is easy to use from a console application.
|
1,880,676 | 1,894,653 | Linker can not find static library in same directory | I'm porting some Visual Studio 2008/VC9 stuff to Code::Blocks/MinGW and for some reason the linker cannot find a static library from another project in the workspace.
In Visual Studio 2008 I could just set the static lib project as a dependency, and it would build in the right order (i.e. static lib needs to be built b... | Apparently the directory containing the project files is not included in the linker search path, and needed to be defined explicitly by adding ".\" to the list of directories containg library files for the projects.
|
1,880,738 | 1,880,813 | searching for winapi functions | I'm learning programing windows applications with C++. Now I'm reading about messages and I'm playing with the spy++.
What function spy++ use in order to mark/highlight the window under mouse cursor?
Also, can you give me some tips about using MSDN? I'm my opinion is not user friendly at all.
I'm learning programmin... | Writing a Windows application with just the windows API is possible, but you'll end up writing huge amounts of boilerplate code just to create simple things. This is why people normally use libraries built on top of it to make things easier - MFC for example.
The MSDN article Creating Win32 Applications provides a good... |
1,880,854 | 1,880,993 | CPP: avoiding macro expansion of a macro function parameter | what I'd like to do (for logging purposes) is something like this:
This code has been written to show my problem, actual code is complex and yes, I have good reasons to use macros even on C++ =)
# define LIB_SOME 1
# define LIB_OTHER 2
# define WHERE "at file #a, line #l, function #f: "
// (look for syntax hightlight... | I'm doing:
#include <cstdio>
#define FOO 1
#define BAR 2
#define LOG_SIMPLE(ptr, lib, str) printf("%s\n", #lib);
#define LOG(ptr, lib, str) LOG_SIMPLE(ptr, ##lib, str)
int main()
{
LOG_SIMPLE(0, FOO, "some error");
LOG(0, BAR, "some other error");
}
which prints out:
FOO
BAR
Works with MSVC2005 but not with gc... |
1,880,866 | 1,880,898 | Can I set a default argument from a previous argument? | Is it possible to use previous arguments in a functions parameter list as the default value for later arguments in the parameter list? For instance,
void f( int a, int b = a, int c = b );
If this is possible, are there any rules of use?
| The answer is no, you can't. You could get the behaviour you want using overloads:
void f(int a, int b, int c);
inline void f(int a, int b) { f(a,b,b); }
inline void f(int a) { f(a,a,a); }
As for the last question, C doesn't allow default parameters at all.
|
1,880,984 | 1,881,000 | When are variables removed from memory in C++? | I've been using C++ for a bit now. I'm just never sure how the memory management works, so here it goes:
I'm first of all unsure how memory is unallocated in a function, ex:
int addTwo(int num)
{
int temp = 2;
num += temp;
return num;
}
So in this example, would temp be removed from memory after the functi... | The local variable temp is "pushed" on a stack at the beginning of the function and "popped" of the stack when the function exits.
Here's a disassembly from a non optimized version:
int addTwo(int num)
{
00411380 push ebp
00411381 mov ebp,esp //Store current stack pointer
00411383 sub ... |
1,881,200 | 1,907,233 | Implement Register/Unregister-Pattern in C++ | I often come accross the problem that I have a class that has a pair of Register/Unregister-kind-of-methods. e.g.:
class Log {
public:
void AddSink( ostream & Sink );
void RemoveSink( ostream & Sink );
};
This applies to several different cases, like the Observer pattern or related stuff. My concern is, how sa... | You are safe unless the client object has two derivations of ostream without using virtual inheritance.
In short, that is the fault of the user -- they should not be multiply inheriting an interface class twice in two different ways.
Use the address and be done with it. In these cases, I take a pointer argument rather ... |
1,881,468 | 1,881,730 | What is compile-time polymorphism and why does it only apply to functions? | What is compile-time polymorphism and why does it only apply to functions?
| Way back when, "compile time polymorphism" meant function overloading. It applies only to functions because they're all you can overload.
In current C++, templates change that. Neil Butterworth has already given one example. Another uses template specialization. For example:
#include <iostream>
#include <string>
templ... |
1,881,494 | 1,881,711 | How to expose STL list over DLL boundary? | I have a DLL which needs to access data stored in STL containers in the host application. Because C++ has no standard ABI, and I want to support different compilers, the interface between the application and DLL basically has to remain plain-old-data.
For vectors this is relatively straightforward. You can simply ret... | Perhaps you can pass something like "handles" to list/deque iterators? These handle types would be opaque and declared in a header file you would ship to the users. Internally, you would need to map the handle values to list/deque iterators. Basically, the user would write code like:
ListHandle lhi = GetListDataBegin()... |
1,881,589 | 1,882,045 | redirected cout -> std::stringstream, not seeing EOL | I've read a bunch of posts regarding redirecting std::cout to stringstreams, but I'm having problem reading the redirected string.
std::stringstream redirectStream;
std::cout.rdbuf( redirectStream.rdbuf() );
std::cout << "Hello1\n";
std::cout << "Hello2\n";
while(std::getline(redirectStream, str))
{
// This does no... | Works fine for me:
Note: the std::getline() reads the line (but not the '\n' character, the line terminator is thrown away after each line is read). But the loop will be entered once for each line.
#include <iostream>
#include <sstream>
int main()
{
std::stringstream redirectStream;
std::streambuf* oldbu... |
1,881,627 | 1,881,647 | Updating a QProgressDialog with a QFuture | What's the proper way for the main GUI thread to update a QProgressDialog while waiting for a QFuture. Specifically, what goes in this loop:
QProgressDialog pd(...);
QFuture f = ...;
while (!f.isFinished()) {
pd.setValue(f.progressValue());
// what goes here?
}
Right now I have a sleep() like call there, but tha... | Use a QFutureWatcher to monitor the QFuture object using signals and slots.
QFutureWatcher watcher;
QProgressDialog pd(...);
connect(&watcher, SIGNAL(progressValueChanged(int)), &pd, SLOT(setValue(int)));
QFuture f = ...
watcher.setFuture(f);
|
1,881,681 | 1,881,799 | Using delete on pointers passed as function arguments | Is it okay( and legal) to delete a pointer that has been passed as a function argument such as this:
#include<iostream>
class test_class{
public:
test_class():h(9){}
int h;
~test_class(){std::cout<<"deleted";}
};
void delete_test(test_class* pointer_2){
delete pointer_2;
}
int main(){
test_class*... | It will always compile without error.
Whether it's a good thing to pass a pointer into a function and delete it in that function is potentially another story, depending on the specifics of your program.
The main idea you need to consider is that of "ownership" of the pointed-to data. When you pass that pointer, does th... |
1,881,891 | 1,887,749 | DCOM CoCreateInstanceEx E_ACCESSDENIED | I am working with 2 PCs, both running both running Windows XP. Both have the same application registered with its DCOM interface. Now i'm trying to start the program from one computer on the other.
First I called CoInitializeSecurity, after that CoCreateInstanceEx, but the result is a E_ACCESSDENIED.
I did also run dco... | You have to add the user explicitly and give him all permissions. After that it works.
|
1,882,070 | 1,884,830 | Find out if a function is called within a C++ project? | I'm trying to remove functions that are not used from a C++ project. Over time it's become bloated and I'm looking to remove functions that aren't used at all.
I have all the projects in a solution file in Visual Studio, but I use cmake so I can generate project files for another IDE if necessary (which is why this is... | Use __declspec(deprecated) in front of the function declaration you want to get rid of. That will throw up compile warnings if that function is actually used at compile time.
|
1,882,161 | 1,882,540 | How can save Application Settings in the Registry via MFC? | I have a MFC application created by the MFC Project Wizard. I wanted to save/read application settings in the registry and so asked this question to find a C++ Registry wrapper as the Windows API is very messy. However, I have now heard that the MFC provides a way to do this. Is this true? If so, how can I read/write v... | MFC provides an easy way to read/write Windows registry.
In your project you'll have a global CMyProjectName theApp; object.
CMyProjectName inherits CWinApp class which provides the SetRegistryKey() method.
That method sets theApp to write in the registry instead of an "ini" file.
In the documentation check out
CWi... |
1,882,195 | 1,882,232 | Getting the size in bytes or in chars of a member of a struct or union in C/C++? | Let's say that I want to get the size in bytes or in chars for the name field from:
struct record
{
int id;
TCHAR name [50];
};
sizeof(record.name) does not work.
| The solution for this is not so pretty as you may think:
size_in_byte = sizeof(((struct record *) 0)->name)
size_in_chars = _countof(((struct record *) 0)->name)
If you want to use the second one on other platforms than Windows try:
#define _countof(array) (sizeof(array)/sizeof(array[0]))
|
1,882,399 | 1,884,922 | Issues with C++ template arguments for inheritance | I have a questions about C++ templates. More specifally, by using template arguments for inheritance.
I am facing strange behaviour in a closed-source 3rd party library. There is a C method
factoryReg(const char*, ICallback*)
which allows to register a subclass of ICallback and overwrite the (simplified) methods:
clas... | OK, it seems that it is safe to assume that SpecialCallback::ENTRY() calls BaseCallback::EXIT() somehow.
Can't be 100% sure, because it's closed source - but it's quite likely.
So much for "callback" functions...
|
1,882,689 | 1,892,073 | Why does GCC allow use of round() in C++ even with the ansi and pedantic flags? | Is there a good reason why this program compiles under GCC even with the -ansi and -pedantic flags?
#include <cmath>
int main (int argc, char *argv [])
{
double x = 0.5;
return static_cast<int>(round(x));
}
This compiles clean (no warnings, even) with g++ -ansi -pedantic -Wall test.cpp -o test.
I see two p... | This is a bug. It's been around for a surprisingly long while. Apparently, there has not been enough of a collective desire to fix it. With a new version of C++ just around the corner which will adopt the C99 functions from math.h, it seems unlikely it will ever be fixed.
|
1,882,740 | 6,745,828 | Passing a pointer to a member function as a template argument. Why does this work? | I have some code that 100% works for the use case I have. I'm just wondering if anyone can explain how and why it works.
I have a template class that sits between some code that handles threading and network communication and the library user to pass data received from the server to the user.
template <class Bar,
... | I think there is a better explanation why it is possible to do so than "because the standard says so":
The reason it works is because pointers-to-members are constant values known at compile time (pointer-to-member is effectively an offset of a member from the start of a class). Thus they can be used as parameters of t... |
1,882,846 | 1,882,889 | Find vector element in second vector | Given two vectors of integers, how to determinate if there's some element from 1st vector is present in 2nd one?
| I guess something like this should work:
std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
std::cout << "found!\n";
|
1,882,965 | 1,882,988 | include boost header file using "" or <> | Why does tuple documentation say to use, for example:
#include "boost/tuple/tuple.hpp"
and not
#include <boost/tuple/tuple.hpp>
I know that it's not probable my code will have a file called "boost/tuple/tuple.hpp",
but using include <> states explicitly not to look in the curent directory.
So what is the reason?
| Afaik the reason is to differentiate between headers that belong to an application and those which are from external libraries. I can't say why they have not used this convention. It is a only a convention and not a rule.
Perhaps someone should raise this issue with the Boost maintainers?
|
1,883,056 | 1,883,161 | std::stringstream to read int and strings, from a string | I am programming in C++ and I'm not sure how to achieve the following:
I am copying a file stream to memory (because I was asked to, I'd prefer reading from stream), and and then trying to access its values to store them into strings and int variables.
This is to create an interpreter. The code I will try to interpret ... | You can use a std::stringstream to pull tokens, assuming that you already know the type.
For an interpreter, I'd highly recommend using an actual parser rather than writing your own. Boost's XPressive library or ANTLR work quite well. You can build your interpreter primitives using semantic actions as you parse the gra... |
1,883,160 | 1,887,025 | QSignalMapper and original Sender() | I have a bunch of QComboBoxes in a table. So that I know which one was triggered I remap the signal to encode the table cell location (as described in Selecting QComboBox in QTableWidget)
(Why Qt doesn't just send the cell activated signal first so you can use the same current row/column mechanism as any other cell edi... | Why not connect the QComboBox's signal straight to your slot?
QComboBox *combo = ...
connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changedType(int)));
And then in your slot you can use the sender() method to retrieve the QComboBox that was changed.
void myDlg::changedType(int row)
{
QComboBox *combo... |
1,883,202 | 1,883,247 | Auto linking dependencies of a static lib | I have a static lib A, which also uses static libs B, C and D.
I then have applications X and Y which both use A, but not B, C or D.
Is there some way to make it so X and Y will automatically see that A used B, C and D and link them, so that I don't need to keep track for the entire dependency tree so I can explicitly ... | Static libraries do not link with other static libraries. Only when building the executable (or shared library/DLL) is linkage performed, and the way to keep track of this is (of course) to use make.
|
1,883,380 | 1,884,653 | Openfeint caused this: ISO C++ forbids of declaration 'myClass' with no type | To cut a long story short, my project (an iPhone app) was all working fine until I started using a C++ sdk (openfeint). Everything was working fine, including the C+++ Openfeint stuff, until I switched from tesitng on the device to testing in the simulator.
Now it won't compile for anything and I'm getting just under ... | Jason here from OpenFeint. If you'd like to send over a code sample to devsupport at openfeint dot com that demonstrates the problem we'll take a look at it for you. It sounds like you may be including the header file from a .CPP instead of a .MM file.
If all you did was change the iPhone Target SDK, double check that ... |
1,883,385 | 1,886,911 | Rounding to use for int -> float -> int round trip conversion | I'm writing a set of numeric type conversion functions for a database engine, and I'm concerned about the behavior of converting large integral floating-point values to integer types with greater precision.
Take for example converting a 32-bit int to a 32-bit single-precision float. The 23-bit significand of the float ... | std::numeric_limits<float>::digits10 says you only get 6 precise digits for float.
Pick an efficient algorithm for your language, processor, and data distribution to calculate-the-decimal-length-of-an-integer (or here). Then subtract the number of digits that digits10 says are precise to get the number of digits to cu... |
1,883,518 | 1,890,725 | How to relate WAVE_MAPPER audio line with its audio device | I'm developing an application that among other things, enumerates all input audio devices (using SetupAPI) and then for each audio device, it lists all input audio lines (using winmm.dll).
Basically, the way I'm relating the two is getting the device path from the audio device and then using waveInMessage to compare t... | Please correct me if I'm wrong, but I've been watching some videos from past Microsoft conferences on sound development. On the latest one from Larry Osterman, he mentions new sound features in [I believe] Windows 7 that his team worked on.
One of the features was [the name is my interpretation] "device hot swap". Let'... |
1,883,674 | 1,883,713 | Checking Mutex release | I have a multithreaded application written in C++. And I'm using mutex for file writes. I have a suspicion that somewhere during the execution of the program, the mutex isn't being released.
So I was wondering if there was a way to check for mutex locks and releases on a file, programmatically or otherwise.
I'm running... | Welcome to the wonderful world of debugging multi-threaded code. There is no magic bullet to solve your problems, but at the very least you should be using RAII idioms to manage your mutex. This means wrapping the mutex in a C++ class that claims the mutex when instances of the class are created and releases it when it... |
1,883,740 | 1,884,265 | C++ Declarative Parsing Serialization | Looking at Java and C# they manage to do some wicked processing based on special languaged based anotation (forgive me if that is the incorrect name).
In C++ we have two problems with this:
1) There is no way to annotate a class with type information that is accessable at runtime.
2) Parsing the source to generate stuf... | Lately, I had a look at the following:
The Nocturnal Initiative which made available a C++ Reflection system
C++ Runtime Type System by Avi Bar-Zeev
The blog posts on Reflection in C++(1, 2, 3) by Maciej Sinilo
Have a good read :)
|
1,883,862 | 1,883,914 | C++, oop, list of classes (class types) and creating instances of them | I have quite a lot of classes declared, all of them are inheriting from a base (kind of abstract) class ... so all of them have common methods I'd like to use ...
now, I need to have a list of classes (not objects), later make instance of them in a loop and use the instances for calling mentioned common methods ...
the... | You could create a templated factory object:
struct IFactory { virtual IBaseType* create() = 0; };
template< typename Type > struct Factory : public IFactory {
virtual Type* create( ) {
return new Type( );
}
};
struct IBaseType { /* common methods */ virtual ~IBaseType(){} };
IFactory* factories[] = {
... |
1,883,885 | 1,884,308 | Standalone, OS-independent, Architecture-neutral, Multi-threaded Library | What multi-threaded C++ library can be used for writing Linux, Windows, Solaris, and iPhone applications? Such as:
TBB
Boost
OpenMP
ACE
POCO
Any others?
| Boost threads is really the de facto C++ threading standard. I'd recommend at least familiarizing yourself with the Boost threading API, as it is more or less identical to the upcoming standardized C++0x std::thread.
|
1,884,229 | 1,885,891 | Mapping enum values to strings in C++ | Is there a way to, at runtime, map the value of an enum to the name? (I'm building with GCC.)
I know GDB can do it and I'm willing to use something that's unportable and mucks with debug data.
Edit: I'm looking for a solution that doesn't require modifying the original enum declaration nor hand copying all the values ... | If you don't want to invest the time to utilize GCCs symbol information, gcc-xml provides you information about C++ sources in a reusable XML format, including enumeration names.
Simplified example... this source:
enum E {
e1 = 1,
e2 = 42
};
becomes:
<GCC_XML>
<!-- ... -->
<Enumeration name="E">
<EnumValue... |
1,884,316 | 1,884,397 | Cross-platform OOP in C++ | Of course, I know the best answer is "don't write your own cross-platform code, someone has already done what you need," but I'm doing this as a hobby/learning exercise and not in any paid capacity. Basically, I'm writing a smallish console application in C++, and I'd like to make it cross platform, dealing with thing... | Define your interface, which forwards to detail calls:
#include "detail/foo.hpp"
struct foo
{
void some_thing(void)
{
detail::some_thing();
}
}
Where "detail/foo.hpp" is something like:
namespace detail
{
void some_thing(void);
}
You'd then implement this in detail/win32/foo.cpp or detail/pos... |
1,884,339 | 1,884,492 | How is C# inspired by C++ more than by Java? | When looking at the history of C#, I found out that C# was seen as an update to C and/or C++. This came a bit as a surprise to me, as on the surface, I see much more common ideas between C# and Java (Garbage collection comes to mind). I don't write code in Java, but I have usually no problem following Java code, and ro... | IMO, the idea that C# is inspired more from C++ than Java is marketing only; an attempt to bring die-hard C++ programmers into the managed world in a way that Java was never able to do. C# is derived from Java primarily; anyone who looks at the history, particularly the Java VM wars of the mid 90s between Sun and Micro... |
1,885,021 | 1,885,428 | Problem with storing COM pointers in global singleton object | Background
The application I am working with has several COM DLLs.
One of the COM DLLs has a global singleton object, which stores pointers to COM interfaces in other DLLs. Because it is a global singleton object, I have employed the lazy initialization idiom because it is possible that the interface I am trying to ge... | Rather than implementing your own global singleton, look at using the IGlobalInterfaceTable interface instead. It is a singleton that is provided by the OS at the process level. Any of your DLLs can put their COM objects into the table, and the other DLLs can retreive them when needed. All you would need to implemen... |
1,885,450 | 1,885,468 | What is a good way to test whether a file has required permissions? | I see that ifstream::open() returns void and does not offer any way to see if the file did not open due to permissions. What is a good api to test whether read permission or alternatively write permissions are available on a file for the current process in C++?
| Try the POSIX access() function, in unistd.h
|
1,885,471 | 1,885,500 | Forward declaration of class doesn't seem to work in C++ | The follwing code is compiled in VC++6. I don't understand why I am getting the compilation error C2079: 'b' uses undefined class 'B' for the following code.
Class B Source
#include "B.h"
void B::SomeFunction()
{
}
Class B Header
#include "A.h"
struct A;
class B
{
public:
A a;
void SomeFunction(... | In order to define a class or struct, the compiler has to know how big each member variable of the class is. A forward declaration does not do this. I've only ever seen it used for pointers and (less often) references.
Beyond that, what you're trying to do here cannot be done. You cannot have a class A that contains... |
1,885,494 | 1,885,509 | CRecordset.Open only retrevies one record! | Here is the code:
CDatabase m_db;
m_db.OpenEx(_T( "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=mydb;UID=root;PASSWORD=123123;OPTION=3;"), FALSE );
CRecordset recSet(&m_db);
recSet.Open(AFX_DB_USE_DEFAULT_TYPE, _T("SELECT * From articles"), CRecordset::executeDirect);
int nRecords = recSet.GetRecordCount()... | That's a limitation of the way CRecordset works. You'll need to call MoveNext until IsEOF returns TRUE, then the record count will be accurate.
|
1,885,586 | 1,885,649 | Language Mixing: Model and View | Consider developing an application where the model will be written in C++ (with Boost), and the view will be written in Objective-C++ (with Cocoa Touch).
Where are some examples showing how to integrate C++ and Objective-C++ for developing iPhone applications?
| Take it straight from the source: Apple has documentation on using C++ With Objective-C.
There really isn't much more to it besides, in my opinion, trying to keep the C++ and Objective-C parts as cleanly seperated as possible.
In your case it comes natural:
limit definition of C++ classes et al to the C++ model
restr... |
1,885,750 | 1,887,781 | Lagged Fibonacci Rng For Project Euler #149 | Hey guys, this is very likely a total brain fart on my part but I was hoping someone could have a look at the following statement which describes how to set up the lagged fibonacci rng:
First, generate four million pseudo-random numbers using a specific form of what is known as a "Lagged Fibonacci Generator":
For 1 ≤ ... | Looks like you're having integer overflows in your code.
Try using int64_t type instead of int.
|
1,885,785 | 1,885,793 | Passing C++ strings by value or by reference | I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.
| No. Pass it by reference:
void foo(const std::string& pString);
In general, pass things by-reference if they have a non-trivial copy-constructor, otherwise by-value.
A string usually consists of a pointer to data, and a length counter. It may contain more or less, since it's implementation defined, but it's highly unl... |
1,885,849 | 1,885,897 | Difference between 'new operator' and 'operator new'? | What is difference between "new operator" and "operator new"?
| I usually try to phrase things differently to differentiate between the two a bit better, but it's a good question in any case.
Operator new is a function that allocates raw memory -- at least conceptually, it's not much different from malloc(). Though it's fairly unusual unless you're writing something like your own c... |
1,885,894 | 1,885,907 | Double Linked Lists in C++ | I have an assignment that requires us to implement a doubly linked list class. For some reason they defined the node struct as follows:
struct node {
node *next;
node *prev;
T *o;
};
It seems to me that it would be a lot easier to write the class if the struct member 'data' were not a pointer. Needless ... | the T val you create is an automatic variable. Your mistake is storing the address to that stack variable.
You should be using new to allocate space on the heap, as you suspect, but your data pointer needs to point directly to the address returned by new.
Your mistake in your latest attempt is here:
valp = &val;
You ... |
1,886,030 | 1,886,068 | Why is this explicit scope resolution necessary? | Setup:
class A {
public:
void a() {}
};
class B {
public:
void b() {}
};
class C: public A, public B {
public:
void c() {}
};
What (I thought) I should be able to do:
C* foo = new C();
foo->b();
And I get the following linker error from GCC:
`... undefined reference to 'C::b(void)'`
If I use expl... | I don't think that either of the snippets that you've posted should compile.
class C: public A, public B {
public
void c();
};
You need a : after the public access specifier.
C foo = new C();
foo->b();
You are trying to initialized a C from a pointer to dynamically allocated C object. . not -> is the correct op... |
1,886,280 | 1,886,351 | How to find determinant of large matrix | I found some C++ code for finding the determinant of matrix, for 4x4 to 8x8. It works ok, but my project needs matrices that are 18x18 or more, and the code is too slow. The code is recursive, but is recursion the right concept to deal with an 18x18 matrix? How else can I find the determinant?
| I assume you're using the naive method of expanding Laplace's formula. If you want to gain in speed, you can decompose your matrix M using LU decomposition (into two lower- and upper-diagonal matrices) which you can achieve with a modified Gauss-Jordan elimination in 2*n^3/3 FLOPS and then calculate the determinant as:... |
1,886,358 | 1,886,371 | malloc pointer function passing fread | Can't figure out what's wrong, I don't seem to be getting anything from fread.
port.h
#pragma once
#ifndef _PORT_
#define _PORT_
#include <string>
#ifndef UNICODE
typedef char chr;
typedef string str;
#else
typedef wchar_t chr;
typedef std::wstring str;
inline voi... | You're mixing pointers and references all over the place.
Your function only needs to take a pointer to the buffer:
void Read_Whole_File(char *buffer) { ... }
And you should pass that pointer as-is to fread(), don't take the address of the pointer:
size_t amount_read = fread(buffer, _length, sizeof *buffer, _file_poin... |
1,886,491 | 1,886,499 | Why does my program terminate when an exception is thrown by a destructor? | I am not getting why if there is an active exception then if an exception is raised again, it leads to termination of program. Could someone explain?
| What is it suppose to do? It can't "double catch" or anything, nor does it make sense to simply ignore one. The standard specifies that if, during stack unwinding, another exception escapes, then terminate shall be called.
There is more discussion in the C++ FAQ. One "solution" is to wrap your destructor code in a try/... |
1,886,540 | 1,886,566 | Undefined symbols error in C++ / Eclipse | I have a function to display the values of a vector in a table, but I keep getting an "Undefined symbols" error when linking.
Here is my function prototype:
void displayVectors(vector<string> & nameVec, vector<double> & scoreVec, vector<char> & gradeVec);
Here is the definition:
void dipslayVectors(vector<string> & na... | Assuming you cut & pasted your question directly, then void dipslayVectors is a misspelling in the definition
|
1,886,606 | 1,922,335 | GDB gets activated automatically and has 100% CPU activity | I'm using Debian x64 2.6.26 to host a server application we've written in C++. Sometimes GDB gets activated on its own and it uses 100% CPU time giving no room for other processes to run. The GDB version is 6.8-debian. I don't know why this happens and how may i prevent this. It seems that it only happens when out serv... | I am inclined to believe that GDB is getting called by a signal handler in some code. Another suspect is some system monitoring daemon like 'monit'. When there is a rogue process eating too much memory or CPU, it might be trying to take a backtrace or dump using GDB. On way to troubleshoot is to use 'lsof' on the GDB p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.