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,168,241 | 2,171,570 | Is it required to add 'extern C' in source file also? | I found some code recently where extern "C" was added in source file also for functions. They were also added in the header files where they were declared.
I was under the assumption that adding 'extern "C" in header files was sufficient.
Where should extern "C" blocks be added?
UPDATE:
Suppose I am compiling my C code using a CPP compiler and have added extern "C" guards for all the functions in header files (i.e. all my functions have their prototypes in headers), but in source files I have not added the same. Will this cause a problem?
| Since you mean
extern "C" { ... }
style guards, these declare some functions to be of "C" linkage, rather than "C++" linkage (which typically has a bunch of extra name decoration to support things like overloaded functions).
The purpose, of course, is to allow C++ code to interface with C code, which is usually in a library. If the library's headers weren't written with C++ in mind, then they won't include the extern "C" guards for C++.
A C header written with C++ in mind will include something along the lines of
#ifdef __cplusplus
extern "C" {
#endif
...
#ifdef __cplusplus
}
#endif
to make sure C++ programs see the correct linkage. However, not all libraries were written with C++ in mind, so sometimes you have to do
extern "C" {
#include "myclibrary.h"
}
to get the linkage correct. If the header file is provided by someone else then it's not good practice to change it (because then you can't update it easily), so it's better to wrap the header file with your own guard (possibly in your own header file).
extern "C" isn't (AFAIK) ANSI C, so can't be included in normal C code without the preprocessor guards.
In response to your edit:
If you are using a C++ compiler, and you declare a function as extern "C" in the header file, you do not need to also declare that function as extern "C" in the implementation file. From section 7.5 of the C++ standard (emphasis mine):
If two declarations of the same
function or object specify different
linkage-specifications (that is, the
linkage-specifications of these
declarations specify different
string-literals), the program is
ill-formed if the declarations appear
in the same translation unit, and the
one definition rule
applies if the declarations appear in
different translation units. Except
for functions with C++ linkage, a
function declaration without a linkage
specification shall not precede the
first linkage specification for that
function. A function can be declared
without a linkage specification after
an explicit linkage specification has
been seen; the linkage explicitly
specified in the earlier declaration
is not affected by such a function
declaration.
I'm not convinced it's good practice though, since there's the potential for the linkage specifications to diverge by accident (if, for example, the header file containing the linkage specification isn't included in the implementing file). I think it's better to be explicit in the implementation file.
|
2,168,329 | 2,168,653 | RegQueryValueEx() always returns only 4 bytes of the string | What im doing wrong this time? The following code always returns 4 bytes only, instead of the whole string:
HKEY hkey;
DWORD dwType, dwSize;
char keybuffer[512];
if(RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("software\\company name\\game name"), 0, KEY_READ, &hkey) == ERROR_SUCCESS){
dwType = REG_SZ;
dwSize = sizeof(keybuffer);
RegQueryValueEx(hkey, TEXT("setting"), NULL, &dwType, (PBYTE)&keybuffer, &dwSize);
RegCloseKey(hkey);
}
Even if i change dwSize to anything, it will still return 4 bytes.
Edit: Apparently there was no bug in above code, but somewhere else -_-
| I see two more potential pitfalls here. First, as Francis mentioned, you should check the return value. Do the 4 bytes actually correspond to the string characters you expect? They might be anything. From the documentation:
If the buffer specified by lpData parameter is not large enough to hold the data, the function returns ERROR_MORE_DATA and stores the required buffer size in the variable pointed to by lpcbData. In this case, the contents of the lpData buffer are undefined.
The second potential pitfall is that you're using a char array with a function that takes TCHAR parameters. If you're compiling for Unicode, the compiler will happily let you write a wide string to your narrow string buffer, due to the cast to PBYTE. It's safer to either use TCHAR consistently or don't use it at all (i.e. call RegQueryValueExA or RegQueryValueExW).
|
2,168,362 | 2,168,379 | iostream use of << to construct string | How can << be used to construct a string ala
int iCount;
char szB[128];
sprintf (szB,"%03i", iCount);
| using namespace std;
stringstream ss;
ss << setw(3) << setfill('0') << iCount;
string szB = ss.str();
|
2,168,365 | 2,169,201 | In what language is there a "guard" keyword or concept? | I recently tried to understand a C++ program that was written by somebody who I assume had a background in functional programming: For example, he had declared a closure class which he extensively used and which does somewhat resemble what is known as a closure in functional programming. Another class was called a guard, but I haven't quite figured out yet what it is good for. It seems to have some sort of cleanup functionality attached to it.
The only language in which I have seen a concept called guard is Erlang, but that does not remotely look similar to the code I found. In what other languages does such a concept exist that the author of the C++ code may have alluded to?
| To me it sounds like he was using RAII.
The class constructor/destructor is used to symetrically handle some form of resource allocation/release in an exception safe context (What Java programmers would call finally {} as the destructor is guranteed to be called.).
This is a very common C++ idiom and is ued extensively in modern C++.
Did the code look like this:
void Plop()
{
Guard guard(lock);
// Do lots of stuff
}
Here the guard is locking the lock in the constructor and unlocking the lock in the destructor.
|
2,168,446 | 2,168,466 | Method of derived class needs to downcast its parameter | Here is a sample code:
class Base {
public:
virtual void common();
};
class Derived {
public:
void common();
virtual void spec(); // added function specific for this class
};
class BaseTracker {
public:
void add(Base* p);
private:
vector < Base* > vec;
};
class DerivedTracker {
public:
void add(Derived* p);
private:
vector < Derived* > vec;
};
I want DerivedTracker and BaseTracker to be derived from class Tracker, because a lot of code for these two classes is the same, except one method, add(). DerivedTracker::add() method needs to call functions specific to Derived class. But I don't want to do dynamic casting. I think it is not the case when I should use it. Also Tracker class should include container, so functions which are implemented in this class could use it.
| It sounds like the Tracker class would best be a template instead of being derived from a common ancestor:
template<typename Element>
class Tracker {
public:
void add(Element* p);
private:
vector< Element* > vec;
};
typedef Tracker<Base> BaseTracker;
typedef Tracker<Derived> DerivedTracker;
You could then add a specialization of the add() method that uses Derived's special features:
template<>
void Tracker<Derived>::add(Derived* p) {
p->spec();
vec.push_back(p);
}
|
2,168,996 | 2,169,088 | How to write unicode character farsi in C++ in ms-dos console? | How to write unicode character farsi in c++ in ms-dos?
cout<<"Helo world"<<"سلام جهان";
| #include <iostream>
#include <locale>
#include <string>
int main()
{
using namespace std;
wstring wcs = L"中文";
locale old = wcout.imbue(locale("") ); // "" is environment's default locale
wcout<<wcs<<endl;
wcout.imbue(old ); // restore old locale
}
|
2,169,092 | 2,319,728 | Low-Level C++ App Crashes on Windows Vista/7 Unless Run in XP Compatibility Mode | I have a low-level (like really low-level, it's basically all IOCTL calls and several calls to enumeration APIs) that crashes sporadically on Windows Vista/7 on clients' machines. Unfortunately, I have not been able to procure any crash dumps but one helpful user did mention that running the program in XP Compatibility Mode solved the problem.
The application is always launched with full admin rights (it's launched from another program that requires admin authorization) so it's not a UAC issue. I don't use any deprecated APIs and I'm not relying on any registry hacks, etc. I'm just issuing calls to enumerate disks, then using IOCTL commands to get some more low-level info about all attached devices.
What happens in XP Compatibility mode? What does Windows inject into my application or otherwise sandbox it with that prevents it from crashing on Vista/7? I had originally suspected heap corruption (though I've pulled my hair out attempting to replicate or to track down the issue) before being told that it runs fine in XP Compatibility Mode.
Can anyone suggest any possible issues that would be avoided in XP Compat Mode that I should look into to try to address this issue? Thanks!
EDIT:
One more thing that's probably very important to mention: I'm calling DDK/Kernel functions from userspace in order to get at certain features not exposed via the WIN32 API.
I'm using ZwReadFile, ZwCreateFile, ZwWriteFile, RtlInitUnicodeString, ZwQueryVolumeInformationFile, ZwDeviceIoControlFile, ZwSetInformationFile, ZwClose.
The IOCTLs I'm calling include IOCTL_DISK_GET_PARTITION_INFO_EX, IOCTL_STORAGE_GET_DEVICE_NUMBER, IOCTL_DISK_GET_LENGTH_INFO, and IOCTL_DISK_GET_DRIVE_LAYOUT_EX.
| This is very odd, but I was calling ZwQueryVolumeInformationFile with FsInformationClass set to FileFsVolumeInformation.
I had passed in a buffer of FILE_FS_VOLUME_INFORMATION first normally allocated, then overallocated to (sizeof(FILE_FS_VOLUME_INFORMATION) + sizeof(TCHAR)*FILE_FS_VOLUME_INFORMATION->VolumeLabelLength).
Then I called
FILE_FS_VOLUME_INFORMATION->VolumeLabel[FILE_FS_VOLUME_INFORMATION->VolumeLabelLength/2] = _T('\0'); and only on some machines this would result in memory corruption.
Regardless of the size of the overallocation (even tried allocating a full 256 chars extra!), this would reliably result in heap corruption even when using a vector<unsigned char> as the FILE_FS_VOLUME_INFORMATION buffer.
It seems that the kernel places some sort of write protection on the buffer somehow that was resulting in corruption regardless of the size. Copying the first VolumeLableLength bytes to a second buffer, then post-pending _T('\0') solved the problem. Not sure how/why Windows was making the buffer that I allocated and passed in as a parameter readonly or if it was storing after the FILE_FS_VOLUME_INFORMATION struct (which should end with the character array!), but simply not modifying any data in the buffer that I passed did the trick.... which is crazy because it only happens (consistently and 100% reproducible) on certain machines.
At any rate: problem solved *phew*!
|
2,169,322 | 2,169,355 | When to use pointers in C++ | I just started learning about pointers in C++, and I'm not very sure on when to use pointers, and when to use actual objects.
For example, in one of my assignments we have to construct a gPolyline class, where each point is defined by a gVector. Right now my variables for the gPolyline class looks like this:
private:
vector<gVector3*> points;
If I had vector< gVector3 > points instead, what difference would it make? Also, is there a general rule of thumb for when to use pointers? Thanks in advance!
| The general rule of thumb is to use pointers when you need to, and values or references when you can.
If you use vector<gVector3> inserting elements will make copies of these elements and the elements will not be connected any more to the item you inserted. When you store pointers, the vector just refers to the object you inserted.
So if you want several vectors to share the same elements, so that changes in the element are reflected in all the vectors, you need the vectors to contain pointers. If you don't need such functionality storing values is usually better, for example it saves you from worrying about when to delete all these pointed to objects.
|
2,169,384 | 2,169,658 | Is CLIM possible in C++? | CLIM = Common Lisp Interface Manager, it's like the REPL, ported to the GUI.
Is something like this similar possible in C++? If so, pointers?
Thanks!
| Here's a REPL built atop GNU C++:
http://www.artificialworlds.net/wiki/IGCC/IGCC
There's no reason why it shouldn't work okay these days - it probably builds up a short program from successive statements, which on a modern machine will compile and run to display output in short order.
From the look of the examples, it could use a simple improvement: a line of input with no semicolon should be treated as an expression to be evaluated, so if you want to know the value of a, just enter a and it would be equivalent to:
std::cout << a << std::endl;
|
2,169,387 | 2,169,551 | X throws out errors when forkpty is called. (C++) | When my program gets to this line:
pid_t nPid = forkpty( &m_nMasterFD, NULL, NULL, NULL );
Outputs this:
X Error: BadIDChoice (invalid resource ID chosen for this connection) 14
Extension: 148 (RENDER)
Minor opcode: 17 (RenderCreateGlyphSet)
Resource id: 0x3600002
<unknown>: Fatal IO error 4 (Interrupted system call) on X server :0.0.
And terminates. As you can see, I'm trying to make a pty to run stuff in, but it's not working.
Also, is there a way forkpty() can be called within a class? ( I tried both ways, but neither worked. )
I'm programming in QT C++ on Ubuntu 9.10.
EDIT: Here's a link to the question with the code that finally worked for me.
| forkpty() forks your process. You need to close the filedescriptors first, in particular the connection to the X server in your child process. This means you likely cannot use forkpty , but have to use openpty(), fork(),close filedescriptors in the child process, logintty/()
|
2,169,441 | 2,169,451 | C++ typedef question | if I make a typedef someobject* pntr;
I can use this typedef to make a pointer to point to an object of type someobject. but can I also use a pointer made from this typedef to point to an array of someobject?
| Yes:
pntr p = new someobject[10];
However, it is considered poor style in both C++ and C to use typedefs to disguise the fact that something is a pointer, so don't do this.
|
2,169,460 | 2,169,505 | Polymorphism by function parameter | Ok - this may be a very stupid question, but it's been bothering me.
Is there a language where
class Animal;
class Ape : public Animal
{...}
void doStuff(Animal* animalPtr)
{
cout << "doing animal stuff" << endl;
}
void doStuff(Ape* apePtr)
{
cout << "doing ape stuff" << endl;
}
Animal *ape = new Ape();
doStuff(ape);
would yield "doing ape stuff"? (please bear with me using C++ syntax)
To clarify, I want "a function that accepts an argument and acts on it according to the type of the argument".
And would it make sense? Of course, as a developer you'd need to take care since instances that look just like an Animal pointer might actually call Ape code, because at runtime it's an Ape instance being pointed to.
| Yes, there are! This is called multiple dispatch. The Wikipedia article is very good. Sadly, it seem to only be supported via language extensions for most popular languages, but there are a few (mostly esoteric) languages which support it natively.
|
2,169,828 | 2,169,912 | Is there a better (more modern) tool than lex/flex for generating a tokenizer for C++? | I recent added source file parsing to an existing tool that generated output files from complex command line arguments.
The command line arguments got to be so complex that we started allowing them to be supplied as a file that was parsed as if it was a very large command line, but the syntax was still awkward. So I added the ability to parse a source file using a more reasonable syntax.
I used flex 2.5.4 for windows to generate the tokenizer for this custom source file format, and it worked. But I hated the code. global variables, wierd naming convention, and the c++ code it generated was awful. The existing code generation backend was glued to the output of flex - I don't use yacc or bison.
I'm about to dive back into that code, and I'd like to use a better/more modern tool. Does anyone know of something that.
Runs in Windows command prompt (Visual studio integration is ok, but I use make files to build)
Generates a proper encapsulated C++ tokenizer. (No global variables)
Uses regular expressions for describing the tokenizing rules (compatible with lex syntax a plus)
Does not force me to use the c-runtime (or fake it) for file reading. (parse from memory)
Warns me when my rules force the tokenizer to backtrack (or fixes it automatically)
Gives me full control over variable and method names (so I can conform to my existing naming convention)
Allows me to link multiple parsers into a single .exe without name collisions
Can generate a UNICODE (16bit UCS-2) parser if I want it to
Is NOT an integrated tokenizer + parser-generator (I want a lex replacement, not a lex+yacc replacement)
I could probably live with a tool that just generated the tokenizing tables if that was the only thing available.
| Ragel: http://www.complang.org/ragel/ It fits most of your requirements.
It runs on Windows
It doesn't declare the variables, so you can put them inside a class or inside a function as you like.
It has nice tools for analyzing regular expressions to see when they would backtrack. (I don't know about this very much, since I never use syntax in Ragel that would create a backtracking parser.)
Variable names can't be changed.
Table names are prefixed with the machine name, and they're declared "const static", so you can put more than one in the same file and have more than one with the same name in a single program (as long as they're in different files).
You can declare the variables as any integer type, including UChar (or whatever UTF-16 type you prefer). It doesn't automatically handle surrogate pairs, though. It doesn't have special character classes for Unicode either (I think).
It only does regular expressions... has no bison/yacc features.
The code it generates interferes very little with a program. The code is also incredibly fast, and the Ragel syntax is more flexible and readable than anything I've ever seen. It's a rock solid piece of software. It can generate a table-driven parser or a goto-driven parser.
|
2,169,867 | 2,219,028 | How to detect the current input language? | I am looking for a working code snippet for Symbian S60 5th edition in which:
a) an application can detect the current input language (not the UI language);
b) an application can receive notifications when current input language is changed.
The function CurrentLanguage() from CPtiEngine always returns NULL, so that does not seem to be an option.
Thank you.
| I eventually found the answer on my own. Here is the code:
CAknSettingCache& cache = CAknEnv::Static()->SettingCache();
TLanguage lang = cache.InputLanguage();
|
2,169,916 | 2,170,010 | How to check if button is pressed and working on LPT port in C++ | I have a button I got out of a random item around the house and I wanna hook it up to my LPT port and check if its pressed or not in C++ and if it is display a message.
| Your best bet is to use the inpout32.dll which will enable you to read/write from/to the LPT port. The usage of direct addressing of hardware ports is restricted, the dll will enable you to get around the restriction as it executes an internal driver which is already built into the dll and therefore communicating with the driver in an indirect fashion. The dll can be downloaded from here, there is one available for x64bit platform here.
Hope this helps,
Best regards,
Tom.
|
2,169,920 | 2,169,928 | Do <cctype> functions work with Unicode? | Page 601 of the C++ Special Edition says...
In <ctype.h> and <cctype>, the standard library provides a set of useful functions for dealing with ASCII and similar character sets.
Would Unicode fall under this "similar character sets" category?
| Unicode support has been a major pain point of the language. You will have to set a locale for non-ANSI and use the wchar_t variants. The exact meaning of the wchar_t varies with implementation. E.g:
setlocale(LC_CTYPE, "en_ca.UTF-8");
Take a look at the the Unicode Consortium page on locales.
|
2,169,932 | 2,170,078 | non-class rvalues always have cv-unqualified types | §3.10 section 9 says "non-class rvalues always have cv-unqualified types". That made me wonder...
int foo()
{
return 5;
}
const int bar()
{
return 5;
}
void pass_int(int&& i)
{
std::cout << "rvalue\n";
}
void pass_int(const int&& i)
{
std::cout << "const rvalue\n";
}
int main()
{
pass_int(foo()); // prints "rvalue"
pass_int(bar()); // prints "const rvalue"
}
According to the standard, there is no such thing as a const rvalue for non-class types, yet bar() prefers to bind to const int&&. Is this a compiler bug?
EDIT: Apparently, this is also a const rvalue :)
EDIT: This issue seems to be fixed in g++ 4.5.0, both lines print "rvalue" now.
| The committee already seems to be aware that there's a problem in this part of the standard. CWG issue 690 talks about a somewhat similar problem with exactly the same part of the standard (in the "additional note" from September, 2009). I'd guess new language will be drafted for that part of the standard soon.
Edit: I've just submitted a post on comp.std.c++, noting the problem and suggesting new wording for the relevant piece of the standard. Unfortunately, being a moderated newsgroup, nearly everybody will probably have forgotten this question by the time it makes it through the approval queue there.
|
2,169,948 | 2,172,689 | Using code generated by Py++ as a Python extension | I have a need to wrap an existing C++ library for use in Python. After reading through this answer on choosing an appropriate method to wrap C++ for use in Python, I decided to go with Py++.
I walked through the tutorial for Py++, using the tutorial files, and I got the expected output in generated.cpp, but I haven't figured out what to do in order to actually use the generated code as an extension I can import in Python. I'm sure I have to compile the code, now, but with what? Am I supposed to use bjam?
| Py++ generates you syntax you use along with boost::python to generate python entry points in your app.
Assuming everything went well with Py++ you need to download the Boost framework, and add the boost include directory and the boost::python lib to your project then compile with the Py++ generated cpp.
You can use whatever build system you want for your project, but boost is built with bjam. You need to choose whether you want a static lib or a dynamic boost python lib then follow the instructions for building boost here.
If on windows, you need to change the extension on your built library from .dll to.pyd. And yes it needs to be a library project, this does not work with executables.
Then, place the pyd where the python on your machine can find it and go into python and execute import [Your-library-name] and hopefully everything will work.
One final note, the name given in generated.cpp in this macro:
BOOST_PYTHON_MODULE( -name- )
needs to be the exact name of your project, otherwise python will complain.
I just went through all this less than a month ago so I know about the confusion.
One thing I did to make my python extension very easy to use while building the library and testing, was to build boost::python and python myself in my build environment. That way the pyd ends up exactly where I want it and users do not need to install python in order to run with my extension. That may be overkill for what you are doing though.
Edit:
If you want your extension to be easily installed and compiled on a machine, check out python's setuptools. With just a few simple lines you can have python compile and install your package for you. One downside though is its not IDE compatible for those of us who like developing in visual studio.
|
2,170,064 | 2,170,102 | STL-Like range, What could go wrong if I did this? | I am writing (as a self-teaching exercise) a simple STL-Like range. It is an Immutable-Random-Access "container". My range, keeps only the its start element, the the number of elements and the step size(the difference between two consecutive elements):
struct range
{
...
private:
value_type m_first_element, m_element_count, m_step;
};
Because my range doesn't hold the elements, it calculates the desired element using the following:
// In the standards, the operator[]
// should return a const reference.
// Because Range doesn't store its elements
// internally, we return a copy of the value.
value_type operator[](size_type index)
{
return m_first_element + m_step*index;
}
As you can see, I am not returning a const reference as the standards say. Now, can I assume that a const reference and a copy of the element are the same in terms of using the non-mutating algorithms in the standard library?
Any advice about the subject is greatly appreciated.
@Steve Jessop: Good point that you mentioned iterators.
Actually, I used sgi as my reference. At the end of that page, it says:
Assuming x and y are iterators from the same range:
Invariants Identity
x == y if and only if &*x == &*y
So, it boils down to the same original question I've asked actually :)
| The standard algorithms don't really use operator[], they're all defined in terms of iterators unless I've forgotten something significant. Is the plan to re-implement the standard algorithms on top of operator[] for your "ranges", rather than iterators?
Where non-mutating algorithms do use iterators, they're all defined in terms of *it being assignable to whatever it needs to be assignable to, or otherwise valid for some specified operation or function call. I think all or most such ops are fine with a value.
The one thing I can think of, is that you can't pass a value where a non-const reference is expected. Are there any non-mutating algorithms which require a non-const reference? Probably not, provided that any functor parameters etc. have enough const in them.
So sorry, I can't say definitively that there are no odd corners that go wrong, but it sounds basically OK to me. Even if there are any niggles, you may be able to fix them with very slight differences in the requirements between your versions of the algorithms and the standard ones.
Edit: a second thing that could go wrong is taking pointers/references and keeping them too long. As far as I can remember, standard algorithms don't keep pointers or references to elements - the reason for this is that it's containers which guarantee the validity of pointers to elements, iterator types only tell you when the iterator remains valid (for instance a copy of an input iterator doesn't necessarily remain valid when the original is incremented, whereas forward iterators can be copied in this way for multi-pass algorithms). Since the algorithms don't see containers, only iterators, they have no reason that I can think of to be assuming the elements are persistent.
|
2,170,222 | 2,170,237 | PThread vs boost::thread? | Having no experience with threading in the past, which threading technique in C++ will be the easiest for a beginner? boost::thread or pthreads?
| Go for boost::thread. It's closely related to the work on the upcoming C++ standard threads, and the interface is quite easy to use and idiomatic to C++ (RAII instead of manual resource management).
|
2,170,523 | 2,171,721 | CoreAudio AudioUnitSetProperty always fails to set Sample Rate | I need to change the output sample rate from 44.1 to 32.0, but it always throws an error, Out: AudioUnitSetProperty-SF=\217\325\377\377, -10865. I don't know why it will let me set it for input, but then not set it for output.
My code is:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
OSStatus MyRenderer(void *inRefCon, AudioUnitRenderActionFlags *ioActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList *ioData){
NSLog(@"Running...");
ioData->mBuffers[0].mDataByteSize = 2048;
ioData->mBuffers[0].mData = lbuf;
ioData->mBuffers[0].mNumberChannels = 1;
return noErr;
}
void CreateDefaultAU(){
OSStatus err = noErr;
// Open the default output unit
AudioComponentDescription desc;
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_DefaultOutput;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
desc.componentManufacturer = 0;
AudioComponent comp = AudioComponentFindNext(NULL, &desc);
if (comp == NULL) { printf ("FindNextComponent\n"); return; }
err = AudioComponentInstanceNew(comp, &gOutputUnit);
if (comp == NULL) { printf ("OpenAComponent=%ld\n", err); return; }
// Set up a callback function to generate output to the output unit
AURenderCallbackStruct input;
input.inputProc = MyRenderer;
input.inputProcRefCon = NULL;
err = AudioUnitSetProperty(gOutputUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, sizeof(input));
if (err) { printf ("AudioUnitSetProperty-CB=%ld\n", err); return; }
AudioStreamBasicDescription streamFormat;
streamFormat.mSampleRate = 32000.00; // the sample rate of the audio stream
streamFormat.mFormatID = kAudioFormatLinearPCM; // the specific encoding type of audio stream
streamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger;//kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsNonMixable;
streamFormat.mFramesPerPacket = 1;
streamFormat.mChannelsPerFrame = 1;
streamFormat.mBitsPerChannel = 16;
streamFormat.mBytesPerPacket = 2;
streamFormat.mBytesPerFrame = 2;
err = AudioUnitSetProperty(gOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &streamFormat, sizeof(streamFormat));
if (err) { printf ("In: AudioUnitSetProperty-SF=%4.4s, %ld\n", (char*)&err, err); return; }
err = AudioUnitSetProperty(gOutputUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &streamFormat, sizeof(streamFormat));
if (err) { printf ("Out: AudioUnitSetProperty-SF=%4.4s, %ld\n", (char*)&err, err); return; }
}
void TestDefaultAU(){
OSStatus err = noErr;
// Initialize unit
err = AudioUnitInitialize(gOutputUnit);
if (err) { printf ("AudioUnitInitialize=%ld\n", err); return; }
Float64 outSampleRate;
UInt32 size = sizeof(Float64);
err = AudioUnitGetProperty(gOutputUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &outSampleRate, &size);
printf("Out srate %f\n",outSampleRate);
if (err) { printf ("AudioUnitSetProperty-GF=%4.4s, %ld\n", (char*)&err, err); return; }
AudioOutputUnitStart (gOutputUnit);
if (err) { printf ("AudioOutputUnitStart=%ld\n", err); return; }
AudioUnitReset (gOutputUnit, kAudioUnitScope_Input, 0);
}
| With the DefaultOuput AudioUnit you only set the input side of the AudioUnit to the format you wish to render. The output side of the unit will match what you specify on the input side but you cannot set it yourself.
Try this after you have set the input stream format and you'll see that you are all set to go...
Float64 outSampleRate = 0.0;
UInt32 size = sizeof(Float64);
AudioUnitGetProperty (gOutputUnit,
kAudioUnitProperty_SampleRate,
kAudioUnitScope_Output,
0,
&outSampleRate,
&size);
NSLog(@"Output sample rate is now at %f Hz", outSampleRate);
You can also look at the Audio Unit Component Services Reference to see that error code -10865 is kAudioUnitErr_PropertyNotWritable.
|
2,170,541 | 2,170,565 | What operations are thread-safe on std::map? | Suppose I have:
stl::map<std::string, Foo> myMap;
is the following function thread safe?
myMap["xyz"] ?
I.e. I want to have this giant read-only map that is shared among many threads; but I don't know if even searching it is thread safe.
Everything is written to once first.
Then after that, multiple threads read from it.
I'm trying to avoid locks to make this as faast as possible. (yaya possible premature optimization I know)
| In theory no STL containers are threadsafe. In practice reading is safe if the container is not being concurrently modified. ie the standard makes no specifications about threads. The next version of the standard will and IIUC it will then guarantee safe readonly behaviour.
If you are really concerned, use a sorted array with binary search.
|
2,170,637 | 2,170,664 | How to view source code of header file in C++? | similar to iostream.h ,conio.h , ...
| The standard library is generally all templates. You can just open up the desired header and see how it's implemented†. Note it's not <iostream.h>, it's <iostream>; the C++ standard library does not have .h extensions. C libraries like <string.h> can be included as <cstring> (though that generally just includes string.h)
That said, the run-time library (stuff like the C library, not-template-stuff) is compiled. You can search around your compiler install directory to find the source-code to the run-time library.
Why? If just to look, there you go. But it's a terrible way to try to learn, as the code may have non-standard extensions specific to the compiler, and most implementations are just generally ugly to read.
If you have a specific question about the inner-workings of a function, feel free to start a new question and ask how it works.
† I should mention that you may, on the off chance, have a compiler that supports export. This would mean it's entirely possible they have templated code also compiled; this is highly unlikely though. Just should be mentioned for completeness.
|
2,170,725 | 2,170,756 | How does the following foward-declared multi-inheritance pointer converted code work? | In the followint code, how does the pointer conversion & multi-inheritance play together?
class Foo {
public:
virtual void someFunc();
};
class Bar;
void someWork(Bar *bar) {
((Foo*) bar)->someFunc();
}
class Bar: public Zed, public Foo {
...
virtual void someFunc() { ... do something else ... }
}
Bar bar;
int main() {
someWork(&bar);
}
My understanding is kinda shaky.
On one hand, someWork knows nothing about Bar, so this shouldn't work; but on the other hand, I have forward declared Bar.
Thanks!
| This doesn't work and it isn't doing quite what you think it is. Your use of the c-style cast:
(Foo*) bar
is incorrect in this case. What you are trying to do is upcast the Bar* to a Foo* (i.e., perform a static_cast from a pointer to a dervied class to a pointer to a base class).
Since the definition of Bar is not available at this point, however, the compiler does not know that Foo is a base class of Bar. Thus, the static_cast fails and the compiler falls back and uses a reinterpret_cast, which is not at all the same thing.
|
2,170,785 | 2,170,804 | Guarantees on address of baseclass in C++? | In C struct's, I'm guaranteed that:
struct Foo { ... };
struct Bar {
Foo foo;
...
}
Bar bar;
assert(&bar == &(bar.foo));
Now, in C++, if I have:
class Foo { ... };
class Bar: public Foo, public Other crap ... {
...
}
Bar bar;
assert(&bar == (Foo*) (&bar)); // is this guaranteed?
If so, can you give me a reference (like "The C++ Programming Language, page xyz")?
Thanks!
| There is no guarantee. From the C++03 standard (10/3, class.derived):
The order in which the base class subobjects are allocated in the most derived object (1.8) is unspecified.
|
2,170,886 | 2,170,904 | Dynamic array allocation in C++ question | I have a struct of type Duplicate
I have a variable of type int called stringSize, it has a value of 5
I am creating a dynamic array:
Duplicate *duplicates;
duplicates = new Duplicate[stringSize - 1];
Later I delete[] duplicates;
I'm getting one member in that array only? I've verified that stringSize - 1 = 4 with a debug walk through. What can I do to get the 4 members I need?
Any help appreciated,
Thanks // :)
| Duplicate *duplicates;
duplicates = new Duplicate[stringSize - 1];
Indeed gives you duplicates[0-3] (Assuming stringSize - 1 is 4, like you say). How are you determining you're getting less?
I suspect you may be doing something like: sizeof(duplicates) / sizeof(duplicates[0]), and on an off-change getting one. The above code only works for statically allocated arrays, where sizeof(duplicates) would match the size of the array, in bytes. In your case, it'll simply return the size of a pointer on your system. (duplicates is a Duplicate*)
And mandatory: Use std::vector if this is "real" code.
Your debugger is doing the best it can. As far is it's concerned, you've merely got a pointer to some data. Consider:
Duplicate foo;
Duplicate *duplicates_A;
duplicates_A = &foo; // points to one Duplicate
Duplicate *duplicates_B;
duplicates_B = new Duplicate[4]; // points to memory containing 4 Duplicate's
bar(duplicates_A);
bar(duplicates_B);
void bar(Duplicate* p)
{
// is p a pointer to one value, or is it an array?
// we can't tell, and this is the same boat your debugger is in
}
How should the debugger, just given a pointer, know if it's pointing to an array or just one value? It cannot, safely. (It would have to determine, somehow, if the pointer was to an array, and the size of that array.)
|
2,170,972 | 2,171,022 | Seeking tool to graphically show (header) file dependancies in C/C++ | I know that header guards avoid (most) trouble; call me @n@l if you like, but I just don't like a sloppy header-file tree.
If I draw on paper a box for each header file and connect them by lines representing #include, I like to see a neat hierarchy. But what I usually see is a complex web.
Maybe I am @n@l, but to me that tangled web represents sloppy-thinking and I would like to induce order by reorganizing the #include hierarchy.
Does anyone know of a tool which will let me vizualize the #include hierarchy? Preferably a free tool.
(and, yes, I know that I "could probably do it with graphviz dot", but that is not an answer ;-)
| Doxygen can do this for you if you use it along with the dot tool.
Here is an example: http://www.neuraladvance.com/json-c/html/json_8h.html
|
2,171,041 | 2,171,620 | how to change address of variable? | i have
Tree<std:string> tree;
now
new Tree<std:string>;
leads to a pointer,
how can i change address of tree to that of pointer generated by new?
| Making C++ code look like Java is a bad idea, the two languages are very different.
That said, in C++ operator new returns a pointer to the allocated object.
Tree<std::string> * tree = new Tree<std::string>;
tree->do_something();
You can also bind a reference to your object.
Tree<std::string> & tree2 = *tree;
tree.do_something();
I urge you not to do that. Writing -> instead of . is not that difficult.
|
2,171,047 | 2,171,153 | bad_alloc in detail? | I work on a game project. Recently, we run into a problem which we catch a "bad_alloc" exception when we load/unload different scenes for about three times.
Eachtime we load a scene, we first load the compressed .zip folder into the memory and then extract game objects from it. Since we don't have any memory profiler tool, I simply use the performance graph of Process Explorer to see what is going on:
Run the game ==> ~620 MB
Load the 1st scene ==> ~1.1 GB
Unload it ==> ~620 MB
Load the 2nd scene ==> ~1.1 GB
Unload it ==> ~620 MB
Load the 3rd scene ==> bad_alloc
I trace down to the new operator of each load. The loading of the compressed folder costs 100~120 MB memory itself, and the bad_alloc is throw from it at the 3rd load.
Our platform is installed with 2GB physics memory. It seems that we do not left anything behind after unloading the scene. Each compressed folder is about the same size. However, the new operator of the 3rd load just doesn't work.
I'm wondering, what's the possible meaning of this bad_alloc? Out of memory? or simply can't allocate a contiguous block of the required size? If it does have several possibility, how can I determine it?
Any help is apppreciated, thanks!
| If you are allocating all that memory at a time (only one new), probably the heap is too fragmented to find enough contiguous memory to allocate what you requested.
That could be solved by allocating the new scene by parts.
|
2,171,081 | 2,171,186 | how c++ implements the polymorphism internally? | Respected Sir!
i should tell you that what i know and what i don't know about the asked question so that you can address the weak area of my understanding.
i know that c++ implements the polymorphism by using the Vtable which is array of pointers
each pointer points to the virtual function of the class, each class in the hierarchy has a vtable. now suppose i have the following class
class person
{
char name[20];
public:
person(char* pname)
{
strcpy(name,pname);
}
virtual void show()
{
cout<<"inside person show method, Name: "<<name;
}
};
class teacher:public person
{
int scale;
teacher(char*pname, int s):person(pname)
{
scale=s;
}
void show()
{
cout<<"inside the teacher show method, Scale: "<<scale;
}
};
now suppose i write in main program
person *ptr;
ptr=new teacher(16,"Zia");
ptr->show();
now i am confuse at this point, the call will go to the show function of the base class, now as it is a virtual function so it inturn calls the approprite function. i know i am wrong here. i am confused that what would be the sequence of calls. What is the role of Vtable and how it works please elaborate.
| I think you should draw attention to Stanley B. Lippman's book "Inside C++ object model".
Lets look for internal presentation for your classes:
Virtual Table for person and teacher
|---------------| +---> |------------------------|
| name | | | "type_info" for person |
|---------------| | |------------------------|
|__vptr__person |--+ | "person::~person" |
|---------------| |------------------------|
person p; | "person::show" |
|------------------------|
|----------------| +---> |-------------------------|
|person subobject| | | "type_info" for teacher |
|----------------| | |-------------------------|
|__vptr__teacher |--+ | "teacher::~teacher" |
|----------------| |-------------------------|
teacher t; | "teacher::show" |
|-------------------------|
In general, we don't know the exact type of the object ptr addresses at each invocation of show(). We do know, however, that through ptr we can access the virtual table associated with the object's class.
Although we don't know which instance of show() to invoke, we know that each instance's address is contained in slot 2.
This information allows the compiler to internally transform the call into
( *ptr->vptr[ 2 ] )( ptr );
In this transformation, vptr represents the internally generated virtual table pointer inserted within each class object and 2 represents show()'s assigned slot within the virtual table associated with the Point hierarchy. The only thing we need to do in runtime is compute ptr's dynamic type (and appropriate vtable) using RTTI.
|
2,171,181 | 2,171,200 | Declaring a variable as a "Class" datatype, without calling the "Class" constructor? | Forgive me if I'm just blatantly missing something, but I'm trying to make the transition from structs and c to classes and c++.
Heres what I'm trying to do:
A have a "Checkers" class and a "Board" class.
Now with structs, I could just create an array of Checkers in my "board.cpp" file by doing:
Checker checkers[2][12]
(0 and 1 for each side, 0-11 for each piece)
The problem is that with classes, doing the same declaration will attempt to call the "Checkers" constructor. I get this error: "error: no matching function for call to ‘Checker::Checker()’"
My Checker constructor deals with initializing an individual piece (like if it is on side 0 or 1, piece 0-11), so I didnt mean to call it there.
Is there a way to avoid this, or am I going about this the wrong way? Thanks.
EDIT: Or maybe I should just design the constructor to initialize an array of checkers? Can you even declare variables as a datatype of a class/object?
| Create a default constructor. Then use an initial function. I do recomend you use STL vector.
|
2,171,247 | 2,171,559 | standalone tool for generating makefile(s) from Eclipse's .cproject file? | Is there a standalone tool, that can be ran from a shell script, to generate a makefile from the .cproject? Actually, the same functionality as the CDT itself, but that can be non-interactive.
As is probably obvious, I want to be able to run a script that checkouts and builds the software, comprising from several C++ project. I am trying to avoid moving to a build system like maven, as it seems as like an overhead in this early stage of our project. thanks!
| I know that there was discussions on the CDT-dev mailinglist a few months back about having a command-line tool for building CDT projects. Writing such a tool is really not very difficult (there was an example mentioned), it is simply a matter of defining your own Eclipse-application, load the project, and build it. Searching the CDT-dev list on "standalone build" should give you some relevant hits.
|
2,171,263 | 2,191,822 | Release a socket in Boost.Asio (opposite of assign), or don't transfer ownership | There is a function assign in Boost.Asio sockets, however I'm looking for something like
release/unassign that would transfer the ownership on socket back to user.
or
some type of assign that would not transfer ownership to socket class, so it would not close it when destroyed.
I'm aware of this solution but it involves duplicating socket (i.e. creating new descriptor rather then releasing one).
Does anybody knows how can this be done?
Edit: There is no such feature, opened ticket for Boost.Asio https://svn.boost.org/trac/boost/ticket/3900
| I couldn't find any such way in the .hpp files (Boost 1.35), so I think you'll have to patch ASIO yourself and add a release() method. When done, you could keep the patch for yourself, post it on your website (or here), or submit it back to Boost.
Do try the Boost mailing lists. The people there might tell you whether such a method is a good or bad idea, and why. If you find anything interesting there, please post a summary here.
BTW: Boost 1.42 was released yesterday.
|
2,171,540 | 2,171,554 | C++ destructor example | My C++ is a little rusty but I have made a program that reverses a linked list and now I am trying to write the proper destructors for it but I don't know exactly what to destroy. Here are my class definitions:
class LinkedList
{
private:ListElement *start;
public:LinkedList();
public:void AddElement(int val);
public:void PrintList();
public:void InvertList();
};
class ListElement
{
public:int value;
public:ListElement * link;
public:ListElement(int val);
public:ListElement();
};
class Stack
{
private:ListElement ** stack;
private:int index;
public:Stack(int size);
public:void push(ListElement * le);
public:ListElement * pop();
};
The stack is for when I reverse the list.
Anyway ...
How would I go about writing the destructors for these?
I was thinking:
For the ListElement make the value 0 and the link 0(NULL).
For the LinkedList go through the elements and call up the ListElementDestructor for all of them.
I am not very sure about this because as I understand the destructor automatically calls the destructors of the member objects so would only writing an empty destructor for LinkedList suffice in this case? I don't know ... that is why I am asking
For the stack I don't know ... the pointers are already 0(NULL) after the list is inversed because they are all poped.
I am a bit confused.
Can anyone help?
Thank you in advance.
|
For the ListElement make the value 0 and the link 0(NULL).
You don't need to reset any of the values in the destructor, as values won't exist after the destructor executed.
The main thing you need to be sure of is that all elements allocated on the heap (i.e Using new) are deleted using delete (or delete [] in the case of arrays).
For the LinkedList go through the elements and call up the ListElementDestructor for all of them.
For a object allocated on the stack it is automatically called when the object goes out of scope.
For a dynamically allocated object (i.e created using new) the destructor is called when
it is deleted using delete. In other words, you don't need to call any destructors as they are called automatically if you clean up your objects correctly.
Given (I assume) that you are allocating new ListElements on the heap in the LinkedList class, you should ensure that in the LinkedList destructor, every ListElement is deleted in the destructor by walking down the list and calling delete on every ListElement (after you have retrieved the address of the next list element from it of course). Something like this:
ListElement* current = list.start;
while( current ){
ListElement* next = current->next;
delete current;
current = next;
}
There is nothing in the ListElement class that needs cleaning up, as although it has a pointer to the next element the deletion should probably be handled in the LinkedList class, which means it doesn't need a destructor.
It isn't required that you write a destructor for every class, as the compiler will automatically generate an empty one for you.
As I said in the comments, you shouldn't be using a stack for reversing a linked list. You should just be swapping the direction of the pointers.
An quick example of roughly the sort of thing you would want.
ListElement* previous = 0;
ListElement* current = list.start;
while( current->next ){
//copy the address of current item on the list
ListElement* next = current->next;
//point the current list item to the previous list item
current->next = previous;
//set the current list item to the next list item
current = next;
//and the previous list item to the current one
previous = current;
}
//set the start of the list to what was the end
list.start = current;
|
2,171,650 | 2,171,759 | Callback for button in Qt Designer? | I just started using QtCreator tonight, and it seems it puts all of the interface stuff inside of the ui file. I followed a tutorial to create a resource for my icons, then I added them to a menu bar at the top.
I need to make a connection when one of them is clicked though, and cannot figure out how to make a callback for it.
Am I going to have to completely create them through code or is there some way to add a callback for them (rather than just making them interact with other objects).
| Menu bar items are action objects. To do something when they are clicked, you need to catch the triggered() signal from the action. Read more about signals and slots here.
To do this, you need to declare a new slot in your MainWindow class. Qt also supports doing this automatically, without the need to connect anything, but I prefer doing it myself. If you're not interested, just skip this part.
First, we declare a new slot in your window class:
private slots:
void clickMenuButton();
Then, in your constructor, you need to connect the triggered signal to your new slot:
connect(ui.actionObject, SIGNAL(triggered()), this, SLOT(clickMenuButton()));
The first argument is the object that holds the signal we'll listen to (your menu button). The second is the name of the signal. The third is the object that holds the receiving slot (in this case, our window). The fourth is the slot.
And just like that, clickMenuButton() will be called whenever the action is clicked.
As I said before, Qt can also automatically connect signals to slots. The disadvantage here seems to be that you can't change the slot's name, but you don't need to connect it either.
Qt Creator supports creation of slots for widgets: in the case of your menu action, you should go to the form designer, and you should see a list of actions in your form (if you don't, find the Action Editor). Right click the action you want, and push Go to slot.... There, double click triggered().
Qt Creator will then open the new slot in your code editor, and you can do whatever you want to here!
|
2,171,715 | 2,171,729 | Do we have design patterns in C++ as we have in java? | As we have so many design patterns in java, like wise do we have any in c++.Or can we use the same sort of patterns in c++.
| The original book on Design patterns (Design Patterns: Elements of Reusable Object-Oriented Software by the Gang of Four) predates Java. The examples in there are in C++ and Smalltalk.
Design patterns are applicable to many object-oriented programming languages; maybe it's just that in Java they are usually so ubiquitous that you need them to solve anything non-trivial.
However, some design patterns are solved by language features (you don't need to explicitly implement an Observer Pattern in C#, for example). Others aren't even applicable to Java, as they need multiple class inheritance.
|
2,171,799 | 2,171,838 | conversion operator as standalone function | Why does C++ require that user-defined conversion operator can only be non-static member?
Why is it not allowed to use standalone functions as for other unary operators?
Something like this:
operator bool (const std::string& s) { return !s.empty(); }
| The one reason I can think of is to prevent implicit conversions being applied to the thing being cast. In your example, if you said:
bool( "foo" );
then "foo" would be implicitly converted to a string, which would then have the explicit bool conversion you provided applied to it.
This is not possible if the bool operator is a member function, as implicit conversions are not applied to *this. This greatly reduces the possibilities for ambiguity - ambiguities normally being seen as a "bad thing".
|
2,171,891 | 2,173,326 | Using std::streams to format output | I have an object that I want to be able to stream. But I want to be able to stream it in different ways by using different formats, or should I say ways to describe this object. And I wonder how this is supposed to be solved with streams.
What I want is to be able to use a generic format and use some kind of format adapter to transform the generic format into the preferred format.
I also want to be able to separate the format from the implementation of Item, so I do not have to change Item each time a new format is added or changed.
this code illustrate approximately what I want.
Item item;
std::cout << "generic formatted:" << item;
std::cout << "custom formatted:" << CustomItemFormat() << item;
but this might not be possible or practical.
how is the streaming library intended to be used facing such problems?
| Try using the Visitor design pattern:
struct Object_Writer_Interface
{
virtual void write_member_i(int value) = 0;
virtual void write_member_c(char value) = 0;
};
struct Object
{
int i;
char c;
void write(Object_Writer_Interface * p_writer)
{
if (p_writer)
{
p_writer->write_member_i(i);
p_writer->write_member_c(c);
}
}
};
struct Stream_Object_Writer
: public Object_Writer_Interface
{
Stream_Object_Writer(std::ostream& out)
: m_out(out)
{ ; }
void write_member_i(int value)
{
m_out << i << '\n';
}
void write_member_c(char c)
{
m_out << "'" << c << "'\n";
}
std::ostream& m_out;
};
int main(void)
{
Object o;
o.i = 5;
o.c = 'M';
// Create a writer for std::cout
Stream_Object_Writer writer(std::cout);
// Write the object to std::cout using the writer
o.write(&writer);
return EXIT_SUCCESS;
}
With this design, to write the objects to a socket, you derive a class from Object_Writer_Interface to handle the socket. And similarly if you want to serialize the Object.
I'm currently using this technique for writing objects to GUI list boxes, database records and Xml files. Unlike the technique for overloading operator <<, I didn't have to modify the principle class when developing new Writers.
|
2,171,892 | 2,171,921 | Use struct as base for derived class in C++ | Is it possible to have a class inheriting from a struct?
More specifically, how can I wrap a C struct with a class, so that I can pass class pointers to methods that requires struct ptr and cast back when I receive the pointer in e.g. callbacks?
(Or even more specifically, the address of the class should be same same address as the struct...)
| You just derive from the C struct. In C++, the only difference between a struct and a class is that the latter's default member accessibility is private, while the former's is public.
If only single inheritance is involved, the class's address should be the same as the struct's which acts as a base class. If the inheritance only serves the implementation (that is, there is no Is-A relationship between the two), consider using private inheritance.
|
2,171,975 | 2,171,997 | Completely OO C++ SQL Wrapper? | So I'm looking for a SQL wrapper for C++ that completely hides any textual SQL statements. I just can't seem to find any, I'm wondering why all the wrappers out there seem at some point to want you to write a textual SQL statement such as:
SELECT * FROM stock WHERE item = 'Hotdog Buns'
here's MySQL++ for example:
mysqlpp::Query query = conn.query("select * from stock where item = 'Hotdog Buns'");
The most obvious way to do this for me is to create a class that contains properties (columns) with each instance of that class being a row. So to do the above query I would do something like:
// Class defined something like this...
class stock_item : public sql::row
{
public:
stock_item() : m_name( NULL ), m_amount( 0 ) {};
~stock_item() {};
// Statically define the table
static void CreateTable( void )
{
// Some C++ reflective mechanism
sql::column( "name", char[50] );
sql::column( "amount", u32 );
}
private:
const char* m_name;
u32 m_amount;
}
// Then a table defined like this
sql::table<stock_item> stock;
// Query function defined something like this...
stock GetHotDogBuns( const stock& shopStock )
{
stock hotDogBuns = shopStock.Select( stock_item::Name(), "Hotdog Buns" );
return hotDogBuns;
}
Now I'm no SQL expert and I haven't spent very long thinking about the above code but it just seems quite a logical way to deal with a database if your from a C++ background rather than having to be a database expert. What are the problems with this kind of approach?
Is there an open source library that allows you access to a database in a similar fashion?
EDIT The reason why I would like something like this is so that C++ programmers using our code don't have to learn SQL syntax and to provide a much more natural environment for them to code in. I've seen something like this in the SilverStripe CMS written in php.
| Check out hiberlite and litesql.
|
2,171,996 | 2,172,058 | Memory allocators for a native C++ library to be used by C# | I'm writing some native C++ code which needs to be called from C# (and I can't replace the C++ native code with C# code).
I found memory corruptions while allocating/deallocating some memory in the native C++ code using malloc/free. Then I used LocalAlloc/LocalFree and HeapAlloc/HeapFree and had the same problems.
The allocations/deallocations seem to be correct, and they happen in a separate thread, created by the native code.
I was wondering which is the best allocation strategy to use in a native C++ library called by C#
EDIT: found the problem: the problem wasn't in the allocation/deallocation code, but in some memory being written after being deallocated.
| As long as the C# side of the code uses the compiler's /unsafe switch and the fixed keyword used for holding the buffer of data, I think you should be ok.
As to the question of your memory allocation, it may not be the C++ memory allocation code that is causing the problem, it could be the way how the C++ code is interacting with the driver...maybe using VirtualAlloc/VirtualFree pair as per the MSDN docs...
Edit: When you try to allocate the buffer to hold the data from the C++ side after interacting with the driver...possibly a race-condition or interrupt latency is causing a memory corruption...just a thought...
Hope this helps,
Best regards,
Tom.
|
2,172,053 | 2,172,056 | C++, can I statically initialize a std::map at compile time? | If I code this
std::map<int, char> example = {
(1, 'a'),
(2, 'b'),
(3, 'c')
};
then g++ says to me
deducing from brace-enclosed initializer list requires #include <initializer_list>
in C++98 ‘example’ must be initialized by constructor, not by ‘{...}’
and that annoys me slightly because the constructor is run-time and can, theoretically fail.
Sure, if it does, it will fail quickly and ought to do so consistently, so that I ought to quickly locate & correct the problem.
But, still, I am curious - is there anyway to initialize map, vector, etc, at compile time?
Edit: I should have said that I am developing for embedded systems. Not all processors will have a C++0x compiler. The most popular probably will, but I don't want to encounter a gotcha & have to maintain 2 versions of the code.
As to Boost, I am undecided. They are wishy-washy on the use of their Finite State Machine classes in embedded systems, so that is actually what I am coding here, Event/State/Fsm classes.
Sigh, I guess I'd better just play it safe, but I hope that this discussion has been helpful for others.
| Not in C++98. C++11 supports this, so if you enable C++11 flags and include what g++ suggests, you can.
Edit: from gcc 5 C++11 is on by default
|
2,172,293 | 2,172,311 | Getting Unresolved External error | I have made a class and it compiles with no syntax errors, but I get 6 unresolved external symbols?
THE CLASS:
struct CELL {
private:
static bool haslife;
static int x;
static int y;
public:
static bool has_life()
{
return haslife;
}
static void set_coords(int xcoord, int ycoord)
{
x = xcoord;
y = ycoord;
}
static void get_coords(int &xcoord, int &ycoord)
{
xcoord = x;
ycoord = y;
}
};
class cell_grid {
private:
static int cell_size;
static int cell_count_x;
static int cell_count_y;
CELL **cell;
public:
cell_grid();
cell_grid(unsigned int width,unsigned int height, unsigned int cellsize)
{
//set size based on cellsize
this->cell_size = cellsize;
this->cell_count_x = floor((double)width / this->cell_size);
this->cell_count_y = floor((double)height / this->cell_size);
this->cell = new CELL*[this->cell_count_y];
for(int i = 0; i < this->cell_count_y; i++)
{
cell[i] = new CELL[this->cell_count_x];
}
for(int y = 0; y < this->cell_count_y; ++y)
{
for(int x = 0; x < this->cell_count_x; ++x)
{
int cur_x = x * this->cell_size;
int cur_y = y * this->cell_size;
this->cell[x][y].set_coords(cur_x,cur_y);
}
}
} //end of constructor
static int get_cell_size()
{
return cell_size;
}
static void render(BITMAP *buff)
{
circlefill(buff,70,70,60,makecol(27,37,0));
}
};
MAIN
int main()
{
start_allegro();
cell_grid *grid = new cell_grid(scr_w,scr_h,10);
grid->render(buffer);
//Main Loop
while (!done && !key[KEY_ESC]) //until 'X' pressed or ESC
{
//***** Start Main Code Here *****
while (speed_counter > 0)
{
//render the buffer to the screen
blit(
buffer,
screen,
0,0,0,0,
scr_w,
scr_h);
clear_bitmap(buffer);
speed_counter --;
}
//***** End Main Code Here *****
rest(1); //Normalize cpu usage
}
return 0;
}
END_OF_MAIN()
Thanks
| Don't define all of the class variables as static.
When you define a data member as static it means there is only one single instance of it. This doesn't seem to be what you want to do here.
Instead of
private:
static bool haslife;
static int x;
static int y;
write:
private:
bool haslife;
int x;
int y;
Further more, when you define a static member, you need to define it again in the CPP file and initialize it with a value. It doesn't look like you're doing that and that's why you're getting the linker errors.
Also, next time you post something, make sure you actually ask a question rather than just simply stating facts.
|
2,172,379 | 2,172,627 | Get outline for NSGlyph | With Core Text it was possible to get the outline of a CGGlyph by CTFontCreatePathForGlyph(...). Now I'd like to port from Core Text to Cocoa's font engine, so the question is:
Is there a way to get the outline for a NSGlyph?
| Yes, you can use NSBezierPath's -appendBezierPathWithGlyph:inFont:.
I'd like to add that you can use CoreText with Cocoa, too. So in that sense you don't have to port at all.
|
2,172,448 | 2,172,479 | Common term for the "value-based" OR operator | Just a quick question
printf("%d", 99 || 44) prints "1" in C
print 99 || 44 prints "99" in perl
There are two different kinds of evaluation. Does each one have a name?
edit: i'm interested to know how this Perl evaluation is commonly called when compared to C. When you say "C example is X, and perl example is not X, but Y" which words would you use for X and Y. "short circuit" is not what i'm looking for.
| The C version uses || as the logical OR between the two values. Both 44 and 99 evaluate to true in C as they are not 0, so the result of an OR between them returns 1 (AKA true in C)
In that particular perl snippet, || is the null-coalescing operator, an binary which evaluates to the second argument if the first is null, otherwise evaluating to the first argument. Since 99 is the first argument and not null, it gets returned and printed.
EDIT: Thanks Evan for the clafication: The || operator in perl is not the null-coalescing operator, it returns the RHS if the LHS evaluates to false, other wise returning the LHS. // is the "proper" null-coalescing operator.
Here's the list of values in perl that evaluate to false (from wikipedia)
$false = 0; # the number zero
$false = 0.0; # the number zero as a float
$false = 0b0; # the number zero in binary
$false = 0x0; # the number zero in hexadecimal
$false = '0'; # the string zero
$false = ""; # the empty string
$false = undef; # the return value from undef
$false = 2-3+1 # computes to 0 which is converted to "0" so it is false
|
2,172,621 | 2,172,631 | cannot open shared object file: No such file or directory | I met the share library not found on the head node of a cluster with torch. I have built the library as well as specify the correct path of the library while compiling my own program "absurdity" by g++. So it looks strange to me. Any idea? Thanks and regards!
[tim@user1 release]$ make
...
...
g++ -pipe -W -Wall -fopenmp -ggdb3 -O2 -I/home/tim/program_files/ICMCluster/ann_1.1.1/include -I/home/tim/program_files/ICMCluster/libsvm-2.89 -I/home/tim/program_files/ICMCluster/svm_light -o absurdity xxxxxx.o -L/home/tim/program_files/ICMCluster/ann_1.1.1/release/lib -L/home/tim/program_files/ICMCluster/libsvm-2.89/release/lib -L/home/tim/program_files/ICMCluster/svm_light/release/lib -lm -ljpeg -lpng -lz -lANN -lpthread -lsvm -lsvmlight
[tim@user1 release]$ ./absurdity
./absurdity: error while loading shared libraries: libsvmlight.so: cannot open shared object file: No such file or directory
[tim@user1 release]$ ls /home/tim/program_files/ICMCluster/svm_light/release/lib/libsvmlight.so -l
-rwxr-xr-x 1 tim Brown 121407 Jan 31 12:14 /home/tim/program_files/ICMCluster/svm_light/release/lib/libsvmlight.so
[tim@user1 release]$ LD_LIBRARY_PATH= /home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PAT
[tim@user1 release]$ export LD_LIBRARY_PATH
[tim@user1 release]$ ./absurdity
./absurdity: error while loading shared libraries: libsvmlight.so: cannot open shared object file: No such file or directory
[tim@user1 release]$ ls /home/tim/program_files/ICMCluster/svm_light/release/lib
libsvmlight.a libsvmlight.so
| Your LD_LIBRARY_PATH doesn't include the path to libsvmlight.so.
$ export LD_LIBRARY_PATH=/home/tim/program_files/ICMCluster/svm_light/release/lib:$LD_LIBRARY_PATH
|
2,172,647 | 2,172,766 | Template Metaprogramming - Difference Between Using Enum Hack and Static Const | I'm wondering what the difference is between using a static const and an enum hack when using template metaprogramming techniques.
EX: (Fibonacci via TMP)
template< int n > struct TMPFib {
static const int val =
TMPFib< n-1 >::val + TMPFib< n-2 >::val;
};
template<> struct TMPFib< 1 > {
static const int val = 1;
};
template<> struct TMPFib< 0 > {
static const int val = 0;
};
vs.
template< int n > struct TMPFib {
enum {
val = TMPFib< n-1 >::val + TMPFib< n-2 >::val
};
};
template<> struct TMPFib< 1 > {
enum { val = 1 };
};
template<> struct TMPFib< 0 > {
enum { val = 0 };
};
Why use one over the other? I've read that the enum hack was used before static const was supported inside classes, but why use it now?
| Enums aren't lvals, static member values are and if passed by reference the template will be instanciated:
void f(const int&);
f(TMPFib<1>::value);
If you want to do pure compile time calculations etc. this is an undesired side-effect.
The main historic difference is that enums also work for compilers where in-class-initialization of member values is not supported, this should be fixed in most compilers now.
There may also be differences in compilation speed between enum and static consts.
There are some details in the boost coding guidelines and an older thread in the boost archives regarding the subject.
|
2,172,726 | 2,209,160 | Are there any reasons why the StringPiece/StringRef idiom is not more popular? | From the documentation of the StringPiece class in Chromium's source code:
// A string-like object that points to a sized piece of memory.
//
// Functions or methods may use const StringPiece& parameters to accept either
// a "const char*" or a "string" value that will be implicitly converted to
// a StringPiece.
//
// Systematic usage of StringPiece is encouraged as it will reduce unnecessary
// conversions from "const char*" to "string" and back again.
Example of use:
void foo(StringPiece const & str) // Pass by ref. is probably not needed
{
// str has same interface of const std::string
}
int main()
{
string bar("bar");
foo(bar); // OK, no mem. alloc.
// No mem. alloc. either, would be if arg. of "foo" was std::string
foo("baz");
}
This seems like such an important and obvious optimization that I can't understand why it's not more widespread, and why a class similar to StringPiece is not already in the standard.
Are there any reasons why I shouldn't replace the use of string and char* parameters in my own code with this class? Is there anything like it already in the C++ standard libraries?
UPDATE. I've learnt that LLVM's source uses a similar concept: the StringRef class.
| Because why bother? With copy elision and/or pass by reference, memory allocations for std::string can usually be avoided as well.
The string situation in C++ is confusing enough as it is, without adding still more string classes.
If the language was to be redesigned from scratch, or if backwards compatibility wasn't an issue, then this is one of many possible improvements that could be done to string handling in C++. But now that we're stuck with both char* and std::string, adding a stringref-style class into the mix would cause a lot of confusion, with limited benefit.
Apart from this, isn't the same effect achieved more idiomatically with a pair of iterators?
If I want to pass a sequence of characters, whether they belong to a string or a char*, why shouldn't I just use a pair of iterators to delimit them?
|
2,172,879 | 2,172,900 | in C++, how to use a singleton to ensure that each class has a unique integral ID? | I have a bunch of C++ classes.
I want each class to have something like:
static int unique_id;
All instances of a same class should have the same unique_id; different classes should have different unique_id's.
The simplest way to do this appears to be threading a singleton through the classes.
However, I don't know what's called when for static class members / things that happen before main.
(1) if you have a solution that does not involve using singleton, that's fine too
(2) if you have a solution that gives me a :
int unique_id();
that is fine too.
Thanks!
| Have a class that increments it's ID on each creation. Then use that class as a static field in each object that is supposed to have an ID.
class ID
{
int id;
public:
ID() {
static int counter = 0;
id = counter++;
}
int get_id() { return id; }
};
class MyClass
{
static ID id;
public:
static int get_id()
{
return id.get_id();
}
};
|
2,172,919 | 2,172,997 | A C++ syntax question involving non trivial templating and friend declaration | The following code should be self explanatory. I have two questions regarding the used syntax (which is the syntax that must be used). I'll be forever grateful if you could provide me with answers for these presented questions.
template <typename T>
struct A {
template <typename S>
void f (const A<S> &s);
template <typename S>
friend struct A;
// Question 1: why isn't the syntax 'friend struct A<S>' ?
// The semantic would stay, since we would like A<S> (for ANY S) to be friend of every A<T>..
private:
void g () const {}
};
template <typename T>
template <typename S> // Question 2: Why can't the syntax be 'template <typename T, typename S>' ?
void A<T>::f (const A<S> &s) {
s.g();
}
int main () {
A<bool> abool;
A<char> achar;
abool.f(achar);
}
I have verified that indeed this is the only correct syntax (I'll be happy to find out I'm mistaken). My questions are more regarding the reasoning behind the syntax, as explained in the questions' body.
Thanks for any help.
|
why isn't the syntax ...
Why can't the syntax be ...
What do you expect us to say? Whoever decided this syntax (mostly Stroustrup himself, AFAIK) thought their syntax better than yours.
Which one is nicer or easier to remember I wouldn't know - but I do find theirs making more sense than yours. You're free to disagree, of course.
Edit: OK, Alexander has nicely answered question #2. About #1:
The difference is that A<S> names a type, which is what is expected for a function argument, while A by itself is the name of a template, from which types are to be created, which makes sense if you want to befriend a template instead of a type:
template <typename S>
void f (const A<S> &s); // A<S> being the name of a type
template <typename S>
friend struct A; // A being the name of a template
You can befriend a specific template instance instead of the whole template, but for that the template must already be known by the compiler (i.e., declared) at the friend declaration:
template< typename T >
class foo;
class bar {
friend class foo<int>; // foo<int> being the name of a specific instance of foo
};
So befriending a template is an exception (the "usual" friend declarations declares a function or class) and does need the differing syntax.
|
2,172,943 | 2,172,948 | Size of character ('a') in C/C++ | What is the size of character in C and C++ ? As far as I know the size of char is 1 byte in both C and C++.
In C:
#include <stdio.h>
int main()
{
printf("Size of char : %d\n", sizeof(char));
return 0;
}
In C++:
#include <iostream>
int main()
{
std::cout << "Size of char : " << sizeof(char) << "\n";
return 0;
}
No surprises, both of them gives the output : Size of char : 1
Now we know that characters are represented as 'a','b','c','|',... So I just modified the above codes to these:
In C:
#include <stdio.h>
int main()
{
char a = 'a';
printf("Size of char : %d\n", sizeof(a));
printf("Size of char : %d\n", sizeof('a'));
return 0;
}
Output:
Size of char : 1
Size of char : 4
In C++:
#include <iostream>
int main()
{
char a = 'a';
std::cout << "Size of char : " << sizeof(a) << "\n";
std::cout << "Size of char : " << sizeof('a') << "\n";
return 0;
}
Output:
Size of char : 1
Size of char : 1
Why the sizeof('a') returns different values in C and C++?
| In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.
|
2,173,063 | 2,179,327 | Drawing Collision on Screen | And here we are for another question.
After the previous one, i finally completed the kDop system and everything related. (Hierarchycal tree of kDop, etc..)
Everything works fine.
Now i want to draw on screen the collision for debug purpose and to see the result of the work. (To see if the hierarchical choice i've done in a particular mode is fine or not)
For the AABB/Sphere no problem, its pretty much easy to create.
The problem is with the kDOP...
I have :
axises
(1,0,0)(0,1,0)(0,0,1)(1,1,1)(-1,1,1)(1,-1,1)(1,1,-1)(1,1,0)(1,0,1),(0,1,1),(1,-1,0),(1,0,-1),(0,1,-1)
and the Min/Max values calculated using the axes.
How can i create a series of polygon (a simple mesh in fact) with these data?
(I don't care about implementation, i just want to understand it theorically so I can implement it)
Thanks a lot for the answers!!!
EDIT : I can calculate EASILY the normals of the mesh cause I already have the axis. The problem is calculating the vertex position...
EDIT 2: I found on the net this code that seems to be useful (or at least in the doc it says its for creating a debug mesh), but I don't know how to use it to find the vertex position :
real Kdop::getDistanceOfPlaneToOrigin(int k) const {
if (k < 0 || k >= mK) {
return 0.0f;
}
if (k >= mK/2) {
return (real) (mDistances[k] * -1.0);
}
return mDistances[k];
}
EDIT 3: I thought and having normals and a point (the origin, that i'm sure the plane pass over), i can build all the planes related to the operation... Now I need something more....
| In general, each vertex is the intersection of three planes. Additionally, each vertex you want to draw needs to be on the correct side of all remaining planes. This may be an annoying combinatorial description of the problem, but with a kDop, at least it's a fixed-size problem...
To get a bit more clever about it, you should look at some Linear Programming math. Specifically, once you have a valid vertex (i.e., an intersection of 3 planes that is on the correct side of the remaining planes), you can slide along each edge to the next valid vertex. You can recursively explore the entire graph of valid vertices and edges this way: do a breadth-first search of the graph, keeping track of which vertices you've explored -- and once you've exhausted the possibilities (finite, remember!) you've got what you want to draw.
Oh, and to calculate the actual vertices based on the planes, check out this mathworld page.
[edit:] -- Actually, you may be able to simplify your search quite a lot, if you know for sure that none of your planes are redundant (i.e., if none of them are entirely outside your kDop). In that case, your kDop has a standard structure, with each polygon having a fixed configuration of neighbors; in that case, you can just plug your planes in, compute your fixed set of vertices, and draw your standard figure with them. You could easily (if somewhat tediously) work out all the details by hand.
You might want to watch out for degenerate cases, though -- e.g. if you put an oriented cube in your kDop, so that most of your facets are zero-sized.
[edit2:] -- On further consideration, I'm thinking your configuration may not be entirely fixed. For example, say there are 4 nearby planes; and based on their depth, the edge between them may go one way or another, like so:
plane A | plane B
|
/ \
/ \
/ \
________/ \
| \
| \
plane C | plane D \
vs.
plane A | plane B
|
|
________|
\
\
|\
| \
| \
| \
| \
| \
| \
| \
| \
plane C | plane D \
However, I think you can still simplify your setup somewhat. You will still need to check whether your vertices are valid or not, but you can reduce both the number of vertices and the number of planes to check by considering your particular plane configuration.
|
2,173,151 | 2,173,273 | How to end line with QTextEdit | I'm trying to create QTextEdit with some text, and in this text I have end of line characters (\n), but it is not accepted in QTextEdit object (whole text is displayed without any breaks). Any reason why?
| If you're using Qt 4.3 or later, then you can use setPlainText(const QString &text)
You can turn off rich text editing with setAcceptRichText(bool accept) (Qt 4.1 or later)
|
2,173,177 | 2,173,188 | try all or just what's necessary? | What is better coding practice: if I have to have a try/catch block shall I place everything (every initialization and so on) in this block or just those variables which may throw? Is there any difference between those two constructions?
In example:
Having:
struct A {
A();
int a;
int* b;
};
and later on in .cpp:
A::A() {
a = 5;
try {
b = new int;
}
catch(...){
}
}
or
A:A() {
try {
a = 5; //this time in try block
b = new int;
}
catch(...) {
}
}
is there any difference between those two constructs or is this in a way if I have to have a try/catch block I may aswell put everything in it?
Thank you.
P.S.
For God efin sake, formatting here drives me really crazy! And I know that I mentioned this many times, I'm not going mad.
| I think a good general principle is to make a try block as "narrow" as possible -- don't put in it things that you believe won't ever cause exceptions. That way, should you ever be wrong and have one of those "can't cause exception" parts actually do cause an exception, you won't be accidentally "swallowing" the astonishing exception (and no doubt dealing with it in inappropriate ways, since your code would not be expecting that exception but other kinds).
|
2,173,256 | 2,173,303 | Why don't I have setTextFormat in my QTextEdit? | Anyone have any Idea why I don't have this function (setTextFormat) in my QTextEdit class?
Thanks in advance.
| See this answer to your previous question. QTextEdit API changed in Qt4
QTextEdit docs for Qt 4.6
|
2,173,323 | 2,173,438 | Calculating time by the C++ code | I know this question has been asked few times over SO but none of them is really helping me out, so asking again.
I am using windows xp and running visual studio c++ 2008.
All the code which i am looking is using time.h but i think may be its not working correctly here, because results are making me suspicious.
So this is what i want.
star time = get time some how (this is my question)
my code
end time = get time some how (this is my question)
time passed = start time - end time
| Here is what I use to print time in milliseconds.
void StartTimer( _int64 *pt1 )
{
QueryPerformanceCounter( (LARGE_INTEGER*)pt1 );
}
double StopTimer( _int64 t1 )
{
_int64 t2, ldFreq;
QueryPerformanceCounter( (LARGE_INTEGER*)&t2 );
QueryPerformanceFrequency( (LARGE_INTEGER*)&ldFreq );
return ((double)( t2 - t1 ) / (double)ldFreq) * 1000.0;
}
Use it like this:
_int64 t1;
StartTimer( &t1 );
// do some stuff
printf( "Time = %.3f\n", StopTimer( t1 ));
|
2,173,342 | 2,173,372 | C++ template class and template function | If I have one template class and template function like this
template <class T> T getMax (T a, T b) {
return (a>b?a:b);
}
template <class T> class GetMax {
public:
static T getMax(T a, T b) {
return (a>b?a:b);
}
};
Why are these not valid?
x=getMax(1, '2');
but these are valid
x=getMax(1,2);
Does it mean that there is no type conversion in template function?
This is not valid
x=GetMax::getMax(1, 2);
Does it mean that for the template class, the type must be specified?
| What should getMax(1, '2'); return? An int, or a char? Think about it :)
You could write:
template <class T1, class T2> T1 getMax (T1 a, T2 b) {
return (a>b?a:b);
}
But note that you are explicitly returning type 1, what might not work in a case like getMax('1',1000) because 100 would be converted to char type, and that wouldn't be large enough.
The latter is not valid because to use a class, you must first state what type it is -- this mechanism acts first, before type deduction.
It would work if you stated it :
class GetMax {
public:
template <class T>
static T getMax(T a, T b) {
return (a>b?a:b);
}
};
|
2,173,368 | 2,173,387 | fstream >> int failing? | Any idea why the following would fail?
std::fstream i(L"C:/testlog.txt", std::ios::binary | std::ios::in);
int test = 0;
i >> test;
fail() is returning true. The file exists and is opened.
I checked
i._Filebuffer._Myfile._ptr
and it is pointer to a buffer of the file so I don't see why it is failing.
| You're opening the file in binary mode. The extraction operators were meant to be used with text files. Simply leave out the std::ios::binary flag to open the file in text mode.
If you actually do have a binary file, use the read() function instead.
Edit: I tested it too, and indeed it seems to work. I got this from CPlusPlus.com, where it says:
In binary files, to input and output data with the extraction and insertion operators (<< and >>) and functions like getline is not efficient, since we do not need to format any data, and data may not use the separation codes used by text files to separate elements (like space, newline, etc...).
Together with the description of ios::binary, which simply states "Consider stream as binary rather than text.", I'm utterly confused now. This answer is turning into a question of its own...
|
2,173,395 | 2,173,685 | How to encode video? | I want to write a video encoding. What do I need to do?
| Do you mean implement / invent a codec, or do you mean encode a video?
For encoding a video, use libavcodec from ffmpeg.
For implementing or developing a new codec, this is typically done over a series of years by a team of experts, and if you have to ask this general a question it may be a learning experience but would most likely be a waste of your time.
|
2,173,570 | 2,173,895 | Translate a code using pointer, to Assembly in Pascal - Delphi | I have this code below, and I want to translate it to ASM, to use in Delphi too.
var
FunctionAddressList: Array of Integer;
type TFunction = function(parameter: Integer): Integer; cdecl;
function Function(parameter: Integer): Integer;
var
ExternFunction: TFunction;
begin
ExternFunction := TFunction(FunctionAddressList[5]);
Result := ExternFunction(parameter);
end;
It works normaly, but when I try its Assembly version:
function Function(parameter: Integer): Integer; cdecl;
asm
mov eax, FunctionAddressList
jmp dword ptr [eax + 5 * 4]
end;
It is supposed to work, because, in C++ it works in both ways:
void *FunctionAddressList;
_declspec(naked) int Function(int parameter)
{
_asm mov eax, FunctionAddressList;
_asm jmp dword ptr [eax + 5 * 4];
}
typedef int (*TFunction)(int parameter);
int Function(int parameter)
{
TFunction ExternFunction = ((TFunction *)FunctionAddressList)[5];
return ExternFunction(parameter);
}
But it doesn't work in Delphi.
In the Assembly version, it multiplies the array to 4, because it's the offset size between each element of the array, so both versions are equivalent.
So, I want to know why it doesn't work with Delphi. In Delphi, the offset size between Integer values in a array is different than C++?
I've already tried many offsets, as 1, 2, 4, 6, 8, etc. And many types of Array (Array of Pointer; only Pointer; Array of Integer, etc), and I've tried many calling conventions, and cdecl was the only that worked with the non-asm version, but with ASM, all the tests didn't work.
Thanks.
| First test app to reproduce error:
var
FunctionAddressList: Array of Integer;
function Bar(parameter: Integer): Integer; cdecl;
begin
ShowMessage('Bar '+IntToStr(parameter));
end;
function Foo(parameter: Integer): Integer; cdecl;
asm
mov eax, FunctionAddressList
jmp dword ptr [eax + 5 * 4]
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SetLength(FunctionAddressList, 6);
FunctionAddressList[5]:= Integer(@Bar);
Foo(25);
end;
The Bar address is defined correctly, but the problem is that Delphi compiler generates prologue and epilog for Foo, so real Foo code is
0046CD30 55 push ebp
0046CD31 8BEC mov ebp,esp
Unit1.pas.46: mov eax, FunctionAddressList
Unit1.pas.47: jmp dword ptr [eax + 5 * 4]
0046CD3B 5D pop ebp
0046CD3C C3 ret
As a result the stack is corrupted, the parameter is wrong and Bar return address is wrong. If you still want to do the trick, use
function Foo(parameter: Integer): Integer; cdecl;
asm
pop ebp
mov eax, FunctionAddressList
jmp dword ptr [eax + 5 * 4]
end;
|
2,173,696 | 2,173,704 | How to tell if you're compiling on Windows? | Something like:
#ifdef WINDOWS
// do stuff
#endif
| The _WIN32 is always defined on Windows platform, checkout the predefined macros.
|
2,173,746 | 2,173,764 | How do I make this C++ object non-copyable? | See title.
I have:
class Foo {
private:
Foo();
public:
static Foo* create();
}
What need I do from here to make Foo un-copyable?
Thanks!
| class Foo {
private:
Foo();
Foo( const Foo& ); // non construction-copyable
Foo& operator=( const Foo& ); // non copyable
public:
static Foo* create();
}
If you're using boost, you can also inherit from noncopyable : http://www.boost.org/doc/libs/1_41_0/boost/noncopyable.hpp
EDIT: C++11 version if you have a compiler supporting this feature:
class Foo {
private:
Foo();
public:
Foo( const Foo& ) = delete; // non construction-copyable
Foo& operator=( const Foo& ) = delete; // non copyable
static Foo* create();
}
Note that deleted methods should be public: https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rc-delete
|
2,173,771 | 2,175,515 | printf inside CUDA __global__ function | I am currently writing a matrix multiplication on a GPU and would like to debug my code, but since I can not use printf inside a device function, is there something else I can do to see what is going on inside that function. This my current function:
__global__ void MatrixMulKernel(Matrix Ad, Matrix Bd, Matrix Xd){
int tx = threadIdx.x;
int ty = threadIdx.y;
int bx = blockIdx.x;
int by = blockIdx.y;
float sum = 0;
for( int k = 0; k < Ad.width ; ++k){
float Melement = Ad.elements[ty * Ad.width + k];
float Nelement = Bd.elements[k * Bd.width + tx];
sum += Melement * Nelement;
}
Xd.elements[ty * Xd.width + tx] = sum;
}
I would love to know if Ad and Bd is what I think it is, and see if that function is actually being called.
| EDIT
To avoid misleading people, as M. Tibbits points out printf is available in any GPU of compute capability 2.0 and higher.
END OF EDIT
You have choices:
Use a GPU debugger, i.e. cuda-gdb on Linux or Nexus on Windows
Use cuprintf, which is available for registered developers (sign up here)
Manually copy the data that you want to see, then dump that buffer on the host after your kernel has completed (remember to synchronise)
Regarding your code snippet:
Consider passing the Matrix structs in via pointer (i.e. cudaMemcpy them to the device, then pass in the device pointer), right now you will have no problem but if the function signature gets very large then you may hit the 256 byte limit
You have inefficient reads from Ad, you will have a 32-byte transaction to the memory for each read into Melement - consider using shared memory as a staging area (c.f. the transposeNew sample in the SDK)
|
2,173,804 | 2,173,814 | [Windows] Net to Host Not Working | The value is 10240 or 2800 in hex. TOTAL_LENGTH is a unsigned short.
0028 in decimal is 40 which is what I am expecting (or is at least a reasonable value).
Any ideas why I am getting a 0 instead of a 40? Thinking about reversing the bits myself but really don't want to. xD
unsigned short total_length = ntohl(ipData->TOTAL_LENGTH);
These are the headers I am including.
#include <winsock2.h>
#include <ws2tcpip.h>
| u_long WSAAPI ntohl(
__in u_long netlong
);
The result is a long, and you're assigning it to a short. Check if it doesn't get cut.
Also, if it's a short, then why aren't you using ntohs?
|
2,173,995 | 2,174,041 | C++ member function applied to object | I want to call member function by passing it as template parameter, without using boost is possible. Here is an example off what I tried to do,
class object { void method(); }
{
object object_instance;
...
apply<object:: method>();
...
template<class F>
void apply() { F(object_instance); } // want to call object_instance.F()
}
that does not work, so question is how do I go about binding object method to an object.
Thanks
above is an example, not the real code. I have a bunch of functions differing only in name, but with many parameters, that I want to wrap around in operators.
| Something like:
struct foo
{
void bar(void) {}
};
template <typename R, typename C>
R apply(C& pObject, R (C::*pFunc)())
{
return (pObject.*pFunc)();
}
int main(void)
{
foo f;
apply(f, &foo::bar);
}
this.
|
2,174,084 | 2,174,095 | Good source to learn about the differences between ATI and NVIDIA in OpenGL rendering? | The more i learn about OpenGL, the more problems i find!
All i need is a list of the most common problems between ATI/NVIDIA cards, with solutions.
So where is this magical source?
| Unfortunately try it and discuss it on the NeHe and OpenGL forums.
There are no real official lists and the bugs and mis-implemented features differ from card-card and with operating system.
|
2,174,107 | 2,174,136 | Good tools for Multi-threaded C++ debugging on MacOSX? | I recently switched form ubuntu to MacOSX.
I also recently started heavily using multi threading.
What good addons/alternatives are there to g++ for debugging multi-threaded apps on MacOSX? In particular, I'm interested in tools that let me "poke" around classes/structs; to follow pointers, expand members, show the value of members, etc ...
Thanks!
| Valgrind. Especially Helgrind.
It's not a GUI tool like you suggested, but it'll save you a hell of a lot of time.
|
2,174,267 | 2,174,317 | Simple Win32 Trackbar | I have created a simple game using Win32 and gdi. I would like to have a track bar at the bottom that tracks a global variable. I'm just not sure how to add controls. How could I add a trackbar? I can imagine it would get created in the wm_create event.
| Do you mean TrackBar or StatusBar?
A StatusBar is normally located at the bottom of a window and displays informational messages about the application status, a TrackBar allows the user to select a value. Do you want to allow the user to select the value of your global variable or do you just want to display the current value of the variable? (I'm not sure if the trackbar will display the current value of the variable without extra work.)
Either way, there are samples for both StatusBar and TrackBar located on MSDN.
The child windows are normally created either in the WM_CREATE of the parent or after the parent window has been created (i.e. when you obtain a valid hWnd for the parent) and after calling InitCommonControls() and/or initializing COM if needed.
|
2,174,300 | 2,175,718 | function template overloading | Can anybody summarize the idea of function template overloading? What matters, template parameter or function parameter? What about the return value?
For example, given a function template
template<typename X, typename Y> void func(X x, Y y) {}
what's the overloaded function template?
1) template<typename X> void func(X x, int y) {}
2) template<typename X, typename Y> X func(X x, Y y) {}
3) template<class X, class Y, class Z> void func(X x, Y y, Z z) {}
| Of that list only the second introduces ambiguity, because functions - regardless of whether they are templates - can't be overloaded based on return type.
You can use the other two:
template<typename X> void func(X x, int y);
will be used if the second argument of the call is an int, e.g func("string", 10);
template<class X, class Y, class Z> void func(X x, Y y, Z z);
will be used if you call func with three arguments.
I don't understand why some other answers mentions that template functions and function overloading doesn't mix. They certainly do, and there are special rules how the function to call is selected.
14.5.5
A function template can be
overloaded with other function
templates and with normal
(non-template) functions. A normal
function is not related to a
function template (i.e., it is never
considered to be a specialization),
even if it has the same name and type
as a potentially generated function
template specialization.)
A non-templated (or "less templated") overload is preferred to templates, e.g
template <class T> void foo(T);
void foo(int);
foo(10); //calls void foo(int)
foo(10u); //calls void foo(T) with T = unsigned
Your first overload with one non-template parameter also falls under this rule.
Given choice between several templates, more specialized matches are preferred:
template <class T> void foo(T);
template <class T> void foo(T*);
int i;
int* p;
int arr[10];
foo(i); //calls first
foo(p); //calls second
foo(arr); //calls second: array decays to pointer
You can find a more formal description of all the rules in the same chapter of the standard (Function templates)
And finally there are some situations where two or more overloads would be ambiguous:
template <class T> void foo(T, int);
template <class T> void foo(int, T);
foo(1, 2);
Here the call is ambiguous, because both candidates are equally specialized.
You can disambiguate such situations with the use of (for example) boost::disable_if. For example, we can specify that when T = int, then the second overload shouldn't be included as an overload candidate:
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
template <class T>
void foo(T x, int i);
template <class T>
typename boost::disable_if<boost::is_same<int, T> >::type
foo(int i, T x);
foo(1, 2); //calls the first
Here the library produces a "substitution failure" in the return type of the second overload, if T = int, removing it from the set of overload candidates.
In practice you should rarely run into situations like that.
|
2,174,519 | 2,174,542 | How to include boost::thread in your C++ project? | What do I need to do to include boost::thread in my project? I have copied the whole thread folder to my working path (I wish to be able to run this on several computers) and I get
fatal error C1083: Cannot open include
file:
'boost/thread/detail/platform.hpp': No
such file or directory
From the line #include "thread/thread.hpp"
What gives?
edit:
Even if I just link to the boost folder where the precompiled binary installed and I use #include <boost/thread/thread.hpp> I get
fatal error LNK1104: cannot open file
'libboost_thread-vc90-mt-1_41.lib'
| Unfortunately boost::thread is not a "header-only" library -- hence you need to have it compiled. There are basically two ways to go around it.
you download a prebuilt install package from boostpro (assuming that you are on windows) -- https://sourceforge.net/projects/boost/files/boost-binaries/
you can build it yourself - see http://www.boost.org/doc/libs/1_35_0/more/getting_started/index.html
|
2,174,567 | 2,174,572 | c++ how to ? function_x ( new object1 ) | Hi i want to do the next
instead of
MyClass object;
function_x (object);
i want to
function_x ( new object );
so what will be the structure of the MyClass to be able to do that ..
if i just compiled it , it gives me a compile time error
answer function_x (MyClass() )
New Edit thanks for the quick answers.. i did ask the wrong Question i should have asked how
temporary variables created in C++ and the answer
| new is called on classes, not objects. And it returns a pointer, so unless function_x accepts a pointer, this is impossible.
You can do this though:
void function_y(MyClass* ptr)
{
// Do something
}
// Then call
function_y(new MyClass);
Note a few things about this:
The default constructor of MyClass is called when it's created
function_y must keep the pointer in some accessible place to avoid a memory leak
Is this what you need, or something else?
|
2,174,570 | 2,177,640 | Qt: How to send an event to the operating/window system? | I want to create an event in one Qt application that can be picked up by a seperate Qt application running at the same time. The normal sendevent function requires you to name the object which will receive it but I can't use that, I want it to be like a keyboard press event which filters through any open programs in the OS. Does anyone know how to do that? thanks
| Take a look at Inter-Process Communication in Qt. The most cross-platform friendly way is to use a socket.
Shared memory is also an option, but for events I would recommend a socket that you can then attach slots to on the receiving side to handle it like a local event.
Edit: Sorry I think i missed the real point when I read the other answer, you want to make something like a key-logger that records strokes anywhere. Not sure about that one.
|
2,174,584 | 2,406,769 | Binding event to wxMenu instead of wxMenuItem | Im creating a dynamic MenuBar from xml file, and binding events to menu items using Connect().
Some menus does not have items inside, but needs to fire events.
Is there a way to attach an event handler to a wxMenu using Connect()?
*Im Using wxWidgets 2.8.8 & MS VC++ 6.0
| Ive tried many things, but nothing worked out for me.
As a quick answaer ill quote Vadim Zeitlin from wx-widgets list:
No, you shouldn't associate commands
directly to top level menus. This is
discouraged under all systems and is
not supported at all under some of
them.
|
2,174,657 | 2,175,295 | When are header-only libraries acceptable? | Personally, I quite like header-only libraries, but there are claims they cause code bloat due to over-inlining (as well as the other obvious problem of longer compile times).
I was wondering, how much truth is there to these claims (the one about bloat)?
Furthermore, are the costs 'justified'? (Obviously there are unavoidable cases such as when it's a library implemented purely or mostly with templates, however I'm more interested in the case where there's actually a choice available.)
I know there's no hard and fast rule, guideline, etc as far as stuff like this goes, but I'm just trying to get a feel for what others think on the issue.
P.S. Yes this is a very vague and subjective question, I'm aware, and so I have tagged it as such.
| I work for a company that has a "Middleware" department of its own to maintain a few hundreds of libraries that are commonly used by a great many teams.
Despite being in the same company, we shy from header only approach and prefer to favor binary compability over performance because of the ease of maintenance.
The general consensus is that the performance gain (if any) would not be worth the trouble.
Furthermore, the so called "code-bloat" may have a negative impact on performance as more code to be loaded in the cache implies more cache miss, and those are the performance killers.
In an ideal world I suppose that the compiler and the linker could be intelligent enough NOT to generate those "multiple definitions" rules, but as long as it is not the case, I will (personally) favor:
binary compatibility
non-inlining (for methods that are more than a couple of lines)
Why don't you test ? Prepare the two libraries (one header only and the other without inlining methods over a couple of lines) and check their respective performance in YOUR case.
EDIT:
It's been pointed out by 'jalf' (thanks) that I should precise what I meant exactly by binary compatibility.
2 versions of a given library are said binary compatible if you can (usually) link against one or the other without any change of your own library.
Because you can only link with one version of a given library Target, all the libraries loaded that use Target will effectively use the same version... and here is the cause of the transitivity of this property.
MyLib --> Lib1 (v1), Lib2 (v1)
Lib1 (v1) --> Target (v1)
Lib2 (v1) --> Target (v1)
Now, say that we need a fix in Target for a feature only used by Lib2, we deliver a new version (v2). If (v2) is binary compatible with (v1), then we can do:
Lib1 (v1) --> Target (v2)
Lib2 (v1) --> Target (v2)
However if it's not the case, then we will have:
Lib1 (v2) --> Target (v2)
Lib2 (v2) --> Target (v2)
Yep, you read it right, even though Lib1 did not required the fix, you head to rebuild it against a new version of Target because this version is mandatory for the updated Lib2 and Executable can only link against one version of Target.
With a header-only library, since you don't have a library, you are effectively not binary compatible. Therefore each time you make some fix (security, critical bug, etc...) you need to deliver a new version, and all the libraries that depend on you (even indirectly) will have to be rebuilt against this new version!
|
2,174,768 | 2,182,269 | Generating random UUIDs in Linux | I am stuck in a strange predicament. I need to generate UUIDs in my Linux program (which I distribute using RPMs). I do not want to add another dependency to my application by requiring the user to install libuuid (seems like libuuid isn't included in most Linux distros, like CentOS).
Isn't there a standard Linux system call which generates UUIDs (like say, in Windows there CoCreateGuid)? What does the command uuidgen use?
| Thanks for all your comments!
I went through each one, and here's what suited my requirement the best:
What I needed was just plain time-based UUIDs which were generated from random numbers once for every user who installed the application. UUID version 4 as specified in RFC 4122 was exactly it. I went through a the algorithm suggested, and came up with a pretty simple solution which would work in Linux as well as Windows (Maybe its too simplistic, but it does satisfy the need!):
srand(time(NULL));
sprintf(strUuid, "%x%x-%x-%x-%x-%x%x%x",
rand(), rand(), // Generates a 64-bit Hex number
rand(), // Generates a 32-bit Hex number
((rand() & 0x0fff) | 0x4000), // Generates a 32-bit Hex number of the form 4xxx (4 indicates the UUID version)
rand() % 0x3fff + 0x8000, // Generates a 32-bit Hex number in the range [0x8000, 0xbfff]
rand(), rand(), rand()); // Generates a 96-bit Hex number
|
2,174,838 | 2,177,486 | Is "var" in C# analagous to "size_t" in C? | I have gotten used to using size_t in my C++ code by way of C due to a professor's insistence and I was curious if 'var' in C# is the same sort of thing?
| If you are asking whether the use of var is like size_t in that you don't actually need to use size_t, you can get away with an int, then yes, they are kind of similar in that respect.
However, they differ in that size_t is about making your code more explicit, whilst var is about removing some redundant explicitness for the benefit of readability.
So the readability of the following code can be improved with var:
Dictionary<string, Dictionary<int, char>> mapping = new Dictionary<string, Dictionary<int, char>>();
-- vs --
var mapping = new Dictionary<string, Dictionary<int, char>>();
However, excess use of var can harm readability, like in var f = Foo();.
Unlike size_t, there is absolutely no difference in the code that gets compiled with var as opposed to the explicit type.
With size_t, one of the benefits is portability. Object sizes might not be an int on all platforms, but size_t will always be large enough to hold them. This means not using size_t could mean your code doesn't compile correctly on some platform.
However, with var the code that gets compiled at the end of it is exactly the same. You can use var everywhere you possibly can, or you could never use var (with the exception of anonymous types) and it would make no difference.
So whilst it is recommended you always use size_t where possible in C, var is more of a judgement call. It's what you think makes the code more readable.
|
2,174,881 | 2,174,903 | Why have a pointer to a pointer (int **a)? | int **a = malloc2d(M, N) // dynamically allocates a 2D array
What is the purpose of having int **a vice int *a. I understand that pointers are needed for dynamic allocation but why have a pointer to a pointer?
For a 3-dimensional array would it be:
int ***a
?
| You need a pointer to a pointer for several reasons.
In the example you gave, a double pointer is used to store the 2D array.
A 2D array in C is treated as a 1D array whose elements are 1D
arrays (the rows).
For example, a 4x3 array of T (where "T" is some data type) may
be declared by: "T mat[4][3]", and described by the following
scheme:
+-----+-----+-----+
mat == mat[0] ---> | a00 | a01 | a02 |
+-----+-----+-----+
+-----+-----+-----+
mat[1] ---> | a10 | a11 | a12 |
+-----+-----+-----+
+-----+-----+-----+
mat[2] ---> | a20 | a21 | a22 |
+-----+-----+-----+
+-----+-----+-----+
mat[3] ---> | a30 | a31 | a32 |
+-----+-----+-----+
Another situation, is when you have pass a pointer to a function, and you want that function to allocate that pointer. For that, you must the address of the pointer variable, hence a pointer to a pointer
void make_foofoo(int** change) {
*change = malloc(4);
}
|
2,175,189 | 2,175,422 | what are the OOP features which are not in java but c++ has those features? | Respected Sir!
As i have not learnt java yet but most people say that C++ has more OOP features than Java, I would like to know that what are the features that c++ has and java doesn't. Please explain.
| This might be controversial, but some authors say that using free functions might be more object oriented than writting methods for everything. So by those author's point of view, free functions in C++ make it more OO than Java (not having them).
The explanation is that there are some operations that are not really performed on an instance of an object, but rather externally, and that having externally defined operations for those cases improves the OO design. Some of the cases are operations on two objects that are not naturally an operation of either one. Incrementing a value is clearly an operation on the value, but creating a new value with the sum of two others (or concatenating) are not really operations on the instance. When you write:
String a = "Hello";
String b = " World";
String c = a.append( b );
The append operation is not performed on a: after the operation a is still "Hello". The operation is not performed on b either, it is an external operation that is performed on both a and b. In this particular example, the most OO way of implementing the operation would be providing a new constructor that takes two arguments (after all, the operation is performed on the new string), but another solution would be providing an external function append that takes two strings and returns a third one.
In this case, where both instances are of the same type, the operation can naturally be performed as a static method of the type, but when you mix different types the operation is not really part of either one, and in some cases it might end up being of a completely different type. In some cases free functions are faked in Java as in the Collections java class, it does not represent any OO element, but is rather simple glue to tie free functions are static methods because the language does not have support for the former. Note that all those algorithms are not performed on the collection nor an instance of the contained type.
|
2,175,298 | 2,175,324 | Allocate more processor cycles to my program | I've been working on win32, c,c++ for a while. I code on visual studio. Most of the time I see system idle process uses more cpu utilization. Is there a way to allocate more processor cycles to my program to run it faster? I understand there might be limitations from i/o, in those cases this question doesn't make any sense.
OR
did i misunderstood the task manager numbers? I'm in a confusion, please help me out.
And I want to do something in program itself, btw I will be happy if answers are specific to windows.
Thanks in advance
~calvin
| If your program it the only program that has something to do (not wait for IO), its thread will always be assigned to a processor core.
However, if you have a multi-core processor, and a single-threaded program, the CPU usage of your process displayed in the task manager will always be limited by 100/Ncores.
For example, if you have a quad-core machine, your process will be at 25% (using one core), and the idle process at around 75%. You can only additional CPU power by dividing your tasks into chunks that can be worked on by separate threads which will then be run on the idle cores.
|
2,175,302 | 2,175,312 | Unique Numerical ID for a Templated Class using Function Address | So, this question has been asked before, but I wanted a question with some of those key words in the title.
The issue is simple: How can I have a templated class, such that for each instance of the template - but not each instance of the class - there is a unique, numerical identifier?
That is, a way to differentiate:
foo<int> f1;
foo<char> f2;
classID(f1) != classID(f2);
but,
foo<int> f3;
foo<int> f4;
classID(f3) == classID(f4);
Related to:
in C++, how to use a singleton to ensure that each class has a unique integral ID?
Assigning Unique Numerical Identifiers to Instances of a Templated Class
| template<class T>
class Base
{
public:
static void classID(){}
private:
T* t;
};
int main()
{
Base<int> foo;
Base<int> foo2;
Base<char> foo3;
/*
unsigned int i = reinterpret_cast<unsigned int>(Base<int>::classID);
unsigned int ii = reinterpret_cast<unsigned int>(Base<char>::classID);
unsigned int iii = reinterpret_cast<unsigned int>(Base<int>::classID);
/*/
unsigned int i = reinterpret_cast<unsigned int>(foo.classID);
unsigned int ii = reinterpret_cast<unsigned int>(foo2.classID);
unsigned int iii = reinterpret_cast<unsigned int>(foo3.classID);
//*/
return ((i != ii) + (i <= ii) + (i >= ii)) == 2;
}
That's how! It's lightweight, super easy, and doesn't use RTTI, although it uses the ridiculously unsafe reinterpret_cast.
Although, maybe I'm missing something?
|
2,175,418 | 2,175,486 | Quick way to fetch URL html contents with Qt? | I'm not interested in the QNetWork class and all it's callbacks, I want a static function or something where I can just:
QString html = QHttpHelperThingy::fetch("http://blah.com");
Does such a thing exist?
| I believe that this is the replacement path: http://doc.qt.io/archives/4.6/qnetworkaccessmanager.html, but QHttp will work throughout 4.x series.
|
2,175,445 | 2,175,553 | effective C++ data structure to consider in this case | Greetings code-gurus!
I am writing an algorithm that connects, for instance node_A of Region_A with node_D of Region_D. (node_A and node_D are just integers). There could be 100k+ such nodes.
Assume that the line segment between A and D passes through a number of other regions, B, C, Z . There will be a maximum of 20 regions in between these two nodes.
Each region has its own properties that may vary according to the connection A-D. I want to access these at a later point of time.
I am looking for a good data structure (perhaps an STL container) that can hold this information for a particular connection.
For example, for connection A - D I want to store :
node_A,
node_D,
crosssectional area (computed elsewhere) ,
regionB,
regionB_thickness,
regionB other properties,
regionC, ....
The data can be double , int , string and could also be an array /vector etc.
First I considered creating structs or classes for regionB, regionC etc .
But, for each connection A-D, certain properties like thickness of the region through which this connection passes are different.
There will only be 3 or 4 different things I need to store pertaining to a region.
Which data structure should I consider here (any STL container like vector?) Could you please suggest one? (would appreciate a code snippet)
To access a connection between nodes A-D, I want to make use of int node_A (an index).
This probably means I need to use a hashmap or similar data structure.
Can anyone please suggest a good data structure in C++ that can efficiently
hold this sort of data for connection A -D described above? (would appreciate a code snippet)
thank you!
UPDATE
for some reasons, I can not make use of pkgs like boost. So want to know if I can use any libraries from STL
| You should try to group stuff together when you can. You can group the information on each region together with something like the following:
class Region_Info {
Region *ptr;
int thickness;
// Put other properties here.
};
Then, you can more easily create a data structure for your line segment, maybe something like the following:
class Line_Segment {
int node_A;
int node_D;
int crosssectional_area;
std::list<Region_Info>;
};
If you are limited to only 20 regions, then a list should work fine. A vector is also fine if you would prefer.
|
2,175,455 | 2,175,468 | C++ My first template ever | Ok, which is the best to avoid ambiguity here?
template <class T>
inline void swap(T &a, T &b)
{
T c; c = a; a = b; b = c;
}
/* blah blah blah (inside of a function:) */
for (itv = vals.begin(); itv != vals.end(); ++itv)
{
if (at < (*itv)) { swap(at, (*itv)); }
if (at % (*itv) == 0) atadd = false;
}
/* blah blah blah */
Calling with a swap doesn't work either, as it says cannot resolve whether it is "void swap(T &,T &)", "void std::swap(_Ty &,_Ty &)" or ...
Btw, itv is a vector<int>::iterator.
Thx.
| The problem is namespace std also contains swap() function and looks like you have using namespace std; somewhere earlier, so the compiler can't decide which swap() to use - yours from the global namespace or the one from namespace std.
You need to prepend the call with "::" to explicitly tell the compiler to use your swap() from the global namespace instead of from namespace std. Alternatively you could rename your swap() function or not use using namespace std;.
|
2,175,665 | 2,178,062 | CreateProcess, process do not terminate when redirecting std out/in/err | I'm trying to use CreateProcess to launch a powershell script from within my application.
I've used the Microsoft example (http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx) to create the child process and redirect the standard out/in/err pipes.
The only issue left to solve is why the child process (powershell) do not terminate after executing the command.
If I execute the powershell process (with the command) cmd.exe it executes and exits, closing the process.
The only way of closing the powershell process right now is to run TerminateProcess on the handle, but that feels like a last resort.
| Is your parent reading the child's stdout completely? If you don't read it all then I believe the child will hang. Also, if the script expects input you will have to write something to the child's stdin or else it will hang. You could attach windbg to the child and see where it is hanging; maybe it will give you an idea of where to look.
|
2,175,808 | 2,176,433 | boost::spirit composing grammars from grammars | I have figured out how to use spirit -- i.e., I have written a moderately complex grammar. I always take the approach of growing a program -- one subsystem at a time. I've written the data structures for a complex model which has 4 types at the highest level.
I would like to use the grammar composed from rules approach to parse the top level types one type at a time -- i.e., I want to write 4 grammars with one top level grammar. If this is possible (which I am beginning to doubt), could someone please post a snippet or a reference to a project that does this.
One top level grammar with 50+ (possible a lot more) rules (for proper error handling) does not sound like fun (TMP code is volatile / slow to compile, and provides useless error messages).
| simplified from an actual program, Qi should work the same as Karma.
template<class Iter>
struct subgrammar_1
: karma::grammar<Iter, ...>
{
...
}
template<class Iter>
struct top_level_grammar
: karma::grammar<Iter, ...>
{
top_level_grammar() : top_level_grammar::base_type(start)
{
start %= r1 | r2;
}
karma::rule<Iter, ...> r1;
subgrammar_1<Iter> r2;
...
}
|
2,175,867 | 2,175,960 | Can I add file in Visual Studio 2003 and make it point to an existing file in another project? | This is a question about using Visual Studio 2003. Sorry it is not strictly a programming question but it does affect my work in a rather annoying way.
I have a solution with 3 different projects (let's say MyProgram, UnitTest and PerformanceTest), and there is a file (let's say myclass.h) which needs to be shared between the 3 projects.
The file is created in the MyProgram project and now I want to add it to the others.
Say I go to the solution explorer, right click on UnitTest, and select Add -> Add Existing Item from the pop-up menu.
The file myclass.h was added to the project, but instead of pointing to the existing (solution directory)\MyProgram\myclass.h, a new file is created in (solution directory)\UnitTest\myclass.h. Now this means that everytime I change \MyProgram\myclass.h, I need to copy it to \UnitTest\myclass.h or the file is not up to date.
Is this a "feature" of Visual Studio 2003 or have I got something wrong with the options/settings? Is manually editing the .vcproj files the only way to make the links point to an existing file? Thank you very much for your help.
| Try this - To create a link to an existing item:
1.In Solution Explorer, select the target project.
2.On the Project menu, select Add Existing Item.
3.In the Add Existing Item dialog box, locate and select the project item you want to link.
4.From the Open button drop-down list, select Add As Link.
http://msdn.microsoft.com/en-us/library/9f4t9t92.aspx
Your right - that is 2008. This link implies what you want to do was introduced in VS 2005 and is not available in 2003:
"Back in the days of the original Visual Studio .NET and the following version,
Visual Studio .NET 2003, whenever you added an existing file to a project,
it copied the file into the corresponding location in the project.
However, in Visual Studio 2005, the Add Existing Item feature provided the
ability to choose to either Add the item or Add As Link (via the little down
arrow on the button in the dialog box)."
http://blogs.msdn.com/jjameson/archive/2009/04/02/linked-files-in-visual-studio-solutions.aspx
|
2,176,040 | 2,178,453 | How to create artificial nodes in QAbstractItemModel for QTreeView | my question is about Qt and its QAbstractItemModel.
I have a map of strings and doubles (std::map<stringclass, double>) which I would like to present in a Qt widget. While I could use QTableView for that, I would like to exploit the fact that the keys of the map are of form "abc.def.ghi" where there can be multiple strings that can start with "abc.def" and even more that start with "abc".
So I would like to setup a tree data model to present the items in a QTreeView like
(-) abc
|--(-)def
|--ghi 3.1415
|--jkl 42.0815
|--(+)pqr
|--(+)xyz
The keys of my std::map are the leaves of the tree, where all other nodes would be temporary and auxillary constructs to support the folding for user convenience.
Unfortunately, the methods rowCount, index, columnCount, and data have const-modifiers, so I cannot simply setup a auxillary data structure for the headers inside my QAbstractItemModel derivate and change that data structure in there.
What would be the best practice for that? Should I setup another class layer between my std::map and the QAbstractItemModel or is there a smarter way to do this?
Edit 1: The std::map can change while the QTreeView is shown and used, so the auxillary nodes might be thrown away and reconstructed. My assumption is that the best way to handle this is to restructure the QAbstractItemModel - or should I simply throw that model away and assign a newly constructred one to the QTreeView? In that case I could set-up all nodes within the constructor without being bothered by the const-ness of the methods, I guess.
| I would parse the map and create a tree data structure based on it. Make sure you sync the model when you change the map.
If this sync step gets too complicated you might want to hold your data in a tree structure from the start and convert to a map when necessary.
Parsing the map on the fly in the model functions seems like a bad idea to me, you'd want these functions to be as fast as possible.
|
2,176,299 | 2,176,370 | Core dump analysis using gdb | I have a couple of questions regarding core dumps. I have gdb on Windows, using Cygwin.
What is the location of core dump file? Is it a.exe.stackdump file? (This is the only file that generated after crash) I read on other forums that the core dump file is named "core". But I don't see any file with name "core".
What is the command for opening and understanding core dump file?
|
You need to configure Cygwin to produce core dumps by including
error_start=x:\path\to\dumper.exe
in your CYGWIN environment variable (see here in section "dumper" for more information). If you didn't do this, you will only get a stacktrace -- which may also help you in diagnosing the problem, though.
Start gdb as follows to attach it to a core dump file:
gdb myexecutable --core=mycorefile
You can now use the usual gdb commands to print a stacktrace, examine the values of variables, and so on.
|
2,176,336 | 2,176,372 | c++ Socket select and receive problem | Below is the code fragment I have issue with socket programing. Here after select call, If I do not put a sleep on line 9, on Windows XP, 1 byte is received on line 11 (instead 4 byte is sent from server as integer), when I check xmlSize, it is set to 0. Because iResult is 1, execution continues and on line 15 second receive is called with xmlSize=0, and iResult is set to 0 and afterwards because iResult=0 connection is closed.
But on Windows 7 this did not happen, program happily read 4 bytes and continued normal execution. On XP however I put a sleep(I just made this up) and it worked, but Why??
What is the flaw in this code?
1 while(is_running())
2 {
3 FD_ZERO(&readfds);
4 FD_SET(server_socket, &readfds);
5 iResult = select(server_socket+1, &readfds, NULL, NULL, &tv);
6 if (!(iResult != SOCKET_ERROR && FD_ISSET(server_socket, &readfds) )) {
7 continue;
8 }
9 Sleep(500); // This Sleep is not required on Windows 7, but is required on 10 XP but WHY?
11 iResult = recv(server_socket, (char *)&xmlSize, sizeof(xmlSize), 0);
12 xmlSize = htonl(xmlSize);
13 if ( iResult > 0 ){
13 printf("Bytes received: %d, XML Size:%d", iResult, xmlSize);
14
15 iResult = recv(server_socket, xml, xmlSize, 0);
16 if ( iResult > 0 ){
17 xml[xmlSize] = '\0';
18 printf("Bytes received: %d", iResult);
19 operation_connection(xml);
20 }
21 else if ( iResult == 0 ){
22 printf(LL_INTERR, CLOG("Connection closed"));
23 break;
24 }
25 else{
26 printf("recv failed with error: %d", WSAGetLastError());
27 break;
28 }
29 }
30 else if ( iResult == 0 ){
31 printf(LL_INTERR, CLOG("Connection closed"));
32 break;
33 }
34 else{
35 printf("recv failed with error: %d", WSAGetLastError());
36 break;
37 }
38 }
| If this is a TCP socket, you shouldn't care. The socket delivers a stream, it's doesn't correspond in any way or fashion to the size of the original write()s to the other end.
It could deliver a megabyte as one million 1-byte read()s, or as a single 1MB one, or any combination in between.
If you depend on the size of the delivered data "chunks" for a TCP connection, you're doing it wrong.
If you need some kind of message separator, then explicitly design one into your protocol, the way carriage return+linefeed is used by e.g. HTTP. If your protocol is ASCII so you can't use these particular bytes to separate messages, there are of two two classic approaches:
Use some other byte sequence, perhaps ASCII 0x1E, the "record separator".
Escape the CR+LF when they're contained in the message, to make "plain" ones work as separators. This would be the better solution if your protocol "wants" to be text.
Another approach is to explicitly encode the length of each message in the stream itself, preferably as a prefix so you know how much data to expect.
|
2,176,427 | 2,176,455 | Comprehensive gnu make / gcc tutorial | I've just started learning C++ and I find it very hard to find short, comprehensive tutorials on how to use gnu make / gcc. Any ideas (please don't point me to the official gnu make tutorial, it's way too much in-depth for my purposes ;-)).
| Check the book Managing Projects with GNU Make.
The entire text of this book is available online. Part I of this book covers the basic concepts, which I think would help you get comfortable with GNU Make.
|
2,176,711 | 2,176,739 | Sentinel while loop for C++ | Can anyone tell me what is sentinel while loop in C++? Please give me an example using sentinel while loop.
| A "sentinel" in this context is a special value used to indicate the end of a sequence. The most common sentinel is \0 at the end of strings. A "sentinel while loop" would typically have the form:
while (Get(input) != Sentinel) {
Process(input);
}
|
2,176,798 | 2,176,811 | C++ empty class or typedef | I'm currently using something like that in my code:
class B : public A<C> { };
Wouldn't it be better to use a typedef?
typedef A<C> B;
| It depends. If you want A<C> and B to be distinct but related types, B should extend A<C>. If you want them to be identical, you should use a typedef. Can you provide any more context?
|
2,176,877 | 2,176,894 | Sourceannotations.h ? C++ | What is this errormessage in Visual Studio 2008
Error 1 error C2144: syntax error : '__w64 unsigned int' should be preceded by ';' c:\program files\microsoft visual studio 9.0\vc\include\codeanalysis\sourceannotations.h 19 Steg2_Labs
I don't have any headerfiles made myself.
| You are missing a semicolon somewhere before the "integral type" declaration.
Since you say there aren't any other libraries included (written by you) than it must be in the current file and usualy the statement directly before the error line number.
|
2,176,930 | 2,176,955 | C++ STL List calculate average | I have to correct some C++/STL code. Unfortunately I have very little C++ experience and know nothing about STL. Nevertheless I finished most of it, but the function below is still giving me problems:
C++ source:
double MyClass::CalculateAvg(const std::list<double> &list)
{
double avg = 0;
std::list<int>::iterator it;
for(it = list->begin(); it != list->end(); it++) avg += *it;
avg /= list->size();
}
C++ header:
static double CalculateAvg(const std::list<int> &list);
It's most likely meant to calculate the average value from a list, but it complies with a lot of errors. I tried to search for a solutions on the web, but I couldn't find anything. I would be glad if someone could help me out.
Update:
Thank you for your quick replies. The accepted answer solved all my problems.
| So, the first error is there:
std::list<int>::iterator it;
You define an iterator on a list of integers, and use it to iterate on a list of doubles. Also, an iterator can only be used on a non-constant list. You need a constant operator. You should write:
std::list<double>::const_iterator it;
At last, you forgot to return the value.
edit: I didn't see, but you pass the list as reference, but use it as a pointer. So replace all the list-> by list.
|
2,177,105 | 2,177,549 | Windows Performance Analysis Tool usage as a profiler | I have an application written in c++ using visual studio 2005. The application has certain performance problems. I would like to explore where. I need to drill down in which classes/methods/lines the application spends most of the time. Can this be done with the WPA? If yes, can you, please give me a pointer to documentation?
| No, WPT leverages windows events, it would only help you diagnose a problem when Windows is the cause of your slow-down. You certainly won't get any diagnostics for your code. What you need is a real profiler. Good ones cost money. Check this thread for more advice.
|
2,177,209 | 2,177,254 | Is it possible to pass a C ellipsis call through directly? | void printLine(const wchar_t* str, ...)
{
// have to do something to make it work
wchar_t buffer[2048];
_snwprintf(buffer, 2047, ????);
// work with buffer
}
printLine(L"%d", 123);
I tried
va_list vl;
va_start(vl,str);
and things like this but I didn't find a solution.
| Here's a simple C code that does this, you will have to include stdarg.h for this to work.
void panic(const char *fmt, ...){
char buf[50];
va_list argptr; /* Set up the variable argument list here */
va_start(argptr, fmt); /* Start up variable arguments */
vsprintf(buf, fmt, argptr); /* print the variable arguments to buffer */
va_end(argptr); /* Signify end of processing of variable arguments */
fprintf(stderr, buf); /* print the message to stderr */
exit(-1);
}
The typical invocation would be
panic("The file %s was not found\n", file_name); /* assume file_name is "foobar" */
/* Output would be:
The file foobar was not found
*/
Hope this helps,
Best regards,
Tom.
|
2,177,327 | 2,179,212 | Container access and allocation through the same operator? | I have created a container for generic, weak-type data which is accessible through the subscript operator.
The std::map container allows both data access and element insertion through the operator, whereas std::vector I think doesn't.
What is the best (C++ style) way to proceed? Should I allow allocation through the subscript operator or have a separate insert method?
EDIT
I should say, I'm not asking if I should use vector or map, I just wanted to know what people thought about accessing and inserting being combined in this way.
| Separate insert method, definitely. The operator[] on std::map is just stupid and makes the code hard to read and debug.
Also you can't access data from a const context if you're using a operator[] to insert (which will lead to un-const-cancer, the even-more evil cousin of const-cancer).
|
2,177,474 | 2,177,488 | Visual Studio add-on to tag code segments? | I wonder if there exists any add-on for VS that can substitute/tag some lines of code with a descriptive text of my choice ?
Ideally a function like the one below :
bool CreateReportFiles(LPCTSTR fn_neighbours, ULONG nItems, ULONG* items)
{
// Read from file
CFile cf_neighbours;
if (!cf_neighbours.Open(fn_neighbours, CFile::modeRead))
return false;
cf.Read(items, sizeof(ULONG) * nItems);
cf.Close();
// Create reports
DoReport_1(items, nItems);
DoReport_2(items, nItems);
DoReport_3(items, nItems);
FinalizeReports();
}
...would look similar to this :
bool CreateReportFiles(LPCTSTR fn_neighbours, ULONG nItems, ULONG* items)
{
± Read from file
± Do the reports
}
The ± signs would expand / collapse the substituted lines.
Other workarounds also considered !
Thanks for your help !
| The region functionality does pretty much precisely what you describe, and is built into Visual Studio.
The following will compress as you described:
bool CreateReportFiles(LPCTSTR fn_neighbours, ULONG nItems, ULONG* items)
{
#pragma region ReadFile
// Read from file
CFile cf_neighbours;
if (!cf_neighbours.Open(fn_neighbours, CFile::modeRead))
return false;
cf.Read(items, sizeof(ULONG) * nItems);
cf.Close();
#pragma endregion ReadFile
#pragma region CreateReports
// Create reports
DoReport_1(items, nItems);
DoReport_2(items, nItems);
DoReport_3(items, nItems);
FinalizeReports();
#pragma endregion CreateReports
}
|
2,177,619 | 2,177,631 | Finding division by zero in a big project | Recently, our big project began crashing on unhandled division by zero. No recent code seems to contain any likely elements so it may be new data sets affecting old code. The problem is the code base is pretty big, and running on an embedded device with no comfortable debug access (debug is done by a lot of printf()s over serial console, there is no gdb for the device and even if there was, the binary compiled with debug symbols wouldn't fit).
The most viable way would likely be to find all the division operations (they are relatively infrequent), and analyze code surrounding each of them to see if any of the divisor variables was left unguarded.
The question is then either how to find all division operations in a big (~200 files, some big) C++ project, or, if you have a better idea how to locate the error, please give them.
extra info: project runs on embedded ARM9, a small custom Linux distro, crosscompiled with Cygwin/Windows crosstools, IDE is Eclipse but there's also Cygwin with all the respective goodies. Thing is the project is very hardware-specific, and the crashes occur only when running at full capacity, all the essential interconnected modules active. Restricted "fault mode" where only bare bones are active doesn't create them.
| Finding all of the divisions shouldn't be hard with a custom grep search. You can easily distinguish that usage from other usages of the / and % character in C++.
Also, if you know what you are dividing, you could globally overload the / and % operator to have a __FILE__ and __LINE__ informing assertion. If using a makefile, it shouldn't be hard to include the custom operator code in all the linked files without touching the code.
|
2,177,731 | 2,177,757 | How to get a basic preg_match_all replacement for std::string in C++? | with "basic" is meant: Only the operators "+" (->following..) and "|" (->or) are needed.
Prototype:
preg_match_all(std::string pattern, std::string subject, std::vector<std::string> &matches)
Usage Example:
std::vector<std::string> matches;
std::string pattern, subject;
subject = "Some text with a lots of foo foo and " + char(255) + " again " + char(255);
pattern = "/" + char(255) + char(255) + "+|foo+/";
preg_match_all(pattern, subject, matches);
The matches should be available afterwardsa via matches[n]. Someone got a hint without using boost and/or PCRE? If not, how I got this realized with boost?
| You could rollup something using std::string::find, doing matches via a functor, and pushing the results onto a string vector.
The way it's realized in boost is probably overkill for what you want -- you first would need to decompose the expression into lexems and then compile a state machine for parsing the given regexp.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.