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
6,575,448
6,575,474
When reassigning variable, the destructor is not called.. (C++)
When a variable is reassigned, the destructor is not called: Object foo = Object(a,b); foo = Object(c,d); so, the destructor will only be called at the end of the scope for Object(c,d), which can obviously cause problems. Now, in this specific case it doesn't bother me too much: it is enough to declare 2 different ob...
"the destructor will only be called at the end of the scope for Object(c,d)" False. Object(c,d) is a temporary, and its destructor is called at the end of the full-expression which creates it. In this case, that's the semi-colon at the end of foo = Object(c,d);. The destructor of foo is called at end-of-scope. The assi...
6,575,680
6,575,855
Traversing a non-STL linked-list in C++, possible?
Let's say I'm using a non-standard linked-list class, List.h. This class is functioning, template'd and has the typical features of add/remove to front and add/remove to back, isEmpty(), etc. This list does not have any begin() and end() functionality. Also, does a linked-list class have to include iterator functionali...
Your list seems to have 2 ways of iterating it (forwards and backwards) List<int>deposits; .. add stuff: int o; int sum = 0; while(deposits.removeFromFront(o)) { sum+=o; } The bad thing though, is that iterating it, you also destroy the list, you could provide public accessors to List::firstPtr and ListNode::nextPt...
6,575,768
6,576,026
How I use only Asio of Boost Library?
how I use only the Asio of Boost Library without adding any other library? Is that possible? In the Boost, don't have the folder called "lib" with the *.a files?
Asio exists as as standalone library, entirely independent of Boost (this is the "original"). No need to search together the bits from Boost subdirectories if you don't want to use Boost, just download Asio and use that. :-)
6,575,786
6,576,058
How to return bottom element of stack in C++?
I'm trying to add an additional method to my 'stack' class that will return the bottom element in the stack. However.. I'm just having trouble wrapping my head around this one. This is the code I have so far in my stack.cpp, but it's not working correctly: bool Stack::bot(StackItemType& stackBottom){ if (isEmpty()) r...
Have you considered using another data structure. A stack really isn't meant to do this. However, I'm not going to be a doochebag and not answer you question. At first glance, your code is logically sound, assuming you're implementing your stack with a linked list and adding to it pushes an element at the head of the...
6,575,791
6,575,817
What is the correct way of using extern for global variables?
file a.cc int a = 0; file b.cc #include "a.cc" file main.cc #include "b.cc" extern int a; int main() { } g++ -c a.cc g++ -c b.cc g++ main.cc a.o b.o error: multiple definitions of a What am I doing wrong here?
You include a .cc (or .cpp) files, which is wrong. Do not do that. You need a header, and in that put the extern int a;: // a.h // include guards omitted extern int a; // a.cc #include "a.h" int a; // b.cc #include "a.h" // main.cc #include "a.h" int main(){ // use a }
6,575,966
6,576,087
Why are the STL functors themselves templated and not their function call operator?
The STL functors are implemented like this: template<class T> struct less{ bool operator()(T const& lhs, T const& rhs){ return lhs < rhs; } }; This makes us mention the (possibly long) type everytime we create such a functor. Why are they not implemented like shown below? Any reasons? struct less{ template<c...
It would also make it impossible to specialize them for user defined types. They are supposed to be a customization point. To summarize the discussions in the comments: Although it is technically possible to do like Xeo suggests, the language standard doesn't allow it. It is very hard to write a working class templa...
6,575,993
6,576,016
C++ help with STL - sort() function
Another small question about STL: i have Dictionary: map <string,vector <Wordy> > Dictionary; using structure Wordy: struct Wordy{ int count; string word;} also this structure have overloaded operator< bool operator< (Wordy& One, Wordy& Two){return One.count<Two.count;} but this sort() function from algorithm doesn'...
Your operator< should take its parameters by reference-to-const, I think that might be it: bool operator< (const Wordy& One, const Wordy& Two){return One.count<Two.count;} // ^^^^^ ^^^^^
6,576,036
6,576,053
Initialise Global <Key, Value> Hash
I want to intialise a QHash as a global variable. Because it's global I can't write something like QHash<QString, int> MY_HASH; MY_HASH["one"] = 1; MY_HASH["two"] = 2; But I'm not sure how I would assign values to MY_HASH in its intialisation.
Make a function? typedef QHash<QString, int> hash_type hash_type InitMyHash(){ hash_type hash; hash["one"] = 1; hash["two"] = 2; // ... return hash; } hash_type MY_HASH = InitMyHash();
6,576,109
6,576,135
Initialising reference in constructor C++
I don't think is a duplicate question. There are similar ones but they're not helping me solve my problem. According to this, the following is valid in C++: class c { public: int& i; }; However, when I do this, I get the following error: error: uninitialized reference member 'c::i' How can I initialise successful...
There is no such thing as an "empty reference". You have to provide a reference at object initialization. Put it in the constructor's base initializer list: class c { public: c(int & a) : i(a) { } int & i; }; An alternative would be i(*new int), but that'd be terrible. Edit: To maybe answer your question, you prob...
6,576,112
6,576,157
Can one write a function which takes a type and returns a different type
Is it possible to write a function that takes a type and returns a (related) type. For instance, a function which take a type called "RandomVariable" and return a type called "RandomVariableCovariance". I guess in general the question is whether typenames can be parameters or return types. C++0x is fine.
You can't do it with functions, but you can do it with template specialisations. For example template <class T> struct ConvertType; template <> struct ConvertType<RandomVariable> { typedef RandomVariableCovariance type; }; int main() { ConvertType<RandomVariable>::type myVar; } Defines a type ConvertType wh...
6,576,221
6,576,349
Is there a container facade in Boost?
I'm learning how to use iterator_facade to hide some boilerplate of iterator implementation. In my current use case I'm wrapping another container (from .NET code, actually) so I need the begin(), end(), typedefs, etc. At a minimum I want the resulting type to work with BOOST_FOREACH. Is there a convenient thing in boo...
I would wrap a pair of iterators from the given container in a boost::iterator_range from the Boost.Range library.
6,576,307
6,576,324
How to declare global variable in this situation?
Possible Duplicate: What is the correct way of using extern for global variables ? Sorry for repeating a similar question. //object.h object p; //b.h #include object.h //b.cc extern object p; //c.h #include object.h #include b.h //c.cc extern object p; //main.cc #include c.h extern object p; int main() {}...
Declare the global variable in just one of the .cc files. Put its extern declaration in the corresponding .h file, and then include that file in every other .cc that needs to access the global variable. In that way, the variable will be declared in every .cc (thanks to the extern declaration #included from the .h), but...
6,576,333
6,582,706
Joining RTP multicast from the source
This computer is taking SDI video as input and giving RTP stream as output. There is no problem joining this rtp multicast from another computer on the same network but if I run my software on the SDI to RTP machine, I can't get any packets. There is no problem joining multicast but it acts like there are no packets. ...
For jrtplib you need to set acceptOwnPackets before creating a session RTPSessionParams rtp_sp; rtp_sp.SetAcceptOwnPackets( TRUE );
6,576,643
6,576,755
Help with design issue
Here is my problem. I'm using a physics library called Box2D. I'm able to hook up a listener that will tell me when 2 fixtures collide. Essentially the way Box2D works is by creating b2Bodies. Therefore, I only know which b2Body the fixture that collided belongs to. In my game, I have an Entity, and from that I have a ...
This is exactly the purpose that fields like that userData field are for — to refer to your application's data related to the library's object. This is an entirely appropriate use of void *. If you were asking about C, I would say that you should also not have to use any casts, as converting to and from void * can be d...
6,576,757
6,576,824
how do I create a functioning vector<wchar_t> that has an erase(size_t pos) method?
I am creating a C++ wstring class for use with mingw version 4.3.0, cross-compiling for Win32. I want my string to work like std::string which means that I want an erase(int pos) method that erases a single element at position pos. Here is my first attempt: #include <wchar.h> #include <iostream> #include <vector> clas...
The answer to your particular question is to use std::vector<T>::erase( iterator ) instead of remove: std::vector<int> v; v.push_back( 1 ); v.push_back( 2 ); v.push_back( 3 ); v.erase( v.begin()+1 ); // equivalent to v.remove( 1 ) But I don't think that you are barking at the right tree. There is already a std::wstrin...
6,576,769
6,577,088
Lua pattern matching for extracting hard coded strings in code base
I'm working with a C++ code base. Right now I'm using a C++ code calling lua script to look through the entire code base and hopefully return a list of all of the strings which are used in the program. The strings in question are always preceded by a JUCE macro called TRANS. Here are some examples which should extract ...
In the second case, you forgot to escape parentheses. Try for word in string.gmatch(str, 'TRANS%s*%(%s*(%b"")%s*%)') do print(word) end
6,576,803
6,579,011
Generating 32-bit/64-bit Eclipse CDT projects using CMake
I'm setting up a C++ project which will be built for 32-bit and 64-bit versions of Windows and Ubuntu. I'm using CMake 2.8.4 and, after having played with it for a few hours, got the VS2010 32-bit and 64-bit projects set up. The problem I ran into is that the generator for Eclipse on the Ubuntu side (technically for ...
Under Linux CMake looks at the compiler flags to determine if you are compiling for 32-bit or 64-bit. You can pass that information by setting the CMAKE_C_FLAGS and CMAKE_CXX_FLAGS information upon running cmake: cmake -G "Eclipse CDT4 - Unix Makefiles" -DCMAKE_C_FLAGS=-m32 -DCMAKE_CXX_FLAGS=-m32 The portable way to d...
6,576,813
6,581,024
C++: Implementing Row Iterator for Table
I have a generic table class implemented in C++ that uses a shared_ptr< ptr_vector< vector<T> > > as its backing, where T is an arbitrary typename; the ptr_vector contains pointers to the vectors corresponding to the columns in the table. I decided to wrap the ptr_vector in a shared_ptr since the tables may contain man...
The Boost library has a container called multi_array which provides and n-dimensional dynamic array which can be accessed and manipulated along each dimension. This seems to be very similar to what you are trying to build, perhaps you could use it instead?
6,577,166
6,577,463
Is it worth implementing C++ code through JNI in this application?
I'm developing a server application, and would like to harness the flexibility and (possible) speed increases C++ has to offer, by implementing the network code in C++. However, the base application has to be written in Java. I'm aware of the possible reliability and debugging impact implementing JNI-code might have on...
No, it will not be worth it for the reasons you mentioned (related to overhead) and without getting into any c++/java wars about performance, there wouldn't be enough of it (performance) to impact the throughput of client/server type of calls. In most client/server type of applications, the movement of data across th...
6,577,188
6,590,664
SVD to solve harwell-boeing sparse a.x=b system in C/C++?
Does anybody know of a sparse SVD solver for c++? My problem involves some badly conditioned matrices that might have zeroed columns/rows. My data is stored in a uBLAS matrix which is the Harwell-Boeing sparse format. I am having some trouble finding: The SVD solver The SVD solver that can operate on sparse matrices....
SVDLIBC is a C library with partial support for the Harwell-Boeing format. I am not familiar with the library, but on the surface it seems to match your requirements.
6,577,222
6,577,233
c++ sprintf function and fstream to create/check a text file
I am having some trouble with sprintf and fstream functions in order to create new text files for a POS program/check whether the file already exists. I don't know if i am doing something wrong because the same set of functions works fine in other places in my code... This particular section of code is taking input fro...
You seem to be opening the file for reading, but you need to open it for writing. Instead of "rt" use "wt" in fopen_s()
6,577,504
6,577,545
Is there any difference between && and & with bool(s)?
In C++, is there any difference between doing && (logical) and & (bitwise) between bool(s)? bool val1 = foo(); bool val2 = bar(); bool case1 = val1 & val2; bool case2 = val1 && val2; Are case1 and case2 identical or if not how exactly do they vary and why would one choose one over the other? Is a bitwise and of bools...
The standard guarantees that false converts to zero and true converts to one as integers: 4.7 Integral conversions ... If the destination type is bool, see 4.12. If the source type is bool, the value false is converted to zero and the value true is converted to one. So the effect in the example you give is guaranteed...
6,577,561
6,577,588
Error reading float values
I'm trying to make a very simple program that will first read an integer N, after that it will read N datas, which are floats, and just put them back in the screen with 2 digits after the decimal point. It's very simple, right? But it went wrong! Here is the source code : #include<cstdio> int main() { float d; int...
Primitive floating-point types do not have unlimited precision. There are some values that cannot be represented exactly, as you are seeing. You can mitigate this problem somewhat by using double instead of float, but for large enough values you will still see the same issue. Other, more robust solutions include us...
6,577,784
6,577,844
Combining two std::lists of differing types: Possible?
I have a std::list of type Foo* and another of type Bar* of unequal size. Both types implement a positioning system that allows the list to be sorted by z-coordinate for draw order (really just a Point with x, y, z values with them being sorted with a less than Predicate function by z value). Other than the above menti...
You might try having both types inherit from a base that includes the position, perhaps with a virtual Draw(): struct Base { Point pos; virtual ~Base() {} virtual void Draw() = 0; }; struct Foo : base {}; struct Bar : base {}; std::list<Base*> list; //... list.sort([](Base *left, Base *right) { ret...
6,577,849
6,577,921
Using pragma intrinsic(sqrt, pow) in C#?
C++ Summary Using the #pragma intrinsic command in the preprocessor section of your code will greatly increase the speed of most math function calls. #pragma intrinsic(sqrt, pow) The above code allows most math functions calls to be sent directly to the math co-processor rather than being sent to the function stack. Q...
C# shouldn't need "#pragma intrinsic", because: Accessing math coprocessor from C# The JIT compiler knows about the math coprocessor and will use it.
6,577,906
6,578,021
Is size of the object affected by type of access-specifier and type of inheritance?
While answering one of the question, there was a discussion thread below my answer. Which suggests that depending on the access specifier (or may be the type of inheritance) private/protected/public the sizeof the class object may vary! I still don't understand from their brief discussion, how is that possible ?
Note new language for C++11 below In C++03, there is language that makes this possible, 9.2 [class.mem]/12 (emphasis mine): Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of alloca...
6,578,048
6,578,058
size_t vs int warning
I am getting following warning always for following type of code. std::vector v; for ( int i = 0; i < v.size(); i++) { } warning C4267: 'initializing' : conversion from 'size_t' to 'int', possible loss of data I understand that size() returns size_t, just wanted to know is this safe to ignore this warning or should I ...
If you might need to hold more than INT_MAX items in your vector, use size_t. In most cases, it doesn't really matter, but I use size_t just to make the warning go away. Better yet, use iterators: for( auto it = v.begin(); it != v.end(); ++it ) (If your compiler doesn't support C++11, use std::vector<whatever>::itera...
6,578,147
6,578,163
C++: Reserve capacity for a std::vector, which is inside another container
I have following requirement, std::vector< std::vector < std::string > > segments; There are unknown number of segments, but each segment is of fixed size say 1000. But, I am not able to figure out how do I declare variable segments with my requirements. I tried std::vector< std::vector < std::string >(1000) > segm...
You can't. You have to loop through and call reserve manually. (And for that matter there are no vectors inside segments yet.. how could reserve space in a nonexistent vector? :) )
6,578,258
6,578,306
Undefined Symbols with Python.h
I'm trying to embed a Python script into a C++ application. Before I do such a thing though, I'm trying to run the example script. Here's my code: #include <Python/Python.h> int main(int argc, char *argv[]) { Py_Initialize(); PyRun_SimpleString("from time import time,ctime\n" "print 'Today is',ctime(...
You need to link to the python libraries, e.g. libpython.a for static linkage.
6,578,339
6,579,183
using hashmark in program options value (ini file)
I have some trouble reading from an ini file using boost program options. The problem is a key which contains hashmarks (simplyfied example): [section] key="xxx#yyy" Retrieving the key, returns "xxx", which is because the hashmark seems to be interpreted as start of a comment and therefore the rest of the line is skipp...
Perhaps it is time to start using Boost Property Tree as you are way past the 'I'm parsing program options' point here, really. http://www.boost.org/doc/libs/1_46_1/doc/html/property_tree.html Property tree has parsers/formatters for JSON, Xml, Ini (<-- you are here) and the INFO formats. The linked page specifies in a...
6,578,383
6,589,422
Repaint issues when switching between programs
MyApp (.NET c#) is triggered by OtherApp (c++). When triggered my app takes over the whole screen and gives the user two options. One option quits MyApp and returns to the OtherApp home screen. The 2nd option exits the intial screen and shows another screen for user input - after input it exits and returns to the Othe...
Try and get the hwnd of OtherApp's main window and invalidate the whole thing: [DllImport("user32.dll")] static extern bool InvalidateRect(IntPtr hWnd, IntPtr lpRect, bool bErase); [DllImport("user32.dll", SetLastError = true)] static extern IntPtr FindWindow(string lpClassName, string lpWindowName); static void Inva...
6,578,600
6,578,661
How to compile sqlite with ICU?
I downloaded sqlite from http://www.sqlite.org/sqlite-autoconf-3070701.tar.gz How can I compile sqlite with icu ?
1) You can compile it as dynamic extension of SQLite Citing http://www.sqlite.org/cvstrac/fileview?f=sqlite/ext/icu/README.txt The easiest way to compile and use the ICU extension is to build and use it as a dynamically loadable SQLite extension. To do this using gcc on *nix: gcc -shared icu.c `icu-config --c...
6,578,668
6,578,830
a Unhandled exception :Access violation reading location 0x00000004
I get this error in the debugging mode when i first encounter the marked line in the code below #include<fstream> #include<iostream> #include<math.h> #include<string> using namespace std; int main() {int t,i,j,k,n,g[100],w[100],opp[100]; float rpi[100],wp[100],owp[100],oowp[100]; char s[100][100]; ifstream ip; ip.ope...
You don't need to use memset for the 1D arrays. For example int g[100] = {0}; will work. For the 2D array, loop through using a for loop and set each element to '.', or stick with the memset for that step. In terms of your actual problem, you may need to use ip.get() to read character by character instead.
6,578,717
6,579,463
Return by reference in c++
#include<iostream> using namespace std; int& add() { static int a; a++; cout<<"\na="<<a; return a; } int main { int x,y,m; int &z = add(); //it behaves as a reference to "a" which is a static variable x=add();//why does it work correctly y=add();//why does it work correctly z++; m=...
A reference is another name, an alias, for some object. It acts like if it was the object. When add() returns a reference to a, it behaves like if the returned value was a. So the code x = add(); behaves like it had been a++; x = a; So it captures the value a has at that moment. On the other hand, the code int& z = a...
6,578,739
6,579,012
How do I terminate a process started with _spawnl() in a C/C++ Win32 program?
In pseudocode... processHandle = _spawnl(_P_NOWAIT, "foo.exe", ...); /* time passes... */ WossnameKillFunction(processHandle);
There is no terminate counterpart to the VC++ function _spawnl(), but it does return a Win32 HANDLE that you can use: HANDLE handle = (HANDLE)_spawnl(...); TerminateProcess(handle, exit_code); Note it only returns a HANDLE if you call it with one of the NOWAIT args. If not, it will return the process's exit code. Of ...
6,578,841
6,578,867
Compare 4 variables to find the lowest C++
I want to find the lowest number of the four, but this looks kinda wierd , isnt there a smarter and shorter way to do it? That is what I have: int findlowest(int one, int two, int three, int four) { int output = one //as of now , we will be outputting one , except if we find a lower score. if(output > two) { ou...
std::min(a, std::min(b, std::min(c, d))); Include <algorithm>.
6,578,985
6,579,027
Template function having its caller's context?
Consider the following code snippet. template <T> MyPtr<T> CreateObject() { // Do something here first... // return our new object return MyPtr<T>(new T()); } class Foo { private: Foo() { } public: static MyPtr<Foo> GetNewInstance() { // ERROR: Foo is private... return Create...
This is basically the same as attempting to use make_shared with a private constructor. The only way to allow this is with friend. You're pretty much stuck in this case I'm afraid.
6,579,217
6,579,500
Generic Log Parser Algorithm
My Application when running is writing logs. Now I need to check whether indexing is completed or not by checking for a status message as to whether it's written in logs or not (note that logging is going on dynamically and the process is running). My application is not sending a signal as to when it has completed the ...
Polling is the usual solution. Other solutions require the collaboration of the generating process in some way; if this is possible, it's obviously a preferable solution, but if the generating process is to remain unaware of the listener (in the sense of not knowing about its existance), then polling is about the only...
6,579,516
30,723,889
Qt Creator: how to tell win32 from win64
I have to do something like this in a .pro file: win32 { LIBS += -L../3rdparty/libusb-win32/lib/msvc -llibusb } else win64 { LIBS += -L../3rdparty/libusb-win32/lib/msvc_x64 -llibusb } The problem is it doesn't work, it always links win32 library. Any suggestions?
You can use QT_ARCH variable to detect whether your configuration is 32 or 64 : contains(QT_ARCH, i386) { message("32-bit") }else { message("64-bit") } When the target is 32-bit, the variable returns i386 and in case of a 64-bit target it has the value of x86_64.
6,579,535
6,587,684
How to embedd openCV Dll's in Executable
I wrote an image matching tool (console application, without gui or windows), using openCV. I want to port my EXE file to another computer but it asks for opencv dlls (opencv_core220.dll, opencv_highgui220.dll, ...) My question is how to do it. I see two ways any of them is good: Recompile opencv as static library (....
I found an answer. You must open the original openCV project and recompile all the relevant parts in static library mode. Do it for each project starting from libjasper and alphabetically until opencv_video. Also do the same for zlib project For each project, go to project properties\configuration properties\general\...
6,579,563
6,581,723
Serialize mpi threads
Is there anyway to serialize a certain part of your MPI code ? For example when printing the information out to the screen. Something like below: MPI_SERIALIZE(); cerr << "THIS WILL BE PRINTED "; cerr << "IN ORDER" << endl; MPI_END_SERILIZE(); If there are two MPI threads, there will be no case : THIS WILL BE PRINTE...
The way I do this in demonstration programs (and note - you would only do this in little demo programs because of the high synchronization cost; if you're trying to control output to a data file, you'd use MPI-IO, and if you're trying to coordinate output to the terminal, easiest to send data to task 0 and have it do a...
6,579,600
6,582,243
setDIbitstodevice Turbo C++
The program I have uses setDIbitstodevice for the camera. I see that the code is written as: SetDIBitsToDevice( PaintBox->Canvas->Handle, 0, 0, 160, 120, 0, 0, 0, 120, Image, ( LPBITMAPINFO )&mapHead, DIB_RGB_COLORS ); And: Image = new unsigned char [ 160 * 120 * 4 ] I do not know what does it mean. I wa...
unsigned char has size of a byte in turbo C++, so the 'Image = new... ' line is assigning some memory to Image, which is 160 pixels wide, by 120 pixels high , and 4 bytes deep. The 4 bytes will be one byte each for red, green, blue and alpha channel (although these don't support an alpha channel so I don't think that's...
6,580,041
6,580,164
Instance of c++ class
In the below code what does "a" and "&a" contains? class list{ }; int main(){ list *a= new list(); cout<<"\n Values:a="<<a<<" & &a="<<&a<<endl; return 0; }
a is a pointer to the object list which is allocated on heap. basically a contains an address(pointer stores an address,if you are aware). And &a does not contain anything.what you are doing is actually taking the address of that pointer and printing it.
6,580,124
6,580,258
How can I cause the compiler to issue an error for classes that define the method body when using the __interface keyword?
After reading this article: Using Interfaces in C++ I have decided to use the __interface keyword with a macro that will add virtual destructors as described in the above link. I was happy that the __interface keyword will cause the compiler to enforce interface rules, but I was disappointed when I took it for a test d...
__interface is a microsoft specific extension. It's not standard and not portable. Also, C++ allows for pure virtual method to have function body. class Base { virtual void foo () = 0; }; void Base::foo () { } // ok It's advisable to explicitly declare virtual destructor in the class body.
6,580,315
6,580,506
C++/ATL. Best practice to concatenate binary and text data
I have to create BYTE* array that will store some text and binary data for Http request. Something like: Content-Type: multipart/form-data; boundary=Asrf456BGe4h --Asrf456BGe4h Content-Disposition: form-data; name="DestAddress" ... --Asrf456BGe4h Content-Disposition: form-data; name="AttachedFile1"; filename="photo.jp...
First, you can put raw data into an std::string with no risk of any problems occurring. It may confuse the reader, who expects std::string to contain text, but in specific cases (and inserting raw data into an HTTP response could be a valid example), it is justified. For the second, I'm not sure what you mean by "trun...
6,580,324
6,580,558
2 simple variable initialization question
Possible Duplicate: Is there a difference in C++ between copy initialization and direct initialization? Is there any difference between, int x(5); int x = 5; & What's the difference between, int const x(5); const int x(5);
A really good rule of thumb regarding const: Read Declarations Right-to-Left. (see Vandevoorde/Josutiss "C++ Templates: The Complete Guide") E.g.: int const x; // x is a constant int const int x; // x is an int which is const // easy. the rule becomes really useful in the following: int const * const p; // p is co...
6,580,526
6,580,652
C++ Fixed size container with swappable elements
I'm searching for a container with the following functionality: Fixed size at runtime. Thus, memory shouldn't be allocated in little chunks (like std::list does). Elements should be swappable (Something like std::list::splice offers). EDIT: Thinking of a list: I just need to move elements from an arbitrary position t...
It's not too clear to me what you are looking for. Two solutions come to mind: std::vector (created with the maximum size), coupled with a good implementation of swap for your objects, or a custom allocator for std::list, which pre-allocates the number of nodes you'll need in a single block.
6,580,685
6,580,733
What is MSVCP100D.dll?
Possible Duplicate: Application has failed to start because MSVCP100D.dll was not found, reinstalling app may help… I compiled my program using Microsoft visual C++ 2010 Express Edition and tried to run it on another machine that did not have the same compiler. As I double clicked it, and there was message saying MS...
This is the C++ runtime library dll. You've used the debug version, which won't be found in a user's computer. Compile your program in release mode. This will add a dependency in MSVCP100.dll, which is most likely to be present. In any case, you must make sure that the dll will be present in user's machine. You can do ...
6,580,947
6,581,375
Error: wrong number of arguments specified for ‘constructor’ attribute
Before the actual implementation, i wrote a small prototype code, and put a class constructor and ctor constructor in the same file, to see if the ctor would execute first, which is my actual implementation. However, i am facing an error. Here is the code: #include <stdlib.h> #include <string.h> #include <stdio.h> #inc...
Compiling your program as is yields: warning: constructor priorities from 0 to 100 are reserved for the implementation Changing the priority from 1 to 101 gets rid of the warning and the executable produces: Start me called before main This is test constructor Now main called Destructor called This is using GCC 4...
6,581,057
6,581,094
= operator in function prototype
Possible Duplicate: Pure virtual functions may not have an inline definition. Why? I've come accross a function prototype that looks like this: virtual void functionName(const int x) = 0; what does that =0 exactly mean?
This denotes purely virtual (abstract) function. Class containing such function is automatically abstract and any class deriving from it you want to instantiate must implement this function.
6,581,175
6,581,332
C++ text file based database read
I need simple program in C++ that will open text file and going line by line find second argument by knowing first in list. Content of text file: 1, red 2, blue 3, green 4, orange So I need a program that will go line by line and each line turn into array ( of two elements ) and then compare first element with user in...
Q1: How do you open text file in C++ ? Q2: How do you read file line by line? C++ Input/Output with files Q3: How do you turn string with "," into array based on that delimiter? How to split a string in C++?
6,581,221
6,581,664
C++ application and hardware communication
The problem is mostly OOP design problem. I have a class which handles the connection and communication with hardware (Let's say via USB) - CommClass. It has few methods - connect(), disconnect(), read(), write(). The application itself has few other classes that want to communicate with the same HW trough CommClass. T...
If you expect to have a single connection to the device (let's say a USB device) then it makes sense to have one single instance of your CommClass or ICommClass if you want to have a more elegant design and work with an Interface that is implemented by your CommClass. You can also wrap the connection (class or interfac...
6,581,293
6,581,710
Segfault with stringstream
This is my function: string GaugeStr; void someFunction() { float pie = someFloat(); stringstream ss (stringstream::in | stringstream::out); ss << pie; GaugeStr = ss.str(); } When I run the function, it works properly. When I call it however for a second time (someFunction(); someFunction();, then my p...
@Bo spotted a good line (after the question was edited...). I agree. Here is a suggestion to fix it: GaugeWid.clear(); std::copy(GaugeStr.begin(), GaugeStr.end(), std::back_inserter(GaugeWid)); @kongr45gpen: I suspect a threading bug: you are doing updates of a variable names GaugeStr (sounds like meter monitoring) ...
6,581,521
6,581,625
Linking static library with gnu g++, No such file or directory
I'm writing a software that depends on the Poco c++ library. I can manage to compile the library on both Ubuntu and Windows, but only as static. That's fine since I want to use it statically. However, when I try to compile the program that depends on the libraries, I get an error similar to this (freely translated) : P...
This is very common error, I, too, suffer from it every now and then. Did you include the .a to your project? How do you include the headers? with <> or ""? If the latter, make sure the files are in your include folder. If first, make sure you have added the path to the files, or that they reside in g++'s global incl...
6,581,667
6,705,131
EXTRA_DIST for Makefile.am repeats the directory name
I'm using EXTRA_DIST within a Makefile.am to copy some folders: EXTRA_DIST = input/ The problem is that it repeats the directory name input/input/ Do you know any solution for this problem? is this a bug of automake?
I have found the solution. With: "EXTRA_DIST = input" instead of "EXTRA_DIST = input/" works fine
6,581,858
6,582,221
How to create and communicate with a C++ Windows Service in Visual Studio 2010?
I have a (kind of) database implemented in C++. Now I want to create a Windows service for querying it, because P-invoking it is not an option, as the database would have to be loaded with every query, which takes several minutes. But I face several problems: How can I create a C++ Windows Service in VS2010? The templ...
I don't know why, but the template is really gone. For communicating between your application and the service WCF would be an option. One advantage of WCF is, that you can easily switch the transport layer (HTTP, TCP, Shared Memory) Have a look at this MSDN page. It describes exactly what you are trying to achieve: Ho...
6,581,895
6,582,035
How to use sqlite icu in like query
hi I modified my sql statement as CREATE VIRTUAL TABLE [v_fts] USING fts4 ( [title], tokenize=icu )" But when I am trying to insert data I am getting error SQL logic error or missing database Edit I had compiled sqlite with icu option using -DSQLITE_ENABLE_ICU option. how to load icu ? I had uploaded shell code...
According to the full text search documentation you should use tokenize=icu en_US for example (specify an ICU locale identifier). Also, you should have ICU loaded.
6,581,968
6,582,061
auto_ptr and dynamic_pointer_cast
If I wish to use dynamic_cast with a shared_ptr I can use dynamic_pointer_cast. What do I use if I wish to cast an auto_ptr? I'm assuming something that would look like below. struct B : A { }; ... auto_ptr<A> base( ... ); auto_ptr<B> derive = dynamic_pointer_cast<B>(base); I'm using boost for shared_ptr's
auto_ptr<A> base( ... ); if(B* query = dynamic_cast<B>(base.get())) { // take ownership base.release(); auto_ptr<B> derived(query); // use and/or pass derived around here // ... } else { // no dice: leave base as owner } Since you're already doing that, then refactor it, slap it in the namesp...
6,581,977
6,583,703
Programmatically creating/deleting tasks for task scheduler
I'm trying to create a task (via C++) that should be executed with highest privileges, although I cannot see in the docs for Task Scheduler how to set that flag (which is available via the Task Scheduler UI). Ideas ?
It's the ITaskDefinition::Principal property. Set RunLevel in IPrincipal to TASK_RUNLEVEL_HIGHEST.
6,581,998
6,582,188
Factory Pattern in C++: generating explicit createInstance()-Method automatically
i have the problem in writing a C++ framework, that users should have less overhead than possible to use it. Users can publish their work to the frameworks by creating a shared library that contains a class, which is derived by a frameworks' BaseClass and implementing an extern "C" createInstance()-method in order to r...
I can't imagine a way to create this automatically without any coding per part of the user. I can imagine ways to simplify it, perhaps using a macro: #define OBJECT_CREATOR(X) \ extern "C" { \ BaseClass *UserXCreateInstance() {\ return new X(); \ }\ } And the user just n...
6,582,000
6,582,065
Executing "Show Desktop" from C++
I am designing a system where the user makes a gesture, then my program captures it (using a web cam) and my program looks in a rule system (based on XML) which are the actions that it has to do. Ok, once I have explained the background, I'd like to know how I could make my program "execute" the Show Desktop button. I'...
From this MSDN blog post (dated 2004 but surely still valid), you must call ToggleDesktop(). in C#: // Create an instance of the shell class Shell32.ShellClass objShel = new Shell32.ShellClass(); // Show the desktop ((Shell32.IShellDispatch4) objShel).ToggleDesktop(); // Restore the desktop ((Shell32.IShellDispatch4) o...
6,582,239
6,582,331
Avoiding virtual methods in constructor
Say I have the following class hierarchy: class Base { virtual int GetClassID(){ return 0;}; public: Base() { SomeSingleton.RegisterThisObject(this->GetClassID()); } class Derived { virtual int GetClassID(){ return 1;}; public: Derived():Base(){}; } Well, it's all simplified from my real case, but that's ...
You might use the Curiously Recurring Template Pattern template <class T> class Base { protected: // note change Base() { SomeSingleton.RegisterThisObject(T::GetClassID()); } class Derived : Base<Derived> { static int GetClassID(){ return 1;}; public: Derived(): Base<Derived>(){}; } Also, it will require ex...
6,582,532
6,583,114
CoCreateInstance fails with error "System can not find the file specified"
I have .NET COM dll which I am trying to load from unmanaged C++ code. I am trying to do CoCreateInstance from my code which fails with the error "System can not find the file specified". (HRESULT value is 0x80070002). Just to see whether there are any problems with the registration of the component , I tried the same ...
COM doesn't normally generate an ERROR_FILE_NOT_FOUND. But the CLR certainly does, common when trying to find a dependent assembly for example. Be sure to run regasm /codebase from the Release build directory. And use Fuslogvw.exe to trace assembly resolution problems.
6,582,580
6,582,621
Pointers, polymorphism and segmentation fault in C++
I have a Parent class with a number of children. Each function in the Parent class is pure i.e. there are no parent implementations of the functions but the children have their own implementations. No need to post code there - standard stuff. I don't want people creating direct instantiations of the parent class from...
You run into undefined behavior: Parent* parent; if(user_input == "A") { Child1 child1; // stack-allocated object parent = &child1; } //child1 is destroyed at this point, the pointer is dangling now you have to use new (preferably with a smart pointer): Parent* parent = 0; if(user_input == "A") { parent = n...
6,582,633
6,696,832
Program freezes when called by script!
I searched everywhere before posting, but couldn't find an answer.. I need to calculate some statistics (Avg, St. Dev., etc.. ) for the execution time of an algorithm, so i have got this c++ program (bb.exe) that launches the algorithm and outputs the comp time. Whenever i launch this program from the shell, it takes i...
The problem was actually the Blackbox.. It was freezing when weird parameters were applied, and i solved it by using some checks on the main program. Thanks to everyone!
6,582,950
6,587,348
Defining trouble. C++
IT'S SIMPLIFIED CODE! I HAVE C++ FILES(WHERE IS IMPLEMENTATION) AND HEADERS FILES(WHERE IS CLASS DEFINITIONS)! I have a file: Foo.cpp that incliudes main.h. And I have file Bar.cpp that uses funcs Foo.cpp and also includes main.h. It uses struct to access Foo object and call it's function. But struct defined in main.h?...
Works for me: $ cat main.h #pragma once class Foo; struct FoobarPackage { FoobarPackage(Foo *fooObj) { soso = fooObj; } Foo *soso; }; $ cat Foo.cpp #pragma once #include "main.h" class Foo { public: void doSomething(bool ololo) { if (ololo) ; //do something else } }; $ cat bar.cpp #p...
6,583,416
6,584,372
Need a simple SNMP library c++
Possible Duplicate: Easy to use SNMP client library for c++? I just started my first programming job, my first task is to research, and eventually implement, a way to collect data about how the user is using the product, and send the data periodically to a host where it can be read and analyzed. I am told the best w...
The de-facto standard implementation is net-snmp, as stated in the comments. I do not know of any C++ wrapper around it. Someone mentioned SNMP/Agent++ and other libs in the linked answers, but I have not tried them ... My two cents
6,583,460
6,583,500
Online Update of a DLL application
I have a plug-in application which is a C++ DLL running inside a (foreign) C++ host. I want to allow online updates of the plug-in. How can I do that? One possible way is to separate the DLL to a wrapper DLL and a content DLL and to move to a new content DLL on each update. Is there any better way to achieve that? Tha...
If you have no control over the host, then you have to do the dynamic load/unload on your own. As you correctly noticed, you will need two DLLs for this. That's probably the easiest way, but you need to make sure that the host cannot do any harm while you are exchanging the DLLs. The simplest solution is probably to lo...
6,583,719
6,583,779
Difference in MultiThread aspect between Java and C/C++
I have read some tips that multithread implementation largely depends on the target OS you are working on. And the OS finally provides the multithread capability. Such as Linux has POSIX standard implementation and windows32 has another way. But I want to know major different in programming language level. C seems to p...
Java does provide read-write locks - http://download.oracle.com/javase/6/docs/api/java/util/concurrent/locks/ReadWriteLock.html. Have a look at the java.util.concurrent package if you haven't already. I suspect Java's support is comparable to C's. There are also a number of web servers written in Java that use either m...
6,583,769
6,583,961
Manipulating a vector of one class inside of 2 functions of another class
This seems to very very complicated, I tried a lot to solve it, but when I resize a private member inside the template/class, i.e., when I call Operator::InitExtVector, I resize intVect through its address, and when I show/call Operator::ShowExtVector its size is 0 again, which should not be happening. Why the vector ...
I think you want to take your vectors in by reference: void InitExtVector(std::vector <Base<float> > & BaseVect); void ShowExtVector(std::vector <Base<float> > & BaseVect); Also, did you mean this in InitExtVector: for(i=0 ; i < BaseVect.size() ; ++i){ pVect=BaseVect[i].dataVect(); pVect->resize(10); }
6,584,190
6,584,367
The value of out-of-bounds element of an array - should it change on each execution or stay the same?
For the actual question, jump to question part. For an interesting real-world example of undefined behavior, keep reading :) There was this enumeration: struct EnumStruct { enum Enum { val0 = 0, val1, val2, val3, val4 }; }; and in some function we had this: const int arrayC...
To the actual question of is memory always 0 at the start? Well, it might depend. In general, when the OS provides you with a page of memory it will be cleared (as a security measure, so that you cannot read the values that any other process had in their memory), so in many cases you will find that uninitialized can lo...
6,584,201
6,607,000
Checking if Debugger is present in c++ dll (loaded in C++/CLI wrapper)
I'm checking if a debugger is present in my c++ dll with method if(IsDebuggerPresent()) // set dll name to debug When I load this dll in my C++/CLI wrapper (debug mode in VS) the method always returns false (release) -> why is it so? (or which code I need to determine this information) Thank you for your help! greets ...
That was the solution: just enable unmanaged debugging ! (msdn.microsoft.com/en-us/library/tdw0c6sf.aspx)
6,584,586
6,585,070
Do "#define" and inline behave the same?
I have some short defines in one of my headers like this: #define ROUND_DOWN(a,b) (a)-(a)%(b) e.g. ROUND_DOWN(178,32) = 160 But if I pass this to it: ROUND_DOWN(160*2, 32); then it gets compiled like this? (160*2)-(160*2)%(32), which is just more processing as it does 160*2 twice.. I'm wondering if inline funct...
Do “#define” and inline behave the same? No they dont! There are a number of differences between a macro and a inline function. - No of times of Evaluation Expressions passed as arguments to inline functions are evaluated once. In some cases, expressions passed as arguments to macros can be evaluated more than once. ...
6,584,590
6,584,718
Using void pointers in calculations
This is quite a long introduction to a simple question, but otherwise there will be questions of the type "Why do you want to handle void pointers in C++? You horrible person!". Which I'd rather (a)void. :) I'm using an C library from which I intially retrieve a list of polygons which it will operate on. The function I...
Given that the pointer is pointing to an "internal identifier" I don't think you can make any assumptions about the actual values stored in it. If the pointer can point into the heap you may be just seeing one possible set of values and it will subtly (or obviously) break in the future. Why not just create a one-time r...
6,584,962
6,585,561
Does Boost.Locale support reading and writing UTF-8 encoded files?
It is the only reason I was excited about trying out Boost.Locale but there are no file I/O examples on the web site. I am not sure if it means file I/O is not supported or suppoted but undocumented. My platform is Windows 7
there is such an example: std::locale loc= generator().generate("he_IL.UTF-8"); std::wofstream file; file.imbue(loc); file.open("hello.txt"); file << L"שלום!" << endl; Also Boost.Serialize can help to convert to UTF8
6,585,077
6,585,121
size_t: an operator? (and a way to use unordered_set)
What is operator size_t () const Environment: Visual Studio 2010 Professional TL; DR Today I was searching for a way to use std::tr1::unordered_set. Because I asked for how to use std::map last time, I decided to find it out myself. I googled and most of the results told me to have a struct to do hashing. The way loo...
It's the type cast operator. Basically provides for implicitly converting the object to the specified type, in this case size_t. EDIT: Say you have a function defined as follows: void Foo( size_t x ) { // do something with x } If your class edge defines the type-cast operator for conversion to size_t you can do the ...
6,585,614
6,592,765
iterator for vector of structures in thrust
I'm trying to get access to vector elements in this manner struct point { unsigned int x; unsigned int y; }; ... thrust::device_vector<point> devPoints(hPoints.begin(), hPoints.end()); for(thrust::device_vector<point>::iterator iter = devPoints.begin(); iter != devPoints.end(); iter++) { std::cout << it...
Ok this one was a bit more complicated than I expected :) Here are the results of my investigations: Your problem comes from thrust's implementation. Thrust uses a type called device_reference which, as its documentation says: http://wiki.thrust.googlecode.com/hg/html/classthrust_1_1device__reference.html device_refer...
6,585,787
6,585,912
getting a const_iterator from iterator
Possible Duplicate: Obtaining const_iterator from iterator I want to write a metafunction which returns the corresponding const_iterator from an iterator template <class Iterator> struct get_const_iterator { typedef ??? type; }; get_const_iterator<int*>::type must be const int* get_const_iterator<const int*>::...
You can do it in C++0x template <typename Container> Container container (typename Container :: iterator); template <typemame Iterator> struct get_const_iterator { typedef decltype (container (Iterator())) :: const_iterator type; }; Although I'm starting to agree with Steve -- this is not a general solution since...
6,585,941
6,586,657
C++/TCL how to invoke tk?
So I want to exequte TCL code inside my programm. I want it to be capable of reaching some of my C++ functions and classes. So I use C++/TCL. All general TCL to C++ binding works fine for me. But now I want to have some little UI on top (so I have lot on general TCL code that interacts with my app and now I want to add...
You haven't said what fails, but this isn't going to work. To have a GUI, you need an event loop. I'd recommend a different approach: make your C++ code into a Tcl-loadable module, then your script can run under wish and use both Tk and your objects implemented in C++.
6,585,977
6,586,299
Times when inline functioning cannot be used
Im studying inline functions in C++ and have come to a section concerning limitations of its use. It says: The compiler also cannot perform inlining if the address of the function is taken implicitly or explicitly. Can someone explain to me, perhaps with an example of some sort, what exactly this means?
There are two somewhat separate decisions the compiler makes concerning function inlining: whether a particular function call is inlined; whether a non-inline version of the function exists. The first is decided by the compiler on a case-by-case basis, if inlining is possible at that point. It won't be possible if th...
6,586,205
6,586,248
What are the pointer-to-member operators ->* and .* in C++?
Yes, I've seen this question and this FAQ, but I still don't understand what ->* and .* mean in C++. Those pages provide information about the operators (such as overloading), but don't seem to explain well what they are. What are ->* and .* in C++, and when do you need to use them as compared to -> and .?
I hope this example will clear things for you //we have a class struct X { void f() {} void g() {} }; typedef void (X::*pointer)(); //ok, let's take a pointer and assign f to it. pointer somePointer = &X::f; //now I want to call somePointer. But for that, I need an object X x; //now I call the member function on...
6,586,240
6,586,306
Which functions are dynamically dispatched?
I've searched for questions, looking at forums, books, etc. I can recognize a polymorphic behavior of methods, and there are lots of simple examples when an invoked method is decided in compile or runtime. But I was confused by this code, where a class C inherits from B that inherits from A: class A { protected: in...
objb->change() calls B::change() because objb contains address of an object of type B objc->change(5); calls C::change(int) because objc contains address of an object of type C The method calling will be still dynamic/run time because the methods B::change() & C::change(int) are still virtual, because the virtual att...
6,587,082
6,587,460
How to use C++/TCL and C++/TK at the same time, in the same program?
So it is great of C++/TCL to provide us with easy manageable in TCL C++ functions and classes via APIs like: #include "cpptcl.h" #include <iostream> #include <string> using namespace std; using namespace Tcl; void hello() { cout << "Hello C++/Tcl!" << endl; } int main() { interpreter i; i.def("hello", he...
You can use UI callbacks to do complicated things, including running other Tcl code: #include "cpptcl.h" #include "cpptk.h" #include <iostream> #include <string> using namespace std; using namespace Tcl; class TclHost { interpreter i; static TclHost* singleton; static void hello() { cout << "Hello C++/Tc...
6,587,105
6,587,322
Can't think of a good name for this customized event class
First, I wrote a class which wraps a Windows API Event (using Wait to wrap WaitForSingleObject, Set() to wrap SetEvent(), etc). I called it CEvent and was satisfied. Now I created a class which extends CEvent, adding the functionality to count how many times the event was set, and expose that value with a getCount() pr...
An old saying is "a class does not do something, it is something". In that context, CEvent might be a good name, but only if an object of the class is an event (which I doubt). I would suggest using EventHandler and CountingEventHandler.
6,587,462
6,589,003
C++ destructors and PTHREAD_CANCEL_ASYNCHRONOUS
Are destructors for automatic objects guaranteed to execute if a thread is cancelled asynchronously?
In theory, it SHOULD work fine, but it's worth testing with your platform. Cancelling a thread eventually ends up invoking pthread_exit(), which as far as I can tell from googling will invoke destructors. It does this by throwing some kind of 'guaranteed uncaught' exception all the way out to the thread wrapper, so all...
6,587,535
6,587,574
How to call original function after it's been overridden in C++?
I serialize most of my classes with two functions, read() and write(). What I would like to do is have the read/write() function of the base class called from the subclasses so that I don't have to repeat the serialization code multiple times. For example: class Base { public: base(); virtual read(QDataStream&); ...
You can call base-class functions by prepending the function call with the base-class identifier, followed by the scope operator (::). Like this: class Base { public: virtual void Function(); } class Foo : public Base { public: void Function(); void DoSomething(); } void Foo::DoSomething() { Base:...
6,587,676
6,588,012
Is random_shuffle threadsafe? and using rand_r if it is not
Is std::random_shuffle threadsafe? I presume not since the regular rand() is not threadsafe. If that is the case, how would I use rand_r with random_shuffle so that I can give each thread a unique seed. I've seen examples of using custom random generators with random_shuffle, but it is still unclear to me. Thanks.
To use rand_r with std::random_shuffle, you'll need to write a (fairly trivial) wrapper. The random number generator you pass to random_shuffle needs to accept a parameter that specifies the range of numbers to be produced, which rand_r does not. Your wrapper would look something like this: class rand_x { unsigned...
6,587,778
6,587,814
Where can I find Video for Windows (VFW)
I am working on a project that uses VFW. I have done Google searches for it, but not exactly sure what I am looking for. I have a few questions about it. Is it a dll? If so, where could I find it? Is it still supported?
It's an almost obsolete technology, originally for Windows 3.1! See Wikipedia article for a start, and then proceed to MSDN page.
6,588,110
6,720,927
Help with Visual Studio debugger visualizer with two dynamic arrays
I'm trying to modify autoexp.dat to write a visualizer and I'm only partly achieving what I want. I have a class (below) where Bar1 and Bar2 are dynamically allocated arrays class Foo { double* Bar1; double* Bar2; int size; } and the visualizer in the [Visualizer] section of autoexp.dat that I've come up with...
Extending the suggestion from @IronMensan, you could use a switch statement to get around the dynamic size limitation, perhaps using a suitable length as the default to avoid the switch getting too long... Foo{ children( #( #([size]: [$c.size]), #( #switch ($c.size) ...
6,588,182
6,592,267
How to look up C function in emacs which does not belongs to a class?
So far, I was able to call member functions which belong to a class for a struct. CEDET can give the suggestion nicely. However, for non-member functions, such as functions in C, which usually does not belong to anything i.e. functions like sort, qsort.... I can only auto-complete with CEDET if I have an instance of a ...
CEDET works fine for such functions - you need to be sure, that all necessary headers are included into your source code. You can also force CEDET to re-parse buffer with M-x bovinate command. But it's better to use CEDET from bzr repository, because fixes for C & C++ mode are made very often. If it still don't worki...
6,588,188
6,589,377
C++ Convert from packed DATE to CTime
I have looked but cannot find the API to convert from DATE to CTime and vice versa. Is there such a thing?
There's probably a shorter method, but going by the docs you can store a DATE in a COleDateTime, get that as a SYSTEMTIME and then use that to construct your CTime. Assuming it's representable as a CTime. SYSTEMTIME st; DATE d(whatever); COleDateTime ole(d); d.GetAsSystemTime(st); CTime ct(st);
6,588,249
6,588,349
DLL without exported functions?
I've snooped around a little bit in MS-Office DLLs, and I noticed that some of the DLLs don't have any exported functions. What I don't quite understand, how an application can use these DLLs without any functions exported ?! I mean, the dllmain() does get executed on LoadLibrary(), but whats the point? Why would anyon...
One way of dealing with versions of a program destined for different languages is to put all of the resources into a language DLL. The DLL doesn't contain any code, just resources that have been translated to a target language. When the main program starts up, all it needs to do is load the proper language DLL.
6,588,299
6,588,492
Failure to compile incomplete types; circular dependencies
Hi am having problems compiling some code, I have a situation where A depends and B depends on A. I have put forward declarations but I keep getting the problems. In file included from src/MemoWriteContext.h:7:0, from src/MemoWriteContext.cpp:1: src/MemoContext.h:29:20: error: field ‘memoWriteContext’...
I think your only problem is that MemoWriteContext.h has #include "MemoContext.h". The context only requires a reference which can use the forward declaration. But if you happen to include MemoWriteContext.h first it will then bring in MemoContext.h before it actually declares class MemoWriteContext. That will then ...
6,588,352
6,588,389
how to used c++ variable inside system ( ) function
I have a .txt file containing 2 columns . I have to search for a pattern in the first column and delete that line from the file that matches . I have to do this inside a c++ program. What are the options I could use ? I though of using a system() function and call sed (which seems efficient). But I'm not sure how to u...
assemble in a std::string and then use c_str(). You might find ostringstream (from sstream header) useful for assembling the string.
6,588,487
6,588,619
Is there a way to iterate over an n-dimensional array (where n is variable) without using recursion?
Is there a way to iterate over an n-dimensional array (where n is variable) without using recursion? I'm using C++ at the moment, but I guess an answer in almost any language would do. EDIT: Actually my real question is a bit different: I actually want to enumerate the indices of the array. Simple 2D example, with a 2x...
void iterate(const std::vector<int> &dims) { std::vector<int> idxs(dims.size()); while (1) { // Print for (int i = 0; i < dims.size(); i++) { std::cout << idxs[i] << " "; } std::cout << "\n"; // Update int j; for (j = 0; j < dims....
6,588,499
6,678,215
How can I send a .msg through gates in omnet?
In order to implement tcp/ip simulation I have for each layer create packets. Since the omnet send function only supports sending cMessage object while I subclassed from cMessage using .msg definitions, I can't find a way to send that packet through a gate without losing data. For example, for the application layer I w...
The .cc and .h files for your AppPacket will be generated automaticaly. You're right about the type that send function takes, but notice, that your class inherits the cMessage object so AppPacket is also a cMessage! Look at the exemplary code which sends custom message from tcpApp: CustomMsg *msg = new CustomMsg("data"...
6,588,578
6,588,886
WPF to crossplatform development, What's the most powerful cross platform UI framework?
So we built a WPF app, now for our next version we need a Mac version as well. Mono obviously jumps to mind, but our app is fairly intensive for the UI. Is there anything cross platform that is remotely close to what WPF gives you for styling your apps? Granted the current app is C#, but if we need to go back to c++ f...
Probably the solution requiring the least effort, while still having a decent UI on Mac OS X, would be to use Monobjc or MonoMac. If you want to be lazy, you can always use GTK#. It comes by default with Mono and has the added benefit that it is also be compatible with Linux.
6,588,875
6,588,892
How to find out if enviroment variable is not set?
So I try char buffer[1000]; GetEnvironmentVariable("PATH",(char*)&buffer,sizeof(buffer)); std::cout << buffer << std::endl; to check if it exists but I do not see how to see if its empty? And It couts some really bad output=(
MSDN has this to say about GetEnvironmentVariable: If the function fails, the return value is zero. If the specified environment variable was not found in the environment block, GetLastError returns ERROR_ENVVAR_NOT_FOUND. (Source: http://msdn.microsoft.com/en-us/library/ms683188.aspx) So I guess you should test the ...
6,589,319
6,589,381
What is the actual meaning of keyword "this"?
I have two questions related to C++: In many textbooks, the keyword this is a pointer to the calling object. Correct? As i like to play with coding, i wrote the following simple code: struct Base { void g(); virtual void f(); }; void Base::f() { cout << "Base::f()" << endl; } void Base::g() { cout <...
void Base::g() { cout << "Base::g()" << endl; cout << "sizeof(*this) : " << sizeof(*this) << endl; this->f(); } The important distinction that needs to be made is that sizeof is a compile-time operator, not a runtime operator. The compiler interprets the expression sizeof(*this) as "the size of the object ...
6,589,356
6,589,389
difference between two array declaration methods c++
These of 2 of the probably many ways of declaring arrays (and allocating memory for them) in c++ 1. int a[3]; 2. int *b = new int[3]; I want to understand how c++ is treating the two differently. a. In both cases, i can access array with the following syntax: a[1] and b[1] b. When i try cout<< a and cout<< b, both pr...
a is an array (type int [3]) b is a pointer (type int*) In C++ they are completely different things. The sizeof an array is the number of elements times the size of each element. The sizeof a pointer is independent of the size of the array (usually 4 or 8 bytes). The only thing that arrays and pointers have in common i...