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
3,601,886
3,602,254
How pass data to 'generic' observer? As arguments or as a single struct?
I am busy adding a generic observer mechanism to a legacy C++ application (using Visual Studio 2010, but not using .Net, so .Net delegates are out of the question). In the design I want to separate the application-specific part as much as possible from the generic observer mechanism. The most logical way of implementin...
The design with the struct argument is definitely better as it allows for generic code to be written in the ObserverContainer. It's generally a good design practice to replace longish argument lists with objects that encapsulate the arguments and this is a good example of the payoff. By creating a more general abstra...
3,602,079
3,602,118
Is there a more efficient way to get the length of a 32bit integer in bytes?
I'd like a shortcut for the following little function, where performance is very important (the function is called more than 10.000.000 times): inline int len(uint32 val) { if(val <= 0x000000ff) return 1; if(val <= 0x0000ffff) return 2; if(val <= 0x00ffffff) return 3; return 4; } Does anyone have any ...
How about this one? inline int len(uint32 val) { return 4 - ((val & 0xff000000) == 0) - ((val & 0xffff0000) == 0) - ((val & 0xffffff00) == 0) ; } Removing the inline keyword, g++ -O2 compiles this to the following branchless code: movl 8(%ebp), %edx movl %edx, %eax andl $-16777...
3,602,096
3,604,231
Create Widget in QMainWindow and load to ScrollArea
I tried to create a Mainwindow with an slot, which creates a Widget and loads it to the ScrollArea in the Mainwindow. This doesn't work, so I tired to create the Widget in the constructor of the mainwindow and I always get errors and don't know why.. so what's the right declaration of the Widget? #include <QtGui> cla...
I have played around with your code a bit, noticed a few things: In class Mainwindow you define your QScrollArea variables: QScrollArea *List,*Sublist,*Overall,*Settings; You define a variable named Sublist of type QScrollArea, but you also have a class of the same name: class Sublist : public QWidget Probably would ...
3,602,635
3,602,800
call an exe from within c++ (windows)
I'm using VS2010 and I would like to call an exe file which I've created in another directory. I've tried the following: int main(){ system("C:\\Users\\Li\\Desktop\\Debug\\modelExample_4pcs.exe"); return 0; }; but I get "The system could not find the file specified" error. I've tried to run the exe file di...
Try opening the file for reading, just to check that you have the path right: char* filename = "C:\\Users\\Li\\Desktop\\Debug\\modelExample_4pcs.exe" ; FILE* fp = fopen (filename, "rb") ; // Open for reading, binayr mode if (fp == 0) { printf ("Duh! File not found\n") ; exit (0) ; } printf ("File found\n") ; fclo...
3,602,682
3,602,712
Why does VC2008 think this class is abstract?
I'm writing some code to handle video input from some cameras using DirectShow, so I have to implement ISampleGrabberCB. My class that implements the interface compiles okay, but when I try to instantiate it the compiler raises "error C2259: 'SampleGrabberCB' : cannot instantiate abstract class". Here is the interface ...
SampleCB as declared in the interface doesn't have the third parameter (bufferLen) that is present in the SampleGrabberCB class.
3,603,047
3,603,120
Find the end of stream for cin & ifstream?
I'm running myself through a C++ text book that I have as a refresher to C++ programming. One of the practice problems (without going into too much detail) wants me to define a function that can be passed ifstream or cin (e.g. istream) as an argument. From there, I have to read through the stream. Trouble is, I can't f...
eof() does work for cin. You are doing something wrong; please post your code. One common stumbling block is that eof flag gets set after you try to read behind the end of stream. Here is a demonstration: #include <iostream> #include <string> int main( int, char*[] ) { std::string s; for ( unsigned n = 0; n < ...
3,603,206
3,603,230
C++ array initialization not working
I am trying to initialize an array of bools like so: bool FcpNumberIsOk[MAX_FCPS]={true}; but when I debug it, I only see the first element of the array initialized, the others are false. How can that be so? I am using Qt on ubuntu 10 and the initialization is done on a local array inside a method. Ok thanks for you...
Because that's the way array initialization works in C++. If you don't explicitly give a value for each element, that element defaults to zero (or, here, false) bool FcpNumberIsOk[MAX_FCPS]={true, true, true, true /* etc */ }; Note that bool FcpNumberIsOk[MAX_FCPS]; Will set all values to false or have them set r...
3,603,224
3,603,258
c++ POD initialization
I've read about POD objects in C++. I wanna have a POD struct to be written into a file. So it should have only public data with no ctors/dtors etc. But as far as i know it can have static function in it. So can I use "named constructor idiom" here? I need dynamic initialization, but I don't want to duplicate arguments...
That should be fine. You can even have a non-static member functions (as long as they are not virtual) You cannot have something that is called automatically (like ctor/dtor). Thingsthat you explicitly call are fine.
3,603,249
3,604,295
Time Sampling Problems with gprof
I am attempting to profile some c++ code, compiled with g++ including the option -pg, using gprof. However, in spite of the fact that the program takes 10-15 minutes to run on my computer (with the CPU maxed out), the % time, cumulative seconds and self seconds columns of the table produced by gprof are entirely 0.00s!...
gprof doesn't count any blocked time, like I/O or other stuff. Also "self time" typically is extremely small in any routine that does all its work in subfunctions, like if you're mostly using a library in a DLL where gprof can't see it. Check this answer.
3,603,353
3,603,391
Comparing Character Literal to Std::String in C++
I would like to compare a character literal with the first element of string, to check for comments in a file. Why use a char? I want to make this into a function, which accepts a character var for the comment. I don't want to allow a string because I want to limit it to a single character in length. With that in mi...
Doing this: if (my_string.substr(0,1).compare(&my_char2)==0) Won't work because you're "tricking" the string into thinking it's getting a pointer to a null-terminated C-string. This will have weird effects up to and including crashing your program. Instead, just use normal equality to compare the first character of ...
3,603,461
3,603,539
Is there a specific reason nested namespace declarations are not allowed in C++?
The standard does not allow code like this: namespace Hello::World { //Things that are in namespace Hello::World } and instead requires namespace Hello { namespace World { //Things that are in namespace Hello::World }} What is the rationale? Was this simply not thought of at the time, or is there a specific reaso...
The reason is most likely "because that's how the language evolved." There has been at least one proposal ("Nested Namespace Definition Proposal" in 2003) to allow nested namespace definitions, but it was not selected for inclusion in C++0x.
3,603,465
3,603,725
Multi-agent system in C++ code design
I have a simulation written in C++ in which I need to maintain a variable number of agents, and I am having trouble deciding how to implement it well. Every agent looks something similar to: class Agent{ public: Vector2f pos; float health; float data[DATASIZE]; vector<Rule> rules; } I need to maintain ...
Until now I was using a vector, but I think it pretty hard to erase from this structure: something I need to do quite often, as things die all the time. How many do you actually expect to die per each step of your simulation? What seems like "all the time" to a human could still be considered very infrequent to a com...
3,603,613
3,603,697
How to use Bison (Yacc) to produce 64bit parser in C++?
Can anyone shed some light on this? From Bison's documentation, I didn't see anything related to this topic. Thanks very much in advance. Mark
Bison and Yacc produce a C/C++ code, it depends on your compiler settings what assembly (32/64bit) will be produced.
3,604,181
3,604,215
Namespaces qualified with :: in C++
What does it mean if namespace in C++ is qualified with ::? For example ::testing::Test.
:: is the scope resolution operator. It always means "search the global namespace for the symbol on the right." For example: namespace testing { int a = 1; } namespace foo { namespace testing { int a = 2; } int b = ::testing::a; // b has the value 1 int c = testing::a; // c has the value...
3,604,291
3,632,302
how to create binary and .so using libtool
I have a set of cpp files that I want to compile directly into a binary and also to compile into a shared library. I have bin_PROGRAMS=mybin lib_LTLIBRARIES=libmylib.la COMMON_SOURCES=f1.cpp f2.cpp f3.cpp mybin_SOURCES=main.cpp $(COMMON_SOURCES) libmylib_la_SOURCES=$(COMMON_SOURCES) When I run this the cpp files ar...
The issue is that the common sources need to be compiled differently when they are being made into a shared object than when they are being made into a static archive; in the case of the former, for example, g++ needs to be passed the -fPIC flag. What I suggest is using two build directories. Assuming this source hier...
3,604,370
3,604,424
Instantaneous interruption of a Boost::thread
I'm trying to implement a program which runs a function limited by a fixed amount of time. I've managed to do it with pthreads but I would like to use Boost::thread. So far I've coded the following: #include <boost/thread.hpp> #include <unistd.h> #include <signal.h> #include <iostream> using namespace std; boost::th...
Boost does not provide a method to do interruptions immediately, but they do provide a way to get the native thread handle, so if your native threading library supports immediate interrupts, then you can still utilize that method. Look at boost::thread::native_handle() to get access the the native handle. It might be a...
3,604,510
3,604,676
pthread scheduling problems
I have two threads in a producer-consumer pattern. Code works, but then the consumer thread will get starved, and then the producer thread will get starved. When working, program outputs: Send Data...semValue = 1 Recv Data...semValue = 0 Send Data...semValue = 1 Recv Data...semValue = 0 Send Data...semValue = 1 Recv Da...
No. Unless you are using a lock to prevent it, even if one thread yields it's quantum, there's no requirement that the other thread receives the next quantum. In a multithreaded environment, you can never ever ever make assumptions about how processor time is going to be scheduled; if you need to enforce correct behavi...
3,604,524
3,604,572
Socket programming in C++ in Ubuntu
I have tried to implement a program using sockets in Ubuntu 10.04. Here is the code: #include <iostream> #include <sys/types.h> #include<netinet/in.h> #include <sys/socket.h> #include <netdb.h> #include <unistd.h> #include <errno.h> #include <exception> using namespace std; using std::exception; int main(int argc,char ...
EXIT_FAILURE and exit() are defined in <stdlib.h> since you have not included this in your module, the compiler is pointing out that it does not know what these symbols mean. Adding: #include <stdlib.h> should sort your problem out.
3,604,569
3,604,588
What kinds of optimizations does 'volatile' prevent in C++?
I was looking up the keyword volatile and what it's for, and the answer I got was pretty much: It's used to prevent the compiler from optimizing away code. There were some examples, such as when polling memory-mapped hardware: without volatile the polling loop would be removed as the compiler might recognize that the...
Basically, volatile announces that a value might change behind your program's back. That prevents compilers from caching the value (in a CPU register) and from optimizing away accesses to that value when they seem unnecessary from the POV of your program. What should trigger usage of volatile is when a value changes d...
3,604,620
3,604,717
Cygwin and Eclipse Helios setup
I am trying to learn C++ with Cygwin and Eclipse Helios. I got all the development tools under Cygwin installed; and installed the CDT package for Helios. The problem is I don't see an option to create a C++ project from makefile or any other option. I can only see options for a C Project, C++ project and a new project...
Are you asking how to setup GCC in cygwin + Eclipse? How about this tutorial?
3,604,639
3,604,683
No such signal in QT4
I have a signal and a slot that should fit together quite nicely. class MemberVisitor: public QObject { Q_OBJECT signals: void processMember(Member* member, bool &breakLoop); public: void processList(QList<Member*>* list); }; along with: class MemberFinder: public QObject { Q_OBJECT public slots: v...
The call to connect() should be: QObject::connect(visitor, SIGNAL(processMember(Member*, bool&)), finder, SLOT(processMember(Member*, bool&))); ..provided that visitor and finder are pointers.
3,604,852
3,605,030
From C++Builder to Visual Studio 2008
I'm inheriting a native C++ application. It was developed with C++Builder. Right now, I already have a copy of Visual Studio 2008 installed on my system. Is there anything that would prevent me from building the system with Visual Studio, even though it was developed in C++Builder? I'm already familiar with Visual St...
If the application only uses the Win32 API directly, getting it to work with VC++ is probably a reasonable possibility. If, as seems much more likely, it uses VCL (or one of Borland's other class libraries), then building it with VC++ will probably require a substantial (quite possibly bordering on total) rewrite.
3,604,901
3,604,959
Pointers to functions
I have to pass function into pointer. For this purposes I'm using boost::function. The function which catches the pointer is overloaded for different signatures. For example: void Foo(boost::function<int ()>) { ... } void Foo(boost::function<float ()>) { ... } void Foo(boost::function<double ()>) { ... } Now I wanna p...
Nonono this cannot work. Because boost::function<...> has a templated constructor to accept any and all types. Compatibility with the call signature is checked later on. Overload resolution cannot resolve this. Also, i think you want to pass &obj instead of this. Try converting explicitly: Foo(boost::function<float ()...
3,605,296
3,605,748
"..." in function prototype
I saw someone's C++ code has function declaration like below: void information_log( const char* fmt , ...) or catch block like catch(...) { } What does "..." mean?
The ellipsis ..., in a function prototype, is used to denote the function as variadic. That is, it enables a variable number of arguments to be passed into the function. In this form, a function must define some way for the user to specify exactly how many arguments they presented, since the variadic library functions ...
3,605,345
3,605,377
Getting my conceptions about pointers and references straight
I've been programming a while now at school, and I'm working on my first independent large project. I've been discovering a lot of things about programming that I haven't known before and it's been great. However, more and more, I feel like I no longer understand C++ as a language the more I delve into it. I'd like to ...
While you have some nice ideas in point #1, that's not actually how it works. Conversion is not done in-place, it is done by creating a new object which copies the members it knows about from the conversion source (which is to say, the base class members, unless you have some really weird forward declarations in your ...
3,605,484
3,605,669
Where should I put third-party libraries?
I contribute to a decent-sized C++ project with a number of dependencies. The problem is, the project contains the source of all of its dependencies (e.g. pcre, zlib, etc.). I want to trim the project down to just what's relevant to the program itself. Is there some relatively standard way to compile these libraries an...
A structure that we use on my workplace is having one "External" folder that contains an "Include" and a "Lib" folder for the headers and external Libs. However, as we also use VS, we try to use its "Dependencies" feature as most as possible, removing manual inputs to the linker. That means only projects that are not u...
3,605,697
3,605,705
Inheritance and templates and virtual functions ( this can get messy)
Just finding my way around templates so was trying out a few stuff. Let me know what I am doing wrong here. I am trying to overload a inherited templates virtual method. // class templates #include <iostream> using namespace std; template <class T, class A> class mypair { T a, b; public: mypair (T first, T ...
The next class does not automatically inherit the constructors from its parent class. You have to define any constructors explicitly. This applies to all derived classes, whether template and virtual functions are involved or not. If you want to define a constructor from next that takes two Ts and forwards them to the ...
3,605,970
3,606,149
Is C still being widely used in game engines?
The title is a bit of a misnomer, what I mean really is "C with classes". Let me explain, recently I bought the book ShaderX7 which came with a lite (and old) copy of the Unigine engine for one of the articles about shadow mapping techniques. I was dabbling through the code when I realized that, while the author was us...
First and foremost I must admit that I'm not a games developer, even though I have developed a fully functional 3D game engine in the past. That aside, I do have a few words about optimizations, "spoiling" languages and so on. When developing an application — any application — the golden rule of optimizations is "don'...
3,605,987
3,606,030
How can I safely and quickly extract digits from an int?
We currently have some code to extract digits from an int, but I need to convert this to a platform without snprintf, and I am afraid of a buffer overrun. I have started to write my own portable (and optimized) snprintf but I was told to ask here in case someone had a better idea. int extract_op(int instruction) { ...
Using sprintf should be fine. sizeof type * 3 * CHAR_BIT / 8 + 2 is a sufficiently large buffer for printing an integer of type type. You can simplify this expression if you assume CHAR_BIT is 8 or if you only care about unsigned formats. The basic idea behind it is that each byte contributes at most 3 digits in decima...
3,606,043
3,606,843
C++ MinGW shared libraries problem (Windows only,works on Linux)?
Greetings all, I use MinGW,QT and CMake for my project. As shown in the figure, my project has two modules. libRinzoCore.DLL - a shared library which define some abstract classes and interfaces and some core functionality of the application.This module is used to implement dynamic Plugins (which are also shared libra...
On windows you need to declare "export" part of dynamic library to make it work. #ifdef Q_WS_WIN #ifdef RINZO_EXPORT #define RINZO_LIB __declspec(dllexport) #else #define RINZO_LIB __declspec(dllimport) #endif #else #define RINZO_LIB #endif Then you need to put RINZO_LIB in front of your class declaration inside of li...
3,606,113
3,606,337
Set .h to c++-mode group in emacs
I'm not entirely sure if this question belongs on stackoverflow or superuser (is there an emacs stack exchange?). Based on the meta.stackoverflow post I'll assume that it does. My emacs defaults header files (of the .h variety) to c mode. I can easily type M-x c++-mode and get my highlighting back, but because I progra...
Here's what I have in my .emacs file: ; Make .h files be C++ mode (setq auto-mode-alist(cons '("\\.h$" . c++-mode) auto-mode-alist)) There might be an easier way, but this works.
3,606,319
3,606,406
Exercise Self Study Help
I've started learning C++ and am working through some exercises in the C++ Primer Plus book. In chapter 5 one of the exercises is: Write a program that uses an array of char and a loop to read one word at a time until the word done is entered. The program should then report the number of words entered (not co...
Edit: oops, spec says to read into an array of char… I'm not going to bother editing, this is really stupid. std::string contains an array of char too! cin.exceptions( ios::badbit ); // avoid using if or && to check error state int n; string word; for ( n = 0; cin >> word, strcmp( word.c_str(), "done" ) != 0; ++ n ) ;...
3,606,616
3,606,988
Set Individual Pixels on Back Buffer
I want to be able to set the individual pixels of the back buffer in my program in an efficient way. This is what I call in my rendering function: void render_frame(void) { d3ddev->Clear(0, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0, 40, 100), 1.0f, 0); d3ddev->BeginScene(); d3ddev->GetBackBuffer(0, 0, D3DBAC...
In order to lock the back buffer, you need to specify a flag at device creation: D3DPRESENT_PARAMETERS d3dpp; (...) d3dpp.Flags = D3DPRESENTFLAG_LOCKABLE_BACKBUFFER; However, as specified in Direct3D specifications, this could seriously hurt the performances. You should rather draw textured triangles.
3,606,656
3,606,947
Storing boost function
I have to store a list of different boost::function objects. To provide this I'm using boost::any. I have a few functions which takes different functions signatures, pack them into any and then insert into special map with given type. Here is the code: enum TypeEnumerator { e_int, e_float, e_double }; type...
@TC provided the solution for the runtime error. But I believe you should use Boost.Variant instead of Boost.Any as there are only a fixed selection of types it can store. With Boost.Variant you could eliminate that enum too, as it already provided a standard visitor pattern interface. (result): #include <boost/variant...
3,606,777
3,607,637
Multicasting in C++ : Error "An unknown, invalid, or unsupported option or level was specified in a getsockopt or setsockopt call"
I have developed one server pgm for multicasting in C++, when i register the address and after that when i set the socket option using setsockopt it returns me -1 If this option is not supported in setsockopt then how i can go for multicasting in C++ My code is below : #include"winsock.h" #include<iostream> #include<co...
I resolved the above issue. Just replace ws2_32.lib with wsock32.lib. This will resolve the issue.
3,606,902
3,606,985
can't make sense of LARGE_INTEGER struct
With C++ and some Winapi things, I encountered this guy: #if defined(MIDL_PASS) typedef struct _LARGE_INTEGER { #else // MIDL_PASS typedef union _LARGE_INTEGER { struct { DWORD LowPart; LONG HighPart; }; struct { DWORD LowPart; LONG HighPart; } u; #endif //MIDL_PASS L...
Microsoft provides anonymous structs as an extension (their example shows one struct inside another struct, but a struct in a union is similar). If you don't mind non-portable code based on their extension, you can use things like: LARGE_INTEGER a; a.LowPart = 1; but if you want portable code, you need: a.u.LowPart = ...
3,606,933
3,606,957
How to Send a structure using sendto()
I have created structure : struct buffer { string ProjectName ; string ProjectID ; } buffer buf; buf.ProjectID = "212"; buf.ProjectName = "MyProj"; Now to send this structure using sendto method , I am typecasting the strucure and sending it back as below: char *sendbuf = (char*)&buf; sentbytes = sendto(sock,...
You need to create the structure using POD, the string is not something you can use in that way. Instead you need to declare it something like struct buffer { char ProjectName[MAX_LENGTH_PROJECT_NAME+1]; char ProjectID[MAX_LENGTH_PROJECT_ID+1]; }; EDIT: clarification, the string contains a pointer to a heap alloca...
3,607,216
3,607,270
Choice of the most performant container (array)
This is my little big question about containers, in particular, arrays. I am writing a physics code that mainly manipulates a big (> 1 000 000) set of "particles" (with 6 double coordinates each). I am looking for the best way (in term of performance) to implement a class that will contain a container for these data an...
First of all, you don't want to scatter the coordinates of one given particle all over the place, so I would begin by writing a simple struct: struct Particle { /* coords */ }; Then we can make a simple one dimensional array of these Particles. I would probably use a deque, because that's the default container, but yo...
3,607,262
3,607,450
Why won't this compile (link) with the Q_OBJECT macro in place?
I made a prototype of a project with PyQt and made it work there, now I'm trying to convert it to C++ and am having some problems. If I don't put the Q_OBJECT macro in, it compiles and works, but if I comment it out, I get the following errors: Undefined symbols: "vtable for MapView", referenced from: MapView::...
This kind of errors usually happen when you add the Q_OBJECT macro and forget to rerun moc. If you use qmake, just run make qmake after you added the macro. As for your second question: you won't be able to use signals/slots (among other things) without the Q_OBJECT macro. See the docs for more information about this.
3,607,352
3,607,404
struct with 2 cells vs std::pair?
Possible Duplicate: What is the difference between using a struct with two fields and a pair? Dear all, I have a little question about pairs and struct. Is there any advantage to use a std::pair instead of a struct with two cells ? I have used pairs for a while but the main problem is readability : If you want to re...
A pair is implemented as a templated struct. It provides you with a shorthand for creating a (typically heterogenous) pair. Also, there are some constraints on the types that you can use with a pair: Type requirements T1 and T2 must both be models of Assignable. Additional operations have additional requirements...
3,607,565
3,607,592
how to destroy stl Queue created on heap?
As per req i have to create stl queue on heap i have created stl queue on heap in constructor of my class as per below code queue<int> *myqueue; myqueue=new queue<int>(); Now in destructor i want to destroy it: so i have written code while(!myqueue->empty()) { myqueue->pop(); } please tell me is it right way to d...
All STL containers have a member clear() that can be used to erase their content. All STL containers will call this member in their destructor, so you won't have to do it manually. So all you have to do is to ensure that the queue itself is destroyed. for dynamically (with new) allocated objects, that's done by invokin...
3,607,658
3,607,694
Is there a standard way to convert from container<Type1> to container<Type2>?
I have two classes A and B, and an implicit conversion operator exists to go from one to the other, so that: A a; B b; b = a; // Works Is there a standard way to convert a std::list<A> to a std::list<B> ? (Or even from std::vector<A> to a std::list<B>). I know I can iterate trough to the list and build the second list...
Well, yes. Each sequence container type has a template constructor that takes a pair of iterators (an iterator range) as an input. It can be used to construct one sequence from another, regardless of the sequence types, as long as the sequence element types are convertible to each other. Like for example std::vector<A>...
3,607,775
3,607,819
Why Floating point numbers cant be compared?
Possible Duplicate: strange output in comparision of float with float literal #include<stdio.h> int main() { float me = 1.7; if(me==1.7) printf("C"); else printf("C++"); } Output: C++ Now the reason for this behaviour is said that many floating point numbers cant be represented with absolute precision in bi...
You are comparing a float to a double. the literal 1.7 is a double. You've stored that in a float, which might have less precision than a double, thus the me == 1.7 is comparing 1.7 as a float(promoted to a double) to 1.7 as a double. In this case, me == 1.7f should make them compare as equal, or changing me to a doub...
3,607,974
3,607,998
error C2440: '=' : cannot convert from 'char [5]' to 'char [20]'
This is linked to my previous post Wher I created a Struct : struct buffer { char ProjectName[20]; char ProjectID[20]; }; Now while I am trying to assign values to it: buffer buf; buf.ProjectID = "3174"; buf.ProjectName = "NDS"; I am getting this error: error C2440: '=' : cannot convert from 'char [5]' to ...
You have to copy the string into the array: strcpy(buf.ProjectName, "3174"); Be careful with the length of the strings being copied into the arrays
3,608,103
3,608,665
How could I link my c++ console application to take control of an existing console?
How would I take control of the console of a batch file, and load it into my c++ application?
Make the batch file output to a text file that will then be processed by your application.
3,608,212
3,608,266
How to provide a single function to get data of any derived object through base class pointer?
i have code like below. Base is the base class and D1, D2, D3 are derived classes. D1, D2 and D3 class objects can hold int, float and double values respectively. I have a vector of base class pointers. Each one of them can point to any of the derived class objects. Through Base class pointer i should be able to get th...
In general I'd prefer to avoid such design at all. But if you absolutely have to make it this way, the easiest and fastest method, imho, is to use boost::any. Update: As it was, absolutely correctly, noted boost::variant may be even more convenient and efficient here, since the used types are known (thanks for the rema...
3,608,262
3,608,473
Convert utf-8 std::string to std::wstring on iPhone
I have a UTF-8 string (created an std::string from a byte array) I understand that the encoding means that the size()/length() won't give me the actual number of glyphs if the text is chinese for instance... I understand that in order to get the unicode character code of each glyph I need to convert it to wstring (or a...
To get the number of utf8 'characters/code points' in a std::string you could do this : Traverse the string, if the char is between 0 and 127, it's a one byte character, between 194 and 223 it's a 2 bytes character (so advance in consequence), between 224 and 239 it's a 3 bytes character (so advance in consequence), be...
3,608,305
3,608,478
Class name does not name a type in C++
I just started programming in C++, and I've tried to create 2 classes where one will contain the other. File A.h: #ifndef _A_h #define _A_h class A{ public: A(int id); private: int _id; B _b; // HERE I GET A COMPILATION ERROR: B does not name a type }; #endif File A.cpp: #include "A.h...
The preprocessor inserts the contents of the files A.h and B.h exactly where the include statement occurs (this is really just copy/paste). When the compiler then parses A.cpp, it finds the declaration of class A before it knows about class B. This causes the error you see. There are two ways to solve this: Include B....
3,608,402
3,608,526
dbgrptt.c dbghook.c Iterator Error?
Okay, so long weekend away with Macbook I started making an asset loader for 2D game platforms, its working fine in xcode, but when I got home and tried and load it up on Windows I get a debug error. Essentially what is happening is that the first call to the iterator works? the second doesn't, but only on the second a...
It looks like you don't check the result of the find call on line 239 in the drawGraphic function. Also i think the loadAll loop looks dodgy. You're looping over m_assetsToLoad and modifying it at the same time in loadResource.
3,608,687
3,608,962
What are the principles of an event system in C++?
First of all, I know there are excellent implementations (Qt, Boost, cpp-event, etc.), but I ask the question because I want to know how it works ! If I understand correctly, the "event system" uses the Observer pattern : some objects are observing, waiting for something to happen... and some others send signals. All r...
There is a lot of different implementations possible (whatever the language), but the abstract idea is : have an event type identifier to know wich events have been fired by the observed object (it can be whatever works); have a list of observers (or several, one by event type?) registered in the registered objects - ...
3,608,706
3,608,879
Using getline when reading from a textfile
I'm initially building an index-like mechanism, read each line of the textfile using getline, checking if it matches a known header declaration (string.compare) and saving the tellg position as an index to that point. My intention is then to use seekg(index,ios::beg) to seek to the place in the file where the header i...
Your problem is caused because you have a Bad bit set inside the stream. Operations on the stream will be ignored until the Bad bit has been reset. // After the loop reset the Bad Bits. m_fileIn.clear() Note: A Bad bit is one of many error conditions including EOF But that is not your major problems: You are using the...
3,608,786
3,609,323
sending struct through socket; server and client on same machine
My server and client are running on the same machine so I dont have endian issues etc. I need something that works on both vc++ and g++ and possibly the simplest way. What can I send the struct with? Edit struct Info { int** fields; char** field_names; };
You can declare a static unsigned char like so: #define MSGBUFSIZE 512 static unsigned char ClientSendBuf[MSGBUFSIZE]; then copy your structure into the array like so: memmove(&ClientSendBuf[2], &struct, sizeof(struct)); now this where it is implementation specific next. I am using Borland C++ so my sending acts lik...
3,608,928
3,609,024
qt - widget - positioning
I want to place some widgets in a parent widget in some random places, like one button at Point (10,10) and another at (15,40), etc. How to achieve this?. QGridLayout is pushing everything into row column style. But I want to put the widgets whereever I want,Can anybody help me?
If you really want to set absolute positions, I would ignore using a layout altogether. You can manually set the positions of elements by using the move() function or the setGeometry() function. QWidget *parent = new QWidget(); parent->resize(400, 400); QPushButton *buttonA = new QPushButton(parent); buttonA->setText(...
3,608,953
3,609,020
How to validate length of received byte array, which is not null terminated?
I have a C\C++ code that receives a structure over the network, from this form: struct DataStruct { int DataLen; BYTE* Data; } The code I have runs over Data in a loop of DataLen times and processes the data. ...The problem: After the code came to security experts for penetration tests, they prepared a fake applicatio...
Nice security experts! I wish my company had a department like that. Whenever data is received from the network, the network IO reports the number of bytes actually written to the buffer, whether you used read(2), recv(2), or boost::asio::async_read or anything else I've seen. Typical use case when there's a "number of...
3,609,000
3,609,013
Comparing data bytewise in a effective way (with C++)
Is there a more effective way to compare data bytewise than using the comparison operator of the C++ list container? I have to compare [large? 10 kByte < size < 500 kByte] amounts of data bytewise, to verify the integrity of external storage devices. Therefore I read files bytewise and store the values in a list of uns...
Don't use a std::list use a std::vector. std::list is a linked-list, elements are not guaranteed to be stored contiguously. std::vector on the other hand seems far better suited for the specified task (storing contiguous bytes and comparing large chunks of data). If you have to compare several files multiple times and ...
3,609,110
3,786,034
standalone grammar and parser for php
i'm looking for a ready-made grammar and parser for php (at least 5.2), ideally an utility/library that can parse php code into a readable AST, e.g. xml. The parser itself doesn't have to be written in php, the source language doesn't matter much.
To answer my own question I've managed to compile phc on my OSX box, the parser part seems to work well phc --dump-xml=ast foo.php > bar.xml creates an xml representation of the AST.
3,609,460
3,609,481
Sources of non-determinism
My supposedly deterministic program produces one of a few slightly different outputs on different runs. The input, compiler and computer are unchanging. I'm not sure which output is right because it always looks reasonable. Besides a stray call to rand(), how could this be possible?
In several ways: using multiple threads in a way that involves a data race, using the current system time as input, using uninitialized variables, ... We can surely make more guesses, but if you want to get meaningful help, maybe it would be good for you to publish the relevant parts of your code :-)
3,609,515
3,609,730
Using STL in a closed-source library
Is it safe to use one standard compliant STL in a library, and another in a project that uses that library? For example: //library.h #include <string> //let's say here it uses minGW STL void Foo(std::string& str_mingw); //library.cpp void Foo(std::string& str_mingw) { /*do something*/ } //application.cpp #inclu...
If - by library - you mean dynamic library - The simple answer is: no and the complex answer is: no. C++ and dynamic libraries is a very VERY fragile prospect. Any small change requires a rebuild of all modules, and the runtime used by each library MUST be the exact same library instance. Even if you managed to get a s...
3,609,940
3,636,176
Handling C++ exception thrown in function exported to QtScript
I am using the Qt script engine in my application as an alternative way for the user to access its functionality. As such, I export some C++ classes to the Qt ScriptEngine, that will serve as the interface to the application. The problem is, these C++ classes can throw exceptions. I have a "ScriptInterface" class runn...
I ran into a similar type of problem when trying to use SWIG with Python to wrap C++ libraries. Eventually what happened was that I made a stub for all the wrapped classes which caught the exception and failed quietly. Luckily I had the luxury of wrapping functionality which only passed container classes and state pa...
3,609,941
3,610,069
std::inserter with set - insert to begin() or end()?
I have some code that looks like this: std::set<int> s1, s2, out; // ... s1 and s2 are populated ... std::set_intersection(s1.begin(), s1.end(), s2.begin(), s2.end(), std::inserter(out, out.end())); I've read inserts can be done in amortized constant time if the value bein...
You could use a custom functor instead of std::inserter and re-call out.end() every time a new element is inserted. Alternatively, if your values are sorted descendingly, out.begin() will be fine.
3,609,958
3,610,370
Global multidimensional array not being written to [vs c++]
I have a global multidimensional array, g_iAllData[MAX_LEN][MAX_WIDTH] being used in a Form. When I write to it in a function: g_iAllData[iRow][iColumn]= iByte_Count; I can see in a Watch Window that it's contents are not being changed. If I put the array in the function, it works fine. Is there something I'm missin...
Your code sample really confirms that you have a problem with your variable declaration. As @Graham hinted, the proper way to define globals is: define the variable in a cpp file declare the variable as extern in a header file I.e. //ProgramName.cpp #include "stdafx.h" #include "Form1.h" int g_iAllData[MAX_LEN][M...
3,610,000
3,610,159
Why does istream_iterator<unsigned char, unsigned char> throw std::bad_cast?
What is going on? #include <iostream> #include <iterator> #include <sstream> int main() { std::basic_stringbuf<unsigned char> buf; std::basic_istream<unsigned char> stream(&buf); // the next line throws std::bad_cast on g++ 4.4 std::istream_iterator<unsigned char, unsigned char> it(stream); } I've tri...
It throws from sentry object's constructor where it checks the ctype facet on the stream (it needs it so it can skip whitespace), which happens to be NULL because it's not defined for unsigned chars. Do you need to handle whitespace on that stream? If not, change to std::istreambuf_iterator<unsigned char> it(stream);
3,610,065
3,610,378
Is this a safe way to implement a generic operator== and operator<?
After seeing this question, my first thought was that it'd be trivial to define generic equivalence and relational operators: #include <cstring> template<class T> bool operator==(const T& a, const T& b) { return std::memcmp(&a, &b, sizeof(T)) == 0; } template<class T> bool operator<(const T& a, const T& b) { ...
Never do this unless you're 100% sure about the memory layout, compiler behavior, and you really don't care portability, and you really want to gain the efficiency SOURCE
3,610,267
3,614,154
How to clean up a bad OpenSSL connection
If a call to SSL_accept fails, I want to just bail out. Currently I'm calling SSL_shutdown and then SSL_free, but since implementing this, two customers have had crashes deep down in OpenSSL (when calling SSL_accept at a later time), so I'm guessing maybe this isn't the best way to clean up. The docs say SSL_shutdown i...
Once you've called SSL_free() on the SSL object, you shouldn't use it again. You need to ensure that a new SSL is created with SSL_new() for the subsequent SSL_accept().
3,610,301
3,610,355
Enforce third party methods virtuality
I'm extending a class provided by a third part library. The class, let's call it Foo, has a reset() method which can be called in order to restart Foo's behavior. The reset() method is also used internally by the class. class Foo { public: void reset () { /* ... */ } void something () { re...
You cannot extend classes that were not intended to be extended.
3,610,342
3,610,374
data structure - running time
Just a confusion.... A portion of a C++ sample code is as follows I just re-edit the whole post. Sorry for any confusion int i, j; i = 0; // c1 j = 0; // c2 while (i < n) // (n+1)c3 { i++; // n c4 while ( j < i) // (2+3+....+n+(n+1)c5 { j++; // (1+2+...+n)c6 } j = 0; // c7 } Clearly...
Here, you have a running time of 2n. Everytime i is incremented, j is one smaller, so the inner loop is executed exactly once. i=0, j=0 // init i=1, j=0 // outer loop i=1, j=1 // inner loop i=2, j=1 // outer loop i=2, j=2 // inner loop More typically, you'd reset j to 0 in the outer loop. In that case, you'd have a ru...
3,610,435
4,956,150
Interleaving/deinterleaving 3 vectors in C++ STL
I'm trying to combine three signal waveforms into a single, interleaved waveform. I need to know the best way to do it in C++ STL. Better solutions would use as much C++ STL style as possible, avoid redundant code, etc. Is there some STL "tuple" type class that would do this for me? I need contiguous storage at all tim...
If you're willing to use Boost, you can use slices to get syntax very close to your code in Matlab. Here's a C++ version of your Interleave3 function: template<typename V> V Interleave3(V const& a, V const& b, V const& c) { using namespace boost::numeric::ublas; V v(a.size() + b.size() + c.size()); vector_...
3,610,440
3,610,760
bitset for more than 32 bits?
I need to use bit flags with more than 32 bits (33 to be exact right now). I tried and find std::bitset doesn't handle more than 32 bits (ulong). Do I have to use vector or there's a way to make bitset to work? I am limited to c++98 in this project so I can't use boost. Thanks. Edit: I'd like to do something like this:...
I've just retested std::bitset with 65 bits and on my 32-bit Linux it works fine and as expected. Notable exception is the to_ulong() method which throws exception if any set bit would be truncated during the conversion. Now I think about it and that is rather obvious: there is no other way as to prevent application fr...
3,610,459
3,611,196
Adding vectors of doubles of differing sizes in C++
I have a number of vector containers of varying size each containing doubles. I would like to add the elements of each vector to create a single vector of doubles. This simple example will example what I'm talking about: Consider two vectors A with three elements 3.0 2.0 1.0 and B with two elements 2.0 1.0. I woul...
Once you know you have one vector that is larger than the other std::vector<double> new_vector = bigger_vector; // Copy the largest std::transform(smaller_vector.rbegin(), smaller_vector.rend(), // iterate over the complete smaller vector bigger_vector.rbegin(), // 2nd input is the corresponding entries of the lar...
3,610,565
3,610,742
Why does MAKEINTRESOURCE() work?
The macro is defined as: #define MAKEINTRESOURCEA(i) ((LPSTR)((ULONG_PTR)((WORD)(i)))) #define MAKEINTRESOURCEW(i) ((LPWSTR)((ULONG_PTR)((WORD)(i)))) How come this can be used to indicate either a resource ID (a 16-bit unsigned int) or its name (a pointer to an array of char)? Doesn't this effectively limit the addres...
This works because Windows doesn't allow mapping pages for the first 64 KB of the address space. To catch null pointer references. But I think also to catch pointer bugs in programs that were converted from the 16-bit version of Windows. A side-effect is that this allows to reliably distinguish resource IDs packed in...
3,610,686
3,610,868
Help using MFC CMap (or std::map) please
a C++ noob here. I am trying to tweak some code, with the following key lines (meaning they are not the only ones, but they are the only ones that should matter for this question). By the way, I am using Visual Studio 2010 C++ compiler on Windows. CMap<ATL::CAtlString,LPCTSTR,UINT,UINT> mapForDuplicates; // "dict" defi...
IIRC the four args to the template are there so you can throw one type in and get another (const) type back. Here it throws in CAtlStrings, but it'll get back LPCTSTR. Often you just specify the same to types twice (e.g. int, int, float, float for a map of ints -> floats). Grr, that extra L really irks me nowadays, it ...
3,610,888
3,611,013
Cairo error message on exit
I'm currently doing some tests using Cairo to replace some existing GDI/GDI+ code in Visual C++ 2010 and it seems to be working fine, but I'm getting an error message each time I close down my application : "First-chance exception at 0x68e629dc in CairoTest.exe: 0xC0000005: Access violation reading location 0xabababa7"...
A first chance exception doesn't necessarily mean much -- they're a routine part of Windows' memory management. Basically, any time you access something that's in virtual memory (e.g., on the paging file) a first chance exception is created. The OS handles it by paging in the required data into physical memory, then yo...
3,610,909
3,611,079
Freeing static memory? no, that can't be right
I've been playing around with embedding resources into my c++ program. In order to do this I hexdump the data to a simple array, i.e. unsigned char image_png[] ={ 0x0a, 0x0b, 0x0c, 0x0d, ... }; Some of these resources are not used after loading (i.e. they get converted to something else and then the original data ...
As Tomaka17 says, you don't really have to worry about it - if you never touch that resource, it will never be faulted in, and it won't consume physical memory. When you load a DLL/so/whatever, it really only maps the file into memory; trying to access that file is what results in actually reading the file, piece by pi...
3,610,933
3,610,963
Iterating C++ vector from the end to the beginning
Is it possible to iterate a vector from the end to the beginning? for (vector<my_class>::iterator i = my_vector.end(); i != my_vector.begin(); /* ?! */ ) { } Or is that only possible with something like that: for (int i = my_vector.size() - 1; i >= 0; --i) { }
One way is: for (vector<my_class>::reverse_iterator i = my_vector.rbegin(); i != my_vector.rend(); ++i ) { } rbegin()/rend() were especially designed for that purpose. (And yes, incrementing a reverse_interator moves it backward.) Now, in theory, your method (using begin()/end() & --i) would work, std::vect...
3,610,936
3,610,966
Why can I access a derived private member function via a base class pointer to a derived object?
#include<iostream> using namespace std; class base { public: virtual void add() { cout << "hi"; } }; class derived : public base { private: void add() { cout << "bye"; } }; int main() { base *ptr; ptr = new derived; ptr->add(); return 0; } Output is bye I dont have a ...
add() is only private in derived, but the static type you have is base* - thus the access restrictions of base apply. In general you can't even know at compile time what the dynamic type of a pointer to base will be, it could e.g. change based on user input. This is per C++03 §11.6: The access rules (clause 11) for a ...
3,610,941
3,611,156
How to write a C or C++ program to act as a memory and CPU cycle filler?
I want to test a program's memory management capabilities, for example (say, program name is director) What happens if some other processes take up too much memory, and there is too less memory for director to run? How does director behave? What happens if too many of the CPU cycles are used by some other program whil...
http://weather.ou.edu/~apw/projects/stress/ Stress is a deliberately simple workload generator for POSIX systems. It imposes a configurable amount of CPU, memory, I/O, and disk stress on the system. It is written in C, and is free software licensed under the GPLv2. The functionality you seek overlaps the feature set o...
3,610,943
3,611,082
Correlation between specifier and qualifier?
const and volatile are called cv-qualifier by the C spec. What is exactly defference between specifier and qualifier (cv-qualifier)? Is a qualifier is a specifier as well? Is it necessarry that qualifier is with an lvalue only? What are qualifiers other than cv-qualifier? Does my above understanding make any sense?
Most of it doesn't make sense. Specifier and qualifier are defined in the C++ standard. Qualifier is just an integral part of a specifier. For example, type specifier in a declaration can include cv-qualifiers. I don't see the reason to quote everything from the standard on this topic. Cv-qualifiers are not restricted ...
3,611,132
3,763,730
InternetOpenUrl intermittently times out
I have some InternetOpenUrl requests that are strangely timing out. The endpoint is there and the URL is correct. This happens in a synchronous loop inside an activex control, and about the 6th time it executes, it times out without hitting the server. HINTERNET hINet = InternetOpen(TEXT("InetURL/1.0"), INTERNET_OPEN_T...
OK so I originally thought EricLaw was correct and commented: "my particular problem was that i had javascript ajax calls occuring after each control ajax call. this creates a race condition and eventually 4 javascript ajax calls hadn't returned when i made an ajax call inside the control. (yeah, i misstated my environ...
3,611,182
3,620,854
Corrupted singleton data using CxxTest
This is a weird problem and I'm not sure what to make of it. I have something like the following: struct Parms { const std::string value1; const std::string value2; std::string parm1; std::string parm2; Parms() : parm1(value1), parm2(value1) {} static const Parms& getDefaults() { ...
double free and core dump I think I can explain the "double free and core dump" issue that you are having. I recently encountered the same thing and it sounds like you are doing the same thing I did. From you description you said that when you "run them separately" they work fine but if you "run them together" you get ...
3,611,304
3,611,537
How to use Boost uBLAS C++ library in an iPhone project?
I want to use Boost library in my iPhone project, specifically only boost::numeric::ublas. I managed to build static libraries for boost in order to link them in my iPhone project. However, when I look at those .a libraries I can't find one that's related to ublas (I tried ./bootstrap.sh --with-libraries=ublas in termi...
I can't answer the iPhone-specific part but I can help at least with the Boost part... Boost uBlas is a header-only library so you don't need to build and link against any .a files. Just include the headers in your project if you want to use the library.
3,611,408
3,611,472
How to check if you have live internet connection programmatically using C++
How can I check if I have a internet connection or live internet connection using C++?
C++ has no builtin functions for this, you will need to resort to system APIs. An easiest and obvious way is to create a socket and try to connect it to some known IP or check if DNS is working. Some useful links: http://msdn.microsoft.com/en-us/library/ms740673(VS.85).aspx (Windows Sockets) http://www.tenouk.com/cnli...
3,611,528
3,611,724
Is the Visitor Pattern the fastest way to differentiate parameter types in C++?
Is the Visitor Pattern the fastest way to accomplish method parameter type identification (effectively single dispatch on a parameter, not a member's class) in C++? I might know the exact method(s) I want to invoke on elements of not-yet-know subtype, so invariably making an additional virtual method call like V::visi...
In fact, the interfaces need not be duplicated. The subclasses of the visitor can handle the details of the operation. In your case: class Visitor { virtual void visit(B*) = 0; virtual void visit(D*) = 0; virtual void visit(E*) = 0; } class Foo: public Visitor { private: int result; public: void vi...
3,611,533
3,611,604
Cross source file template instantiation and use
I have a class with several template member functions that I would like to distribute among several source files to speed up compilation times. (The templates are implementation details and are not intended to be used outside the class, hence their definition in sources not headers.) How would I go about splitting up t...
I could not answer it better than C++ FAQ: https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
3,611,882
3,611,953
need help converting c++ definitions to c# equivalent
I'm using an API (written in c++) to connect to a DVR machine, actually I only have the .dll and the .lib files, and I want to do the job in .NET (C#). So, the API doc contains definitions to all functions inside the dll, and I'm having a hard time trying to figure out how to translate those functions to equivalente C#...
[DllImport("search.dll")] [return: MarshalAs(UnmanagedType.U1)] private static extern bool searchEvent( int channel, ref int condition, [MarshalAs(UnmanagedType.U1)] bool next ); [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] private struct Mumble { ...
3,611,909
3,611,941
Is there a reason for the order of destructor calls?
As I have read in certain forums,when derived class object is created base class members and methods are allocated space in the memory but there is no specific base class object. Now as the derived class object goes out of scope , why derived class destructor is called first.What is the constraint of the compiler where...
When a derived class object is created, there is a specific base-class object (sub-object, really). I.e., when you create a derived object, a base class ctor is used to initialize the base class subj-object within the derived object, and only after that completes does the derived class ctor get to do its thing, initial...
3,611,951
3,612,272
Building an unordered map with tuples as keys
In a C++ program with Boost, I am trying to build an unordered map whose keys are tuples of doubles: typedef boost::tuples::tuple<double, double, double, double> Edge; typedef boost::unordered_map< Edge, int > EdgeMap; Initializing the map completes OK, however, when I try to populate it with keys and values EdgeMap ...
You need a bit of front matter. Because of the underlying implementation of boost::tuples::tuple, make Edge a structure to allow the overloads to resolve correctly. Otherwise, you'll get no matches for boost::hash_value(const Edge &) operator==(const Edge &, const Edge &) Code below: struct Edge { Edge(double x1, d...
3,612,164
3,612,183
C++ anonymous class initialization
is it possible to initialize member variables in anonymous class? for example class { public: int &value; } container;
int x = 3; class { public: int &value; } container = {x};
3,612,252
3,612,298
Type casting (from derived class)
I want to make chain-calling like jquery-way in c++. The sample: $('#obj').getParent().remove(); So, as I understand, each method of the class should return the pointer to himself (this). Everything is okay until I call base-derived methods. The code: class Base { Base *base1() { return this; } Base *base2() { r...
Yes. Override the base1 and base2 methods in Derived to change their return value from Base* to Derived*, e.g. class Derived : Base { Derived *base1() { return this; } Derived *base2() { return this; } Derived *derived1() { return this; } Derived *derived2() { return this; } }; This is called covariance of...
3,612,505
3,612,551
Is 'volatile' needed in this multi-threaded C++ code?
I've written a Windows program in C++ which at times uses two threads: one background thread for performing time-consuming work; and another thread for managing the graphical interface. This way the program is still responsive to the user, which is needed to be able to abort a certain operation. The threads communicate...
You should not depend on volatile to guarantee thread safety, this is because even though the compiler will guarantee that the the variable is always read from memory (and not a register cache), in multi-processor environments a memory barrier will also be required. Rather use the correct lock around the shared memory....
3,612,554
3,612,591
Commutative property a[i] == i[a]
For a built in type integer array say int a[10]; int i = 2; a[i] = 10; alternatively i[a] = 10; because a[i] is a postfix expression that is *(a+i) or *(i+a) because commutative property of addition. I want to achieve that for a userdefined type say class Dummy { // }; Is it possible? If yes then how? If no then wh...
It is impossible because "operator[] shall be a non-static member function with exactly one parameter" (standard §13.5.5/1), so you cannot define it such that the first argument is of native scalar type. (Furthermore, a nonstatic operator overload call is interpreted as a member call, so the first operand cannot be im...
3,612,666
3,612,834
Android and C++: Necessary?
Just checking out Android development very superficially, and it seems that most everyone is working in Java. Yet Android includes a set of C/C++ libraries used by various components of the Android system. These capabilities are exposed to developers through the Android application framework. does this mean...
Sometimes. As least as possible, only for time-sensitive code, and even then it might not be a good solution. The standard way to make Android apps is Java. This is because the Java code will truly be cross-platform and will work virtually across all devices. While the ndk is only supported for ARM processors as far ...
3,612,902
3,612,923
extern problems with array of structures c++
I have the main .cpp file with this: #include "stdafx.h" #include "Form1.h" #include <iostream> ... #include <stdio.h> const int MAX_LEN = 1000; struct DataLine { char StartCode; int ByteCount; int Address; int RecType; int DBytes[16]; int Checksum; }; DataLine AllData[MAX_LEN]; Then I ha...
You can't define extern struct DataLine AllData[MAX_LEN]; in the header file because struct DataLine is completely unknown in the header file. No typedef will help you here. The definition of struct DataLine must be present in the header file before you define AllData. Move it there.
3,613,004
3,613,563
STL: set_union, includes, mismatch, find_if but is there no includes_any?
From the title you'd almost assuredly think use set_union to create a list and then check if it's empty. However, the objects I'm comparing are "expensive" to copy. I've looked at includes but that only works if all the items of one list are found in another. I've also looked at mismatch but rejected it for obvious ...
If the sets are unsorted, then you can use find_first_of for an O(N*M) algorithm. If they are sorted (which would be required for set_intersection anyway), then you can iterate over one set calling equal_range in the other for every element. If every returned range is empty, there is no intersection. Performance is O(N...
3,613,065
3,613,179
When to pass by reference and when to pass by pointer in C++?
Common Situations: Passing std::string to a function foo(std::string*) or foo(std::string&); Passing tr1::shared_ptr to a function foo(tr1::shared_ptr* ptr) or foo(tr1::shared_ptr& ptr); In general, what is a good practice. I always get confused. At first, passing everything as references seems consistent, however it...
References are easier to get right. Is your problem with literals that you aren't using const references? You can't bind a temporary (produced by a literal) to a non-const reference, because it makes no sense to change one. You can bind one to a const reference. In particular, when passing an argument to a function, ...
3,613,149
3,614,105
How can my program switch from ASCII to Unicode?
I want to write a program in C++ that should work on Unix and Windows. This program should be able to use both: the Unicode and non Unicode environments. Its behavior should depend only on the environment settings. One of the nice features that I want to have, is to manipulate file names read from directories. These ca...
I want to write a program in C++ that should work on Unix and Windows. First, make sure you understand the difference between how Unix supports Unicode and how Windows supports Unicode. In the pre-Unicode days, both platforms were similar in that each locale had its own preferred character encodings. Strings were ...
3,613,284
3,613,424
c++ std::string to boolean
I am currently reading from an ini file with a key/value pair. i.e. isValid = true When get the key/value pair I need to convert a string of 'true' to a bool. Without using boost what would be the best way to do this? I know I can so a string compare on the value ("true", "false") but I would like to do the conversi...
Another solution would be to use tolower() to get a lower-case version of the string and then compare or use string-streams: #include <sstream> #include <string> #include <iomanip> #include <algorithm> #include <cctype> bool to_bool(std::string str) { std::transform(str.begin(), str.end(), str.begin(), ::tolower);...
3,613,369
3,613,391
What is the Equivalent of Windows WMI for MacOS C++ Development?
I have a C++ application that gets detailed system information (processor type, available disk space, other hardware profile info) on Windows using WMI. I want to perform the same type of operations on OSX 10.5+. What is the equivalent API or interface for MacOS? Links to API documentation or tutorials are very welco...
You can query most of that information through the system_profiler executable. Apple's example for querying such informations involves a popen call to it, so I guess it's the way to go.
3,613,491
3,613,550
C++ COM design. Composition vs multiple inheritance
I'm trying to embed a browser control in my application (IWebBrowser2). I need to implement IDispatch, IDocHostShowUI, IDocHostUIHandler etc to make this work. I am doing this in pure C++/Win32 api. I'm not using ATL, MFC or any other framework. I have a main class, called TWebf, that creates a Win32 window to put the ...
Multiple inheritance is a very common way to do COM interfaces, so yes it's possible. However QueryInterface must still cast the pointer for each interface. One interesting property of multiple inheritance is that the pointer may get adjusted for each class type - a pointer to IDispatch won't have the same value as a p...
3,613,590
3,636,361
Const pointer argument to a method which delegates to removeAll()
Consider a method like this: void Parent::removeChild(Child *child) { children.removeAll(child); } In this case, since child is never modified itself, one could make it a const pointer. But since children is of the type QList, the removeAll() takes a const reference to a non-const pointer. What's the recommended w...
Tricky one. You should have added some more code, but from the docs I assume that you have a QList<Child*> and cannot change it to a QList<const Child*> because you need to access the actual objects in a non-const manner. Since all the removeAll() function does is to remove the entry in the list and it in no way modifi...
3,614,066
3,614,132
write time on FTP server is very off
im trying to compare file write times between a local file and a file on an ftp server. the file times on the local machine work and it makes sense, but when I look at the file on the ftp server it shows two different times, via windows explorer and rightclick->properties. I found out a hack that works and its commente...
SystemTimeToTzSpecificLocalTime( NULL, &stUTC1, &ftpFileWriteTime ) That doesn't work. You'd have to pass the time zone in which the server lives, not your own time zone. Assuming that the server even sends UTC time stamps, that wasn't common the last time I gave up on it. Finding out what timezone it lives in oug...