question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,874,103 | 1,877,905 | negative color with glBlendFunc()? | i want my lines to be drawn with negative color (taken from the screen under the line), i just didnt understand how the blending works, looked at docs etc, tested 50 combinations and so on. started to think its not possible at all...
could someone just give the two values?
| You should use logic ops for that purpose. Not blend.
So all you have to do is to call:
glEnable(GL_COLOR_LOGIC_OP);
glLogicOp(GL_INVERT);
You can use GL_ XOR too, depending what you want to achieve. GL_ XOR is useful if you want to restore the frame buffer exactly in the state that it was before the line draw happened. Just draw a second time the same line with GL_XOR again ((a xor b) xor b == a). It's a common trick in CAD world.
|
1,874,205 | 1,875,157 | C/C++ J2ME interpreter | do anyone know some C or C++ interpreter for cell phones? I have Nokia 5310 and found some Basic interpreter (CellBasic) and want to develop in C or C++ on the go. Or, does anybody knows Scheme J2ME intepreter?
| You don't want to do a C interpreter in J2ME unless you first compile it to bytecode elsewhere: you'd waste a lot of space with the parser.
If you're interested, I have my own interpreter that's used by various people and companies called Hecl, at http://www.hecl.org
It's fairly simple, but has commands to access a variety of things, and is under active development, with a nice user community.
|
1,874,208 | 1,874,417 | Problem using reinterpret_cast<> in c++ | I am trying to cast a datastream into a struct since the datastream consists of fixed-width messages and each message has fulle defined fixed width fields as well. I was planning on creating a struct and then using reinterpret_cast to cast pointer to the datastream to the struct to get the fields. I made some test code and get weird results. Could any explain why I am getting these or how to correct the code. (the datastream will be binary and alpha numeric mixed but im just testing with strings)
#pragma pack(push,1)
struct Header
{
char msgType[1];
char filler[1];
char third[1];
char fourth[1];
};
#pragma pack(pop)
int main(void)
{
cout << sizeof(Header) << endl;
char* data = "four";
Header* header = reinterpret_cast<Header*>(data);
cout << header->msgType << endl;
cout << header ->filler << endl;
cout << header->third << endl;
cout << header->fourth << endl;
return 0;
}
The result that are coming up are
4
four
our
ur
r
I think the four, our and ur is printing since it cant find the null terminator. How do I get around the null terminator issue?
| In order to be able to print an array of chars, and being able to distinguish it from a null-terminated string, you need other operator<< definitions:
template< size_t N >
std::ostream& operator<<( std::ostream& out, char (&array)[N] ) {
for( size_t i = 0; i != N; ++i ) out << array[i];
return out;
}
|
1,874,262 | 1,874,269 | C/C++/C# Force window to be on top | Is the there a way to force another window to be on top? Not the application's window, but another one, already running on the system. (Windows, C/C++/C#)
| You can use the Win32 API BringWindowToTop. It takes an HWND.
You could also use the Win32 API SetWindowPos which also allows you to do things like make the window a top-level window.
|
1,874,297 | 1,874,329 | C++ good coding style - always fully qualify library types? | What is generally considered good coding style in C++ where you use types from the standard library? For example, if I have a using namespace std; directive would you still expect to see library types fully qualified like so: std::string or is it acceptable to just use string as the type identifier?
If you do fully qualify, can you expain the rationale behind it?
| fully qualify in header files. import the namespace in the .cpp files.
keeps the global namespace from being cluttered by a simple #include
|
1,874,354 | 1,874,365 | A dynamic buffer type in C++? | I'm not exactly a C++ newbie, but I have had little serious dealings with it in the past, so my knowledge of its facilities is rather sketchy.
I'm writing a quick proof-of-concept program in C++ and I need a dynamically sizeable buffer of binary data. That is, I'm going to receive data from a network socket and I don't know how much there will be (although not more than a few MB). I could write such a buffer myself, but why bother if the standard library probably has something already? I'm using VS2008, so some Microsoft-specific extension is just fine by me. I only need four operations:
Create the buffer
Write data to the buffer (binary junk, not zero-terminated)
Get the written data as a char array (together with its length)
Free the buffer
What is the name of the class/function set/whatever that I need?
Added: Several votes go to std::vector. All nice and fine, but I don't want to push several MB of data byte-by-byte. The socket will give data to me in few-KB large chunks, so I'd like to write them all at once. Also, at the end I will need to get the data as a simple char*, because I will need to pass the whole blob along to some Win32 API functions unmodified.
| You want a std::vector:
std::vector<char> myData;
vector will automatically allocate and deallocate its memory for you. Use push_back to add new data (vector will resize for you if required), and the indexing operator [] to retrieve data.
If at any point you can guess how much memory you'll need, I suggest calling reserve so that subsequent push_back's won't have to reallocate as much.
If you want to read in a chunk of memory and append it to your buffer, easiest would probably be something like:
std::vector<char> myData;
for (;;) {
const int BufferSize = 1024;
char rawBuffer[BufferSize];
const unsigned bytesRead = get_network_data(rawBuffer, sizeof(rawBuffer));
if (bytesRead <= 0) {
break;
}
myData.insert(myData.end(), rawBuffer, rawBuffer + bytesRead);
}
myData now has all the read data, reading chunk by chunk. However, we're copying twice.
We instead try something like this:
std::vector<char> myData;
for (;;) {
const int BufferSize = 1024;
const size_t oldSize = myData.size();
myData.resize(myData.size() + BufferSize);
const unsigned bytesRead = get_network_data(&myData[oldSize], BufferSize);
myData.resize(oldSize + bytesRead);
if (bytesRead == 0) {
break;
}
}
Which reads directly into the buffer, at the cost of occasionally over-allocating.
This can be made smarter by e.g. doubling the vector size for each resize to amortize resizes, as the first solution does implicitly. And of course, you can reserve() a much larger buffer up front if you have a priori knowledge of the probable size of the final buffer, to minimize resizes.
Both are left as an exercise for the reader. :)
Finally, if you need to treat your data as a raw-array:
some_c_function(myData.data(), myData.size());
std::vector is guaranteed to be contiguous.
|
1,874,467 | 1,874,823 | What does this statement mean? "good C++ programming typically doesn't use pointers in complicated ways." | In this other question in the winning answer I read:
... good C++ programming typically
doesn't use pointers in complicated
ways.
What does it mean to not use pointers in complicated ways?
(I'm really hoping that this isn't a subjective question)
| As the guy who wrote that, I can at least tell you what I meant.
In a good C++ program, of the sorts I'm familiar with, pointers are used to indicate objects, mostly so they can be passed around and used polymorphically. They aren't used to pass by reference, because that's what references are for. There is NO pointer arithmetic. There aren't many raw pointers. Pointers aren't usually used to build up data structures, since most of the data structures you're going to want a lot are built into the standard library or maybe Boost.
In other words, modern C++ typically uses pointers in the same way Java does, except that Java doesn't use the word because it has no concept of something other than a primitive datatype that's accessible except by pointer (at least not when I last used Java). The translation is from something like Foo bar = new Foo(); (syntax not guaranteed) to smart_ptr<Foo> bar = new Foo; and from bar.snarf() to bar->snarf(). At least to get started, a Java programmer doesn't need to pick up the concept like he or she would if he or she were moving to C.
|
1,874,578 | 1,874,625 | C/C++/C# SetWindowPos: Window on top of others | I would like someone to give a working example of SetWindowPos on how to make a window "topmost" (be on top and stay there) using either C/C++/C#. Thanks in advance!
| SetWindowPos with .NET
|
1,874,738 | 1,935,942 | How do I keep Eclipse from automatically deleting my exe file | I use Eclipse for Java development.
There is an *.exe file in a subdirectory of my workspace, which keeps getting deleted.
Specifically, one of the projects is dedicated to C++ development using MSVC; there is no Java there. The root of this project has cpp and h files, and I use MSVC to generate the exe under the /bin directory.
As part of its built-in build process, Eclipse deletes this exe file as it compiles *.java files, apparently because it thinks that the exe file is binary output. Note that the exe is not in any /target directory.
By the way, I am using the Maven-Eclipse plugin, but this behavior apparently occurs when Eclipse is building the workspace, not part of a Maven run.
I'd rather keep the exe in this directory; it is the right place to have it, and so I would rather not go to the effort of moving it as a workaround.
How can I prevent this from happening? Is there some configuration within Eclipse where I can state that exe files are not to be cleaned when building?
| The problem is you are storing your executable in /bin, which is an Eclipse output directory. This directory gets removed each time you do a clean build. Solution: store your executable elsewhere (i.e. /exe).
|
1,875,147 | 1,875,365 | Can you help with creating a zip archive with the LZMA (7zip) SDK? | I am trying to use the LZMA SDK to create a zip archive (either .zip or .7z format). I've downloaded and built the SDK and I just want to use the dll exports to compress or decompress a few files. When I use the LzamCompress method, it returns 0 (SZ_OK) as if it worked correctly. However, after I write the buffer to file and try to open it, I get an error that the file cannot be opened as an archive.
Here is the code I am currently using. Any suggestions would be appreciated.
#include "lzmalib.h"
typedef unsigned char byte;
using namespace std;
int main()
{
int length = 0;
char *inBuffer;
byte *outBuffer = 0;
size_t outSize;
size_t outPropsSize = 5;
byte * outProps = new byte[outPropsSize];
fstream in;
fstream out;
in.open("c:\\temp\\test.exe", ios::in | ios::binary);
in.seekg(0, ios::end);
length = in.tellg();
in.seekg(0, ios::beg);
inBuffer = new char[length];
outSize = (size_t) length / 20 * 21 + ( 1 << 16 ); //allocate 105% of file size for destination buffer
if(outSize != 0)
{
outBuffer = (byte*)malloc((size_t)outSize);
if(outBuffer == 0)
{
cout << "can't allocate output buffer" << endl;
exit(1);
}
}
in.read(inBuffer, length);
in.close();
int ret = LzmaCompress(
outBuffer, /* output buffer */
&outSize, /* output buffer size */
reinterpret_cast<byte*>(inBuffer),/* input buffer */
length, /* input buffer size */
outProps, /* archive properties out buffer */
&outPropsSize,/* archive properties out buffer size */
5, /* compression level, 5 is default */
1<<24,/* dictionary size, 16MB is default */
-1, -1, -1, -1, -1/* -1 means use default options for remaining arguments */
);
if(ret != SZ_OK)
{
cout << "There was an error creating the archive." << endl;
exit(1);
}
out.open("test.zip", ios::out | ios::binary);
out.write(reinterpret_cast<char*>(outBuffer), (int)(outSize));
out.close();
delete inBuffer;
delete outBuffer;
}
| I do not know about LZMA specifically, but from what I know of compression in general, it looks like you are writing a compressed bit stream to a file without any header information that would let a decompression program know how the bit stream is compressed.
The LzmaCompress() function probably writes this information to outProps. There should be another function in the SDK that will take the compressed bit stream in outBuffer and the properties in outProps and create a proper archive from them.
|
1,875,167 | 1,876,431 | Performance profiling on Linux | What are the best tools for profiling C/C++ applications on *nix?
(I'm hoping to profile a server that is a mix of (blocking) file IO, epoll for network and fork()/execv() for some heavy lifting; but general help and more general tools are all also appreciated.)
Can you get the big system picture of RAM, CPU, network and disk all in one overview, and drill into it?
There's been a lot of talk on the kernel lists about things like perf timechart, but I haven't found anything turning up in Ubuntu yet.
| I recommend taking stackshots, for which pstack is useful. Here's some more information:
Comments on gprof.
How stackshots work.
A blow-by-blow example.
A very short explanation.
If you want to spend money, Zoom looks like a pretty good tool.
|
1,875,228 | 1,875,439 | Practical and advanced C++ usage | I've studied C++ as a college course. And I have been working on it for last three years. So I kinda have a fairly good idea what is it about. But I believe to know a language is quite different from using it to full potential. My current job doesn't allow me to explore much.
I have seen you guys suggest studying a open source project and perhaps contributing to one too. So my question is, can you suggest one(of both?) to start with that is simple and doesn't overwhelm a starter.
| I was in the same situation 12 years ago when I got my first programming job out of college. I didn't do any open source but I managed to gain a lot of practical and advanced C++ knowledge by reading books (the dead tree kind).
In particular, there was an excellent series by Scott Meyers which I feel helped the most in turning me from newbie to professional:
Effective C++: 55 Specific Ways to Improve Your Programs and Designs
More Effective C++: 35 New Ways to Improve Your Programs and Designs
Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library
The topics in these books range from beginner to advanced. It took me about 2 years working in C++ to understand every chapter in these books, so don't be disheartened if it goes over your head at some point... just try reading it again later :)
|
1,875,247 | 1,875,292 | Cross-compile from (open)Solaris to Windows? | Is there any way I can cross-compile C/C++ code for Windows (XP, Vista, Win7), ideally in 64-bit as well as 32-bit (for Vista and Win7), from a Solaris or OpenSolaris setup? My codebase is already cross-platform, I would like to cross-compile it (generate windows DLLs and EXEs) from Solaris or Linux as part of an automated process.
I would like to use the GCC suite, and would rather not need to use the Cygwin DLLs, if possible.
If it is possible, which tools would I need in my Solaris environment? How would I go about compiling/linking an entire project?
If this is not possible in Solaris, how should I proceed from Linux, considering I would like 32- and 64-bit binaries for all of the versions of Windows I have mentioned?
Thanks in advance for any help!
| I'm not sure if you want cross-compilation (creation of Windows EXE files on the the Solaris box) or cross-platform (code that compile on Solaris or Windows). The latter is easier, and to do it you should start by installing the MinGW version of the GCC compiler on your Windows box.
|
1,875,296 | 1,875,369 | Problem with class template specialisations | I'm trying to port some code from VC9 to G++, however Ive run into a problem with template specialisations apparently not being allowed for class members.
The following code is an example of these errors for the getValue specialisations of the class methods. In all cases the error is "error: explicit specialization in non-namespace scope class ..."
template<typename T> T getValue(const_iterator key)const
{
try{return boost::lexical_cast<T>(key->second);}
catch(boost::bad_lexical_cast &e)
{
throw TypeParseError<T>(name, key->first, e.what());
}
}
template<typename T> T getValue(const std::string &key)const
{
iterator i = find(key);
if(i == end())throw KeyNotFound(name,key);
else return getValue(i);
}
template<> std::string getValue<std::string>(const_iterator key)const
{
return key->second;
}
template<> std::string getValue<std::string>(const std::string &key)const
{
const_iterator i = find(key);
if(i == end())throw KeyNotFound(name,key);
else return i->second;
}
Is it just the exact syntax is not supported, and that a minor change will make it work, or will I need to change the code to avoid specialisations like this? If the latter which is the best way to do so in general?
| You haven't shown the class definition enclosing these function-declarations. But i assume it's some class where these templates are declared in. You have to define the specializations outside:
struct SomeClass {
template<typename T> T getValue(const_iterator key)const
{
try{return boost::lexical_cast<T>(key->second);}
catch(boost::bad_lexical_cast &e)
{
throw TypeParseError<T>(name, key->first, e.what());
}
}
template<typename T> T getValue(const std::string &key)const
{
iterator i = find(key);
if(i == end())throw KeyNotFound(name,key);
else return getValue(i);
}
};
template<> inline std::string SomeClass::getValue<std::string>(const_iterator key)const {
return key->second;
}
template<> inline std::string SomeClass::getValue<std::string>(const std::string &key)const {
const_iterator i = find(key);
if(i == end())throw KeyNotFound(name,key);
else return i->second;
}
Remember that since you have defined them outside, they are not inline implicitly, so you either have to make them inline explicitly, or move them into a cpp file (not a header), and forward-declare the specializations in the header like this:
template<> inline std::string SomeClass::getValue<std::string>(const_iterator key)const;
template<> inline std::string SomeClass::getValue<std::string>(const std::string &key)const;
If you omit the forward-declaration, the compiler has no way to know whether to instantiate the functions or to use the explicit specializations. The forward declaration tells it.
|
1,875,388 | 1,875,413 | Help on linking in gcc | In Microsoft visual c++ compiler, you can specify linker options using
#pragma comment(lib, "MSVCRT") //links with the MVCRT library
see this page
I find this feature very useful because linker errors are common and i want to just place all the linker options in my source code instead of specifying them to the compiler.
question: Is there a way to do this in gcc (or dev-cpp or codeblocks ide)?
Thanks in advance.
| GCC doesn't support this because to link correctly, the order in which you link your objects matters.
See also my answer and others in the question "#pragma comment(lib, “xxx.lib”) equivalent under Linux?"
|
1,875,425 | 1,875,448 | want to make a complex c++ gui simply | I want to make a nice simple gui using c++. which have drag and drop capabilities, must be light weight. Im thinking of a gui like utorrent client gui.Its light weight and simple.
please give me information about most easy to use libraries / ide /plugin (on windows platform may be good).
| Either use QT or wxWidgets. Both are free to use, but QT uses more advanced features of C++ and is used slightly more than wxWidgets (From what I have seen) and has the backing of Nokia.
Both have various gui editors. QT has a QT Creator and there is a list of tools on the wxWiki, which includes a lot of open source RAD gui designers.
I have experience of using wxWidgets in both C++ and Python, and would recommend wxFormBuilder as a GUI designer.
The downside to both is they feel the need to use their own string classes etc which duplicates the functionality of the stl. From what I understand is that this is because when the projects were started there wasn't a standard.
|
1,875,542 | 1,877,527 | How do I overload the I/O operators C++ | I have created a class that allows the user to input their mailing address, order date, type of cookie ordered and the quantity. There were other errors, but I stayed late and with the assistance of my prof, I have fixed them. Now all that is left is that I need to be able to change code to overload the I/O stream operators so that the objects may be used in standard input and output statements.
I'm not sure what all part of the code everyone will need to see, but I'm going to post the parts I believe are needed for what I'm trying to do.
I need to have it where in the output(), I have cout << order << endl; I will look over the net and will hopefully have it ready by tonight. Thanks for everyone's input.
Was instructed to take down my code due to other students from class copying my code pieces to do their work (knew it was possible but didn't think about it)
However, my code is complete.
| Implement two functions:
basic_ostream & operator<< (basic_ostream& ostr, const CookieOrder& co)
basic_istream & operator>> (basic_istream& istr, CookieOrder& co)
the operator<<= function will be called when you use cout << order << endl; and the operator>> function will be called when you use the >> (stream extraction) operator. Be very careful how you implement the stream extraction operator.
You may want to declare either of these as friend to the CookieOrder, as that will allow the function to access the private parts of the class as if the function is a member of the class.
edit to respond to changes in the question
delcare your class as before:
class CookieOrder {
public:
// public methods as before
private:
// private parts as before
};
basic_ostream & operator<< (basic_ostream& ostr, const CookieOrder& co);
basic_istream & operator>> (basic_istream& istr, CookieOrder& co);
Implement the two functions using only the public interface of the CookieOrder class.
For example:
basic_ostream & operator<< (basic_ostream& ostr, const CookieOrder& co)
{
ostr << co.get_customerName() << endl;
/* the rest of the output */
}
These functions are not members of the CookieOrder class, they are normal functions with no special access to the CookieOrder class or instanaces of the class.
|
1,875,609 | 1,875,728 | Better way to count things? | In one of my programs for school, I use the following function to count the frequency of identifiers in a string, separated by newlines and #:
Input:
dog
cat
mouse
#
rabbit
snake
#
Function:
//assume I have the proper includes, and am using namespace std
vector< pair<string,int> > getFreqcounts(string input) {
vector<string> items = splitString(input,"\n");
map<string,int> counts;
for (int i=0; i<items.size(); i++) {
if (items[i] == "#") continue;
counts[items[i]] = 0;
}
for (int i=0; i<items.size(); i++) {
if (items[i] == "#") continue;
counts[items[i]]++;
}
return vector< pair<string,int> > (counts.begin(),counts.end());
}
I would like to at the very least
remove the double for loop
find a better way to get a vector< pair<string,int> >
Any ideas?
BTW, this is NOT homework. The real homework will use this function, but this is purely out of my own curiosity and desire to have "better" code.
| You can get rid of the first for loop by simply deleting it. It accomplishes nothing useful. When/if the subscript into the map creates a new item, that item will have the chosen key, and your associated int will be initialized to zero automatically.
Personally, I'd probably do things a bit differently, using a stringstream instead of your SplitString(). I'm hesitant about posting code, but I guess I'll trust you...
typedef vector<pair<string, int> > count_vec;
count_vec GetFreqCounts(string const &input) {
istringstream in(input);
string line;
map<string, int> counts;
while (getline(in, line))
if (line != "#")
++counts[line];
return count_vec(counts.begin(), counts.end());
}
Edit: I honestly didn't pay a whole lot of attention to efficiency as I was writing this, but I think Steve Jessop's comment on it is pretty accurate. As long as the input is small, it won't make any real difference. If the input is really big, the fact that this only uses an extra copy of one word at a time could save enough memory to be meaningful.
The solution Steve gave in his reply looks pretty nice too though. Since it also processes words as they're produced, I'd expect it to have characteristics similar to the code above. If you can break the string into words faster than stringstream does, it'll undoubtedly be faster. Given the number of virtual functions that get in the way with iostreams, there's a pretty good chance of that -- but unless you're dealing with a lot of text there's not much chance of it making a significant difference. Of course, exactly what qualifies as significant is open to question. To put it in perspective, I ran some similar code across a word list I had handy. Using code pretty close to what's above, it processes text at a little over 10 megabytes a second.
|
1,875,695 | 1,875,737 | Constructor and variable names in C++ vs. Java | I'm learning C++ coming from a Java background (knowing a little C from many years ago)...
In Java, it's common practice to use "this" inside a constructor to distinguish the variable passed in as arguments to the constructor from the one declared in the class:
class Blabla {
private int a;
private int b;
Blabla(int a, int b){
this.a = a;
this.b = b;
}
}
I like this, because the variable Blabla.a and the one passed in as an argument to the constructor represents the same thing, so it feels logical that they should have the same name...
Is it possible to do this in C++?
| Yes, you can use this to refer to member variables. That said, you'll often find that your code looks as follows in idiomatic C++:
class Blabla {
private:
int a_;
int b_;
public:
Blabla(int a, int b) : a_(a), b_(b) {}
};
As you can see, you normally do not apply the access control specifiers (public, protected or private) to each member, but you group them in sections.
Also, if you use the type of initialisation that you used above, the members get initialised twice - once with the default constructor when the object is created (basically, before the code inside the curly brackets is executed) and the second time during the assignments to this->a.
|
1,875,727 | 1,875,924 | C# COM Server - Testing in C++ | I have some C# interfaces exposed to COM:
interface IMyInterface
{
IMyListObject[] MyList
{
get;
}
}
interface IMyListObject
{
//properties that don't matter
}
So far I'm testing how our assembly is exposed to COM from C++ and most is working just fine.
My current problem is at one point I have 2 instances of IMyInterface and need to copy from one MyList to another.
If I just call this in C++:
myInterfaceB->MyList = myInterfaceA->MyList;
This gives the HRESULT of E_POINTER.
MyList returns a SAFEARRAY*, the equivalent code works just fine in C#.
I'm not generally a C++ developer, how do I fix this?
| Not sure if E_POINTER makes sense or why it would work in C#. It can't work, your MyList property doesn't have a property setter. It doesn't really need one, you don't have to change the array, only the array contents. Use the SafeArrayXxxx() functions, using the ATL CComSafeArray or MFC COleSafeArray wrappers makes it easier.
|
1,875,830 | 1,876,578 | How to implement collision effects in a game? | I building a game with QT. Every objects on my GraphicsScene inherits from GraphicsPixmapItem (Player, Obstacles, bombs...). I would like to implment collision effects. For example when the player gets hover a bonus he can pick it.
With the QT framework I can get the collidings items but I don't know which type they are as there isn't instanceof function. Any tips ?
edit: I get the collision "event" the thing I want to do is handle the different collisions. I made another question with better wording.
| Design considerations:
I can't recommend inheriting Game objects from their graphic representation. Why? You may want to have multiple graphic representations of one game object (like one in game view or another one in minimap, or whatever). The relation is "Player 'has-a' graphic representation" and not "Player 'is-a' graphic representation". Better solution is to use composition and not inheritance. Other nice effect is possible encapsulation of other collision detection if you are not happy with one provided by Qt, decoupling, ... Truth also is, that for simple game it can be sufficient though.
For simple enough game logic, inheritance where other objects react to active object. Probably too simplistic for any more complex game mechanics.
class Asteroid {
public:
virtual void CollideWithPlayer(Player&) { p.loseHealth(100); }
};
class ExplodingAsteroid: Asteroid {
public:
virtual void CollideWithPlayer(Player&) { explode(); p.loseHealth(1000); }
};
If interaction gets complex(many active objects behaving on their own) you may need to identify your objects:
There's is RTTI, but erm it's hard to recommend see: How expensive is RTTI?
In short: expensive, hard to maintain.
You can use double-dispatch. Identifies objects using two virtual calls.
Problems: Quite a bit of syntax, sometimes difficult to maintain (especially when you add new objects), ownership problems (see more).
Game example from Wikipedia:
class SpaceShip {};
class GiantSpaceShip : public SpaceShip {};
class Asteroid {
public:
virtual void CollideWith(SpaceShip&) {
cout << "Asteroid hit a SpaceShip" << endl;
}
virtual void CollideWith(GiantSpaceShip&) {
cout << "Asteroid hit a GiantSpaceShip" << endl;
}
};
class ExplodingAsteroid : public Asteroid {
public:
virtual void CollideWith(SpaceShip&) {
cout << "ExplodingAsteroid hit a SpaceShip" << endl;
}
virtual void CollideWith(GiantSpaceShip&) {
cout << "ExplodingAsteroid hit a GiantSpaceShip" << endl;
}
};
"enumeration"
virtual function id
class GameObject() {
virtual getId() { return GAME_OBJECT; }
};
class Asteroid() {
virtual getId() { return ASTEROID; }
};
or as a member
class GameObject() {
ID getId() { return id; }
protected:
GameObject(ID id):id(id) {}
private:
ID id;
};
or using template with auto initialization of id (a little mind-boggling syntax, let's omit it :o)
and others
Now for game loop like this:
for each object
update by (fixed) time step
detect collisions and resolve them
you will encounter:
Ownership problems:
player loses health when being hit by asteroid and asteroid is destroyed afterwards..
Asteorid::collideWithPlayer(Player& p) { p.loseHealth(100); this->explode(); }
now consider also
Player::collideWithAsteroid(Asteroid& a) { this->loseHealth(100); a.explode(); }
result: code duplicity or unclear game mechanics
poor man's solution: call someone else to help you :o)
Asteorid::collideWithPlayer(Player& p) { resolveCollision(p, *this); }
Player::collideWithAsteroid(Asteroid& a) { resolveCollision(*this, a); }
resolveCollision(Player, Asteroid) { p.loseHealth(100); a.explode(); }
|
1,875,998 | 1,876,052 | Can POSIX message queues be used cross user on Linux? | I have implemented a POSIX message queue.
On the listener side, I am opening the queue like this:
mqdes = mq_open(s_mailbox_name.c_str(), O_RDONLY | O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, NULL);
On the sender side, I am opening the queue like this:
mqdes = mq_open(m_s_mailbox_name.c_str(), O_WRONLY);
The string is the same on both, lets call it /foobox
Now, when I run both the sender and receiver as the same user on the box, everything works perfectly. However If the sender and receiver are 2 different users, the receiver can not open the queue. I would think this wouldn't be a problem because I am opening the queue as 0777 above so everyone can RWX.
Is there something obvious i'm doing wrong? Or is this not possible (Please don't let it be this one)
Thanks
| Check umask.
From man mq_open: "The permissions settings are masked against the process umask."
|
1,876,051 | 1,876,694 | How can I change a module's checksum in a minidump? | The software that I write (and sell) is compressed and encrypted before I distribute it. Everytime I release a new build, I keep all the .map files and the generated binaries including the exe before it is compressed and encrypted.
When it crashes on a client's machine I get a minidump back. I open these minidumps in Visual Studio and explore them there.
I have made good use of these minidumps by searching for addresses in the .map files. This will typically get me in the correct area of the code and I can generally reason about why the crash occured and fix it but this is VERY time consuming.
It would be helpful if I could use the symbols that I saved from the original build in the debugging of the minidump.
My problem is that I get warnings about being unable to find the right symbols. My research leads me to believe that this is because the checksum of the exe on the client's machine does not match the checksum of the exe that Visual Studio built. And I understand why, it has been compressed and encypted. Of course the checksums don't match.
I figure I can manually edit the minidump or change the checksum of the saved binaries to match the checksum of the distributable. I would prefer to manipulate the stored copies so I don't have to modify every dump that comes in, but I'd be estatic with either.
So, my question is: How can I locate these checksums and figure out what I should replace them with? As an auxiliary question: Is there a better way?
| Without knowing how exactly you are compressing and encrypting your binaries, it's hard for me to be very specific.
This blog post by John Robbins points out that executable images are associated with their PDBs via a GUID that's embedded in the executable's PE header. You should be able to view it by running DUMPBIN /HEADERS on the executable, and looking for the output of Debug Directories. If your compression and encryption has modified the PE headers such that this information isn't available (or correct), then it would explain why your debugger can't find anything.
There are a few approaches that I think that you could take to resolve this issue. To really try to get this to work, you might want to consider using WinDbg instead of the Visual Studio debugger. You'll understand why I am recommending this in a moment...
WinDbg provides some options that allow the relaxed loading of symbol files. The idea with this option is that, if the source code hasn't changed but the binaries are from a different build than the PDB, the GUID check can be waived and the mismatched symbol file can be loaded. I don't know how well this will work with your compression and encryption, so YMMV.
WinDbg and its accompanying tools can be used to dump the GUID from both the executable and the PDB, but I'm omitting that for now because I am hoping that those steps won't be necessary.
After you have opened your minidump in WinDbg, you will need to enter several commands into the command line to get this all to work:
.symopt +0x40
!sym noisy
ld <exe name>
The first command enables the SYMOPT_LOAD_ANYTHING option that skips the GUID check. The !sym command enables verbose output for symbol loading so that you may see more detailed error messages. The ld command directs WinDbg to try to load the symbols for the executable name that you will type in the place of <exe name>. If you repeat the ld command, WinDbg will indicate if it successfully loaded the symbols the first time.
Hopefully this helps -- again, I don't know how well this will work with your compression and encryption, but it's worth trying.
|
1,876,150 | 1,876,178 | Simple, efficient weak pointer that is set to NULL when target memory is deallocated | Is there a simple, efficient weak/guarded pointer? I need multiple pointers to the same object that are all automatically set to NULL when the object is deleted. There is one "master" pointer that is always used to delete the object, but there can be several other pointers that reference the same object.
Here are some solutions that don't quite match my needs:
QPointer: I am not developing a QT app; I do not wish to include this libary/derive from QObject.
boost::weak_ptr: an exception is thrown when accessing a deallocated object. Too expensive for my situation: it should be normal to test a weak pointer; I plan to do some manual clean-up when a weak pointer is no longer valid. update:weak_ptr can be tested without throwing exceptions
Low-Overhead Weak Pointers: This is very close to what I am looking for, except I don't like the fact "This scheme is only guaranteed to work as long as you don’t allocate 2**sizeof(int) times in the same location."
Why I need these weak/guarded pointers:
I have a game with a list of game objects. Some objects are dependent on others, for example a debug/stats object that is associated with a game entity. The debug/status object displays useful info about the game entity, but it only makes sense while the game entity exists. So if the game entity is deleted, the debug/stats object should realize this and delete itself. (Another idea is a tracking missile: instead of deleting itself, it may search for a new target.)
I wish to keep the debug/stats logic separate from the game entity. The game entity should not have to know a debug/stats object is attached to it. While I'd prefer an answer for weak/guarded pointers, I also welcome different ways to approach my specific task. I am thinking I may have to implement a game object manager that tracks object lifetimes and uses handles instead of raw pointers to memory addresses.
I am developing in C++.
| You can use the lock() member of boost::weak_ptr to be able to test (then use) the value of the weak_ptr without dealing with exceptions.
|
1,876,179 | 5,611,886 | How to handle multiple collision type in c++? | I'm building a game in c++ using Qt. I got the collision detection right using GraphicsItem methods the thing is that I don't know how to deal with every different collision type as there is different objects with different behaviour.
| It's actually possible to know which kind of object participate in the collision, through custom type, see the documentation for more info http://doc.qt.io/qt-5/qgraphicsitem.html#type
|
1,876,433 | 1,876,512 | SSE2 - 16-byte aligned dynamic allocation of memory | EDIT:
This is a followup to SSE2 Compiler Error
This is the real bug I experienced before and have reproduced below by changing the _mm_malloc statement as Michael Burr suggested:
Unhandled exception at 0x00415116 in SO.exe: 0xC0000005: Access violation reading
location 0xffffffff.
At line label: movdqa xmm0, xmmword ptr [t1+eax]
I'm trying to dynamically allocate t1 and t2 and according to this tutorial, I've used _mm_malloc:
#include <emmintrin.h>
int main(int argc, char* argv[])
{
int *t1, *t2;
const int n = 100000;
t1 = (int*)_mm_malloc(n*sizeof(int),16);
t2 = (int*)_mm_malloc(n*sizeof(int),16);
__m128i mul1, mul2;
for (int j = 0; j < n; j++)
{
t1[j] = j;
t2[j] = (j+1);
} // set temporary variables to random values
_asm
{
mov eax, 0
label: movdqa xmm0, xmmword ptr [t1+eax]
movdqa xmm1, xmmword ptr [t2+eax]
pmuludq xmm0, xmm1
movdqa mul1, xmm0
movdqa xmm0, xmmword ptr [t1+eax]
pshufd xmm0, xmm0, 05fh
pshufd xmm1, xmm1, 05fh
pmuludq xmm0, xmm1
movdqa mul2, xmm0
add eax, 16
cmp eax, 100000
jnge label
}
_mm_free(t1);
_mm_free(t2);
return 0;
}
| I think the 2nd problem is that you're reading at an offset from the pointer variable (not an offset from what the pointer points to).
Change:
label: movdqa xmm0, xmmword ptr [t1+eax]
To something like:
mov ebx, [t1]
label: movdqa xmm0, xmmword ptr [ebx+eax]
And similarly for your accesses through the t2 pointer.
This might be even better (though I haven't had an opportunity to test it, so it might not even work):
_asm
{
mov eax, [t1]
mov ebx, [t1]
lea ecx, [eax + (100000*4)]
label: movdqa xmm0, xmmword ptr [eax]
movdqa xmm1, xmmword ptr [ebx]
pmuludq xmm0, xmm1
movdqa mul1, xmm0
movdqa xmm0, xmmword ptr [eax]
pshufd xmm0, xmm0, 05fh
pshufd xmm1, xmm1, 05fh
pmuludq xmm0, xmm1
movdqa mul2, xmm0
add eax, 16
add ebx, 16
cmp eax, ecx
jnge label
}
|
1,876,444 | 1,877,231 | Boost Unit Testing and Visual Studio 2005/Visual C++ and the BOOST_AUTO_TEST_SUITE(stringtest) namespace? | I'm reading this article on the Boost Unit Testing Framework.
However I'm having a bit of trouble with the first example, my guess is that they left something out (something that would be obvious to hardcore C++ coders) as IBM often does in their articles. Another possibility is that my Visual Studio 2005 C++ compiler is just too old for the example.
#include "stdafx.h"
#define BOOST_TEST_MODULE stringtest
#include <boost/test/unit_test.hpp>
//#include "mystring.h"
BOOST_AUTO_TEST_SUITE(stringtest) // name of the test suite is stringtest
BOOST_AUTO_TEST_CASE(test1)
{
/*
mystring s;
BOOST_CHECK(s.size() == 0);
*/
BOOST_CHECK(0 == 0);
}
BOOST_AUTO_TEST_CASE(test2)
{
/*
mystring s;
s.setbuffer("hello world");
BOOST_REQUIRE_EQUAL('h', s[0]); // basic test
*/
BOOST_CHECK(0 == 0);
}
BOOST_AUTO_TEST_SUITE_END()
To me the BOOST_AUTO_TEST_SUITE and BOOST_AUTO_TEST_CASE lines look a little suspect (especially since they don't have quotes around the arguments, and they are undeclared identifiers...but this probably means they are macros and I'm not certain I understand the concept or if that is available in VC++ 8.0)...
#ifdef _MYSTRING
#define _MYSTRING
class mystring {
char* buffer;
int length;
public:
void setbuffer(char* s) { buffer s = s; length = strlen(s); }
char& operator[ ] (const int index) { return buffer[index]; }
int size() {return length; }
}
#endif
Is there any reason why this code won't work?
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(7) : error C2065: 'stringtest' : undeclared identifier
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(9) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(9) : error C2146: syntax error : missing ';' before identifier 'BOOST_AUTO_TEST_CASE'
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(9) : error C2065: 'test1' : undeclared identifier
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(10) : error C2448: 'BOOST_AUTO_TEST_CASE' : function-style initializer appears to be a function definition
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(18) : error C2065: 'test2' : undeclared identifier
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(19) : error C2448: 'BOOST_AUTO_TEST_CASE' : function-style initializer appears to be a function definition
1>c:\users\andy\documents\visual studio 2005\projects\unittesttests\unittesttests\unittesttests.cpp(29) : fatal error C1004: unexpected end-of-file found
| Looks correct to me. My Boost.Test code looks the same way. I'm running VS2008, but I know it works in 2005 as well.
Seems like your problem lies elsewhere.
If you use precompiled headers (and why do you do that in such a small test program?), shouldn't stdafx.h be included as the very first thing in the file?
And what is the first line for? You don't seem to use it, and _MYSTRING is a reserved name in C++ (everything that begins with underscore followed by a capital letter is off limits)
|
1,876,474 | 1,892,029 | C++ Newbie needs helps for printing combinations of integers | Suppose I am given:
A range of integers iRange (i.e. from 1 up to iRange) and
A desired number of combinations
I want to find the number of all possible combinations and print out all these combinations.
For example:
Given: iRange = 5 and n = 3
Then the number of combinations is iRange! / ((iRange!-n!)*n!) = 5! / (5-3)! * 3! = 10 combinations, and the output is:
123 - 124 - 125 - 134 - 135 - 145 - 234 - 235 - 245 - 345
Another example:
Given: iRange = 4 and n = 2
Then the number of combinations is iRange! / ((iRange!-n!)*n!) = 4! / (4-2)! * 2! = 6 combinations, and the output is:
12 - 13 - 14 - 23 - 24 - 34
My attempt so far is:
#include <iostream>
using namespace std;
int iRange= 0;
int iN=0;
int fact(int n)
{
if ( n<1)
return 1;
else
return fact(n-1)*n;
}
void print_combinations(int n, int iMxM)
{
int iBigSetFact=fact(iMxM);
int iDiffFact=fact(iMxM-n);
int iSmallSetFact=fact(n);
int iNoTotComb = (iBigSetFact/(iDiffFact*iSmallSetFact));
cout<<"The number of possible combinations is: "<<iNoTotComb<<endl;
cout<<" and these combinations are the following: "<<endl;
int i, j, k;
for (i = 0; i < iMxM - 1; i++)
{
for (j = i + 1; j < iMxM ; j++)
{
//for (k = j + 1; k < iMxM; k++)
cout<<i+1<<j+1<<endl;
}
}
}
int main()
{
cout<<"Please give the range (max) within which the combinations are to be found: "<<endl;
cin>>iRange;
cout<<"Please give the desired number of combinations: "<<endl;
cin>>iN;
print_combinations(iN,iRange);
return 0;
}
My problem:
The part of my code related to the printing of the combinations works only for n = 2, iRange = 4 and I can't make it work in general, i.e., for any n and iRange.
| Here is your code edited :D :D with a recursive solution:
#include <iostream>
int iRange=0;
int iN=0; //Number of items taken from iRange, for which u want to print out the combinations
int iTotalCombs=0;
int* pTheRange;
int* pTempRange;
int find_factorial(int n)
{
if ( n<1)
return 1;
else
return find_factorial(n-1)*n;
}
//--->Here is another solution:
void print_out_combinations(int *P, int K, int n_i)
{
if (K == 0)
{
for (int j =iN;j>0;j--)
std::cout<<P[j]<<" ";
std::cout<<std::endl;
}
else
for (int i = n_i; i < iRange; i++)
{
P[K] = pTheRange[i];
print_out_combinations(P, K-1, i+1);
}
}
//Here ends the solution...
int main()
{
std::cout<<"Give the set of items -iRange- = ";
std::cin>>iRange;
std::cout<<"Give the items # -iN- of iRange for which the combinations will be created = ";
std::cin>>iN;
pTheRange = new int[iRange];
for (int i = 0;i<iRange;i++)
{
pTheRange[i]=i+1;
}
pTempRange = new int[iN];
iTotalCombs = (find_factorial(iRange)/(find_factorial(iRange-iN)*find_factorial(iN)));
std::cout<<"The number of possible combinations is: "<<iTotalCombs<<std::endl;
std::cout<<"i.e.the combinations of "<<iN<<" elements drawn from a set of size "<<iRange<<" are: "<<std::endl;
print_out_combinations(pTempRange, iN, 0);
return 0;
}
|
1,876,708 | 1,876,748 | evaluate trig functions in degrees as opposed to radians | So I have a function in an app that needs to let the user calculate a trig function (sin,cos,tan) using radians OR degrees, and also to expect a returned value from inverse trig functions (asin,acos,atan) as either radians or degrees. is there any way to do this without building in a converter directly into the way they input something? what i am trying to avoid is having to convert: sin(45) to sin(dtor(45))
thanks!
| There isn't a way to change the way the functions operate.
A "solution" would be to re-make the interface, and do the conversions:
// for example
float sin(float pX)
{
return std::sinf(d2r(pX));
}
And use that interface instead. Put it in a math:: namespace.
|
1,876,844 | 1,876,870 | Segfault when assigning one pointer to another | My brain has never really quite grasped linked lists and the finer points of pointers but I'm trying to help out a friend with some C++ assignments. (And before I go any further, yes, there is std::list but I'm looking for an academic answer, and maybe something that will make linked lists more understandable to he and myself).
What we need to do is generate a linked list of objects (a Employee object) based on user input, and then display that information back to the user. Whenever I try to assign the object into the Linked List Container, it segfaults.
I have the following Linked List object:
class LinkedListContainer {
private:
Employee *emp;
LinkedListContainer *next;
public:
Employee getEmployee() { return *emp; }
void setEmployee(Employee *newEmp) {
*emp = *newEmp // This is what is causing the segfault
}
LinkedListContainer getNext() { return *next; }
void setNext(LinkedListContainer *newContainer) {
*next = *newContainer;
}
}
I'm sure that I'm doing something horribly wrong.
| Looking at your class, there doesn't appear to be a place where the pointer emp is set to point at an actual object.
This line:
*emp = *newEmp;
assigns the value of the object pointed to by newEmp to the object pointed to by emp. Unless both pointers point at valid objects, the code will have undefined behaviour.
You may be better having emp as an Employee object rather than as a pointer to an object requiring manually management of the pointed to object's lifetime.
This assumes that your LinkedListContainer class is a node which will own the Employee.
On the other hand when you do:
*next = *newContainer;
from the naming I would assume that you just want to point the next pointer at another LinkedListContainer for which you would probably want to do:
next = newContainer;
as this assigns the value of the pointer to the variable next.
You need to be clear when you design your class and use pointers, on which objects own which other objects and ensure that you manage their lifetimes appropriately.
|
1,877,427 | 1,877,855 | C++ implementing a regex map | I have multiple regex expressions, each mapped to a different object. After passing in a string, I want to loop through each regex expression until one evaluates to true, then I would like to return the mapped object.
What is the best way to implement this in C++? Is there a boost object available for this?
| The simplest approach is probably best.
vector<pair<regex,Object>> regexes;
Object* find_it( string looking_for )
{
auto found = find_if( regexes, [&]( const pair<regex,Object>& thing )
{
return get<0>(thing).match(looking_for);
}
if( found != regexes.end() ) return & get<1>(*found);
return nullptr;
}
But, the simple approach is never a fun answer. If you use a Trie you can essentially have fast look up for regexes of the style <prefix>.*. With a little imagination you might be able to muster good look up time for slightly more expressive "regexes". I, however, doubt you could transform a trie to efficiently handle general regexes. But it could be fun to ... trie :).
|
1,877,439 | 1,877,496 | sqlite3_open - problems checking if a file is a sqlite3 database | I'm working with sqlite3 for the first time, and cannot get it to properly check a file before it opens it. So far, sqlite always returns OK on any file.
Also, the file name is a variable returned from the GTK file chooser. It returns an absolute path, I'm guessing this is not a problem.
Thanks for any help.
This is a snippet of the code:
int rc;
char *filename;
sqlite3 *db;
filename = gtk_file_chooser_get_filename(etc.);
if(SQLITE_OK == rc = sqlite3_open(filename,&db))
{ etc. }
| sqlite3_open doesn't actually read the file until the first non-pragma statement is prepared.
sqlite3_open_v2 provides other options.
|
1,877,500 | 1,877,522 | C++ stl stringstream direct buffer access | this should be pretty common yet I find it fascinating that I couldn't find any straight forward solution.
Basically I read in a file over the network into a stringstream. This is the declaration:
std::stringstream membuf(std::ios::in | std::ios::out | std::ios::binary);
Now I have some C library that wants direct access to the read chunk of the memory. How do I get that? Read only access is OK. After the C function is done, I dispose of the memorystream, no need for it.
str() copies the buffer, which seems unnecessary and doubles the memory.
Am I missing something obvious? Maybe a different stl class would work better.
Edit:
Apparently, stringstream is not guaranteed to be stored continuously. What is?
if I use vector<char> how do I get byte buffer?
| You can call str() to get back a std::string. From there you can call c_str() on the std::string to get a char*. Note that c_str() isn't officially supported for this use, but everyone uses it this way :)
Edit
This is probably a better solution: std::istream::read. From the example on that page:
buffer = new char [length];
// read data as a block:
is.read (buffer,length);
|
1,877,576 | 1,883,827 | C++ socket message contains extra ASCII 0 character | So this is a really strange problem. I have a Java app that acts as a server, listens for and accepts incoming client connections, and then read data (XML) off of the socket. Using my Java client driver, everything works great. I receive messages as expected. However, using my C++ client driver on the first message only, the very first character is read to be an ASCII 0 (shows up like a little box). We're using the standard socket API in C++, sending in a char* (we've done char*, std::string, and just text in quotes).
I used Wireshark to sniff the packet and sure enough, it's in there off of the wire. Admittedly, I haven't done the same on the client computer. My argument is that it really shouldn't matter, but correct me if that assumption is incorrect.
So my question: what the heck? Why does just the first message contain this extra prepended data, but all other messages are fine? Is there some little trick to making things work?
| So, the encoding thing didn't work. In the end, I simply did a substring(startIndex) call on the incoming message using xmlMessage.indexOf("<") as the starting index. It may not be elegant, but it'll work. And the box, will remain a mystery. I appreciate the insight that you three provided.
|
1,877,579 | 1,877,665 | Dealing with char arrays in C++ | I have this C-styled piece of initialization code:
const char * const vlc_args[] =
{
"-I", "dummy",
"--ignore-config",
"--extraintf=logger",
"--verbose=2"
"--plugin-path=/usr/lib/vlc"
};
//tricky calculation of the char space used
libvlc_new(sizeof(vlc_args)/sizeof(vlc_args[0]), vlc_args, &exc);
Since I need to make the --plugin-path parameter dynamic, I can't use a static array anymore. So I came up with a C++ alternative:
std::string pluginpath = "test";
libvlc_exception_t exc;
std::vector<std::string> args;
args.push_back("-I");
args.push_back("dummy");
args.push_back("--ignore-config");
args.push_back("--extraintf=logger");
args.push_back("--verbose=2");
args.push_back("--ipv4");
args.push_back("--plugin-path=" + pluginpath);
std::string combinedString;
for (size_t idx = 0; idx < args.size(); ++idx)
{
combinedString.append(args[idx]);
combinedString.resize(combinedString.size() + 1);
combinedString[combinedString.size() - 1] = 0;
}
combinedString.resize(combinedString.size() + 1);
combinedString[combinedString.size() - 1] = 0;
size_t size = combinedString.size();
const char * data = combinedString.c_str();
libvlc_new(size, &data, &exc); // => error occurs here (not at end of scope or anything)
But this results in a segmentation fault. So there must be an error in my code, which I can't seem to find.. Can anyone spot it?
Solved!
Thanks to Joseph Grahn and Jason Orendorff. My idea on the memory layout of the C-style array was wrong. I thought all data was organized as a big sequential block. In reality it's a list of pointers to the first character of each individual string.
This code works:
std::vector<const char*> charArgs;
for (size_t idx = 0; idx < args.size(); ++idx)
{
charArgs.push_back(&(args[idx][0]));
}
mVLCInstance = libvlc_new(charArgs.size(),
&charArgs[0],
&mVLCException);
| I think Josef Grahn is right: the API wants an actual array of pointers.
If you don't need to add arguments programmatically, you can just go back to using an array:
std::string pluginpath = "test";
std::string pluginpath_arg = "--plugin-path=" + pluginpath;
const char *args[] = {
"-I", dummy, "--ignore-config", ..., pluginpath_arg.c_str()
};
libvlc_exception_t exc;
libvlc_new(sizeof(args) / sizeof(args[0]), args, &exc);
EDIT: There might also be a problem with using c_str() here. This is true if VLC keeps the pointer and uses it again later; I can't tell if that's the case from the docs.
|
1,877,743 | 1,877,767 | Will using new (std::nothrow) mask exceptions thrown from a constructor? | Assume the following code:
Foo* p = new (std::nothrow) Foo();
'p' will equal 0 if we are out of heap memory.
What happens if we are NOT out of memory but Foo's constructor throws? Will that exception be "masked" by the nothrow version of 'new' and 'p' set to 0?... Or will the exception thrown from Foo's constructor make it out of the function?
| No, it won't be. The nothrow only applies to the call to new, not to the constructor.
|
1,877,816 | 1,878,092 | difference between -h <name> and -o <outputfile> options in cc (C++) | I am building .so library and was wondering - what is the difference b/w -h and -o cc complier option (using the Sun Studio C++) ?
Aren't they are referring to the same thing - the name of the output file?
| -o is the name of the file that will be written to disk by the compiler
-h is the name that will be recorded in ELF binaries that link against this file.
One common use is to provide library minor version numbers. For instance, if
you're creating the shared library libfoo, you might do:
cc -o libfoo.so.1.0 -h libfoo.so.1 *.o
ln -s libfoo.so.1.0 libfoo.so.1
ln -s libfoo.so libfoo.so.1
Then if you compile your hello world app and link against it with
cc -o hello -lfoo
the elf binary for hello will record a NEEDED entry for libfoo.so.1 (which you can
see by running elfdump -d hello ).
Then when you need to add new functions later, you could change the -o value to
libfoo.so.1.1 but leave the -h at libfoo.so.1 - all the programs you already built
with 1.0 still try to load libfoo.so.1 at runtime, so continue to work without being
rebuilt, but you'll see via ls that it's 1.1.
This is also sometimes used when building libraries in the same directory they're
used at runtime, if you don't have a separate installation directory or install
via a packaging system. To avoid crashing programs that are running when you
overwrite the library binary, and to avoid programs not being able to start when
you're in the middle of building, some Makefiles will do:
cc -o libfoo.so.1.new -h libfoo.so.1 *.o
rm libfoo.so.1 ; mv libfoo.so.1.new libfoo.so.1
(Makefiles built by the old Imake makefile generator from X commonly do this.)
|
1,877,823 | 1,878,184 | Most efficient tree structure for what I'm trying to do | I'm wondering what the most generally efficient tree structure would be for a collection that has the following requirements:
The tree will hold anywhere between 0 and 232 - 1 items.
Each item will be a simple structure, containing one 32-bit unsigned integer (the item's unique ID, which will be used as the tree value) and two pointers.
Items will be inserted and removed from the tree very often; some items in the tree will remain there for the duration of the program, while others will only be in the tree very briefly before being removed.
Once an item is removed, its unique ID (that 32-bit unsigned integer) will be recycled and reused for a new item.
The tree structure needs to support efficient inserts and deletions, as well as quick lookups by the unique ID. Also, finding the first available unused unique ID needs to be a fast operation.
What sort of tree would be best-suited for these requirements?
EDIT: This tree is going to be held only in memory; at no point will it be persisted to disk. I don't need to worry about hitting the disk, or disk caching, or anything of the sort. This is also why I'm not looking into using something like SQLite.
| Have you considered something like a trie? Lookup is linear in key length, which in your case means essentially constant, and storage can be more compact due to nodes sharing common substrings.
Keep in mind, though, that if your data set is actually filling large amounts of your key space your bigger efficiency concern is likely to be caching and disk access, not lookups.
|
1,878,001 | 40,441,240 | How do I check if a C++ std::string starts with a certain string, and convert a substring to an int? | How do I implement the following (Python pseudocode) in C++?
if argv[1].startswith('--foo='):
foo_value = int(argv[1][len('--foo='):])
(For example, if argv[1] is --foo=98, then foo_value is 98.)
Update: I'm hesitant to look into Boost, since I'm just looking at making a very small change to a simple little command-line tool (I'd rather not have to learn how to link in and use Boost for a minor change).
| Use rfind overload that takes the search position pos parameter, and pass zero for it:
std::string s = "tititoto";
if (s.rfind("titi", 0) == 0) { // pos=0 limits the search to the prefix
// s starts with prefix
}
Who needs anything else? Pure STL!
Many have misread this to mean "search backwards through the whole string looking for the prefix". That would give the wrong result (e.g. string("tititito").rfind("titi") returns 2 so when compared against == 0 would return false) and it would be inefficient (looking through the whole string instead of just the start). But it does not do that because it passes the pos parameter as 0, which limits the search to only match at that position or earlier. For example:
std::string test = "0123123";
size_t match1 = test.rfind("123"); // returns 4 (rightmost match)
size_t match2 = test.rfind("123", 2); // returns 1 (skipped over later match)
size_t match3 = test.rfind("123", 0); // returns std::string::npos (i.e. not found)
|
1,878,285 | 1,948,473 | Iterate Over Struct; Easily Display Struct Fields And Values In a RichEdit Box | Is there an easier way to display the struct fields and their corresponding values in RichEdit control?
This is what I am doing now:
AnsiString s;
s = IntToStr(wfc.fontColor);
RichEdit1->Lines->Append(s);
etc...
Is there an easier way than having to individually call each one? I want to read a binary file and then display the corresponding structure in a RichEdit control for a small utility I am building and have found no other way. I know how to read binary files and read the values into the struct already.
| BOOST_FUSION_ADAPT_STRUCT seems to fit well here. For example:
// Your existing struct
struct Foo
{
int i;
bool j;
char k[100];
};
// Generate an adapter allowing to view "Foo" as a Boost.Fusion sequence
BOOST_FUSION_ADAPT_STRUCT(
Foo,
(int, i)
(bool, j)
(char, k[100])
)
// The action we will call on each member of Foo
struct AppendToTextBox
{
AppendToTextBox(RichEditControl& Ctrl) : m_Ctrl(Ctrl){}
template<typename T>
void operator()(T& t)const
{
m_Ctrl.Lines.Append(boost::lexical_cast<std::string>(t));
}
RichEditControl& m_Ctrl;
};
// Usage:
void FillTextBox(Foo& F, RichEditControl& Ctrl)
{
boost::fusion::for_each(F, AppendToTextBox(Ctrl));
}
|
1,878,539 | 1,878,567 | Does the stack get unwound when a SIGABRT occurs? | Does the stack get unwound (destructors run) when a SIGABRT occurs in C++?
Thanks.
| This answer indicates that destructors aren't called.
|
1,878,645 | 1,878,678 | Where does the -DNDEBUG normally come from? | Our build system has somehow changed such that optimized builds are no longer getting the -DNDEBUG added to the compile line. I searched our makefiles and didn't find this.
Where does -DNDEBUG originate for most people and how might that have changed? Before we did have -DNDEBUG, and I don't think this was removed from any of our makefiles.
| Since the compiler can't decide on its own when to add the NDEBUG define and when not to, the flag is always set by either the makefile or project file (depending on your build system).
|
1,879,287 | 1,913,051 | OpenDDS and notification of publisher presence | Problem: How can I get liveliness notifications of booth publisher connect and disconnect?
Background:
I'm working with a OpenDDS implementation where I have a publisher and a subscriber of a data type (dt), using the same topic, located on separate computers.
The reader on the subscriber side has overridden implementations of on_data_available(...)and on_liveliness_changed(...). My subscriber is started first, resulting in a callback to on_liveliness_changed(...) which says that there are no writers available. When the publisher is started I get a new callback to telling me there is a writer available, and when the publisher publishes, on_data_available(...) is called. So far everything is working as expected.
The writer on the publisher has a overridden implementation of on_publication_matched(...). When starting the publisher, on_publication_matched(...) gets called since we already have a subscriber started.
The problem is that when the publisher disconnects, I get no callback to on_liveliness_changed(...) on the reader side, nor do I get a new callback when the publisher is started again.
I have tried to change the readerQos by setting the readerQos.liveliness.lease_duration.
But the result is that the on_data_available(...) never gets called, and the only callback to on_liveliness_changed(...) is at startup, telling me that there are no publishers.
DDS::DataReaderQos readerQos;
DDS::StatusKind mask = DDS::DATA_AVAILABLE_STATUS | DDS::LIVELINESS_CHANGED_STATUS | DDS::LIVELINESS_LOST_STATUS ;
m_subscriber->get_default_datareader_qos( readerQos );
DDS::Duration_t t = { 3, 0 };
readerQos.liveliness.lease_duration = t;
m_binary_Reader = static_cast<binary::binary_tdatareader( m_subscriber->create_datareader(m_Sender_Topic,readerQos,this, mask, 0, false) );
/Kristofer
| Ok, guess there aren't many DDS users here.
After some research I found that a reader/writer match occurs only if this compatibility criterion is satisfied: offered lease_duration <= requested lease_duration
The solution was to set the writer QoS to offer the same liveliness. There is probably a way of checking if the requested reader QoS could be supplied by the corresponding writer, and if not, use a "lower" QoS, all thou I haven't tried it yet.
In the on_liveliness_changed callback method I simply evaluated the alive_count in the from the LivelinessChangedStatus.
/Kristofer
|
1,879,388 | 1,879,411 | virtual functions in C++ | In my C++ program:
#include<iostream.h>
class A
{
public:
virtual void func()
{
cout<<"In A"<<endl;
}
};
class B:public A
{
public:
void func()
{
cout<<"In B"<<endl;
}
};
class C:public B
{
public:
void func()
{
cout<<"In C"<<endl;
}
};
int main()
{
B *ptr=new C;
ptr->func();
}
the statement should call B::func(). However, the function, C::func() is called. Please throw some light on this. Once the virtual keyword is removed in 'class A', this does not happen anymore.
| For the basics you should read C++ FAQ Lite on Virtual Functions.
A virtual function allows derived classes to replace the implementation provided by the base class. The compiler makes sure the replacement is always called whenever the object in question is actually of the derived class, even if the object is accessed by a base pointer rather than a derived pointer. This allows algorithms in the base class to be replaced in the derived class, even if users don't know about the derived class.
|
1,879,400 | 1,950,629 | How to prevent a globally overridden "new" operator from being linked in from external library | In our iPhone XCode 3.2.1 project, we're linking in 2 external static C++ libraries, libBlue.a and libGreen.a. libBlue.a globally overrides the "new" operator for it's own memory management. However, when we build our project, libGreen.a winds up using libBlue's new operator, which results in a crash (presumably because libBlue.a is making assumptions about the kinds of structures being allocated). Both libBlue.a and libGreen.a are provided by 3rd parties, so we can't change any of their source code or build options.
When we remove libBlue.a from the project, libGreen.a doesn't have any issues. However, no amount of shuffling the linking order of the libraries seems to fix the problem, nor does any experimentation with the various linking flags. Is there some way to tell XCode to tell the linker to "have libGreen's use of the new operator use the standard C++ new operator rather than the one redefined by libBlue"?
| Perhaps you could investigate using GNU objcopy, something along the lines of objcopy --redefine-sym oldNew=newNew libBlue.a. The biggest problem I see with this is that Apple's developer tool suite doesn't seem to include objcopy. You can install objcopy from MacPorts (sudo port install binutils), but that objcopy probably can't manipulate ARM object files. There are a couple of ARM binutils in MacPorts, and I'm guessing arm-elf-binutils is your best bet.
Barring that, you could possibly disassemble libBlue.a, rename its new operator with a sed script, then reassemble it. Perhaps you could even manipulate the libBlue.a symbol table directly.
|
1,879,421 | 1,879,753 | C++ text menu: writing, reading, and sorting data | So my assignment is to create multiple classes for a Person, Name, ID #, Address, and Phone #.
Name makes up: First, Middle, and Last name.
ID # makes up: 9 digits.
Address makes up: street, city, state, and 5 digit zip code.
Phone # makes up: 3 digit area code and 7 digit number.
Person makes up: a full Name (First, Middle, Last), an Address, a Phone # (area code, and number), and a ID # (9 digit number).
I have accomplished all of this. My problem is we are also supposed to make a menu, to specify how many people the user wishes to type in, where they want to save the file, if they want to read or write to a file specified by the user, and being able to sort the people by name (last, first, or middle) or by ID #, and save the sorted list to a user specified file.
I have all the code written, but my write function is not working for some reason. What happens is I run the program, the menu I created pops up. I select '1' enter the file, then the menu pops up again, and I select '2' to make sure it cant read since there is nothing in the specific file I am testing with. Next, I select '3' to write People to the user specified file. It prompts me for how many People I want to enter and I enter a number (2). Then the prompt for typing in the first name pops up and I get some error saying "an unhandled win32 exception occured" in my project .exe...
Here is my code:
//global variables
char filename[256];
fstream file2 (filename);
int r;
Person * stuArrPtr=new Person[r];
int w;
Person * stuArrPtr2=new Person[w];
//global functions
void WriteUserFile () {
//write as many ppl as specified to a file...
// int w;
cout << "How many students would you like to enter?: ";
cin >> w;
// Person * stuArrPtr2=new Person[w];
if (!file2.is_open ()) {
cout << "File did not open" << endl;
file2.clear ();
file2.open (filename, ios_base::out);
file2.close ();
file2.open (filename, ios_base::out | ios_base::in);
}
else {
for (int i = 0; i < w/*!file2.eof ()*/; i++) {
stuArrPtr2[i].InputPerson();
if (strcmp(stuArrPtr2[i].PersonNam.GetFirst(), "EOF") != 0)
stuArrPtr2[i].Display (file2);
}
}
cout << endl;
// delete [] stuArrPtr2;
}
void Menu () {
int option;
do {
//display menu
cout << " Type '1' - to open a file for reading or writing" << endl << endl;
cout << " Type '2' - to read from the file you specified in '1'" << endl << endl;
cout << " Type '3' - to write from the file you specified in '1'" << endl << endl;
cout << " Type '4' - sort students by last name" << endl << endl;
cout << " Type '5' - sort students by first name" << endl << endl;
cout << " Type '6' - sort students by middle name" << endl << endl;
cout << " Type '7' - sort students by ID number" << endl << endl;
cout << " Type '8' - exit" << endl << endl;
// cout << " Enter appropriate number here: [ ]\b\b";
cout << " Enter appropriate number here: ";
cin >> option;
switch(option) {
case 1:
cout << "you entered option 1" << endl;
OpenUserFile ();
break;
case 2:
cout << "you entered option 2" << endl;
ReadUserFile ();
break;
case 3:
cout << "you entered option 3" << endl;
WriteUserFile ();
break;
case 4:
cout << "you entered option 4" << endl;
SortLastName ();
break;
case 5:
cout << "you entered option 5" << endl;
SortFirstName ();
break;
case 6:
cout << "you entered option 6" << endl;
SortMiddleName ();
break;
case 7:
cout << "you entered option 7" << endl;
SortIDNumber ();
break;
case 8:
cout << "you entered option 8" << endl; //exit
delete [] stuArrPtr;
delete [] stuArrPtr2;
break;
default:
cout << "you screwed up, no big deal, just try again!" << endl;
} //end switch
//if (option == 6) {
// break;
//}
} while (option != 8);
// system("pause");
}
void main () {
Menu ();
}
/////////////////END OF CODE///////
Sorry the code is so long, and any help is very, very much appreciated!
| the problem with your code are the first few lines.
int w;
Person * stuArrPtr2=new Person[w];
At program startup w is most probably initialized with 0. So you create an array of zero Persons.
The moment you call stuArrPtr2[i].InputPerson() which should be stuArrPtr2[i]->InputPerson() by the way, you try to access a member function of an non existing object.
What you will have to do is create new Person objects depending on the number you just entered like stuArrPtr2 = new Person[w] within the function WriteUserFile().
Cheers
Holger
|
1,879,431 | 1,879,448 | how to destruct an array | #include <cstdlib>
#include <iostream>
using namespace std;
const unsigned long MAX_SIZE = 20;
typedef int ItemType;
class Heap {
private:
ItemType array[MAX_SIZE];
int elements; //how many elements are in the heap
public:
Heap( )
~Heap( )
bool IsEmpty( ) const
bool IsFull( ) const
Itemtype Retrieve( )
void Insert( const Itemtype& )
};
Let's say I have this as my header file. In my implementation for this, what is the best way to do Heap() constructor and ~Heap() destructor.
I have
Heap::Heap()
{
elements = 0;
}
Heap::~Heap()
{
array = NULL;
}
I am wondering if this is the proper way to destruct and construct an array in this case.
| array is not dynamically allocated, so the storage for it goes away when the object no longer exists in scope. In fact, you can't reassign to array; it's an error to do so.
|
1,879,527 | 1,879,557 | windows: is it possible to dump (direct) a text file into a named pipe | I have a setup where a program gets its input like so:
1) user enters a command in a command prompt
2) the text from the command prompt is written to a named pipe
3) a process on the other side of the pipe is reading the input parse and execute the command
I would like to have the ability to store a set of commands in a text file and then have the named pipe feed of the text file.
is there some way to chine the pipe and the file together? or do I need to read the text file and split it into lines which I will write to the pipe one by one
| If you use named pipe it might be possible,
if you take a look at this, you can see they use plain CreateFile to open the pipe, taking a look at that, it seems you cannot redirect but you have to read and write, at least with the API is the same ReadFile WriteFile.
void WriteToPipe(void)
// Read from a file and write its contents to the pipe for the child's STDIN.
// Stop when there is no more data.
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
BOOL bSuccess = FALSE;
for (;;)
{
bSuccess = ReadFile(g_hInputFile, chBuf, BUFSIZE, &dwRead, NULL);
if ( ! bSuccess || dwRead == 0 ) break;
bSuccess = WriteFile(g_hChildStd_IN_Wr, chBuf, dwRead, &dwWritten, NULL);
if ( ! bSuccess ) break;
}
// Close the pipe handle so the child process stops reading.
if ( ! CloseHandle(g_hChildStd_IN_Wr) )
ErrorExit(TEXT("StdInWr CloseHandle"));
}
|
1,879,768 | 1,880,000 | How do I replace __asm jno no_oflow with an intristic in a VS2008 64bit build? | I have this code:
__asm jno no_oflow
overflow = 1;
__asm no_oflow:
It produces this nice warning:
error C4235: nonstandard extension used : '__asm' keyword not supported on this architecture
What would be an equivalent/acceptable replacement for this code to check the overflow of a subtraction operation that happened before it?
| First define the following:
#ifdef _M_IX86
typedef unsigned int READETYPE;
#else
typedef unsigned __int64 READETYPE;
#endif
extern "C"
{
READETYPE __readeflags();
}
#pragma intrinsic(__readeflags)
You can then check the eflags register as follows:
if ( (__readeflags() & 0x800))
{
overflow = 1;
}
|
1,879,883 | 1,879,898 | Template class method collides with overloaded method | I have a template class in C++ (somewhat simplified):
template<typename T>
struct C
{
T member;
void set(const &T x) { member = x; }
void set(int x) { member = x; }
};
As you can see the set() function can be called either with the type T, or with an int. This works fine unless T is an int, in which case I get an ambiguous conversion error. I understand why this is happening, but is there any way to implement what I want?
| One way around this would be to provide a specialisation of the template for int that only has one set function. Otherwise you might want to have a look at the Boost libraries if something like enable_if in their template meta programming code would allow you to turn on the function set(int x)only when T is not of type int.
|
1,880,052 | 1,880,574 | C++: duplicated static member? | I have a class which needs to be a singleton. It implemented using a static member pointer:
class MySinglton
{
public:
static MySinglton& instance() { ... }
private:
static MySinglton* m_inst;
};
This class is compiled into a .lib which is used in multiple dlls in the same application. The problem is that each dll sees a different m_inst. since it is compiled and linked separatly.
What is simple way to solve this problem?
Separating the .lib to its own dll is not an option. it must be a .lib.
| A solution could be transferring the instantiation to the application, and the DLLs will get reference to it during initialization.
It may not be as elegant as you'd like, but it would do it.
Need to know what's the REAL problem behind your question.
The answer may not be in the form you expect it. ;)
|
1,880,275 | 1,880,339 | Good Windows Registry Wrapper for C++ | Does anyone know of any good free/open source Windows Registry wrappers for VC++ which do not require MFC (i.e. can be run in a console app)?
| ATL comes with a basic CRegKey wrapper that might suit your needs and is easy to use from a console application.
|
1,880,676 | 1,894,653 | Linker can not find static library in same directory | I'm porting some Visual Studio 2008/VC9 stuff to Code::Blocks/MinGW and for some reason the linker cannot find a static library from another project in the workspace.
In Visual Studio 2008 I could just set the static lib project as a dependency, and it would build in the right order (i.e. static lib needs to be built before linking the other project), and link the correct library for the configuration.
I couldn't find such an option in Code::Blocks, so I made sure to explicitly build the static lib first (libcommon.a) then under "build options" for the other project add "libcommon.a" in the "linker settings". The .a file is located in the same directory as the project files, however I still get an error from the linker of the other projects saying they cant find it...
ld.exe cannot find -lcommon
What am I doing so it cant find the library, even though its right next to the projects file?
Also is there a better way to simulate the Visual Studio dependencies within a single solution/workspace?
| Apparently the directory containing the project files is not included in the linker search path, and needed to be defined explicitly by adding ".\" to the list of directories containg library files for the projects.
|
1,880,738 | 1,880,813 | searching for winapi functions | I'm learning programing windows applications with C++. Now I'm reading about messages and I'm playing with the spy++.
What function spy++ use in order to mark/highlight the window under mouse cursor?
Also, can you give me some tips about using MSDN? I'm my opinion is not user friendly at all.
I'm learning programming by myself and i can't get some real life experience tips as those which are learning at college or in teams.
ty
| Writing a Windows application with just the windows API is possible, but you'll end up writing huge amounts of boilerplate code just to create simple things. This is why people normally use libraries built on top of it to make things easier - MFC for example.
The MSDN article Creating Win32 Applications provides a good explanation of the ins-and-outs of a Windows application using the Win32 API. Bare in mind though that you could build the same application in minutes using MFC.
I agree that MSDN is not the most user friendly source of information for a beginner. In my opinion it works much better as a reference.
My advice would be to focus on building some test applications using MFC (assuming you are tied to C++ as a language). Try looking at the codeproject MFC sections for example, and perhaps even buy a book to help get you started. This does of course require Visual Studio, but you can download the free express edition here
|
1,880,854 | 1,880,993 | CPP: avoiding macro expansion of a macro function parameter | what I'd like to do (for logging purposes) is something like this:
This code has been written to show my problem, actual code is complex and yes, I have good reasons to use macros even on C++ =)
# define LIB_SOME 1
# define LIB_OTHER 2
# define WHERE "at file #a, line #l, function #f: "
// (look for syntax hightlighting error at SO xd)
# define LOG_ERROR_SIMPLE(ptr, lib, str) ptr->log ("ERROR " str \
" at library " #lib);
# define LOG_ERROR(ptr, lib, str) LOG_ERROR_SIMPLE(ptr, lib, WHERE str)
LOG_ERROR_SIMPLE (this, LIB_SOME, "doing something")
LOG_ERROR (this, LIB_OTHER, "doing something else")
LOG_ERROR_SIMPLE() writes the stringification of the lib parameter (a macro name surrounded by " ")
but then LOG_ERROR writes the stringification of the macro already expanded ("2"). this is expected, since lib got its expansion before expanding and calling LOG_ERROR_SIMPLE. but this is not what I need.
Basically my question is this: how to avoid macro expansion of a macro function parameter when calling another macro function?
There is a trick I use that avoids macro expansion:
LOG_ERROR(ptr, lib, str, x) LOG_ERROR_SIMPLE(ptr, x##lib, WHERE str)
LOG_ERROR(this, LIB_OTHER, "some error",)
(pasting x and lib produces LIB_OTHER and this value is used to call LOG_ERROR_SIMPLE, its not macro expanded before that call)
There is some way to obtain this same behaviour without using a trick?
| I'm doing:
#include <cstdio>
#define FOO 1
#define BAR 2
#define LOG_SIMPLE(ptr, lib, str) printf("%s\n", #lib);
#define LOG(ptr, lib, str) LOG_SIMPLE(ptr, ##lib, str)
int main()
{
LOG_SIMPLE(0, FOO, "some error");
LOG(0, BAR, "some other error");
}
which prints out:
FOO
BAR
Works with MSVC2005 but not with gcc/g++.
EDIT: to make it work with gcc/g++ you can abuse variadic macros:
#include <stdio.h>
#define FOO 1
#define BAR 2
#define LOG_SIMPLE(ptr, str, lib) printf("%s\n", #lib);
#define LOG(ptr, str, lib, ...) LOG_SIMPLE(ptr, str, lib##__VA_ARGS__)
int main()
{
LOG_SIMPLE(0, "some error", FOO);
LOG(0, "some other error", BAR);
LOG(0, "some other error", FOO, BAR);
}
However, it's your discipline not to use the macro with too many parameters. MSVC2005 prints out
FOO
BAR
FOO2
while gcc prints out
FOO
BAR
FOOBAR
|
1,880,866 | 1,880,898 | Can I set a default argument from a previous argument? | Is it possible to use previous arguments in a functions parameter list as the default value for later arguments in the parameter list? For instance,
void f( int a, int b = a, int c = b );
If this is possible, are there any rules of use?
| The answer is no, you can't. You could get the behaviour you want using overloads:
void f(int a, int b, int c);
inline void f(int a, int b) { f(a,b,b); }
inline void f(int a) { f(a,a,a); }
As for the last question, C doesn't allow default parameters at all.
|
1,880,984 | 1,881,000 | When are variables removed from memory in C++? | I've been using C++ for a bit now. I'm just never sure how the memory management works, so here it goes:
I'm first of all unsure how memory is unallocated in a function, ex:
int addTwo(int num)
{
int temp = 2;
num += temp;
return num;
}
So in this example, would temp be removed from memory after the function ends? If not, how is this done. In C# a variable gets removed once its scope is used up. Are there also any other cases I should know about?
Thanks
| The local variable temp is "pushed" on a stack at the beginning of the function and "popped" of the stack when the function exits.
Here's a disassembly from a non optimized version:
int addTwo(int num)
{
00411380 push ebp
00411381 mov ebp,esp //Store current stack pointer
00411383 sub esp,0CCh //Reserve space on stack for locals etc
00411389 push ebx
0041138A push esi
0041138B push edi
0041138C lea edi,[ebp-0CCh]
00411392 mov ecx,33h
00411397 mov eax,0CCCCCCCCh
0041139C rep stos dword ptr es:[edi]
int temp = 2;
0041139E mov dword ptr [temp],2
num += temp;
004113A5 mov eax,dword ptr [num]
004113A8 add eax,dword ptr [temp]
004113AB mov dword ptr [num],eax
return num;
004113AE mov eax,dword ptr [num]
}
004113B1 pop edi
004113B2 pop esi
004113B3 pop ebx
004113B4 mov esp,ebp //Restore stack pointer
004113B6 pop ebp
004113B7 ret
The terms "pushed" and "popped" are merely meant as an analogy. As you can see from the assembly output the compiler reserves all memory for local variables etc in one go by subtracting a suitable value from the stack pointer.
|
1,881,200 | 1,907,233 | Implement Register/Unregister-Pattern in C++ | I often come accross the problem that I have a class that has a pair of Register/Unregister-kind-of-methods. e.g.:
class Log {
public:
void AddSink( ostream & Sink );
void RemoveSink( ostream & Sink );
};
This applies to several different cases, like the Observer pattern or related stuff. My concern is, how safe is that? From a previous question I know, that I cannot safely derive object identity from that reference. This approach returns an iterator to the caller, that they have to pass to the unregister method, but this exposes implementation details (the iterator type), so I don't like it. I could return an integer handle, but that would require a lot of extra internal managment (what is the smallest free handle?). How do you go about this?
| You are safe unless the client object has two derivations of ostream without using virtual inheritance.
In short, that is the fault of the user -- they should not be multiply inheriting an interface class twice in two different ways.
Use the address and be done with it. In these cases, I take a pointer argument rather than a reference to make it explicit that I will store the address. It also prevents implicit conversions that might kick in if you decided to take a const reference.
class Log {
public:
void AddSink( ostream* Sink );
void RemoveSink( ostream* Sink );
};
You can create an RAII object that calls AddSink in the constructor, and RemoveSink in the destructor to make this pattern exception-safe.
|
1,881,468 | 1,881,730 | What is compile-time polymorphism and why does it only apply to functions? | What is compile-time polymorphism and why does it only apply to functions?
| Way back when, "compile time polymorphism" meant function overloading. It applies only to functions because they're all you can overload.
In current C++, templates change that. Neil Butterworth has already given one example. Another uses template specialization. For example:
#include <iostream>
#include <string>
template <class T>
struct my_template {
T foo;
my_template() : foo(T()) {}
};
template <>
struct my_template<int> {
enum { foo = 42 };
};
int main() {
my_template<int> x;
my_template<long> y;
my_template<std::string> z;
std::cout << x.foo << "\n";
std::cout << y.foo << "\n";
std::cout << "\"" << z.foo << "\"";
return 0;
}
This should yield 42, 0, and "" (an empty string) -- we're getting a struct that acts differently for each type.
Here we have "compile time polymorphism" of classes instead of functions. I suppose if you wanted to argue the point, you could claim that this is at least partially the result of the constructor (a function) in at least one case, but the specialized version of my_template doesn't even have a constructor.
Edit: As to why this is polymorphism. I put "compile time polymorphism" in quotes for a reason -- it's somewhat different from normal polymorphism. Nonetheless, we're getting an effect similar to what we'd expect from overloading functions:
int value(int x) { return 0; }
long value(long x) { return 42; }
std::cout << value(1);
std::cout << value(1L);
Function overloading and specialization are giving similar effects. I agree that it's open to some question whether "polymorphism" applies to either, but I think it applies about equally well to one as the other.
|
1,881,494 | 1,881,711 | How to expose STL list over DLL boundary? | I have a DLL which needs to access data stored in STL containers in the host application. Because C++ has no standard ABI, and I want to support different compilers, the interface between the application and DLL basically has to remain plain-old-data.
For vectors this is relatively straightforward. You can simply return the memory block of the vector, because it is guaranteed to be contigious:
// To return vector<int> data
virtual void GetVectorData(const int*& ptr, size_t& count) const
{
if (!vec.empty())
ptr = &(vec.front());
count = vec.size();
}
Now the DLL can have safe read-only access to the vector's data via that interface. The DLL can also wrap this to copy the contents in to a vector for itself as well.
What about STL lists (and deques) though? Is there another straightforward way to allow access via a DLL boundary? Or will I have to resort to some kind of GetFirst()/GetNext() interface? I might need to do this for a lot of lists, so it'd be nice to have a solution as simple as vector's.
| Perhaps you can pass something like "handles" to list/deque iterators? These handle types would be opaque and declared in a header file you would ship to the users. Internally, you would need to map the handle values to list/deque iterators. Basically, the user would write code like:
ListHandle lhi = GetListDataBegin();
const ListHandle lhe = GetListDataEnd();
while (lhi != lhe)
{
int value = GetListItem(lhi);
...
lhi = GetNextListItem(lhi);
}
|
1,881,589 | 1,882,045 | redirected cout -> std::stringstream, not seeing EOL | I've read a bunch of posts regarding redirecting std::cout to stringstreams, but I'm having problem reading the redirected string.
std::stringstream redirectStream;
std::cout.rdbuf( redirectStream.rdbuf() );
std::cout << "Hello1\n";
std::cout << "Hello2\n";
while(std::getline(redirectStream, str))
{
// This does not work - as the contents of redirectStream
// do not include the '\n' - I only see "Hello1Hello2"
}
I need to pick out the new lines within the initial output - can anyone enlighten me as to how to do that?
Thanks.
| Works fine for me:
Note: the std::getline() reads the line (but not the '\n' character, the line terminator is thrown away after each line is read). But the loop will be entered once for each line.
#include <iostream>
#include <sstream>
int main()
{
std::stringstream redirectStream;
std::streambuf* oldbuf = std::cout.rdbuf( redirectStream.rdbuf() );
std::cout << "Hello1\n";
std::cout << "Hello2\n";
std::string str;
while(std::getline(redirectStream, str))
{
fprintf(stdout,"Line: %s\n",str.c_str());
// loop enter once for each line.
// Note: str does not include the '\n' character.
}
// In real life use RAII to do this. Simplified here for code clarity.
std::cout.rdbuf(oldbuf);
}
Note: you need to put the old stream-buffer back in std::cout. Once the stringstream 'redirectStream' goes out of scope its buffer will be destroyed leaving std::cout pointing at an invalid stream-buffer. Since std::cout lives longer than 'redirectStream' you need to make sure that std::cout does not access an invalid object. Thus the easiest solution is to put back the old buffer.
|
1,881,627 | 1,881,647 | Updating a QProgressDialog with a QFuture | What's the proper way for the main GUI thread to update a QProgressDialog while waiting for a QFuture. Specifically, what goes in this loop:
QProgressDialog pd(...);
QFuture f = ...;
while (!f.isFinished()) {
pd.setValue(f.progressValue());
// what goes here?
}
Right now I have a sleep() like call there, but that's not optimal (and ofcourse introduces some GUI latency).
If I put nothing, the main thread will loop-pole pd.setValue(), wasting CPU cycles.
I was hoping of putting something like QCoreApplication::processEvents(flags,maxtime), but that returns immediately if the event queue is empty. I'd like a version that waits until maxtime or whatever even if the queue is empty. That way, I get my delay and the main thread is always ready to respond to GUI events.
| Use a QFutureWatcher to monitor the QFuture object using signals and slots.
QFutureWatcher watcher;
QProgressDialog pd(...);
connect(&watcher, SIGNAL(progressValueChanged(int)), &pd, SLOT(setValue(int)));
QFuture f = ...
watcher.setFuture(f);
|
1,881,681 | 1,881,799 | Using delete on pointers passed as function arguments | Is it okay( and legal) to delete a pointer that has been passed as a function argument such as this:
#include<iostream>
class test_class{
public:
test_class():h(9){}
int h;
~test_class(){std::cout<<"deleted";}
};
void delete_test(test_class* pointer_2){
delete pointer_2;
}
int main(){
test_class* pointer_1;
while(true){
pointer_1 = new test_class;
//std::cout<<pointer_1->h;
delete_test(pointer_1);
}
}
This compiles fine now, but I just want to make sure it'll always be that way.
| It will always compile without error.
Whether it's a good thing to pass a pointer into a function and delete it in that function is potentially another story, depending on the specifics of your program.
The main idea you need to consider is that of "ownership" of the pointed-to data. When you pass that pointer, does the calling function have ownership of the data being passed in? i.e. is it in the only place that this data can be referenced from? Are you giving up ownership of the pointed-to-data, with no chance that the calling function is ever going to reference the data again? If so, then you must delete it.
If the calling function might reference the data again, then you must not delete it.
If there are other references to the data through various data structures, then it's not safe to delete this data unless you have some discipline in place in your code to ensure that you will never reference the data again from those places. This is hard to do, and is the source of many programming bugs.
C++ tr1's shared_ptr<> is a smart pointer that helps in these kinds of situations - it manages this ownership concept by keeping a reference count that tracks the number of references to the data. If the reference count is 1, then there is 1 clear owner. If the reference count is larger than 1, then ownership is shared. If the reference count is 0, then there are no more references to the data, and shared_ptr<> will delete it when the shared_ptr<> destructor is called.
|
1,881,891 | 1,887,749 | DCOM CoCreateInstanceEx E_ACCESSDENIED | I am working with 2 PCs, both running both running Windows XP. Both have the same application registered with its DCOM interface. Now i'm trying to start the program from one computer on the other.
First I called CoInitializeSecurity, after that CoCreateInstanceEx, but the result is a E_ACCESSDENIED.
I did also run dcomcnfg, to give anyone access, but it didn't help.
| You have to add the user explicitly and give him all permissions. After that it works.
|
1,882,070 | 1,884,830 | Find out if a function is called within a C++ project? | I'm trying to remove functions that are not used from a C++ project. Over time it's become bloated and I'm looking to remove functions that aren't used at all.
I have all the projects in a solution file in Visual Studio, but I use cmake so I can generate project files for another IDE if necessary (which is why this isn't tagged with visual-studio).
Does something like this exist? Where it'll analyze the source and tell me which functions are not called. I saw PC-Lint mentioned in a few questions here, but that doesn't seem to do this.
What I really want to do is call "Find all references" on each function and remove the functions not called, but doing this manually would take much too long.
| Use __declspec(deprecated) in front of the function declaration you want to get rid of. That will throw up compile warnings if that function is actually used at compile time.
|
1,882,161 | 1,882,540 | How can save Application Settings in the Registry via MFC? | I have a MFC application created by the MFC Project Wizard. I wanted to save/read application settings in the registry and so asked this question to find a C++ Registry wrapper as the Windows API is very messy. However, I have now heard that the MFC provides a way to do this. Is this true? If so, how can I read/write values, see whether a key exists and get a list of all the keys?
| MFC provides an easy way to read/write Windows registry.
In your project you'll have a global CMyProjectName theApp; object.
CMyProjectName inherits CWinApp class which provides the SetRegistryKey() method.
That method sets theApp to write in the registry instead of an "ini" file.
In the documentation check out
CWinApp::GetProfileInt
CWinApp::GetProfileString
CWinApp::WriteProfileInt
CWinApp::WriteProfileString
methods on how to read and write integers and strings in the registry.
|
1,882,195 | 1,882,232 | Getting the size in bytes or in chars of a member of a struct or union in C/C++? | Let's say that I want to get the size in bytes or in chars for the name field from:
struct record
{
int id;
TCHAR name [50];
};
sizeof(record.name) does not work.
| The solution for this is not so pretty as you may think:
size_in_byte = sizeof(((struct record *) 0)->name)
size_in_chars = _countof(((struct record *) 0)->name)
If you want to use the second one on other platforms than Windows try:
#define _countof(array) (sizeof(array)/sizeof(array[0]))
|
1,882,399 | 1,884,922 | Issues with C++ template arguments for inheritance | I have a questions about C++ templates. More specifally, by using template arguments for inheritance.
I am facing strange behaviour in a closed-source 3rd party library. There is a C method
factoryReg(const char*, ICallback*)
which allows to register a subclass of ICallback and overwrite the (simplified) methods:
class ICallback
{
public:
virtual void ENTRY(void* data) = 0;
virtual void EXIT(void* data) = 0;
const char* getName() { return _name; } const
ICallback(const char* name) : _name(name) {}
virtual ~ICallback() {}
private:
const char* _name;
};
I have
class BaseCallback : public ICallback
{
public:
BaseCallback(const char* name) : ICallback(name) {}
virtual void ENTRY(void* data) {
std::cout << "in ENTRY base" << std::endl;
}
virtual void EXIT(void* data) {
std::cout << "in EXIT base" << std::endl;
};
class SpecialCallback : public BaseCallback
{
public:
SpecialCallback(const char* name) : BaseCallback(name) {}
virtual void ENTRY(void* data) {
// actually, it's 3rd party code too - assumed to do something like
...
BaseCallback::ENTRY();
}
// no redecl. of EXIT(void* data)
};
template <typename Base>
TemplCallback : public Base
{
public:
TemplCallback(Base& myT) : Base(myT.getName()), _myT(myT)
virtual void ENTRY(void* data) {
std::cout << "in ENTRY templ." << std::endl;
_myT.ENTRY();
}
virtual void EXIT(void* data) {
std::cout << "in EXIT templ." << std::endl;
_myT.EXIT();
}
private:
Base& _myT;
}
Upon registering
SpecialCallback spc("validName");
TemplCallback<SpecialCallback> myCallback(spc);
factoryReg(spc.getName(), &myCallback);
...
// output: "in ENTRY base"
// "in EXIT base"
the callback somehow does not work (debug output not being put out // breakpoints do not apply).
If I omit implementation of the EXIT(void* data) method in my template class TemplCallback - everything works fine!
// output: "in ENTRY templ."
// "in EXIT base"
Is this expected behaviour? I have been told it might be an issue of the MSVC compiler 13.10.6030 I use. Not sure about that.
BTW: The template idea presented here might not be the best choice for whatever I am trying to do ;)
But I am still interested in the matter itself, regardless about design questions.
| OK, it seems that it is safe to assume that SpecialCallback::ENTRY() calls BaseCallback::EXIT() somehow.
Can't be 100% sure, because it's closed source - but it's quite likely.
So much for "callback" functions...
|
1,882,689 | 1,892,073 | Why does GCC allow use of round() in C++ even with the ansi and pedantic flags? | Is there a good reason why this program compiles under GCC even with the -ansi and -pedantic flags?
#include <cmath>
int main (int argc, char *argv [])
{
double x = 0.5;
return static_cast<int>(round(x));
}
This compiles clean (no warnings, even) with g++ -ansi -pedantic -Wall test.cpp -o test.
I see two problems:
round() shouldn't be available to C++ in ISO-conformant mode (since it comes from C99)
Even if round() were available in this case, it should only be so from the std namespace
Am I wrong?
| This is a bug. It's been around for a surprisingly long while. Apparently, there has not been enough of a collective desire to fix it. With a new version of C++ just around the corner which will adopt the C99 functions from math.h, it seems unlikely it will ever be fixed.
|
1,882,740 | 6,745,828 | Passing a pointer to a member function as a template argument. Why does this work? | I have some code that 100% works for the use case I have. I'm just wondering if anyone can explain how and why it works.
I have a template class that sits between some code that handles threading and network communication and the library user to pass data received from the server to the user.
template <class Bar,
class Baz,
class BazReturnType,
void (Bar::*BarSetterFunction)(const BazReturnType &),
BazReturnType (Baz::*BazGetterFunction)(void) const>
class Foo
{
Foo( Bar *bar )
: m_bar(bar)
{
}
void FooMemberFunction( const Baz *baz )
{
boost::bind( BarSetterFunction, m_bar,
boost::bind( BazGetterFunction, baz )() ) ();
}
Bar *m_bar;
};
This template is instantiated and used in the library depending on the types of Bar and Baz like so:
typedef Foo<MyBar,
MyBaz,
ReturnTypeFromBazGetterFunction,
&MyBar::ActualSetterFunction,
&MyBaz::ActualGetterFunction >
MyFoo;
MyBar *bar = new MyBar;
MyBaz *baz = new MyBaz;
MyFoo *f = new MyFoo( bar );
f->FooMemberFunction( baz );
This all works and boost::bind calls the getter/setter functions to pass the data around where it needs to go. How and why does passing pointers to member functions as a template argument like in this case work?
In response to comments, I hadn't realized that pointers to member functions were valid template arguments. It's not something I had seen "in the wild" before. I tried it and it worked, but I wasn't expecting it to.
| I think there is a better explanation why it is possible to do so than "because the standard says so":
The reason it works is because pointers-to-members are constant values known at compile time (pointer-to-member is effectively an offset of a member from the start of a class). Thus they can be used as parameters of templates, just as any other integer constant can be.
On the other hand, normal pointers are not compile time constants, because they depend on memory layout which only exists at runtime. They cannot be template arguments.
|
1,882,846 | 1,882,889 | Find vector element in second vector | Given two vectors of integers, how to determinate if there's some element from 1st vector is present in 2nd one?
| I guess something like this should work:
std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
std::cout << "found!\n";
|
1,882,965 | 1,882,988 | include boost header file using "" or <> | Why does tuple documentation say to use, for example:
#include "boost/tuple/tuple.hpp"
and not
#include <boost/tuple/tuple.hpp>
I know that it's not probable my code will have a file called "boost/tuple/tuple.hpp",
but using include <> states explicitly not to look in the curent directory.
So what is the reason?
| Afaik the reason is to differentiate between headers that belong to an application and those which are from external libraries. I can't say why they have not used this convention. It is a only a convention and not a rule.
Perhaps someone should raise this issue with the Boost maintainers?
|
1,883,056 | 1,883,161 | std::stringstream to read int and strings, from a string | I am programming in C++ and I'm not sure how to achieve the following:
I am copying a file stream to memory (because I was asked to, I'd prefer reading from stream), and and then trying to access its values to store them into strings and int variables.
This is to create an interpreter. The code I will try to interpret is (ie):
10 PRINT A
20 GOTO 10
This is just a quick example code. Now the values will be stored in a "map" structure at first and accessed later when everything will be "interpreted".
The values to be stored are:
int lnum // line number
string cmd // command (PRINT and GOTO)
string exp // expression (A and 10 in this case but could hold expressions like (a*b)-c )
question is given the following code, how do I access those values and store them in memory?
Also the exp string is of variable size (can be just a variable or an expression) so I am not sure how to read that and store it in the string.
code:
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <map>
#include <sstream>
using namespace std;
#include "main.hh"
int main ()
{
int lenght;
char *buffer;
// get file directory
string dir;
cout << "Please drag and drop here the file to interpret: ";
getline (cin,dir);
cout << "Thank you.\n";
cout << "Please wait while your file is being interpreted.\n \n";
// Open File
ifstream p_prog;
p_prog.open (dir.c_str());
// Get file size
p_prog.seekg (0, ios::end);
lenght = p_prog.tellg();
p_prog.seekg(0, ios::beg);
// Create buffer and copy stream to it
buffer = new char[lenght];
p_prog.read (buffer,lenght);
p_prog.close();
// Define map<int, char>
map<int, string> program;
map<int, string>::iterator iter;
/***** Read File *****/
int lnum; // line number
string cmd; // store command (goto, let, etc...)
string exp; // to be subst with expr. type inst.
// this is what I had in mind but not sure how to use it properly
// std::stringstream buffer;
// buffer >> lnum >> cmd >> exp;
program [lnum] = cmd; // store values in map
// free memory from buffer, out of scope
delete[] buffer;
return 0;
}
I hope this is clear.
Thank you for your help.
Valerio
| You can use a std::stringstream to pull tokens, assuming that you already know the type.
For an interpreter, I'd highly recommend using an actual parser rather than writing your own. Boost's XPressive library or ANTLR work quite well. You can build your interpreter primitives using semantic actions as you parse the grammar or simply build an AST.
Another option would be Flex & Bison. Basically, these are all tools for parsing pre-defined grammars. You can build your own, but prepare for frustration. Recursively balancing parentheses or enforcing order of operations (divide before multiply, for example) isn't trivial.
The raw C++ parsing method follows:
#include <sstream>
#include <string>
// ... //
istringstream iss(buffer);
int a, b;
string c, d;
iss >> a;
iss >> b;
iss >> c;
iss >> d;
|
1,883,160 | 1,887,025 | QSignalMapper and original Sender() | I have a bunch of QComboBoxes in a table. So that I know which one was triggered I remap the signal to encode the table cell location (as described in Selecting QComboBox in QTableWidget)
(Why Qt doesn't just send the cell activated signal first so you can use the same current row/column mechanism as any other cell edit I don't know.)
But this removes all knowledge of the original sender widget. Calling QComboBox* combo = (QComboBox* )sender() in the slot fails, presumably because sender() is now the QSignalMapper.
I can use the encoded row/column to lookup the QComboBox in the table widget but that seems wrong. Is there a more correct way to do it?
e.g.:
// in table creator
_signalMapper = new QSignalMapper(this);
// for each cell
QComboBox* combo = new QComboBox();
connect(combo, SIGNAL(currentIndexChanged(int)), _signalMapper, SLOT(map()));
_signalMapper->setMapping(combo, row);
// and finally
connect(_signalMapper, SIGNAL(mapped(int)),this, SLOT(changedType(int)));
// slot
void myDlg::changedType(int row)
{
QComboBox* combo = (QComboBox* )sender(); // this doesn't work !!
}
EDIT: Added for future search: there is a new book "Advanced Qt Programming" by Mark Summerfield that explains how to do this sort of thing.
| Why not connect the QComboBox's signal straight to your slot?
QComboBox *combo = ...
connect(combo, SIGNAL(currentIndexChanged(int)), this, SLOT(changedType(int)));
And then in your slot you can use the sender() method to retrieve the QComboBox that was changed.
void myDlg::changedType(int row)
{
QComboBox *combo = qobject_cast<QComboBox *> sender();
if(combo != 0){
// rest of code
}
}
Alternatively, to use the QSignalMapper method you would just need to change your slot to use the mapping you set up:
void myDlg::changedType(int row)
{
QComboBox *combo = qobject_cast<QComboBox *>(_signalMapper->mapping(row));
if(combo != 0){
// rest of code
}
}
|
1,883,202 | 1,883,247 | Auto linking dependencies of a static lib | I have a static lib A, which also uses static libs B, C and D.
I then have applications X and Y which both use A, but not B, C or D.
Is there some way to make it so X and Y will automatically see that A used B, C and D and link them, so that I don't need to keep track for the entire dependency tree so I can explicitly pass every static lib (quite a lot with things like Windows, Boost, etc)?
| Static libraries do not link with other static libraries. Only when building the executable (or shared library/DLL) is linkage performed, and the way to keep track of this is (of course) to use make.
|
1,883,380 | 1,884,653 | Openfeint caused this: ISO C++ forbids of declaration 'myClass' with no type | To cut a long story short, my project (an iPhone app) was all working fine until I started using a C++ sdk (openfeint). Everything was working fine, including the C+++ Openfeint stuff, until I switched from tesitng on the device to testing in the simulator.
Now it won't compile for anything and I'm getting just under 200 errors. It's all just spiralled out of control and wont compile on any device. As I said, everything was working perfectly, I didn't change a single line of code, I simply switched Active SDK's.
So I'll start at the beginning. The first error is...
Error 1: ISO C++ forbids of declaration 'BrickControlLayer' with no type
Clicking on this error takes me to the header file for another class...
// GameScene.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "brickSprite.h"
#import "BrickControlLayer.h"
#import "GameState.h"
#import "ScoreController.h"
#import "FeedbackLayer.h"
#import "TimeBar.h"
@interface GameScene : Layer {
GameState *gameState;
ScoreController *scoreController;
CocosNode *spriteHolder;
brickSprite *targetBrick;
// Heres the line it takes me too <<<<<<<<<<<<<<<<<
BrickControlLayer *controls;
NSInteger difficulty;
NSMutableArray *pointsLookupArray;
BitmapFontAtlas *scoreLabel;
FeedbackLayer *feedback;
NSDate *startTime;
TimeBar *timeProgress;
int rowScanCount, foundRows;
}
// methods here....
@end
I'm new to this, so bear with me. I was confused as I'm clearly stating that *controls is of the type 'BrickControlLayer'. So I'm thinking there's something wrong inside 'BrickControlLayer' itself.
Here's the header...
// BrickControlLayer.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "brickSprite.h"
#import "HighScores.h"
@interface BrickControlLayer : Layer{
CocosNode *spriteHolder;
CGPoint touchedStartPoint, moveFromPoint;
brickSprite *touchedBrick;
BOOL editorMode;
int movecount;
// Control buttons
AtlasSpriteManager *buttonManager;
AtlasSprite *rotLeft, *rotRight, *newBrick, *deleteBrick, *makeTarget, *save, *run;
BOOL tapToContinue;
}
@property (retain, readwrite) CocosNode *spriteHolder;
@property (retain, readwrite) brickSprite *touchedBrick;
-(void)showEditorControls;
-(void)selectBrickAtLocation:(CGPoint)location;
-(void)hideEditorControls;
-(void)deactivate;
@end
I've been over it and over it. It was all working fine before and I simply can't figure it out. I've been googling it and the only thing that crops up is the term "Forward Declaration", but that doesn't mean anything to me and all the info I've found talks about structs.
I suspect the errors are more of an indication that I'm doing lot's of other things wrong, rather than committing a simple one line typo or something. Can anyone explain in laymans terms what's going on here?
| Jason here from OpenFeint. If you'd like to send over a code sample to devsupport at openfeint dot com that demonstrates the problem we'll take a look at it for you. It sounds like you may be including the header file from a .CPP instead of a .MM file.
If all you did was change the iPhone Target SDK, double check that when you setup compiler options you did it for all SDKs and build configurations (release, debug).
The error you're getting sounds like the compiler doesn't recognize that you're in an Objective-C declaration OR it can't find the header declaration for BrickControlLayer. Could be a circular include? (do you use include guards or #pragma once?)
Hope that helps,
- Jason Citron
- Founder & CEO, Aurora Feint
|
1,883,385 | 1,886,911 | Rounding to use for int -> float -> int round trip conversion | I'm writing a set of numeric type conversion functions for a database engine, and I'm concerned about the behavior of converting large integral floating-point values to integer types with greater precision.
Take for example converting a 32-bit int to a 32-bit single-precision float. The 23-bit significand of the float yields about 7 decimal digits of precision, so converting any int with more than about 7 digits will result in a loss of precision (which is fine and expected). However, when you convert such a float back to an int, you end up with artifacts of its binary representation in the low-order digits:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int a = 2147483000;
cout << a << endl;
float f = (float)a;
cout << setprecision(10) << f << endl;
int b = (int)f;
cout << b << endl;
return 0;
}
This prints:
2147483000
2147483008
2147483008
The trailing 008 is beyond the precision of the float, and therefore seems undesirable to retain in the int, since in a database application, users are primarily concerned with decimal representation, and trailing 0's are used to indicate insignificant digits.
So my questions are: Are there any well-known existing systems that perform decimal significant digit rounding in float -> int (or double -> long long) conversions, and are there any well-known, efficient algorithms for doing so?
(Note: I'm aware that some systems have decimal floating-point types, such as those defined by IEEE 754-2008. However, they don't have mainstream hardware support and aren't built into C/C++. I might want to support them down the road, but I still need to handle binary floats intuitively.)
| std::numeric_limits<float>::digits10 says you only get 6 precise digits for float.
Pick an efficient algorithm for your language, processor, and data distribution to calculate-the-decimal-length-of-an-integer (or here). Then subtract the number of digits that digits10 says are precise to get the number of digits to cull. Use that as an index to lookup a power of 10 to use as a modulus. Etc.
One concern: Let's say you convert a float to a decimal and perform this sort of rounding or truncation. Then convert that "adjusted" decimal to a float and back to a decimal with the same rounding/truncation scheme. Do you get the same decimal value? Hopefully yes.
This isn't really what you're looking for but may be interesting reading: A Proposal to add a max significant decimal digits value to the C++ Standard Library Numeric limits
|
1,883,518 | 1,890,725 | How to relate WAVE_MAPPER audio line with its audio device | I'm developing an application that among other things, enumerates all input audio devices (using SetupAPI) and then for each audio device, it lists all input audio lines (using winmm.dll).
Basically, the way I'm relating the two is getting the device path from the audio device and then using waveInMessage to compare the audio line's device path.
Now, I want to be able to do the same with the windows default [input] audio line (WAVE_MAPPER).
The problem is that using waveInGetDevCaps for WAVE_MAPPER returns "Microsoft Sound Mapper", and using waveInMessage with DRV_QUERYDEVICEINTERFACE returns an empty string.
Any suggestions on how to find out which device the Microsoft Mapper is mapping to?
| Please correct me if I'm wrong, but I've been watching some videos from past Microsoft conferences on sound development. On the latest one from Larry Osterman, he mentions new sound features in [I believe] Windows 7 that his team worked on.
One of the features was [the name is my interpretation] "device hot swap". Let's say your application is playing back using the "windows default sound playback" endpoint, and that at this moment is a set of USB Headphones. Suddenly you disconnect the headphones. Up to Windows 7, your application would crash [if you didn't foresee that test scenario]. In Windows 7 [and here's the hook to the original subject], IF you're using the Windows default playback device, Windows will gracefully and automatically swap the output stream to the new default, which could be the speakers.
What I'm trying to get to, is that I'm trying to fit the WAVE_MAPPER device into a class where it is not supposed to be. Maybe, conceptually speaking, the WAVE_MAPPER despite having the same capability of audio stream input and output, should be treated as an exception.
I'll try to be more concrete. In my application, I have a list of audio devices, and each audio device has a list of audio lines. Audio devices have properties such as VID and PID that are easily discoverable through the SetupAPI and can be related to audio lines via winmm's waveInMessage. WAVE_MAPPER doesn't follow that logic and I was trying to make it do.
So instead of trying to relate the WAVE_MAPPER with its underlying audio device, I will just treat it as what it is: the default audio device.
|
1,883,674 | 1,883,713 | Checking Mutex release | I have a multithreaded application written in C++. And I'm using mutex for file writes. I have a suspicion that somewhere during the execution of the program, the mutex isn't being released.
So I was wondering if there was a way to check for mutex locks and releases on a file, programmatically or otherwise.
I'm running the code on SuseLinux, btw.
Thanks,
| Welcome to the wonderful world of debugging multi-threaded code. There is no magic bullet to solve your problems, but at the very least you should be using RAII idioms to manage your mutex. This means wrapping the mutex in a C++ class that claims the mutex when instances of the class are created and releases it when it (the class instance) is destroyed. You can also profitably log the claim/releases, but be aware that this may introduce timing bugs and artefacts.
|
1,883,740 | 1,884,265 | C++ Declarative Parsing Serialization | Looking at Java and C# they manage to do some wicked processing based on special languaged based anotation (forgive me if that is the incorrect name).
In C++ we have two problems with this:
1) There is no way to annotate a class with type information that is accessable at runtime.
2) Parsing the source to generate stuff is way to complex.
But I was thinking that this could be done with some template meta-programming to achieve the same basic affect as anotations (still just thinking about it). Like char_traits that are specialised for the different types an xml_traits template could be used in a declaritive way. This traits class could be used to define how a class is serialised/deserialized by specializing the traits for the class you are trying to serialize.
Example Thoughs:
template<typename T>
struct XML_traits
{
typedef XML_Empty Children;
};
template<>
struct XML_traits<Car>
{
typedef boost::mpl::vector<Body,Wheels,Engine> Children;
};
template<typename T>
std::ostream& Serialize(T const&)
{
// my template foo is not that strong.
// but somthing like this.
boost::mpl::for_each<typename XML_Traits<T>::Children,Serialize>(data);
}
template<>
std::ostream& Serialize<XML_Empty>(T const&)
{ /* Do Nothing */ }
My question is:
Has anybody seen any projects/decumentation (not just XML) out there that uses techniques like this (template meta-programming) to emulate the concept of annotation used in languges like Java and C# that can then be used in code generation (to effectively automate the task by using a declaritive style).
At this point in my research I am looking for more reading material and examples.
| Lately, I had a look at the following:
The Nocturnal Initiative which made available a C++ Reflection system
C++ Runtime Type System by Avi Bar-Zeev
The blog posts on Reflection in C++(1, 2, 3) by Maciej Sinilo
Have a good read :)
|
1,883,862 | 1,883,914 | C++, oop, list of classes (class types) and creating instances of them | I have quite a lot of classes declared, all of them are inheriting from a base (kind of abstract) class ... so all of them have common methods I'd like to use ...
now, I need to have a list of classes (not objects), later make instance of them in a loop and use the instances for calling mentioned common methods ...
the pseudo-code
class Abstract {
void Something();
}
class TaskOne : public Abstract {
void Something(); // method implemented somewhere below
}
class TaskTwo : public Abstract {
void Something(); // method implemented somewhere below
}
...
list<Abstract> lst;
lst.push_back(TaskOne); // passing class type, not instance!
lst.push_back(TaskTwo);
Abstract tmpObject = new lst[0]; //I know its wrong, just a way of expressing what I'd like to do to have instance of TaskOne!
please give any tips ...
| You could create a templated factory object:
struct IFactory { virtual IBaseType* create() = 0; };
template< typename Type > struct Factory : public IFactory {
virtual Type* create( ) {
return new Type( );
}
};
struct IBaseType { /* common methods */ virtual ~IBaseType(){} };
IFactory* factories[] = {
new Factory<SubType1>
, new Factory<SubType2>
// ...
};
std::vector<IBaseType*> objects;
objects.push_back( factories[1]->create() ); // and another object!
// don't forget to delete the entries in the
// vector before clearing it (leak leak)
|
1,883,885 | 1,884,308 | Standalone, OS-independent, Architecture-neutral, Multi-threaded Library | What multi-threaded C++ library can be used for writing Linux, Windows, Solaris, and iPhone applications? Such as:
TBB
Boost
OpenMP
ACE
POCO
Any others?
| Boost threads is really the de facto C++ threading standard. I'd recommend at least familiarizing yourself with the Boost threading API, as it is more or less identical to the upcoming standardized C++0x std::thread.
|
1,884,229 | 1,885,891 | Mapping enum values to strings in C++ | Is there a way to, at runtime, map the value of an enum to the name? (I'm building with GCC.)
I know GDB can do it and I'm willing to use something that's unportable and mucks with debug data.
Edit: I'm looking for a solution that doesn't require modifying the original enum declaration nor hand copying all the values out in a mapping function. I already know how to do both of those.
Effectively; I want a function that does whatever GDB does when it formats runtime enum values.
| If you don't want to invest the time to utilize GCCs symbol information, gcc-xml provides you information about C++ sources in a reusable XML format, including enumeration names.
Simplified example... this source:
enum E {
e1 = 1,
e2 = 42
};
becomes:
<GCC_XML>
<!-- ... -->
<Enumeration name="E">
<EnumValue name="e1" init="1"/>
<EnumValue name="e2" init="42"/>
</Enumeration>
<!-- ... -->
</GCC_XML>
|
1,884,316 | 1,884,397 | Cross-platform OOP in C++ | Of course, I know the best answer is "don't write your own cross-platform code, someone has already done what you need," but I'm doing this as a hobby/learning exercise and not in any paid capacity. Basically, I'm writing a smallish console application in C++, and I'd like to make it cross platform, dealing with things like files, sockets, and threads. OOP seems like a great way to handle this, but I haven't really found a good pattern for writing classes that share the same interface cross platform.
The easy approach is to just plan out some meta-interface, use that throughout the rest of the program, and just compile the same class with different files depending on the platform, but I feel like there's got to be a better way that's more elegant; at the very least, something that doesn't confuse IntelliSense and its ilk would be nice.
I've taken a look at some of the smaller classes in the wxWidgets source, and they use an approach that uses a private member holding data for the class, e.g
class Foo
{
public:
Foo();
void Bar();
private:
FooData data;
};
You can then compile this by simply choosing different implementation files depending on the platform. This approach seems pretty clunky to me.
Another approach I've considered is writing an interface, and swapping out classes that inherit from that interface depending on the platform. Something like this:
class Foo
{
public:
virtual ~Foo() {};
virtual void Bar() = 0;
};
class Win32Foo
{
public:
Win32Foo();
~Win32Foo();
void Bar();
};
Of course this kind of screws up the actual instantiation since you don't know which implementation to create an object of, but that can be worked around by using a function
Foo* CreateFoo();
and varying the implementation of the function based on which platform you're running on. I'm not a huge fan of this either, because it still seems clunky littering the code with a bunch of instantiation method (and this would also be inconsistent with the method of creating non-cross-platform objects).
Which of these two approaches is better? Is there a better way?
Edit: To clarify, my question is not "How do you write cross-platform C++?" Rather, it's "What is the best method to abstract away cross-platform code using classes in C++, while retaining as much benefit from the type system as possible?"
| Define your interface, which forwards to detail calls:
#include "detail/foo.hpp"
struct foo
{
void some_thing(void)
{
detail::some_thing();
}
}
Where "detail/foo.hpp" is something like:
namespace detail
{
void some_thing(void);
}
You'd then implement this in detail/win32/foo.cpp or detail/posix/foo.cpp, and depending on which platform your compiling for, compile one or the other.
Common interface just forwards calls to implementation-specific implementations. This is similar to how boost does it. You'll want to look at boost to get the full details.
|
1,884,339 | 1,884,492 | How is C# inspired by C++ more than by Java? | When looking at the history of C#, I found out that C# was seen as an update to C and/or C++. This came a bit as a surprise to me, as on the surface, I see much more common ideas between C# and Java (Garbage collection comes to mind). I don't write code in Java, but I have usually no problem following Java code, and routinely read books about patterns in Java that I can readily transpose in C#, and can honestly not say the same about C++.
So my question is, how is C# closer to C++ than to Java? Is this simply a refusal to acknowledge Java, or am I missing or misunderstanding something?
| IMO, the idea that C# is inspired more from C++ than Java is marketing only; an attempt to bring die-hard C++ programmers into the managed world in a way that Java was never able to do. C# is derived from Java primarily; anyone who looks at the history, particularly the Java VM wars of the mid 90s between Sun and Microsoft, can see that Java is the primary parent.
The syntax of C# is closer to C++ in only certain areas: pointer manipulation (which Java doesn't have), derivation declaration (i.e. public class Foo : Bar, IBaz rather than public class Foo extends Bar implements IBaz), and operator overloading.
Everything else is either just like Java (static main declared in a class declaration, no header files, single inheritance, many others), just like both Java and C++ (basic syntax), or uniquely C# (properties, delegates, many many others).
|
1,885,021 | 1,885,428 | Problem with storing COM pointers in global singleton object | Background
The application I am working with has several COM DLLs.
One of the COM DLLs has a global singleton object, which stores pointers to COM interfaces in other DLLs. Because it is a global singleton object, I have employed the lazy initialization idiom because it is possible that the interface I am trying to get a pointer to exists in a DLL which hasn't yet been loaded.
(Side-note: This is especially important when registering a single DLL, as the global objects will be constructed within the regsvr32 process, and I don't want the DLL to attempt to acquire an interface to another DLL during this process.)
For example, my lazy initialization method would do something like this:
CComPtr<IMyOtherObject>&
CGlobalSingleton::
GetMyOtherObject()
{
// SNIP: Other code removed for clarity...
if (! m_pMyOtherObject)
{
hr = pUnknown->QueryInterface(IID_IMyOtherObject,
(void**) &m_pMyOtherObject);
}
return m_pMyOtherObject;
}
NOTE: m_pMyOtherObject is a member variable of the CComPtr type.
The lazy initialization may not be relevant to my problem here, but I'm including it for completeness.
Problem
What I have noticed is that in some circumstances, I get failed assertions when my application shuts down. However, if I change my code to call QueryInterface() every time I need to access IID_IMyOtherOBject (rather than storing it as a member variable) this prevents the assertions.
This appears to me to be a COM object lifetime issue. My hypothesis is that because I am storing a COM pointer, there needs to be some sort of synchronisation between the destruction of the COM interface that I'm pointing to, and my own pointer to it.
My understanding of the CComPtr class (which I am using) is that it takes away a lot of the headaches of dealing with lifetime issues (i.e. calling AddRef() and Release()). But it doesn't appear to be working in my case.
Can anyone pick what I may be doing wrong?
| Rather than implementing your own global singleton, look at using the IGlobalInterfaceTable interface instead. It is a singleton that is provided by the OS at the process level. Any of your DLLs can put their COM objects into the table, and the other DLLs can retreive them when needed. All you would need to implement on your part is a way for the DLLs to exchange the table's DWORD cookies with each other.
|
1,885,450 | 1,885,468 | What is a good way to test whether a file has required permissions? | I see that ifstream::open() returns void and does not offer any way to see if the file did not open due to permissions. What is a good api to test whether read permission or alternatively write permissions are available on a file for the current process in C++?
| Try the POSIX access() function, in unistd.h
|
1,885,471 | 1,885,500 | Forward declaration of class doesn't seem to work in C++ | The follwing code is compiled in VC++6. I don't understand why I am getting the compilation error C2079: 'b' uses undefined class 'B' for the following code.
Class B Source
#include "B.h"
void B::SomeFunction()
{
}
Class B Header
#include "A.h"
struct A;
class B
{
public:
A a;
void SomeFunction();
};
struct A Header
#include "B.h"
class B;
struct A
{
B b;
};
If I changed class B header to the following, then there will be no error. But the header declaration won't be at the top!
Class B Header with weird header declaration
struct A;
class B
{
public:
A a;
void SomeFunction();
};
#include "A.h"
| In order to define a class or struct, the compiler has to know how big each member variable of the class is. A forward declaration does not do this. I've only ever seen it used for pointers and (less often) references.
Beyond that, what you're trying to do here cannot be done. You cannot have a class A that contains an object of another class B that contains an object of class A. You can, however, have class A contain a pointer to class B that contains an object of class A.
B.cpp
#include "B.h"
void B::SomeFunction()
{
}
B.h
#ifndef __B_h__ // idempotence - keep header from being included multiple times
#define __B_h__
#include "A.h"
class B
{
public:
A a;
void SomeFunction();
};
#endif // __B_h__
A.h
#ifndef __A_h__ // idempotence - keep header from being included multiple times
#define __A_h__
#include "B.h"
class B; // forward declaration
struct A
{
B *b; // use a pointer here, not an object
};
#endif // __A_h__
Two points. First, be sure to use some form of idempotence to keep the headers from being included multiple times per compilation unit. Second, understand that in C++, the only difference between classes and structs is the default visibility level - classes use private visibility by default while structs use public visibility by default. The following definitions are functionally equivalent in C++.
class MyClass
{
public: // classes use private visibility by default
int i;
MyClass() : i(13) { }
};
struct MyStruct
{
int i;
MyStruct() : i(13) { }
};
|
1,885,494 | 1,885,509 | CRecordset.Open only retrevies one record! | Here is the code:
CDatabase m_db;
m_db.OpenEx(_T( "DRIVER={MySQL ODBC 3.51 Driver};SERVER=localhost;DATABASE=mydb;UID=root;PASSWORD=123123;OPTION=3;"), FALSE );
CRecordset recSet(&m_db);
recSet.Open(AFX_DB_USE_DEFAULT_TYPE, _T("SELECT * From articles"), CRecordset::executeDirect);
int nRecords = recSet.GetRecordCount(); // Equals to 1!
the article table has more than 1000 records. I tried with different database/tables but problem not fixed!
| That's a limitation of the way CRecordset works. You'll need to call MoveNext until IsEOF returns TRUE, then the record count will be accurate.
|
1,885,586 | 1,885,649 | Language Mixing: Model and View | Consider developing an application where the model will be written in C++ (with Boost), and the view will be written in Objective-C++ (with Cocoa Touch).
Where are some examples showing how to integrate C++ and Objective-C++ for developing iPhone applications?
| Take it straight from the source: Apple has documentation on using C++ With Objective-C.
There really isn't much more to it besides, in my opinion, trying to keep the C++ and Objective-C parts as cleanly seperated as possible.
In your case it comes natural:
limit definition of C++ classes et al to the C++ model
restrict the Objective-C part to the view related code and using the C++ model
I don't know of any actual simple examples, but any cross-platform project that has a native GUI on the mac uses the same approach. One mostly clean example would be the Chromium source.
|
1,885,750 | 1,887,781 | Lagged Fibonacci Rng For Project Euler #149 | Hey guys, this is very likely a total brain fart on my part but I was hoping someone could have a look at the following statement which describes how to set up the lagged fibonacci rng:
First, generate four million pseudo-random numbers using a specific form of what is known as a "Lagged Fibonacci Generator":
For 1 ≤ k ≤ 55, s(k) = [100003 −
200003k + 300007k^(3)] (modulo
1000000) − 500000.
For 56 ≤ k ≤ 4000000, s(k) = [s(k−24)
+ s(k−55) + 1000000] (modulo 1000000) − 500000.
Thus, s(10) = −393027 and s(100) =
86613.
So seems pretty straightforward (this is used to generate the matrix, which is then the actual problem to be solved, this link has the question). Anyways, here is my implementation and its output for s(10) and s(100):
class lagged_fib
{
private:
typedef std::deque<int> seed_list;
seed_list seeds;
size_t k;
public:
lagged_fib()
{
k = 1;
}
int operator()()
{
if (k<56)
{
seeds.push_back(((100003 - 200003*k + 300007*k*k*k)%1000000) - 500000);
k++;
}
else
{
seeds.push_back(((seeds[31]+seeds[0]+1000000)%1000000) - 500000);
seeds.pop_front();
}
return seeds.back();
}
};
Which yields:
s(10) = -393027
s(100) = -422827
You'll note that s(10) is as expected (so assumably the first part of the algorithm is correct), but s(100) is not. So, hopefully someone can spot where I've gone wrong, this is driving me up the wall.
Thanks
| Looks like you're having integer overflows in your code.
Try using int64_t type instead of int.
|
1,885,785 | 1,885,793 | Passing C++ strings by value or by reference | I'm wondering whether the C++ string is considered small enough to be more efficient when passed by value than by reference.
| No. Pass it by reference:
void foo(const std::string& pString);
In general, pass things by-reference if they have a non-trivial copy-constructor, otherwise by-value.
A string usually consists of a pointer to data, and a length counter. It may contain more or less, since it's implementation defined, but it's highly unlikely your implementation only uses one pointer.
In template code, you may as well use const T&, since the definition of the function will be available to the compiler. This means it can decide if it should be a reference or not for you. (I think)
|
1,885,849 | 1,885,897 | Difference between 'new operator' and 'operator new'? | What is difference between "new operator" and "operator new"?
| I usually try to phrase things differently to differentiate between the two a bit better, but it's a good question in any case.
Operator new is a function that allocates raw memory -- at least conceptually, it's not much different from malloc(). Though it's fairly unusual unless you're writing something like your own container, you can call operator new directly, like:
char *x = static_cast<char *>(operator new(100));
It's also possible to overload operator new either globally, or for a specific class. IIRC, the signature is:
void *operator new(size_t);
Of course, if you overload an operator new (either global or for a class), you'll also want/need to overload the matching operator delete as well. For what it's worth, there's also a separate operator new[] that's used to allocate memory for arrays -- but you're almost certainly better off ignoring that whole mess completely.
The new operator is what you normally use to create an object from the free store:
my_class *x = new my_class(0);
The difference between the two is that operator new just allocates raw memory, nothing else. The new operator starts by using operator new to allocate memory, but then it invokes the constructor for the right type of object, so the result is a real live object created in that memory. If that object contains any other objects (either embedded or as base classes) those constructors as invoked as well.
|
1,885,894 | 1,885,907 | Double Linked Lists in C++ | I have an assignment that requires us to implement a doubly linked list class. For some reason they defined the node struct as follows:
struct node {
node *next;
node *prev;
T *o;
};
It seems to me that it would be a lot easier to write the class if the struct member 'data' were not a pointer. Needless to say I can't change it so I'm going to have to just work around it. I tried implementing the method that adds an element to the beginning of the list as follows:
template <typename T>
void Dlist<T>::insertFront(T *o) {
node *np = new node;
T val = *o;
np->o = &val;
np->prev = NULL;
np->next = first;
if (!isEmpty()) {
first->prev = np;
} else {
last = np;
}
first = np;
}
While using ddd to debug I realized that everything works fine the first time you insert a number but the second time around everything gets screwed up since as soon as you set 'val' to the new element it "overwrites" the first one since the memory address of val was used. I tried doing other things like instead of just having the 'val' variable doing the following:
T *valp = new T;
T val;
valp = &val;
val = *o;
np->o = valp
This didn't seem to work either. I think this is because it's pretty much just a more complicated form of what I did above just with an additional memory leak :)
Any ideas/pointers in the right direction would be great.
| the T val you create is an automatic variable. Your mistake is storing the address to that stack variable.
You should be using new to allocate space on the heap, as you suspect, but your data pointer needs to point directly to the address returned by new.
Your mistake in your latest attempt is here:
valp = &val;
You are changing valp to point somewhere else (the address of val), when you are likely trying to copy val's data, not its address.
The data passed to your function should be copied to the new memory where valp points.
|
1,886,030 | 1,886,068 | Why is this explicit scope resolution necessary? | Setup:
class A {
public:
void a() {}
};
class B {
public:
void b() {}
};
class C: public A, public B {
public:
void c() {}
};
What (I thought) I should be able to do:
C* foo = new C();
foo->b();
And I get the following linker error from GCC:
`... undefined reference to 'C::b(void)'`
If I use explicit scope resolution it works, as in:
C* foo = new C();
foo->B::b();
A, B, and C share no members with similar signatures, so I know nothing is being hidden. Two questions:
1) Why, theoretically, am I not able to access public base class members implicitly?
2) What (if anything) in practice can I do to avoid this annoying syntax?
I can continue development with the explicit syntax (although I'd rather be rid of it) but I'm more looking to learn something here about my (apparently incorrect) knowledge of public inheritance in C++.
Cheers!
EDIT: Sorry, updated the sample code - some bad mistypes in my original.
EDIT2: Here's the (relevant parts of) the real code:
from src/creature.h:
#include "container.h"
#include "identifiers.h"
class Creature: public Identifiers, public Container {
public:
Creature( void );
Creature( const Creature& ref );
virtual ~Creature( void );
};
from src/identifier.h:
class Identifiers {
public:
Identifiers( void );
Identifiers( const Identifiers& ref );
~Identifiers( void );
};
from src/container.h:
class Container {
public:
Container( std::string (Object::*getName)( void ) const );
Container( const Container& ref );
~Container( void );
void add( Object* object );
void add( const std::list<Object*>& objects );
void remove( Object* object );
void remove( const std::list<Object*>& objects );
};
from src/container.cpp:
Container::Container( std::string (Object::*getName)( void ) const ) {
_getName = getName;
return;
}
Container::Container( const Container& ref ) {
_getName = ref._getName;
return;
}
Container::~Container( void ) {
while ( !objectList().empty() ) {
delete objectList().front();
objectList().pop_front();
}
return;
}
void Container::add( Object* object ) {
objectList().push_back( object );
return;
}
void Container::add( const std::list<Object*>& objects ) {
objectList().insert( objectList().end(), objects.begin(), objects.end() );
return;
}
void Container::remove( Object* object ) {
objectList().remove( object );
return;
}
void Container::remove( const std::list<Object*>& objects ) {
for ( std::list<Object*>::const_iterator it = objects.begin(); it != objects.end(); ++it ) {
remove( *it );
}
return;
}
from the application itself:
bool CmdWear::execute( Creature* creature, const std::string& args ) {
std::list<Object*> objects;
Object* removed = NULL;
std::string error;
objects = creature->searchObjects( args );
for ( std::list<Object*>::iterator it = objects.begin(); it != objects.end(); ++it ) {
if ( creature->wear( *it, error, removed ) ) {
creature->remove( *it );
}
}
return true;
}
Notes:
1) All methods shown here are defined in their appropriate .cpp file.
2) Each associated object file compiles just fine. Only the linker fails at the last step of linking all the object files together.
3) GCC spits out: undefined reference to `Creature::remove(Object*)' unless I qualify explicitly the scope by saying:
creature->Container::remove( *it );
Makefile:
PROJECT = symphony
CPPC = g++
FLAGS_DEV = -ggdb3 -ansi -Wall -Werror -pedantic-errors
LIBS = `pcre-config --libs` `mysql_config --libs`
SRC_DIR = src
OBJ_DIR = obj
BIN_DIR = .
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst src/%.cpp,obj/%.o,$(SRC_FILES))
dev: $(OBJ_FILES)
$(CPPC) $(LIBS) $(FLAGS_DEV) $(OBJ_FILES) -o $(BIN_DIR)/$(PROJECT)
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
$(CPPC) -c $(FLAGS_DEV) $< -o $@
| I don't think that either of the snippets that you've posted should compile.
class C: public A, public B {
public
void c();
};
You need a : after the public access specifier.
C foo = new C();
foo->b();
You are trying to initialized a C from a pointer to dynamically allocated C object. . not -> is the correct operator to call a function on an object type. -> is for pointer types (or objects with an overloaded -> operator) only.
You need something like:
C foo;
foo.b();
I'm not sure how the snippet that you say works actually compiles.
|
1,886,280 | 1,886,351 | How to find determinant of large matrix | I found some C++ code for finding the determinant of matrix, for 4x4 to 8x8. It works ok, but my project needs matrices that are 18x18 or more, and the code is too slow. The code is recursive, but is recursion the right concept to deal with an 18x18 matrix? How else can I find the determinant?
| I assume you're using the naive method of expanding Laplace's formula. If you want to gain in speed, you can decompose your matrix M using LU decomposition (into two lower- and upper-diagonal matrices) which you can achieve with a modified Gauss-Jordan elimination in 2*n^3/3 FLOPS and then calculate the determinant as:
det(M) = det(L) * det(U), which for triangular matrices is just the product of the entries in their diagonal.
This process will still be faster than O(n!).
Edit: you can also use Crout's method, which is widely implemented.
|
1,886,358 | 1,886,371 | malloc pointer function passing fread | Can't figure out what's wrong, I don't seem to be getting anything from fread.
port.h
#pragma once
#ifndef _PORT_
#define _PORT_
#include <string>
#ifndef UNICODE
typedef char chr;
typedef string str;
#else
typedef wchar_t chr;
typedef std::wstring str;
inline void fopen(FILE ** ptrFile, const wchar_t * _Filename,const wchar_t * _Mode)
{
_wfopen_s(ptrFile,_Filename,_Mode);
}
#endif
#endif
inside main()
File * f = new File(fname,FileOpenMode::Read);
chr *buffer;
buffer = (wchar_t*)malloc(f->_length*2);
for(int i=0;i<f->_length;i++)
{
buffer[i] = 0;
}
f->Read_Whole_File(buffer);
f->Close();
for(int i=0;i<f->_length;i++)
{
printf("%S",buffer[i]);
}
free(buffer);
inside file class
void Read_Whole_File(chr *&buffer)
{
//buffer = (char*)malloc(_length);
if(buffer == NULL)
{
_IsError = true;
return;
}
fseek(_file_pointer, 0, SEEK_SET);
int a = sizeof(chr);
fread(&buffer,_length ,sizeof(chr) , _file_pointer);
}
| You're mixing pointers and references all over the place.
Your function only needs to take a pointer to the buffer:
void Read_Whole_File(char *buffer) { ... }
And you should pass that pointer as-is to fread(), don't take the address of the pointer:
size_t amount_read = fread(buffer, _length, sizeof *buffer, _file_pointer);
Also remember:
If you have a pointer ptr to some type, you can use sizeof *ptr and remove the need to repeat the type name.
If you know the length of the file already, pass it to the function so you don't need to figure it out twice.
In C, don't cast the return value of malloc().
Check for errors when doing memory allocation and I/O, things can fail.
|
1,886,491 | 1,886,499 | Why does my program terminate when an exception is thrown by a destructor? | I am not getting why if there is an active exception then if an exception is raised again, it leads to termination of program. Could someone explain?
| What is it suppose to do? It can't "double catch" or anything, nor does it make sense to simply ignore one. The standard specifies that if, during stack unwinding, another exception escapes, then terminate shall be called.
There is more discussion in the C++ FAQ. One "solution" is to wrap your destructor code in a try/catch block, and simply don't let exceptions escape.
Another is to come up with some sort of custom exception chaining scheme. You'd do the above, but instead of ignoring an exception, you would append it to the currently thrown exception, and at the catch site handle both by hand.
The best solution, I think, it to try to remove the exceptional code from your destructor.
|
1,886,540 | 1,886,566 | Undefined symbols error in C++ / Eclipse | I have a function to display the values of a vector in a table, but I keep getting an "Undefined symbols" error when linking.
Here is my function prototype:
void displayVectors(vector<string> & nameVec, vector<double> & scoreVec, vector<char> & gradeVec);
Here is the definition:
void dipslayVectors(vector<string> & nameVec, vector<double> & scoreVec, vector<char> & gradeVec) {
for (int i = 0; i < nameVec.size(); i++) {
cout << setw(12) << nameVec[i]
<< setw(8) << scoreVec[i]
<< setw(2) << gradeVec[i]
<< endl;
}
}
Here's where I called it:
displayVectors(nameVec, scoreVec, gradeVec);
I'm certain nameVec, scoreVec, and gradeVec are all the right types of vectors, and I have all the libraries included, so I'm stumped. I've seen other people on Google have problems with vectors like this, but they always found some error they made. Does anyone have any ideas?
| Assuming you cut & pasted your question directly, then void dipslayVectors is a misspelling in the definition
|
1,886,606 | 1,922,335 | GDB gets activated automatically and has 100% CPU activity | I'm using Debian x64 2.6.26 to host a server application we've written in C++. Sometimes GDB gets activated on its own and it uses 100% CPU time giving no room for other processes to run. The GDB version is 6.8-debian. I don't know why this happens and how may i prevent this. It seems that it only happens when out server application is running. I need to know how to stop this from happening or if there is something wrong in our application then how may i find it. Any help is much appreciated.
Thanks
| I am inclined to believe that GDB is getting called by a signal handler in some code. Another suspect is some system monitoring daemon like 'monit'. When there is a rogue process eating too much memory or CPU, it might be trying to take a backtrace or dump using GDB. On way to troubleshoot is to use 'lsof' on the GDB process and see what files are opened by GDB and see if it gives you any clue. Using 'ps -ef -o cmd,pid,ppid | grep -i gdb', you can figure out how GDB was launched and if it gives you the PID of the attached process, you will know which process is being inspected.
A sledge hammer approach to stub such automatic execution is replacing 'GDB' with a stub 'GDB' which does nothing. Non existence of GDB might signal an error though. I have done such dirty tricks when I had no time to dig deeper into the problem. In the stub GDB, you can log all the command line arguments and the calling process name.
A sample stub in 'C':
#include <stdio.h>
int
main(int argc, char *argv[]) {
size_t sz;
FILE *fp = 0;
fp = fopen("/tmp/gdbstub.log", "a");
if (fp) {
fprintf(fp, "\n%s invoked:", argv[0]);
for (sz = 0; sz < argc - 1; sz++) {
fprintf(fp, "%s ", argv[sz]);
}
fclose(fp);
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.