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,105,635
6,105,692
istream >> ostream << Operator Overloading with * Pointer
How would I overload the >> and << operators if they are dealing with pointers? in header: friend std::istream& operator >>( std::istream& ins, Classname* & e); friend std::ostream& operator <<( std::ostream& outs, const Classname * e); in cpp: std::ostream& operator <<( std::ostream& outs, const Classname * e) { /...
It depends on what is in the class Classname. If for example you have: class Classname { //... private: int a; }; .. then you might do: std::ostream& operator <<( std::ostream& outs, const Classname * e) { outs << e->a; return outs; } std::istream& operator >>( std::istream& ins, Classname* & e){ ins >> e-...
6,105,644
6,111,746
use of XMPP in flex code on UDP Protocol
I am working private network.This alread developped product which implemented using TCP(client server technology). Existing product is as follows There is a UI which is developed using flex, where user can see video or snapshot There is a server which is developed using c++,which redirects request from UI to ga...
Yes. You can use the as3xmpp library to communicate to servers using that protocol. To my knowledge, no. My understanding is that the network protocol used in p2p connections is internalized, and doesn't allow for public APIs to define their own network protocol (unlike Sockets for example).
6,105,811
6,117,220
How to use libumem to find heap corruption, without relying on a 'core' file?
I want to know how to use libumem on solaris. If I follow http://www.unix.com/man-page/OpenSolaris/3malloc/umem_debug/ and start the process with all the options, how will I get the output? Can I get a text file of the results? I have used wdb on HP-UX for the same. This generates a text file after the program exits, t...
You can create a core file of the process before it exits and examine the code with mdb later. One way to generate that core file at the right moment could be a dtrace script that will trigger the gcore just when exit is called.
6,105,837
6,105,865
Parallel processing - does the slaves generate the data set?
In my parallel programming book, I came across this code that says the slaves generate the data set, however, I think the master acutally generates the data set. This line in particular is why I believe that master generates the data set. for (i=0; i < ARRAY_SIZE; i++) numbers[i] = i; Can someone confirm if...
Both the master and the slaves generate the entire array. You have to remember that your program runs on all nodes and the part of the code in question doesn't distinguish between master/slave. So the wording of your book isn't wrong, but it could be clarified. :)
6,105,994
6,106,094
Storing States in C++ Metaprogramming?
Is it possible to store states in C++ metaprograms? I'm not entirely sure what I mean, but I want a template class that can be "assigned" to, e.g. state::value can be changed via the use of C++ templates. I know I probably sound very vague, but I hope someone understands what I'm talking about (also please no Boost.MPL...
It's not possible, the TMP part of C++ is a purely functional language without the concept of side effects.
6,106,017
6,106,074
simple c++ operator overloading help
How do I overload the << operator? From the error I am getting, it seems that std::cout doesn't know how to use <<. This is in a class: // uint64_t UPPER, LOWER; std::ostream & operator<<(std::ostream & stream){ if (UPPER) stream << UPPER; stream << LOWER; return stream; } I am getting error: no ma...
The << operator takes two arguments, a left hand side, and a right hand side. Therefore you have to define the function with two parameters: std::ostream operator<<(std::ostream &os, const MyClass &obj); And you have to define it outside of your class definition, as far as I can remember. Inside of the class definitio...
6,106,095
6,106,145
C++: &a[2] - &a[1] ==?
a is array of integers, if I try to subtract the address value of &a[2] - &a[1] == ? what should the result be 4 or 1 ? EDIT: see 4th comment on top answer here why he says 1 ?? this is why I'm confused I thought it will be 4 EDIT: here is a test
&a[2] is same as &(*(a + 2)) (i.e (a + 2)) and &a[1] is same as &(*(a + 1)) (i.e. (a + 1)). So answer will be 1.
6,106,158
6,106,766
How does "sizeof" work in this helper for determining array size?
I've found this article that brings up the following template and a macro for getting array size: template<typename Type, size_t Size> char ( &ArraySizeHelper(Type( &Array )[Size]) )[Size]; #define _countof(Array) sizeof(ArraySizeHelper(Array)) and I find the following part totally unclear. sizeof is applied to a func...
template<typename Type, size_t Size> char (&ArraySizeHelper(Type(&Array)[Size]))[Size]; #define _countof(Array) sizeof(ArraySizeHelper(Array)) sizeof is applied to a function declaration. I'd expect the result to be "size of function pointer". Why does it obtain "size of return value" instead? It's not sizeof ArrayS...
6,106,193
6,106,221
Char * of std::vector<char>
Possible Duplicate: Is it possible to get the pointer the continous memory fragment in a std::vector<char> in C++? How do I get char* from std::vector<char>, just like the function std::string.c_str()?
Take the adress of the first element: char * foo = &my_vec[0];
6,106,194
6,106,240
definition of static const outside the class definition
Should we define a static const member outside of the class definition even if it is initialised inside the class? #include<iostream> using namespace std; class abc { static const int period=5; int arr[period]; public: void display() { cout<<period<<endl; } }; cons...
You are defining the static memberperiod by writing const int abc::period;. You are allowed to provide an in class initializer for static const member of a class but that's not definition, but that's merely a declaration. 9.4.2/4 - If a static data member is of const integral or const enumeration type, its declaration...
6,106,493
6,106,588
What does && mean in void *p = &&abc;
I came across a piece of code void *p = &&abc;. What is the significance of && here? I know about rvalue references but I think && used in this context is different. What does && indicate in void *p = &&abc; ?
&& is gcc's extension to get the address of the label defined in the current function. void *p = &&abc is illegal in standard C99 and C++. This compiles with g++.
6,106,597
6,106,617
Overloading << operator ostream
Why doesn't the line below work? #include <iostream> std::ostream& operator <<( std::ostream& os, const char *c) { os << c; // why does this line doesn't work? return os; } int main() { const char *c = "Hi"; std::cout << c; }
The problem is std::ostream& operator <<( std::ostream& os, const char *c) has already been overloaded in iostream.
6,106,625
6,106,674
c++ headers keeping sane
The biggest problem I seem to run into when coding in c++ is the fact that you must declare a class before you can reference it. Say I have two header file like this... Header1.h #include "Header2.h" #include <deque> #include <string> #include <iostream> using namespace std; class HelloPackage; class Hello { public: ...
Use header include guards, either "#ifndef / #define / #endif", or "#pragma once" Put your code in a .cpp, not inline in the header ??? Profit The reason this will work for you is because you can then use forward declarations of the class you want to reference without including the file if you so wish.
6,106,811
6,106,884
(Boost) Why do we need a generic type?
why do we need a generic type specified in Boost library? Isn't template enough? Fore example, if I want a container of a specific type, I would just do: template<class Type> vector<Type> v; If I want to specify a container which contains everything, I simply write: vector v; In explanation for boost::any (http://www...
Because C++ does not have generic type. It has type templates, which are compiled for each substituted type separately. The expression vector v; is a syntax error, because vector is not a class (it's a class template that can be instantiated to class by giving it template parameters). There is a somewhat generic type ...
6,107,041
6,107,106
Allocating memory to a pointer of a class
QGeoRoutingManager: http://apidocs.meego.com/1.0/qtmobility/qgeoroutingmanager-members.html This class doesn't have a constructor. I have forgotten the way to allocate memory to its pointer. I did: QGeoRoutingManager *a = new QGeoRoutingManager (); This lands in the error: calculateRoute.cpp:16: error: no matching fun...
This is a singleton class, you can access it like this: QGeoServiceProvider::routingManager(). Check the docs
6,107,052
26,648,312
How to use IOCTL_DISK_GROW_PARTITION?
I'm trying to shrink my partition to the last used LCN. Has anybody used this control code? I'm getting System Error code 87 every time in the following code: HANDLE hDiskHandle = NULL; DISK_GROW_PARTITION dgp; DWORD dwBytesReturned = 0; dgp.PartitionNumber = 2; dgp.BytesToGrow.QuadPar...
[OP's solution converted to answer below] It turns out my program was fine. It started working after changing access from GENERIC_ALL to GENERIC_READ | GENERIC_WRITE
6,107,187
6,107,793
Problem accessing C++ server with C++ client
C++ based Server Something_server has a method that prints ping #include "Something.h" #include <protocol/TBinaryProtocol.h> #include <server/TSimpleServer.h> #include <transport/TServerSocket.h> #include <transport/TBufferTransports.h> using namespace ::apache::thrift; using namespace ::apache::thrift::protocol; usin...
It means that you should first run ./Something_server & (& puts the job in background so it doesnt clutter output). Then you run ./Something_client which apparently pings the server.
6,107,221
6,107,341
Alternatives to passing a flag into a method?
Sometimes when fixing a defect in an existing code base I might (often out of laziness) decide to change a method from: void MyClass::foo(uint32_t aBar) { // Do something with aBar... } to: void MyClass::foo(uint32_t aBar, bool aSomeCondition) { if (aSomeCondition) { // Do something with aBar... ...
There is not only one solution for this kind of problem. Boolean has a very low semantic. If you want to add in the future a new condition you will have to add a new parameter... After four years of maintenance your method may have half a dozen of parameters, if these parameters are all boolean it is very nice trap for...
6,107,455
6,107,602
Using a const reference to a returned by value value
Look at the following example: string foo(int i) { string a; ... Process i to build a ... return a; } void bar(int j) { const string& b = foo(j); cout << b; } I know RVO and NRVO, but I thought that in order to do that, I need to write bar as the following: void bar(int j) { string b = foo(j); cout << b...
Assigning a temporary to a const reference is perfectly valid. The temporary object will live until the reference goes out of scope. While it does not make sense in your example, this feature is often used for function arguments: string foo(int i) { string a; // ... return a; } void bar(const string& str)...
6,107,738
6,108,811
How to execute shell program and get its stout in c++ silently without popup cmd window
I'm using create process win32 function to start windows shell application for example Ipconfig and get its output but without popup cmd windows . Also I trying with the POCO library and its process class but each time the cmd popup. does any body knows how to do it with the POCO lib there is not mush support in th...
To hide thw window, try passing SH_HIDE when calling CreateProcess on lpStartupInfo. STARTUPINFO si = {0}; si.cb = sizeof(si); si.dwFlags = STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; CreateProcess(/*...*/, &si /*...*/); If you want to collect the results, you can call CreateFile to obtain a file handle, and p...
6,107,914
6,114,546
How to test whether expression is a temporary?
With the following macro: #define ASSERT_IF_TEMP(expr) static_assert(?, "Is temporary!"); What should I put for question mark?
First we should clarify: What do you mean by "temporary"? Many people mean different things when they say temporary. Technically, int() is not a temporary, but most people will include them into their own meaning of that term. Technically, given std::string s;, then move(s) isn't a temporary either, but you may want to...
6,107,975
6,108,007
Can you explain what extern means and some other things?
I know that extern C means the function should be compiled in C style however what does just extern function_datatype functionname mean? extern void sharelog(const char *rem_host, const char *username, const char *, const char *, const char *, const char *); What does extern without "C" mean? Also, ...
The extern without "C" comes from pre-C++ times when you needed a way to tell the C compiler that a function is available "somewhere" and it should allow the linker to figure it out. The declaration with extern allowed the compiler to add the function to the list of known names even if it couldn't resolve the address.
6,107,983
6,109,829
In C++0x is there something like static_assert which gives a warning instead of an error?
I would like to do this for usages which may be inefficient but not necessarily incorrect.
The attributes are introduced in C++0x for that purpose. See http://docwiki.embarcadero.com/RADStudio/en/C%2B%2B0x_attribute_deprecated for an example.
6,108,094
33,650,045
Render cairo surface directly to OpenGL texture
I'm using cairo (http://cairographics.org) in combination with an OpenGL based 3D graphics library. I'm currently using the 3D library on Windows, but I'm hoping to receive an answer that is platform independent. This is all done in c++. I've got the straight forward approach working which is to use cairo_image_surface...
As of 2015, Cairo GL SDL2 is probably the best way to use Cairo GL https://github.com/cubicool/cairo-gl-sdl2 If you are on an OS like Ubuntu where cairo is not compiled with GL you will need to compile your own copy and let cairo-gl-sdl2 know where it is.
6,108,336
6,108,422
Redirecting stderr to stdout using string stream
I have a code like this int main() { std::stringstream oss; std::cerr.rdbuf( oss.rdbuf() ); std::cerr << "this goes to cerr"; std::cout << "[" << oss.str() << "]"; } But i get the output of the program as [this goes to cerr]Segmentation fault How does the program segfault?
This is because you do not restore the buffer of cerr before your program exits. Do it like this: #include <iostream> #include <sstream> int main() { std::stringstream oss; std::streambuf* old = std::cerr.rdbuf( oss.rdbuf() ); std::cerr << "this goes to cerr"; std::cout << "[" << oss.str() << "]"; std::cerr...
6,108,552
6,110,399
Equivalent of boost xml (nvp) serialization in java
I am moving from C++ to Java, and I am used to the way boost serialization works for xml. What is very good with it is: that I only have to write one function that is used for both parsing and generating the XML. This function is basically a mapping between the field value and the name of the xml tag. that the XML gen...
Take a look at jaxb.
6,109,224
6,109,361
C++ Namespace member access in different files how to? how "namespace std" implemented?
I have declared the below namespace in sample.h // namespace with identifier namespace N1 { int b = 80; } sample1.cpp use the above namespace declaration #include <iostream> #include "sample.h" using namespace std; using namespace N1; int main(void) { cout << "b (in main) = " << b << endl; foo(); //wri...
Include guards will work only during compile time, but the error is at link time. This is because the sample.h is included in both compilation units and a variable N1::b is created in both. If you really want a variable (not a const) you have to declare it as extern in the header, and create a memory location for it in...
6,109,445
6,109,518
How to map a bool to a 3d point struct with std::map?
How do I use the following struct: struct point { int x; int y; int z; }; as a key for std::map<point, bool>? How should I define operator< for two points?
Standard library containers like std::map require that your ordering is a "Strict Weak Ordering", so you have to be very careful when designing one. The typical approach for a 3-ary tuple looks like this: bool operator<(const point& other) const { if (x != other.x) return (x < other.x); if (y != other.y) ...
6,109,751
6,109,781
C++ compiler which I can bundle with my application
I'm working on developing my own programming language, and to generate executables I wished to convert the source to C++ and the run it through a C++ compiler. Does anybody know of a C++ compiler which I can simply include with my application and then invoke from the command line without installation? I'm using Windows...
Have you tried gcc (the windows port)?
6,109,810
6,109,854
Interlocked Exchange of a struct
I want to use InterlockedExchange from the WinAPI to use a lock free synchronization of threads. At the moment I have a class like this. struct DataExchange { volatile LONG m_value; void SetValue(LONG newVal) { InterlockedExchange(&m_value, newVal); } LONG GetValue() { LONG work...
No there isn't unless you can fit your struct into 32 bits, in which case you can continue to use InterlockedExchange.
6,110,278
6,111,328
Template function in eMbedded Visual C++ 4.0 for Windows CE
Does eMbedded Visual C++ 4.0 (SP4) support template functions? I get an error when I try to compile code that works fine in Visual C++ 6.0. Here is my template function, which does compile: template<class NodeType> NodeType* MyFunction() { // ... do stuff return new NodeType("foo"); // return a new class instan...
Found the answer here. "It works fine when the template function is not a class member. Oh well, I guess I'll have to leave it as a global function."
6,110,361
6,110,905
vector::operator[] overhead
Apparently, after profiling my (scientific computation) C++ code, 25% (!) of the time is spent with calls to vector::operator[]. True, my code spends all of its time reading and writing in vector<float>s (and a few vector<int>s too), but still, I'd like to know if there's supposed to be some significant overhead of op...
std::vector::operator[] should be rather efficient, however the compiler must be paranoid and for every call made to a function it must assume that the vector could have been moved somewhere else in memory. For example in this code for (int i=0,n=v.size(); i<n; i++) { total += v[i] + foo(); } if the code of foo is...
6,110,467
6,110,604
Drawing a simple library dependency scheme
I am looking for a tool and a guide/example to show how you can write a simple picture that explains the relationship between the following components: A java applet A c++ library A java wrapper for the C++ library (using JNI) A c library The applet is using the java wrapper methods. The java wrapper is a wrapper fo...
The UML tutorial of Enterprise Architect here may give you some idea about the several UML diagrams that are of use to your needs. In general dependencies are shown in class diagrams (between several classes), package diagrams (between namespaces/libraries) and component diagrams. If you ask more specifically about UML...
6,110,725
6,111,123
c++ \ Compile successful, can't debug - STATUS_DLL_NOT_FOUND
Why can't I debug my application (though compile is good)? 1. Does it really need windows dlls? how can I attach them? 2. Why can't it recognize my Dlls? It resides in the same folder.. (VS2005, main program is c++ with c# code). The Error is - Debugger:: An unhandled non-continuable STATUS_DLL_NOT_FOUND exception was ...
This error is being returned because a DLL file required for your application to run is missing. Check your linker settings, and make sure all the DLLs your application depends on are where they're supposed to be (i.e. in the same folder as the executable, or elsewhere in the DLL search path.)
6,111,532
6,111,636
Convert QT/C++ to C#
This might seem a little ridiculous, but as some of you here may already know, I'm converting an application written in C++ to C#. I've noticed that a lot of the code uses references to objects like "QObject", "QWidget", or "QFrame." Because of this, I'm not quite sure if I should look up the source for QT and port the...
Have a look at Qyoto it might just drop in to you code with a few modifications.
6,111,565
6,113,104
Now that we have std::array what uses are left for C-style arrays?
std::array is vastly superior to the C arrays. And even if I want to interoperate with legacy code, I can just use std::array::data(). Is there any reason I would ever want an old-school array?
Unless I've missed something (I've not followed the most recent changes in the standard too closely), most of the uses of C style arrays still remain. std::array does allow static initialization, but it still won't count the initializers for you. And since the only real use of C style arrays before std::array was for...
6,111,617
6,112,689
Can you give an example regarding this point: lambda-expression
A point from n3290:ISO Standared draft, §5.1.2/9 A lambda-expression whose smallest enclosing scope is a block scope (3.3.3) is a local lambda expression; any other lambda-expression shall not have a capture-list in its lambda-introducer. The reaching scope of a local lambda expression is ...
The situation should theoretically arise in namespace scope, as @Space_C0wb0y shows in his comment link. #include <iostream> int x = 12; auto l = [&x](){ return x; }; int main() { std::cout << l() << std::endl; } If find it strange that GCC accepts that snippet, as MSVC correctly rejects it with the following er...
6,111,787
6,111,814
Problem using recursive method in c++
I have a class, defined in a .h like this #ifndef JLLABOUR_H #define JLLABOUR_H class JLLabour{ public: JLLabour(int, int); double* recursivefft(double*,int); void FFT(int*); ~JLLabour(); private: int width; int height; }; #endif // JLLABOUR_H and in my .cpp I have the definition of my recursive function, the pr...
C++ is case sensitive. Your method is called recursivefft not recursiveFFT.
6,111,809
6,112,007
Can I return a custom value from a dialog box's DoModal function?
What I wish to do is, after creating a dialog box with DoModal() and pressing OK in the box to exit it, to have a custom value returned. For example, a couple of strings the user would input in the dialog.
You can't change the return value of the DoModal() function, and even if you could, I wouldn't recommend it. That's not the idiomatic way of doing this, and if you changed its return value to a string type, you would lose the ability to see when the user canceled the dialog (in which case, the string value returned sho...
6,111,825
6,111,858
Dynamically allocate or waste memory?
I have a 2d integer array used for a tile map. The size of the map is unknown and read in from a file at runtime. currently the biggest file is 2500 items(50x50 grid). I have a working method of dynamic memory allocation from an earlier question but people keep saying that it a bad idea so I have been thinking whethe...
My preference would be to dynamically allocate. That way should you encounter a surprisingly large map you (hopefully) won't overflow if you've written it correctly, whereas with the fixed size your only option is to return an error and fail. Presumably loading tile maps is a pretty infrequent operation. I'd be willin...
6,111,905
6,111,984
C++: is return value a L-value?
Consider this code: struct foo { int a; }; foo q() { foo f; f.a =4; return f;} int main() { foo i; i.a = 5; q() = i; } No compiler complains about it, even Clang. Why q() = ... line is correct?
No, the return value of a function is an l-value if and only if it is a reference (C++03). (5.2.2 [expr.call] / 10) If the type returned were a basic type then this would be a compile error. (5.17 [expr.ass] / 1) The reason that this works is that you are allowed to call member functions (even non-const member function...
6,111,912
6,111,965
What is a good way to get 0 or a value dependant on a boolean?
I'm currently working on a piece of code that quite simply uses a boolean to see whether the screen is flipped vertically. This is done with : glOrtho(0.0f, _width, flip ? 0.0f : _height, flip ? _height : 0.0f, -1.0f, 1.0f); I was wondering if there would be a more optimized way to do this, for example : glOrtho(0.0f,...
Are you sure that this is a bottleneck in your program?? Don't early optimize and obfuscate your code just for a small gain.
6,112,362
6,112,600
Explicit instantiation of a templated class and dynamic_cast in a shared library
I stumbled into a problem today that I can't seem to solve. I am compiling a shared library that includes a templated class (Derived<T>, whose base is Base) and some explicit instantiations of this class. I would like the library user to extend from this templated class. The problem arises when I try to dynamic_cast th...
I assume you are on Linux/GCC, because on Windows it should "just work". It does not "just work" with GCC, because for performance RTTI support in GCC relies on pointer comparison. It is all explained in this GCC FAQ, including how it can be resolved. EDIT: though, this FAQ says that it does not work with dlopen() whil...
6,112,679
6,113,058
Good Option for XML Edit/Replace
I have a huge (100k+ lines, 5MB+) XML which acts as a database for my C++ Application. The structure of the XML is quite straight forward, for example, it has chunks of: <foo> <bar prop="true"/> <baz>blah</baz> </foo> The nesting of tags is several levels deep and there are many items with multiple properties. What is...
If you don't want to put the entire document in memory, I would read it using a SAX parser. As you read it, you append the transformed document to a second (or a temp) file. I think it could be pretty fast, and use only a little memory footprint.
6,112,782
6,112,963
How to write good software without getting stuck
I've been working for years on my personal project, an operating system made from scratch. As you may imagine it's quite complicated stuff. The problem is that I've been working this from scratch many times. Meaning that at some point (quite advanced too, I had hard disk read/write and some basic networking), things we...
Do you know any code writing strategy that makes you write working, tested, nice code without spending 90% of time at thinking how to make it working, tested and nice? Yes, here. Seriously, no. It is not possible to write good code without thinking. When I see my well-written code, it's difficult to add a new fun...
6,112,948
6,112,994
Where I can see examples of UML schemes with c++ source
Where I can see small examples of UML schemes with c++ code. I have no time to read UML standard :(
You don't have to read the standard to understand UML. I found this book useful as a quick introduction: UML Weekend Crash Course I would also discourage you to think about UML in relation to C++. it's supposed to be a way of modelling systems, not just documenting existing code.
6,112,995
6,113,053
Stateful functors & STL : Undefined behaviour
I am following this Function objects tutorial Copy-pasta below: I am unable to understand the following: Predicates should always be implemented as stateless function objects to avoid unexpected results. There is no guarantee how often an algorithm might internally copy the predicate. Thus, having predicates that are i...
The meaning of that quote should be taken at face value. For the majority of the STL algorithms, you should not implement your predicate functor such that it has observable state (AKA "side effects"), because: the iteration order over the container is not defined, the algorithm is free to make copies of the functor, ...
6,113,006
6,195,313
can't find boost c++ using configure.ac
I wrote a configure.ac to find the path of boost c++ inlclude, but it could not find anything. If I specify the path, it can compile. Could anyone help me please? Here is my configure.ac AC_PREREQ([2.67]) AC_INIT(pkg, 1.1.01) AC_PROG_CXX AC_ARG_WITH( [boost], [AS_HELP_STRING( [--with-boost=DIR], [path to look ...
Just use AX_BOOST_BASE from the autoconf-archive. If you're trying to AC_CHECK_HEADERS to verify the existence of boost headers, remember that you need to AC_LANG_PUSH([C++]) first, or you'll get "header present but cannot be compiled" errors.
6,113,215
6,118,933
reducing junk in gdb print
I am using gdb 7.2 with the configuration by Dan Marinescu that allows printing STL vectors strings, etc. (pstring, pvector, etc) It doesn't seem very good. So looking at one of the answers below, I cleaned out and used the pretty printers available in 7.0 and better. In order to do so, I put the following in my .gdbi...
What you want to do is addressed in GDB 7.0 and above with Python pretty printers. You don't need pstring, regular print just works (for embedded strings too).
6,113,228
6,113,747
Strange function return result
float Calculate(const string &query) { std::cout << "Query: " << query << "\n"; unsigned int size = query.length(); char stack[70]; float res; int m = 0; for (int i = 0; i < size; i++) { if (query[i] >= '0' && query[i] <= '9') { ...
Your cycle here for(int i = operation.size(); i >= 0; i--) { outputStr += operation[i]; // move all operation marks to otput str } does not make any sense. You are obviously attempting to access the vector at invalid index. It is illegal to access the element at operation[i] when i is equal operation.size(). The i...
6,113,393
6,113,983
What C++ libraries do Quora and Facebook use to access database?
I've read that Quora and Facebook use C++ in the backend. Both of them process and fetch big amounts of data. What libraries do they use for that? Did they develop them?
Facebook is known to have been written in php but now the php code is used to generate C++ code. To do that, they developped a converter tool named HipHop that you can use yourself (Open source AFAIK). I don't know about quora. Amazon.com does use C++ but it's, AFAIK, their own code, not a library. If you're intereste...
6,113,509
6,113,573
How to return the greatest key strictly less than the given key in a std::multimap?
multimap offers the methods lower_bound and upper_bound. Both may return an iterator to a value with key greater than the desired, with lower_bound possibly yielding exactly the desired. Now I want an iterator to a value where the key is strictly less the requested. If it were a map rather than multimap, this would be ...
lower_bound points to the smallest element greater than or equal to the argument (or end). Thus decrementing it once gives you the desired element (if it exists).
6,113,768
6,113,807
Why is the Compiler-Emitted C++ Default Constructor "bad"?
Could someone please explain what is meant by the following? You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. What are they referring to as "badly"?
From the expansion of that link: "The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly."
6,113,837
6,114,044
prevent a std::set from deleting memory
Is there a way to prevent a std::set< Object*>.erase(it) function to delete memory? I only want the Object* to be removed from the set, without freeing memory.. To be specific, I have an object that removes himself from the set and puts itself to another. And it crashes. set1.insert(this); set1.erase(set1.find(this...
Your set<Object*> already doesn't delete the pointed-to object when you call the erase for the iterator. If it's crashing in that area it's for another reason. Likely causes are: You're using the iterator after you erase the item. Missing/incorrect destructor. Missing/incorrect copy constructor/copy assignment operato...
6,113,879
6,113,977
Disposing of Object problem
I have a problem freeing up memory of an object.Here is my code: void Gateway::connect(DWORD dwIP) { if (m_objRRSInterface != NULL) { //delete m_obj; m_obj = NULL; } m_obj = new objClass(); m_obj->SetCallBackFn(fncp); if (m_obj->OpenSocket(dwIP, 3002))//3002 -port number ...
You should investigate about C++ destructors, which are meant to do what you are after. This is where resources clean-up is usually done, but this is up to the programmer of the class. In other words, it is likely that objClass destructor does it resources clean-up there, but without reading the docs or the code, I can...
6,113,903
6,114,228
Using Boost-Regex to parse string into characters and numerals
I'd like to use Boost's Regex library to separate a string containing labels and numbers into tokens. For example 'abc1def002g30' would be separated into {'abc','1','def','002','g','30'}. I modified the example given in Boost documentation to come up with this code: #include <iostream> #include <boost/regex.hpp> using...
From the docs on the sregex_token_iterator: Effects: constructs a regex_token_iterator that will enumerate one string for each regular expression match of the expression re found within the sequence [a,b), using match flags m (see match_flag_type). The string enumerated is the sub-expression submatch for each match fou...
6,113,943
6,114,002
Is it a good idea to save/load an array of struct?
I was wondering if it was a good idea to load/save an array of a certain type of structure using fstream. Note, I am talking about loading/saving to a binary file. Should I be loading/saving independent variables such as int, float, boolean rather then a struct? The reason I ask that is because I've heard that a struct...
A structure may contain padding, which will be written to the file. This is no big deal if the file is going to be read back on the same platform, using code emitted by the same compiler that did the write. However, this is difficult to guarantee, and if you cannot guarantee it, you should normally write the data in s...
6,114,078
6,114,654
How to use a sequence of statements in Boost.Phoenix together with std::transform?
I'd like to use Boost.Phoenix to create a lambda function that consists of a few lines of code and then "returns" a value so I can use it together with std::transform. Like this: std::transform(a.begin(), a.end(), b.begin(), ( //Do something complicated here with the elements of a: state...
No, this isn't possible. From the Boost.Phoenix v2 statement docs: Unlike lazy functions and lazy operators, lazy statements always return void. (Note that this same assertion is in the Boost.Phoenix v3 docs as well.)
6,114,105
6,133,552
Moving to Mouse Pos OpenGL
ive got a program that is moving an object with my mouse click im using gluUnProject and sometimes when i click somewhere the object isnt moving the way i want it my equation seems to be doing fine sometimes but sometimes its not working and i think its somehow rotating the object and getting x and z wrong... so this i...
i found what was wrong today :S it seems like im not using the gluUnproject function the way it should be used and im not normalizing my position vectors so im getting really big numbers :S sry
6,114,185
6,114,491
Partial specialization with type nested in a templated class
I'm playing with templates and partial specialization, but there is one specialization I don't know how to write... I'll simplify code to make it easier to read. Let's condiser template <typename T> class x { ... }; Usually, I can specialize like this : class x<a_type> { ... }; Also works with templates t...
The answer is that you cannot do this specialization. It is not a syntax error, but just something that cannot be realized. You have to see template specializations a little bit like function overloading. The compiler has to take the type argument at the use-site, look at the specializations available, find matches, an...
6,114,231
6,114,473
C++ IO file streams: writing from one file to another using operator<< and rdbuf()
I have a question about copying data from one file to another in C++ (fstream) using operator<<. Here is a code snippet that works for me: #include <fstream> #include <string> void writeTo(string &fname, ofstream &out){ ifstream in; in.open(fname.c_str(),fstream::binary); if(in.good...
EOF-bit is set when trying to read a character, but none is available (i.e. you have already consumed everything in the string). Apparently std::ostream::operator<<() does not attempt to read past the end of the string, so the bit is never set. You should be able to get around this by attempting to access the next char...
6,114,304
6,522,051
Have makefile based cmake projects automatically run make rebuild_cache when an environment variable changes
In my cmake configuration several variables depend on an environment variable in order to be set correctly. This environment variable can change and it means that the cache for cmake should be rebuilt. My configuration can detect the need for this reconfigure and update the appropriate cache entries when either anothe...
Make does not have a memory. There is no way for make to "remember" what a given environment variable was set to the last time make was run. Unless you write the environment variable to a file. I've never used CMake, so I don't know how to best implement it. But on the "raw" make level, the general idea would be to: 1)...
6,114,392
6,114,447
CLOCKS_PER_SEC Not Matching Results From std::clock()
I'm using the following short program to test std::clock(): #include <ctime> #include <iostream> int main() { std::clock_t Begin = std::clock(); int Dummy; std::cin >> Dummy; std::clock_t End = std::clock(); std::cout << "CLOCKS_PER_SEC: " << CLOCKS_PER_SEC << "\n"; std::cout << "Begin: "...
clock() counts CPU time, so it's not adding any time if it's sitting around waiting for input.
6,114,462
6,115,065
How to override the automatically created docstring data for Boost::Python?
I am currently working developing a C++-based module for Python. I have found that Boost::Python is working quite well for what I want to accomplish. However, I am now running into some issues with the docstring that is being generated by Boost::Python. Given the following Boost::Python definitions: BOOST_PYTHON_MOD...
Use the boost::python::docstring_options class to define your auto-created docstring options. All def functions take a docstring as the last parameter. All class_ definitions take the class docstring as the last parameter I.e.: using boost::python; BOOST_PYTHON_MODULE(foo) { // This will enable user-defined docstri...
6,114,657
6,115,319
CUDA extending std::vector to manage host and device data
I learned that std::vector is a nice wrapper around raw arrays in C++ so I started to use it for managing host data in my CUDA app [1]. Since having to allocate and copying things by hand makes the code more complex and less readable I thought about extending std::vector. Since I'm not very experienced I would like to ...
The biggest problem I see with this is that is doesn't really help manage the GPU side of things very much, and it obfuscates a number of very important pieces of information in the process. While the container class contains information about whether the device pointer has been allocated, there is no way of knowing wh...
6,114,664
6,118,123
Easy Way To Send HTML Formatted Email in C++
I have an HTML form that currently takes the inputs and sends them out in an email with HTML formatting, so that the email looks basically like the form webpage, but with all of the fields filled in. <form method="post" action="/cgi-bin/perlscript.pl" enctype="x-www-form-encoded" name="Form"> <input type="text" name...
Thank you all for the responses. I have decided to simply call the Perl script from my code, and send the response data as an argument. I know it's probably not the best solution, but I don't think my C++ options were worth it. // Retrieve the POST data char* contentLength = getenv{"CONTENT_LENGTH"}; int contentS...
6,114,805
6,115,093
Conditional operator: conversion from 'int ' to 'unsigned char ', possible loss of data
I have the following C code: a = (b == B1) ? A1 : A2; a, b, A1, A2 and B1 are all of type unsigned char. A1, A2 and B1 are all constants. When compiling under VC++ I see the following warning: warning C4244: '=' : conversion from 'int ' to 'unsigned char ', possible loss of data I don't understand this warning - none...
In C language arithmetic arguments of ternary ?: operator are subjected to usual arithmetic conversions, i.e. they are promoted to int before any further computations are performed. It doesn't really matter whether they are constants or not. What matters is that they have type unsigned char (as you said) and unsigned c...
6,114,988
6,115,030
Extending a class in C++ using header files
I found found out that to extend a class I would have to do this: class x : public extendsThis { // rest here }; So, I create 2 classes, in two seperate files: - particle.h - class particle : public program { }; - program.h - class program { particle* myParticle; }; However, in the program class I wanted to ...
Yes, you can work around this. You can make a very simple class declaration. In program.h: class particle; class program { particle *myParticle; }; Keep in mind that you need to use a pointer to particle.
6,115,012
6,117,650
How to call a user defined function from c++ using ADO
I'm trying to call a user defined function on my microsoft SQL server from a console application written in c++. I use ADO for the whole thing. My function looks like this (and it works when i use it from within the management studio) CREATE FUNCTION [dbo].[funcHowOftenDidHeWin] ( @playername as varchar(15) @p...
You can rewrite the function as a stored procedure. The FLOAT can be returned either as a RETURN value or as an OUT parameter.
6,115,094
6,115,155
Initializing a union
Previous code : struct Inet_address{ char v4[4]; }; extern "C" Inet_address Inet_loopback = { {127,0,0,1} }; After modifying: I have made Inet_address a union Here Inet address is a union union Inet_address{ char v4[4]; char v6[16]; }; Now I want to do the same operation on extern "C" Inet_address Inet_loopback Sa...
You shouldn't use char arrays for this - make a union out of in_addr and in6_addr: typedef union { struct in_addr inaddr; struct in6_addr in6addr; } in46_addr_t; To set an ipv4 loopback address: addr.inaddr.s_addr = INADDR_LOOPBACK; For IPv6: addr.in6addr = in6addr_loopback; // pre-defined global variable (no...
6,115,204
6,115,281
Question on boost::swap
Couple of questions on boost::swap. Please refer to the code below which is basically a cut-paste from boost/swap.hpp. I am referring to library version 1.43.0. namespace boost_swap_impl { template<class T> void swap_impl(T& left, T& right) { using namespace std;//use std::swap if argument...
This makes it less specialized than std::swap so you don't get overload ambiguity errors when both std::swap and boost::swap are in scope (std::swap will take precedence). No, non-templates always have precedence over templates during overload resolution, so a namespace-scoped non-template swap will take precedence ov...
6,115,580
6,115,700
C++ "expected primary-expression before ‘(’ token" error
I have this code: FILE *f = fopen(intPath, "r"); Node *n; if (f) { try { n = parse(f, intPath); } catch (SyntaxError e) { fclose(f); /***** line 536 *****/ throw LangException( builtin_classes::exception_class::create_ImportError( String::fromAscii(e.filename)...
throw LangException( builtin_classes::exception_class::create_ImportError( String::fromAscii(e.filename)-> append(String::fromAscii(":"))-> append(String::fromInt(e.line))-> append(String::fromAscii(":"))-> append(String::fromInt(e.col))-> append(String::fromAscii(": syntax error:...
6,115,614
6,115,675
Exit code of thread in Windows C++
Suppose I have created multiple threads. Now I am waiting for multiple object as well using : WaitOnMultipleObject(...); Now if I want to know the status of all the thread's return code. How to do that ? Do I need to loop for all the thread's handle in the loop. GetExitCodeThread( __in HANDLE hThread, __out LP...
If you want to wait for a thread to exit, just wait on the thread's handle. Once the wait completes you can get the exit code for that thread. DWORD result = WaitForSingleObject( hThread, INFINITE); if (result == WAIT_OBJECT_0) { // the thread handle is signaled - the thread has terminated DWORD exitcode; ...
6,115,711
6,115,741
How do i include different headers based on my OS?
I'm writing a portable C++ application. How do I include different headers based on the operating system its running on. Is there a way to do this in C++ or do i have to use the build system?
with preprocessor: #ifdef _SUNOS //code #elseif _LINUX //code #elseif _HPUX //code #elseif _WIN32 //code #else #error OS not supported #endif
6,115,826
6,117,539
Adapter design pattern and memory management in C++
Consider the following situation: I have a C++ module which takes an XML node as input, converts it to some other data structure, and returns the result. Right now this module is implemented using TinyXML, so it takes TinyXML classes as input (specifically, a TiXmlNode). This is an issue, because it forces anyone wanti...
One of the most notable disatvantage of chosen approach is a significant burden placed on the developer the abstraction layer. I'd say it'd as hard as turning RapidXml classes into TinyXml ones, so you wouldn't get anything with this new abstraction layer. BTW, you've already did a mistake there attempting to return 'n...
6,116,009
6,116,063
Different Behavior Depending on the Data
Let's make it a simple example. Suppose I have a collection of Number objects, which can then be even or odd. Suppose I want to traverse this collection and process each element. The process depends on the type of element: even or odd. Example: Print each element, such that: if Number is even, I have "This is an even ...
You could separate your Strategy hierarchy from the actual numbers. This way there is no need for an artificial class hierarchy, and you are free to change associations between number (value) types and actions even runtime. The association can be defined if you stick to the Number class hierarchy, then between Number ...
6,116,168
6,116,399
Parsing a SQL INSERT with Boost Spirit Classic
I'm trying to learn Boost Spirit and as an exercise, I've tried to parse a SQL INSERT statement using Boost Spirit Classic. This is the string I'm trying to parse: INSERT INTO example_tab (cola, colb, colc, cold) VALUES (vala, valb, valc, vald); From this SELECT example I've created this little grammar: struct microsq...
To get visibility into what is failing to parse, assign the result of parse to a parse_info<>, then log/examine the parse_info<>::stop field, which in this case should be a const char * pointing at the last byte of you input string that matched your grammar. microsql_grammar g; parse_info<std::string::const_iterator> ...
6,116,188
6,116,594
Understanding the origin of a linker duplicate symbol error
I have a c++ program that compiled previously, but after mucking with the Jamfiles, the program no longer compiled and ld emitted a duplicate symbol error. This persisted after successively reverting to the original Jamfiles, running bjam clean, removing the objects by hand, and switching from clang with the gcc front ...
This is often the result of defining an object in a header file, rather than merely declaring it. Consider: h.h : #ifndef H_H_ #define H_H_ int i; #endif a.cpp : #include "h.h" b.cpp : #include "h.h" int main() {} This will produce a duplicate symbol i. The solution is to declare the object in the header file: exter...
6,116,345
6,118,691
Boost::Python- possible to automatically convert from dict --> std::map?
I've got a C++ class, with a member function that can take a small-to-large number of parameters. Lets name those parameters, a-f. All parameters have default values. As a part of the python project I am working on, I want to expose this class to python. Currently, the member function looks something like this: cla...
I think there's a couple of ways that are easier to accomplish than writing your own converter. You can use boost::python's map_indexing_suite to do the conversion for you, or you can use keyword arguments in python. I personally prefer keyword arguments, as this is the more "Pythonic" way to do this. So this is your...
6,116,444
6,116,488
Compile SSH into C++ app
I need to use SSH to remotely send commands to other servers from a Windows box. Is there source out there I can use to build SSH into an app so I don't have to use cygwin or anything like that? Thanks!
There is a libssh you can use; you could also embed the PuTTY source code (I believe winscp does this).
6,116,471
6,116,844
C++ variable type alike Builder TDateTime type
I'm looking for variable type (in standard C++ libraries) that could easily substitute TDateTime. What I need is hour, minutes, seconds and miliseconds. Thanks for the attention
I think Boost almost qualifies as a standard C++ library these days, so I would recommend boost::date_time I've used this with BCB2010, if that's any help.
6,116,520
6,116,545
c++: is this getInstance() method of my singleton threadsafe?
I am currently trying to write a threadsafe singleton (at least in terms of construction and destruction) using boost::mutex. I read that boost mutex can't be initialized statically(I lost the link where I read it, sorry) so to work around that I tried this, if threadsafety for construction and destruction is: ...
Since each entry to the function will create its own lock, the lock will be completely useless; any number of threads can enter the function, lock different locks, and start messing with the static data at the same time. You could create the lock at file (or class static) scope; this would ensure it's created in time, ...
6,116,747
6,126,909
Locking Output to Output Window in Visual Studio
My application sends debug data to the Output Window in Visual Studio using the TRACE macro. Some of these output strings are built using several calls to the TRACE macro, as is shown in the following snippet of code: BYTE i, len; len = pMsg[APP_LEN_OFFSET] + sizeof(appPktHead_t) - APP_MSG_CODE_LEN; TRACE(_T("%s: ")...
Build a single string, before using the TRACE macro. byMsgLen = pMsg[DEV_LEN_OFFSET] + sizeof(devPktHead_t) + sizeof(devPktTail_t); cmd = pMsg[DEV_CMD_MSB_OFFSET]; cmd <<= 8; cmd |= pMsg[DEV_CMD_LSB_OFFSET]; pCmdIdStr = GetCmdIdStr( cmd ); iPreOffset = ::wcsnlen_s(fnName, 128) // function name + 2 ...
6,116,994
6,117,033
padding with sprintf
I have a dummy question. I would like to print an integer into a buffer padding with 0 but I cannot sort it out the sprintfformat. I am trying the following char buf[31]; int my_val = 324; sprintf( buf, "%d030", my_val ); hoping to have the following string "000000000000000000000000000324" what am I doing wrong? It d...
"%030d" is the droid you are looking for
6,116,998
6,117,354
List iterator outside range
I have a problem with the STL list class. I have a base class called Contact, and three derived classes, Friend, Colleague and Acquaintance. Each instance of the derived classes has certain fields which I modify in the fill*Class*Details() function. The problem is that when it reaches the push_back line, my program giv...
It looks like the list is being mismanaged at a different point in the code, because the error implies end is incorrect. Most likely either the list is deleted/out of scope or some incorrect erases were performed on the list elements (say using invalid iterators).
6,117,017
6,117,046
saving to bitmap with win32 API or GDI+
Question is rather simple but I couldn't find nice & clean solution to my problem on the Internet. What I got are some drawings on my window. Now, I can save those using BitBlt function from window device context to image device context, and also from there to bitmap handle: HDC bitmapDC = CreateCompatibleDC(dc); HBITM...
I gave code here which does pretty much what you want: How to save the client area of a child Window to a Bitmap file? It is very verbose in C. It's a lot better in C++ because of CImage
6,117,054
6,117,093
Determine the first node in a Linked List
If the last node of a linked list is connected to the first node, it makes a ring. Then how would you identify which of the nodes in the linked list is the first node and the last one?
You wouldn't. If it is a ring, then first and last are meaningless. Any node can be first or last. If you define "first" as "created first", then you would probably want to add some sequencing information to the nodes to be able to know that.
6,117,163
12,568,778
Windows 7 and ScreenShot.cpp GDI+ PNG problemo
was using XP without issue for a long time. switched to 7 and trying to capture screenshots with my previously functioning code no longer works. simple concept and relatively generic code...just find the window that i call and save it as a .png. any ideas what might make this bad boy run again? can't debug with my curr...
win7 won't accept encoderParameters.Count == 0 for some reason. Set that == 1 and you should be all set. you probably could also just remove that parameter from Save() (overloaded)
6,117,221
6,129,604
Inserting an image into RTF data in C++ with MFC
I have to create a RTF file using C++ and MFC. This RTF file will contain images with a link on each of them. The RTF is always in memory, it's never written on the hard disk. I need to insert an image in the RTF file at runtime(the image is not always the same). Is it possible to do so with MFC? I'm not sure if CRichE...
Finally, the method at this page worked: http://www.codeguru.com/Cpp/controls/richedit/article.php/c5383
6,117,222
6,118,346
Versioning executable and modifying it in runtime
What I'm trying to do is to sign my compiled executable's first 32 bytes with a version signature, say "1.2.0" and I need to modify this signature in runtime, keeping in mind that: this will be done by the executable itself the executable resides on the client side, meaning no recompilation is possible using an exter...
If your application is meant to patch a game, why not embed the version in there while you're at it? You can use a string like @Juliano shows and modify that from the patcher while the game is not running - which should be the case if you're currently patching anyways. :P Edit: If you're working with Visual Studio, it...
6,117,270
6,117,751
MFC: std::string vs CString?
Using C++ with MFC. Coming from a C# background I typically just use string for all, well, strings. I use them for class members, method parameters, and method return values. Now in C++ I've got std::string, CString, char *, LPCTSTR, and more. As I design my data members, method parameters, and method return value...
I usually prefer to adapt my coding style to the framework I'm working in to be consistent with it. So when I work with MFC (which i haven't for a long time), I prefer the use of CString (and LPCTSTR as function arguments in public interface methods). When working with Qt I prefer QString and Qt's containers over STL c...
6,117,299
6,117,371
c++ transfer matrix to procedure ,memory leaks
i am wandering. i can't believe my eyes! if i allocate matrix in procedure input , after exit from procedure, matrix had been deleted! void input(int **x,int& m,int &n) { int i,j; x=new int*[mx]; for(i=0;i<mx;i++) x[i]=new int[nx]; for(i=0;i<m;i++) for(j=0;j<n;j++) scanf("...
x is passed by value to input; whatever modifications input does to x within itself, they won't be seen outside input. (Hint: try to printf("%p\n", x) inside and outside input). So, if you want to solve it with the least modifications to your code, you have to use a triple indirection here (i.e., int ***x) and pass &x ...
6,117,325
6,117,996
std::map with a char[5] key that may contain null bytes
The keys are binary garbage and I only defined them as chars because I need a 1-byte array. They may contain null bytes. Now problem is, when I have a two keys: ab(0)a and ab(0)b ((0) being a null byte), the map treats them as strings, considers them equal and I don't get two unique map entries. What's the best way t...
Why not use std::string as key: //must use this as: std::string key1("ab\0a",4); std::string key2("ab\0b",4); std::string key3("a\0b\0b",5); std::string key4("a\0\0b\0b",6); Second argument should denote the size of the c-string. All of the above use this constructor: string ( const char * s, size_t n ); descript...
6,117,423
6,117,474
C++ Determining if a variable is set
I have a variable that is defined: SYSTEMTIME m_TOTime; And I call GetSystemTime Function to get the UTC Time: GetSystemTime( &m_TOTime ); Is it possible to determine if GetSystemTime has been called to set m_TOTime? I have another function that uses this variable, but if GetSystemTime has not been called (which some...
Use an initializer. SYSTEMTIME m_TOTime = { 0 }; // Initialize structure to zero ... if (m_TOTime.wYear != 0) // structure has been initialized In general, you cannot do this if all possible values of the variable are "legal", but assuming time travel is impossible, the year will never be zero after GetSystemTi...
6,117,729
6,117,756
strange behavior with stl containers and pointers
I don't understand why the following does not work: queue<int*> q; int counter = 1; for (int i = 0; i < 3; i++) { int a[1] = {counter}; q.push(a); counter++; } while (!q.empty()) { int *top = q.front(); q.pop(); cout << top[0] << endl; } It should print out: 1 2 3, but instead 3 3 3 is print...
You are storing pointers to local variables and using those pointers after the local variables they point to have gone out of scope. In other words: you are invoking Undefined Behavior. Result: It should not print out "1 2 3". It doesn't have to do anything and is allowed to do whatever it likes. "3 3 3" seems reasonab...
6,118,480
6,119,123
windows 7 style for combobox on internet explorer toolbar, how?
I'm developing an Internet Explorer toolbar and I want to place a combobox I create on my toolbar. HWND combobox1=CreateWindow(_T("COMBOBOX"), _T("combobox"), WS_BORDER | WS_VISIBLE | WS_CHILD | CBS_DROPDOWN, 10, 0, 200, 250, m_hWnd, (HMENU) NULL,NULL , NULL); And that works correctly, but the combobo...
Adding a comctl32 manifest to a DLL loaded into another process doesn't impact the default activiation context that was established by the EXE. Instead, your DLL will need to activate it's activation context when it is called. See CreateActCtx, ActivateActCtx. You will then DeactivateActCtx in each method before you re...
6,118,721
6,118,786
Using C++ templates in Linked Lists, with multiple different types appearing in the list
(Firstly, as a disclaimer, this is related to an assignment. I'm not asking anyone to do my assignment for me, just to try and help me understand how to implement templates properly.) My current setup is: I have class A, which is a base class. Class B, C and D all children of Class A. I'm trying to make a linked list t...
Instead of templates you should be using inheritance. Templates, as you guessed, create instance per type T, and that is not what you want. Your code should be something in these lines: class A{...}; class B: public A{...}; class C: public A{...}; class D: public A{...}; struct Node{ A *next; } you can assign to n...
6,118,733
6,118,758
Odd output from program when entering operator?
I'm probably missing something obvious here. This is my code (I'm just learning true C++, and I want to get some practice): #include <iostream> #include <cstring> using namespace std; class String { private: char * value; int len; friend ostream & operator<<(ostream & os, String s); public: String(); ...
Try this: ostream & operator<<(ostream & os, const String& s) { return os << s.value; } otherwise your should define copy constructor for your String class.
6,118,874
6,118,896
Pointer confusion - c++
I've been tasked with making a simple change to a C++ application. Unfortunately I come from a Java background, and I've hit a wall with some pointer problems. The code in question reads in a list of files from a given directory (set using an environment variable), and does something on each file. char * rebuildDir = g...
Current file points to the same memory as rebuilddir so you modify the string in place. You need to duplicate the string. You could do something like: char currentFile[MAX_PATH]; snprintf(currentFile, MAX_PATH, "%s%s", rebuildDir, ent->d.name);
6,119,306
6,119,324
Operator overloading c++ placement
Im having trouble figuring out where to place the overloaded operators i created. should they be in the class they operate on, or inside? both ways are causing me trouble. any pointers would be great. here is my very basic uint128_t class: class uint128_t{ private: uint64_t UPPER, LOWER; public: //...
Why not a mix of both? Put operator= inside, and the rest outside. For the ones that take uint128_t as left-hand-side argument it doesn't matter, if it's a right-hand-side argument then it has to be a global function. So for that reason you can put both functions side-by-side if they're global. You might even get away ...