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
405,112
405,141
How are objects stored in memory in C++?
How are objects stored in memory in C++? For a regular class such as class Object { public: int i1; int i2; char i3; int i4; private: }; Using a pointer of Object as an array can be used to access i1 as follows? ((Object*)&myObject)[0] === i1? Other questions on SO seem to suggest that casting a struct to a pointer will point to the first member for POD-types. How is this different for classes with constructors if at all? Also in what way is it different for non-POD types? Edit: In memory therefore would the above class be laid out like the following? [i1 - 4bytes][i2 - 4bytes][i3 - 1byte][padding - 3bytes][i4 - 4bytes]
Almost. You cast to an Object*, and neglected to take an address. Let's re-ask as the following: ((int*)&myObject)[0] == i1 You have to be really careful with assumptions like this. As you've defined the structure, this should be true in any compiler you're likely to come across. But all sorts of other properties of the object (which you may have omitted from your example) will, as others said, make it non-POD and could (possibly in a compiler-dependent way) make the above statement not true. Note that I wouldn't be so quick to tell you it would work if you had asked about i3 -- in that case, even for plain POD, alignment or endianness could easily screw you up. In any case, you should be avoiding this kind of thing, if possible. Even if it works fine now, if you (or anybody else who doesn't understand that you're doing this trick) ever changes the structure order or adds new fields, this trick will fail in all the places you've used it, which may be hard to find. Answer to your edit: If that's your entire class definition, and you're using one of the mainstream compilers with default options, and running on an x86 processor, then yes, you've probably guessed the right memory layout. But choice of compiler, compiler options, and different CPU architecture could easily invalidate your assumptions.
405,175
405,210
what will happen with the overlapping portion of boost once C++0x becomes mainstream?
what will happen with the overlapping portion of boost once C++0x becomes mainstream? Will boost still contain everything it used to, or will they adapt the library to update it with the new std:: stuff? Will boost have both a normal c++ version and a c++0x version that they will maintain?
One would hope that Boost continues to support existing classes, for a couple of reasons. First, there is a body of code that uses the overlapping features in Boost that needs to be supported, for some time. Second, overlapping implementations allow me to select which one I'd prefer to use. There might be some difference between std::Frob and Boost::Frob that is important to my project, and having a choice is good. In the long term, though, I would expect a migration toward the standard from both the application writers and the tools providers. That makes it a less risky choice to go with std::.
405,673
405,734
What would you do if you coded a C++/OO cross-platform framework and realize its laying on your disk for too much due to no time?
This project started as a development platform because i wanted to be able to write games for mobile devices, but also being able to run and debug the code on my desktop machine too (ie, the EPOC device emulator was so bad): the platforms it currently supports are: Window-desktop WinCE Symbian iPhone The architecture it's quite complete with 16bit 565 video framebuffer, blitters, basic raster ops, software pixel shaders, audio mixer with shaders (dsp fx), basic input, a simple virtual file system... although this thing is at it's first write and so there are places where some refactoring would be needed. Everything has been abstracted away and the guiding principle are: mostly clean code, as if it was a book to just be read object-orientation, without sacrifying performances mobile centric The idea was to open source it, but without being able to manage it, i doubt the software itself would benefit from this move.. Nevertheless, i myself have learned a lot from unmaintained projects. So, thanking you in advance for reading all this... really, what would you do?
I would say that you should open source it. If you do have the time, it may be helpful for other programmers who are interested in the project to know the status of the project, and what is next to do on the project. Writing a to do list may be helpful, or writing comments in the code may also help. If you do not have the time to write up a to do list maybe somebody is willing to take the initiative on the project, find out what needs to be done. Look at it a different way. The worst that can happen is that your work will go unnoticed, and your efforts will be lost. The best that can happen is that you will be recognized for having the foresight to start such a great project, and open sourcing it.
405,766
405,846
Is it possible to use libxml with unicode xmlchar?
Is it possible to use libxml with unicode? For example the xmlParseDoc function takes an xmlChar xmlChar has the following definition: typedef unsigned char xmlChar; I would like for libxml to interpret all as 2 byte chars. I have a feeling that the following would not work properly with the lib: typedef unsigned short xmlChar; Note: I'm not talking about when it actually reads/writes the xml encoding. I know that supports unicode. What I want is for the interface into the lib to be with unicode strings wstring instead of normal strings.
I found the answer in a link provided by @Mitch Wheat You cannot re-define xmlchar to be an unsigned short. However if you encode your strings as UTF-8 then xmlChar will properly handle unicode. You can convert a string in windows to UTF8 via calling WideCharToMultiByte with a parameter of CP_UTF8
405,953
406,130
Generating UML from C++ code?
Is there a tool that can parse C++ files within a project and generate UML from it?
Here are a few options: Step-by-Step Guide to Reverse Engineering Code into UML Diagrams with Microsoft Visio 2000 - http://msdn.microsoft.com/en-us/library/aa140255(office.10).aspx BoUML - http://bouml.fr/features.html StarUML - http://staruml.sourceforge.net/en/ Reverse engineering of the UML class diagram from C++ code in presence of weakly typed containers (2001) - http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.27.9064 Umbrello UML Modeller - http://uml.sourceforge.net/ A list of other tools to look at - http://plg.uwaterloo.ca/~migod/uml.html
406,043
406,291
Terms new to beginners in c++?
What does it mean by POD type?cv-qualified?
Very Nice article on POD
406,315
406,326
C++ Accessing the Heap
This problem involved me not knowing enough of C++. I am trying to access a specific value that I had placed in the Heap, but I'm unsure of how to access it. In my problem, I had placed a value in a heap from a data member function in an object, and I am trying to access it in another data member function. Problem is I do not know how, and I had searched examples online, but none were what I needed as they were all in int main() and were not specifically what I needed. In the first data member function, I declare the value I want to be sent to the Heap; Here's an example of what my first data member function. void Grid::HeapValues() { //Initializing Variable value = 2; //The type is already declared //Pointers point a type towards the Heap int* pValue = new int; //Initialize an a value of in the Heap *pValue = value; } And in data member function This is what want: void Grid::AccessHeap() { //Extracting heap: int heap_value = *pValue; //*pValue does not exist in this function cout << heap_value; //Delays the value 2, which is found //in the first data member function } I feel foolish for asking, but I am unable to find the answers and do not how. Does anyone know how to access a value from the heap in a simple way? And I would need it to be able to access in more then two data member function.
pValue needs to be a member-variable of the class Grid. class Grid { private: int* pValue; public: void HeapValues(); void AccessHeap(); }; Now the member-variable pValue is accessible from any member-function of Grid.
406,613
406,618
C++ Copy Constructors
I recently wrote a piece of code which did SomeClass someObject; mysqlpp::StoreQueryResult result = someObject.getResult(); where SomeClass::getResult() looks like: mysqlpp::StoreQueryResult SomeClass::getResult() { mysqlpp::StoreQueryResult res = ...<something>...; return res; } Now, using the example in the first code snippet, when I compiled and ran, the program crashed with an ABORT signal. I then changed the first snippet to: SomeClass someObject; mysqlpp::StoreQueryResult result(someObject.getResult()); which worked fine. Also, just to try it out, I changed it again to: SomeClass someObject; mysqlpp::StoreQueryResult result; result = someObject.getResult(); which also worked fine. Now, I just can't figure out why the first example failed, and the next two succeeded. As I understand, in the first example, the copy constructor is used to initialise result. But isn't this also the case in the second example? So why did the second example succeed? The 3rd example makes a bit more sense - since the copy const isn't used, we just assign after construction. In short, what's the difference between: FooClass a = someObject.someMethodReturningFooClassInstance(); and FooClass a(someObject.someMethodReturningFooClassInstance());? Muchos thanks!
I don't think there's any difference in the two cases. The same copy constructor is called both times. Are you sure this is exactly what you've written in your code?
406,903
407,916
simple C++ templates suited for STL Containers
I need a template like this, which work perfectly template <typename container> void mySuperTempalte (const container myCont) { //do something here } then i want to specialize the above template for std::string so i came up with template <typename container> void mySuperTempalte (const container<std::string> myCont) { //check type of container //do something here } which doesnt't work, and throws an error. I would like to make the second example work and then IF possible i would like to add some code in the template to check if a std::vector/std::deque/std::list was used, to do something differently in each case. So i used templates because 99% of the code is the same for both vectors and deques etc.
If I am understanding your problem correctly you have an algorithm that will work for STL containers vector, deque etc but are trying to write a template specialisation for string. If this is the case then you can write the generalised templated method that you defined in your question:- template<typename container> void mySuperTempalte( const container &myCont ) { // Implement STL container code } Then for your string specialisation you declare:- template<> void mySuperTempalte( const container<std::string> &myCont ) { // Implement the string code } For any other specialisation just change the type declaration for myCont. If you really need to do this for the vector and deque containers then make the template parameter the parameter for the type in that container rather than the container itself as Sep suggested. template<typename C> void mySuperTempalte( const std::vector<C> &myCont) { // check type of container // do something here } It's worth trying to avoid this by making your first implementation work with all STL containers to make your life easier, then you only need the specialisation for the string class. Even consider converting your string to a vector to avoid the specialisation all together. On a side note, I've changed the container parameter to a const reference, I assume this is what you want, as you declare the object const anyway, this way you avoid a copy.
406,966
407,303
What is the best way to check that external applications are available?
I have an application which had optional extras depending on if the user has the software installed. On Linux what is the best way to determine if something like python and PyUsb is installed? I am developing a C++ Qt application if that helps.
This is inefficient (requires forking and exec'ing /bin/sh). There has to be a better way! But as a generic approach... There's always system(). (Remember to use WEXITSTATUS()! Watch out for making programs uninterruptable!) #define SHOW(X) cout << # X " = " << (X) << endl int main() { int status; SHOW( status = system( "which grep > /dev/null 2>&1" ) ); SHOW( WEXITSTATUS(status) ); SHOW( status = system( "which no_matching_file > /dev/null 2>&1" ) ); SHOW( WEXITSTATUS(status) ); } There is also popen(), which can be useful for grabbing output from programs to verify version numbers, libraries, or whatnot. If you need bidirectional (read&write) access to a subprocess, best to use pipe(), fork(), exec(), close(), & dup2().
407,100
407,753
Calling a const function from a non-const object
I need to call a const function from a non-const object. See example struct IProcess { virtual bool doSomeWork() const = 0L; }; class Foo : public IProcess { virtual bool doSomeWork() const { ... } }; class Bar { public: const IProcess& getProcess() const {return ...;} IProcess& getProcess() {return ...;} void doOtherWork { getProcess().doSomeWork(); } }; Calling getProcess().doSomeWork(); will always results in a call to IProcess& getProcess() Is there another way to call const IProcess& getProcess() const from a non constant member function? I have so far used const_cast<const Bar*>(this)->getProcess().doSomeWork(); which does the trick but seems overly complicated. Edit: I should mention that code is being refactored and eventually only one function will remain. const IProcess& getProcess() const However, currently there is a side effect and the const call may return a different instance of IProcess some of the time. Please keep on topic.
Avoid the cast: assign this to a const Bar * or whatever and use that to call getProcess(). There are some pedantic reasons to do that, but it also makes it more obvious what you are doing without forcing the compiler to do something potentially unsafe. Granted, you may never hit those cases, but you might as well write something that doesn't use a cast in this case.
407,881
407,966
Can I use templates instead of macros for Exception class creation?
I often want to define new 'Exception' classes, but need to have an appropriate constructor defined because constructors aren't inherited. class MyException : public Exception { public: MyException (const UString Msg) : Exception(Msg) { }; } Typedefs don't work for this, because they are simply aliases, not new classes. Currently, to avoid repeating this trivial boilerplate, I use a #define which does the donkeywork. #define TEXCEPTION(T) class T : public Exception \ { \ public:\ T(const UString Msg) : Exception(Msg) {}; \ } ... TEXCEPTION(MyException); But I keep wondering if there's a better way of achieving this - maybe with templates, or some new C++0x feature
If you really want to have new classes derived from Exception, as opposed to having a template parameterized by a parameter, there is no way around writing your own constructor that just delegates the arguments without using a macro. C++0x will have the ability what you need by using something like class MyException : public Exception { public: using Exception::Exception; }; You can read about the details of that (seem to have quite a bit of extra rules) in 12.9 "Inheriting Constructors" in the latest draft of C++0x. In the meantime, i would recommend a policy based design (made small text, because the OP accepted the above, and not this policy stuff): // deriving from Impl first is crucial, so it's built first // before Exception and its Ctor can be used. template<typename Impl> struct ExceptionT : Impl, Exception { // taking a tuple with the arguments. ExceptionT(arg_types const& t = arg_types()) :Exception(Impl::Ctor(t)) { } // taking a string. plain old stuff ExceptionT(std::string const& s):Exception(Impl::Ctor(s)) { } }; struct ExceptionDefImpl { typedef boost::tuple<> arg_types; // user defined ctor args can be done using a tuple std::string Ctor(arg_types const& s) { return std::string(); } std::string const& Ctor(std::string const& s) { return s; } }; // will inherit Ctor modifier from DefImpl. struct MemoryLost : ExceptionDefImpl { typedef boost::tuple<int> arg_types; std::string Ctor(arg_types const& s) { std::ostringstream os; os << "Only " << get<0>(s) << " bytes left!"; return os.str(); } int getLeftBytes() const { return leftBytes; } private: int leftBytes; }; struct StackOverflow : ExceptionDefImpl { }; // alias for the common exceptions typedef ExceptionT<MemoryLost> MemoryLostError; typedef ExceptionT<StackOverflow> StackOverflowError; void throws_mem() { throw MemoryLostError(boost::make_tuple(5)); } void throws_stack() { throw StackOverflowError(); } int main() { try { throws_mem(); } catch(MemoryListError &m) { std::cout << "Left: " << m.getLeftBytes(); } catch(StackOverflowError &m) { std::cout << "Stackoverflow happened"; } }
408,196
408,213
How should overriding delete in C++ behave?
The problem I'm running into is that as far as I know the delete operator should be a static function but sometimes the compiler (VC++) seems to be treating it as dynamic. Given: class Base { public: void* operator new(size_t size) { /* allocate from custom heap */ } void operator delete(void *p) { customFree(p, sizeof(Base)); } Base() {} virtual ~Base() {} }; class Derived: public Base { public: void* operator new(size_t size) { /* allocate from custom heap */ } void operator delete(void *p) { customFree(p, sizeof(Derived)); } Derived() {} virtual ~Derived() {} } What I see happening is that deleting the base pointer will result in call to Derived::opeator delete. Base *p = new Derived(); delete p; //calls Derived::operator delete If I don't define ANY destructors then I get what I expected to happen: Base::operator delete is called. This seems to be happening because the compiler is inserting a function called 'scalar deleting destructor into the vtable when a destructor is defined. Then that function will call Derived::delete. So I have to questions: 1) Is this standard behavior? 2) When should I be using void operator delete( void *, size_t ); vs. void operator delete( void * ); if the above is standard behavior?
It is certainly Standard Behavior. If the derived class's operator new was used, its operator delete will also be used (also note even though you do not explicitly tell the compiler those functions are static, they are implicitly declared so). There might be the naughty case where you have an operator new in the derived class, but the corresponding operator delete is in the base class. I think that's valid, but i would avoid that. Relying on the base operator delete, while defining ones own operator new in the derived class will inevitable cause trouble. If I don't define ANY destructors then I get what I expected to happen: You will get undefined behavior :) Everything can happen, including something you would expect (wrongly). Deleting through a base pointer that points to an object of another type requires a virtual destructor. The implicitly declared destructor is not virtual. When should I be using void operator delete( void *, size_t ); If you want to have the size that was allocated known in the operator delete. I wrote about what it means here: What does the C++ new operator do other than allocation and a ctor call? . If you use (from within your overloaded member operator delete/new) the global operator new & delete to get your memory and release it, or even malloc / free, you don't need that size information. But it could be useful for logging purposes.
408,336
408,370
Concrete type or Interface?
I have the following use case , lot of code which was tightly coupled on a concrete type (say Concrete1). Later figured out the concrete type needs to be changed, so defined an interface . E.g Class ABC { virtual int foo() = 0; virtual int getType() = 0; } class Concrete1 : public ABC { int foo() { ... } int getType() { return 1; } } class Concrete2 : public ABC { int foo() { ... } int getType() { return 2; } } A static factory pattern was used for creation of the objects. So all places where the object new Concrete1 was created is replaced with ABCFactory::createType(). Now there are a lot of places in code where I need to check if the object returned by createType is whether Concrete1 or Concrete2 and accordingly do the relevant logic (So a lot of if else in the code :( ). I want to avoid a lot of if else in the code as part of this change. Any suggestions? The thing which bothers me a lot is if (abc.getType() == 1) { ... } else if (abc.getType() ==2) { ... }
the entire point of using interfaces is so that you can use polymorphism which means you should never have to check what type an instance is. doing so is a very big code smell (see Fowlers Refacotring). move the conditional logic to the concrete classes and add te function that will handle it to the interface EDIT (Adding code example since initial post was done from cell phone): You are trying to do: void Main(string[] args) { Bird bird = BirdFactory.GetPigeon(); if (bird.GetType().Equals(typeof(Duck))) { Console.WriteLine("quack"); } else if (bird.GetType().Equals(typeof(Pigeon))) { Console.WriteLine("coo coo"); } } Instead, try: interface Bird { void Speak(); } class Duck : Bird { void Speak() { Console.Write("quack"); } } class Pigeon : Bird { void Speak() { Console.Write("coo coo"); } } void Main(string[] args) { Bird bird = BirdFactory.GetPigeon(); bird.Speak(); }
408,844
408,887
Why use Web Services instead of RPC between two internal processes?
Can anyone suggest a good reason to use web services instead of RPC (not xml-rpc) as a comms channel between two C++ processes both of which will be developed by the same team? Note: Web services do not guarantee ordered delivery!
When people have a hammer, they tend to see all problems as nails. That's why people tend to put webservices everywhere as if it were the only way for two processes to communicate. In your case RPC seems to be a better choice, more performance, less memory usage, simpler to implement (in C++)...
408,970
408,982
IOCP, Cross platform libraries?
I've recently bumped into something called IOCP on the windows platform, to be more precise: Input/Output Control Ports. This seems to be the most efficient way to code your server software when it needs to hold thousands of users concurrently. (Correct me if I'm wrong, but thread-per-socket, polling, and asynchronous callbacks (thread on every callback) are not efficient enough.) I am wondering if there are any 3rd party libraries available that implement this concept. I know the win32 api supplies us with CreateIoCompletionPort, FreeBSD has kqueue and linux in general can use /dev/epoll that works somewhat similarly... But isn't there a crossplatform library (such as boost::thread) that handles this stuff for me?
Have you looked at boost::asio? I'm not sure if it has all this functionality yet, but I believe that's one of the things it's intended for.
409,198
409,205
To delete or to not delete (call func)?
I remember someone saying if you create a class through a lib you should destroy it through the library. So, does this mean I shouldn't call delete? I should call myclass.deleteMe() instead? Would overloading delete solve the problem?
A problem with your application's deleting something that was created within a lib is that the lib might use a different heap/memory manager. Solutions include: Ensure that your application is built with the same heap manager as the library. Implement a (non-inline) deleteMe method in the class, whose implementation can be delete this; Define custom operator delete within the class, implemented within the library ... if there's a custom operator delete then it will called if and when your application delete an istance of the object.
409,348
409,396
Iteration over std::vector: unsigned vs signed index variable
What is the correct way of iterating over a vector in C++? Consider these two code fragments, this one works fine: for (unsigned i=0; i < polygon.size(); i++) { sum += polygon[i]; } and this one: for (int i=0; i < polygon.size(); i++) { sum += polygon[i]; } which generates warning: comparison between signed and unsigned integer expressions. I'm new in the world of C++, so the unsigned variable looks a bit frightening to me and I know unsigned variables can be dangerous if not used correctly, so - is this correct?
For iterating backwards see this answer. Iterating forwards is almost identical. Just change the iterators / swap decrement by increment. You should prefer iterators. Some people tell you to use std::size_t as the index variable type. However, that is not portable. Always use the size_type typedef of the container (While you could get away with only a conversion in the forward iterating case, it could actually go wrong all the way in the backward iterating case when using std::size_t, in case std::size_t is wider than what is the typedef of size_type): Using std::vector Using iterators for(std::vector<T>::iterator it = v.begin(); it != v.end(); ++it) { /* std::cout << *it; ... */ } Important is, always use the prefix increment form for iterators whose definitions you don't know. That will ensure your code runs as generic as possible. Using Range C++11 for(auto const& value: a) { /* std::cout << value; ... */ Using indices for(std::vector<int>::size_type i = 0; i != v.size(); i++) { /* std::cout << v[i]; ... */ } Using arrays Using iterators for(element_type* it = a; it != (a + (sizeof a / sizeof *a)); it++) { /* std::cout << *it; ... */ } Using Range C++11 for(auto const& value: a) { /* std::cout << value; ... */ Using indices for(std::size_t i = 0; i != (sizeof a / sizeof *a); i++) { /* std::cout << a[i]; ... */ } Read in the backward iterating answer what problem the sizeof approach can yield to, though.
409,483
409,525
Best approach for learning Java after C++?
I've been using C++ for about 6 or 7 years now, and I consider myself fluent in it. I've never bothered with Java until now, but I find myself out of the job (company went under) and I need to expand my skill set. Someone recommended Java, so I am wondering if there is any advice for where somebody like me might start. I am also interested to know what the key aspects of Java are that are most likely to come up in an interview.
There are some popular areas that I think of when we talk about Java Concepts of OOP: I'm sure this will not be much different from C++: Class, Abstract Class, Interface, Polymorphism, Overriding, Overloading, Inheritance, Static member, ... Interface will likely be area that you might want to focus. Since this is not directly available in C++, I don't know. Core Java: Such as the basic syntax and the common classes such as Math, String, System.out, Scanner, Basic file I/O, Stream. Know the concept of Garbage Collection, Reference Type (since pointers are not available here.) Know the Java platform/technologies, J2SE, J2EE. Basic GUI with Swing and its layout managers. Web Applications with Servlet/JSP. Popular tools, frameworks, and libraries: This may not as important as above bullets. But maybe you should know what Eclipse, Netbeans, Spring, Struts, Hibernate, EJB, Ant, JUnit, JavaDoc, are for. You can always search for "C++ to Java" in Google. I'm sure there will plenty of good start points. Don't forget not to put * in front of var name next time you code Java :)
409,688
409,715
Multithreaded paranoia
This is a complex question, please consider carefully before answering. Consider this situation. Two threads (a reader and a writer) access a single global int. Is this safe? Normally, I would respond without thought, yes! However, it seems to me that Herb Sutter doesn't think so. In his articles on effective concurrency he discusses a flawed lock-free queue and the corrected version. In the end of the first article and the beginning of the second he discusses a rarely considered trait of variables, write ordering. Int's are atomic, good, but ints aren't necessarily ordered which could destroy any lock-free algorithm, including my above scenario. I fully agree that the only way to guarantee correct multithreaded behavior on all platforms present and future is to use atomics(AKA memory barriers) or mutexes. My question; is write re-odering ever a problem on real hardware? Or is the multithreaded paranoia just being pedantic? What about classic uniprocessor systems? What about simpler RISC processors like an embedded power-pc? Clarification: I'm more interested in what Mr. Sutter said about the hardware (processor/cache) reordering variable writes. I can stop the optimizer from breaking code with compiler switches or hand inspection of the assembly post-compilation. However, I'd like to know if the hardware can still mess up the code in practice.
Your idea of inspecting the assembly is not good enough; the reordering can happen at the hardware level. To answer your question "is this ever a problem on read hardware:" Yes! In fact I've run into that problem myself. Is it OK to skirt the issue with uniprocessor systems or other special-case situations? I would argue "no" because five years from now you might need to run on multi-core after all, and then finding all these locations will be tricky (impossible?). One exception: Software designed for embedded hardware applications where indeed you have completely control over the hardware. In fact I have "cheated" like this in those situations on e.g. an ARM processor.
409,827
409,930
Boost::Tuples vs Structs for return values
I'm trying to get my head around tuples (thanks @litb), and the common suggestion for their use is for functions returning > 1 value. This is something that I'd normally use a struct for , and I can't understand the advantages to tuples in this case - it seems an error-prone approach for the terminally lazy. Borrowing an example, I'd use this struct divide_result { int quotient; int remainder; }; Using a tuple, you'd have typedef boost::tuple<int, int> divide_result; But without reading the code of the function you're calling (or the comments, if you're dumb enough to trust them) you have no idea which int is quotient and vice-versa. It seems rather like... struct divide_result { int results[2]; // 0 is quotient, 1 is remainder, I think }; ...which wouldn't fill me with confidence. So, what are the advantages of tuples over structs that compensate for the ambiguity?
tuples I think i agree with you that the issue with what position corresponds to what variable can introduce confusion. But i think there are two sides. One is the call-side and the other is the callee-side: int remainder; int quotient; tie(quotient, remainder) = div(10, 3); I think it's crystal clear what we got, but it can become confusing if you have to return more values at once. Once the caller's programmer has looked up the documentation of div, he will know what position is what, and can write effective code. As a rule of thumb, i would say not to return more than 4 values at once. For anything beyond, prefer a struct. output parameters Output parameters can be used too, of course: int remainder; int quotient; div(10, 3, &quotient, &remainder); Now i think that illustrates how tuples are better than output parameters. We have mixed the input of div with its output, while not gaining any advantage. Worse, we leave the reader of that code in doubt on what could be the actual return value of div be. There are wonderful examples when output parameters are useful. In my opinion, you should use them only when you've got no other way, because the return value is already taken and can't be changed to either a tuple or struct. operator>> is a good example on where you use output parameters, because the return value is already reserved for the stream, so you can chain operator>> calls. If you've not to do with operators, and the context is not crystal clear, i recommend you to use pointers, to signal at the call side that the object is actually used as an output parameter, in addition to comments where appropriate. returning a struct The third option is to use a struct: div_result d = div(10, 3); I think that definitely wins the award for clearness. But note you have still to access the result within that struct, and the result is not "laid bare" on the table, as it was the case for the output parameters and the tuple used with tie. I think a major point these days is to make everything as generic as possible. So, say you have got a function that can print out tuples. You can just do cout << div(10, 3); And have your result displayed. I think that tuples, on the other side, clearly win for their versatile nature. Doing that with div_result, you need to overload operator<<, or need to output each member separately.
409,832
410,668
How do I program an offline form of the crucial memory scanner
I like the memory scanner you can get from crucial (http://www.crucial.com/systemscanner/index.aspx) however it only works with an online computer. I would like to be able to do as much as possible of what it does, but off-line. I would like to produce sufficient info to be able to take this info to another online computer and use that to order a memory upgrade. I would like to program this making minimum assumptions about what is on the target computer. My language of choice would be C++. (C# is my current favorite language but using this would require the .Net environment which is an assumption too far for my liking.)
WMI (in the root\cimv2 namespace) has the Win32_MemoryArray, Win32_MemoryDevice, Win32_MemoryDeviceArray, Win32_PhysicalMemory and Win32_PhysicalMemoryArray classes (and a couple of others). These might help.
410,005
410,024
Accessing COM interface from C or C++ in Windows environment
I'm relatively new to the Component Object Model specification - I have a simple question: How can I access a COM interface from a C or C++ application For instance, accessing Microsoft Excel COM interface to perform basic operations, without user intervention. Kind regards
Actually, you will need to instantiate the object using the COM interface. This is fairly complicated, more than we can just answer here. here is a good primer: http://www.codeproject.com/KB/COM/comintro.aspx Another one: http://www.codeguru.com/cpp/com-tech/activex/tutorials/article.php/c5567
410,184
410,662
Accessing an application's COM interface using C++ or C
In response to question, how can I (or find more information to) automate certain functionality without user intervention, from a C++ (or C) using: ATL Or Automation code directly in C/C++ Regards
If the application exposes a type library (and Microsoft Office applications do), then you can get at it from Microsoft C++ by using the #import keyword. This will create C++ wrappers for the COM interfaces exposed by the application. Type libraries are often .TLB files, but they are regularly embedded as Win32 resources in executable files. To find out if an application exposes its functionality in this way, you'll probably need to consult the documentation for the specific application, because discovering (and understanding) type libraries is quite complicated. The Windows SDK includes a tool, "OLE/COM Viewer" that can display typelibrary information for a COM object in the registry, or from a .TLB file or resource. If you want to play with an application, VBScript (or JScript) give you a quick way to experiment. They're both capable of consuming OLE Automation interfaces.
410,823
410,856
Factory method implementation - C++
I have the following code for "factory" design pattern implementation. class Pen{ public: virtual void Draw() = 0; }; class RedPen : public Pen{ public: virtual void Draw(){ cout << "Drawing with red pen" << endl; } }; class BluePen : public Pen{ public: virtual void Draw(){ cout << "Drawing with blue pen" << endl; } }; auto_ptr<Pen> createPen(const std::string color){ if(color == "red") return auto_ptr<Pen>(new RedPen); else if(color == "blue") return auto_ptr<Pen>(new BluePen); } But I heard that it can be done in a better way using "C++ templates". Can anyone help how it is done and how template approach is better than this? Any thoughts
In the example you posted, neither a factory or a template approach makes sense to me. My solution involves a data member in the Pen class. class Pen { public: Pen() : m_color(0,0,0,0) /* the default colour is black */ { } Pen(const Color& c) : m_color(c) { } Pen(const Pen& other) : m_color(other.color()) { } virtual void Draw() { cout << "Drawing with a pen of color " << m_color.hex(); } void setColor(const Color& c) { m_color = c; } const Color& color() const { return m_color; } private: Color m_color; }; class Color { public: Color(int r, int g, int b, int a = 0) : m_red(r), m_green(g), m_blue(other.blue()), m_alpha(a) { } Color(const Color& other) : m_red(other.red()), m_green(other.green()), m_blue(other.blue()), m_alpha(other.alpha()) { } int red() const { return m_red; } int green() const { return m_green; } int blue() const { return m_blue; } int alpha() const { return m_alpha; } std::string hex() const { std::ostringstream os; char buf[3]; os << "#"; sprintf(buf, "%2X", red()); os << buf; sprintf(buf, "%2X", green()); os << buf; sprintf(buf, "%2X", blue()); os << buf; sprintf(buf, "%2X", alpha()); os << buf; return os.str(); } private: int m_red; int m_green; int m_blue; int m_alpha; } Of course, the color class would have to be adjusted to the drawing API you use -- and perhaps be way more advanced than this one (different color spaces, etc). Why not templates? The reason it does not make sense to use templates, is that (presumably) the only difference between the different drawing operations is the color variable. So, by using templates (or manually declaring different classes, as you did), you will duplicate similar code. This will make your program large, and slow it down. So, the draw function should either take the color as an argument, or (as in my example) have the color as a class data member.
410,853
410,867
How do you check for infinite and indeterminate values in C++?
In my programs infinity usually arises when a value is divided by zero. I get indeterminate when I divide zero by zero. How do you check for infinite and indeterminate values in C++? In C++, infinity is represented by 1.#INF. Indeterminate is represented by -1.#IND. The problem is how to test if a variable is infinite or indeterminate. Checking infinity is relatively straightforward: You find the infinity definition in your particular C++. For my case (VS2003), it is std::numeric_limits::infinity(). You have to include "limits" in order to use it. You can assign this infinite value to a variable and you can compare it to some value in order to check if that value is infinite. Indeterminate is a little tricky, because you cannot compare an indeterminate value to some other value. Any comparison returns false. You can use this property to detect an indeterminate value by comparing it to itself. Let's say you have a double variable called aVal. Under normal conditions, aVal != aVal returns false. But if the value is indeterminate, aIndVal != aIndVal returns true. This weird situation is not present for infinite values, i.e. aInfVal != aInfVal always returns false. Here are two functions that can be used to check for indeterminate and infinite values: #include "limits.h" #include "math.h" bool isIndeterminate(const double pV) { return (pV != pV); } bool isInfinite(const double pV) { return (fabs(pV) == std::numeric_limits::infinity()) } Are there better ways for these checks, am I missing anything?
For Visual Studio I would use _isnan and _finite, or perhaps _fpclass. But if you have access to a C++11-able standard library and compiler you could use std::isnan and std::isinf.
410,924
410,934
Overriding an operator using const for both parameters in C++
I'm trying to create an overridden operator function using both const parameters, but I can't figure out how to do it. Here is a simple example: class Number { Number() { value = 1; }; inline Number operator + (const Number& n) { Number result; result.value = value + n.value; return result; } int value; } What I am trying to do here is pass in two arguments into the addition function that are both const and return the result without changing anything in the class: const Number a = Number(); const Number b = Number(); Number c = a + b; Is this possible and how would I go about doing this? Thanks, Dan
inline is understood in class declarations so you don't need to specify it. Most idiomatically, you would make operator+ a non-member function declared outside the class definition, like this: Number operator+( const Number& left, const Number& right ); You might need to make it a friend of the class if it needs access to Number's internals. If you have to have it as a member function then you need to make the function itself const: Number operator+( const Number& n ) const { // ... For classes like Number, operator+ is typically implemented in terms of operator+= as usually you want all the usual operators to work as expected and operator+= is typically easier to implement and operator+ tends not to lose any efficiency over implementing it separately. Inside the class: Number& operator+=( const Number& n ); Outside the class: Number operator+( const Number& left, const Number& right ) { return Number( left ) += right; } or even: Number operator+( Number left, const Number& right ) { return left += right; }
410,981
411,113
What harm can come from defining BOOST_DISABLE_ABI_HEADERS when compiling boost?
What harm can come from defining BOOST_DISABLE_ABI_HEADERS when compiling boost? From the boost file: boost_1_37_0\boost\config\user.hpp // BOOST_DISABLE_ABI_HEADERS: Stops boost headers from including any // prefix/suffix headers that normally control things like struct // packing and alignment. //#define BOOST_DISABLE_ABI_HEADERS Why does boost feel the need to control struct packing and alignment? Does it maybe have to do with boost serialization and making sure it works the same on all platforms? If I'm running windows only, can I safely define this?
Here is a rundown of defining BOOST_DISABLE_ABI_HEADERS: If you use some shared boost dlls, you will get undefined behavior If you statically link to your boost libraries, or you are sure you are only using your own dlls then you may be safe, keep reading for why I say may. If you use boost in several .libs in your project they must all have the same compiler settings as a change in a compiler setting can make the packing and alignment different. I would suspect that compatibility between different OS and platforms (x86 vs x64) may not work for things like boost serialization. Overall it's not very safe to define this and much safer to leave it alone.
411,004
411,010
is it possible to detect pointer-to-member-function?
i want a specialize template in a pointer-to-member-function case. Is there a way to detect this? right now i declare struct isPtrToMemberFunc, then add an extra template (class TType=void) to each class (right now just 1) and specialize the extra template to see if its isPtrToMemberFunc. Is there a way to detect this automatically? if not is my current method the best solution?
There is a way, but it includes that you repeat your specialization for each and every number of arguments and const/volatile modifiers for those member functions. An easier way to do that is to use boost.functiontypes which does that for you: template<typename T> void doit(T t) { if(boost::function_types::is_member_function_pointer<T>::value) { std::cout << "it is"; // ... } else { std::cout << "it is not"; // ... } } Grab it from here.
411,103
411,116
Function with same name but different signature in derived class
I have a function with the same name, but with different signature in a base and derived classes. When I am trying to use the base class's function in another class that inherits from the derived, I receive an error. See the following code: class A { public: void foo(string s){}; }; class B : public A { public: int foo(int i){}; }; class C : public B { public: void bar() { string s; foo(s); } }; I receive the following error from the gcc compiler: In member function `void C::bar()': no matching function for call to `C::foo(std::string&)' candidates are: int B::foo(int) If I remove int foo(int i){}; from class B, or if I rename it from foo1, everything works fine. What's the problem with this?
Functions in derived classes which don't override functions in base classes but which have the same name will hide other functions of the same name in the base class. It is generally considered bad practice to have have functions in derived classes which have the same name as functions in the bass class which aren't intended to override the base class functions as what you are seeing is not usually desirable behaviour. It is usually preferable to give different functions different names. If you need to call the base function you will need to scope the call by using A::foo(s). Note that this would also disable any virtual function mechanism for A::foo(string) at the same time.
411,114
411,125
C++, equivalence between pointer-to-functions and pointer-to-member-functions?
I'm used to thinking of member functions as just being a special case of normal functions, where member functions have an extra parameter at the beginning of their parameter list for the 'this' pointer, that is, the object on which the member function is supposed to act. I've used boost::function this way in the past and never encountered any problems: boost::function f<(void)(MyObject*, int, int)> = &MyObject::method_that_takes_two_ints; But I've seen this syntax for member-function pointers: void (MyObject::*f)( int, int ) = &MyObject::method_that_takes_two_ints; In this syntax, the 'this' parameter is not visible. Which got me wondering if under the hood pointer-to-member-functions are really a separate beast, and that boost was taking care of details for me. What does the standard dictate about the placement of the 'this' parameter? Perhaps just on my compiler the extra 'this' argument comes first, and maybe on other compilers it could be on the end? Am I just lucky that my way of thinking is consistent with how my compilers (GCC4, VS2005) handle it? Are pointer-to-member-functions always just a special case of pointer-to-functions with an extra parameter or can the compiler implement them differently?
The standard says next to nothing about where the this pointer should be placed, and in fact it is fairly common to use a different calling convention for member functions. (So the 'this' pointer is not just an extra first argument, it's actually stored in a different location than the first arg usually is) In particular, MSVC uses the thiscall calling convention for member functions, and stdcall elsewhere. http://www.hackcraft.net/cpp/MSCallingConventions/#thiscall describes the differences between them, but note that thiscall stores the this pointer in the ECX register, while stdcall stores all parameters on the stack. You're definitely better off treating them as completely distinct types. A pointer to a member function is not just a pointer to a function with an extra parameter.
411,142
411,156
How can I find duplicate headers in a large solution in MSVC++ 2005 or 2008?
In Visual Studio (C++), is there a way to easily find duplicate headers that are defined in .cpp files? I'm also trying to find ways to detect this situation: A includes B includes C A includes C => A doesn't need to include C
If you want to detect this situation you could add this macro to the top of every file. Substitute A for the name of the file #if A_H #error "Duplicate include" #else #define A_H #endif
411,218
413,316
Hudson, C++ and UnitTest++
Has anyone used Hudson as a Continuous-Integration server for a C++ project using UnitTest++ as a testing library? How exactly did you set it up? I know there have been several questions on Continuous Integration before, but I hope this one has a narrower scope. EDIT: I'll clarify a bit on what I'm looking for. I already have the build set to fail when the Unit-Tests fail. I'm looking for something like Hudson's JUnit support. UnitTest++ can create XML reports (See here). So, perhaps if someone knows how to translate these reports to be JUnit compatible, Hudson will know how to eat it up?
We are actively doing this at my workplace. Currently, we use a free-style software project to: Check our Subversion repository for updates every 15 minutes Call a windows batch file to clean and build a solution file Project files build and run unit tests as a post-build event Unit test failures are returned by the test main(), thus treated as build errors I have also tested a configuration that uses the XmlTestReporter included with UnitTest++ to generate output files. The xUnit plugin natively supports this output, along with any other output you can convert, although I had to change the XSL file that came with it in version 0.1.3 to get durations recorded in the test history. There are a lot of things we would like to improve about our integration; the build logs are long and hard to parse with no coloring or highlighting, etc., but so far it has still been beneficial to us.
411,295
411,301
alternatives to winsock2 with example server source in c++
i'm using this example implementation found at http://tangentsoft.net/wskfaq/examples/basics/select-server.html This is doing most of what I need, handles connections without blocking and does all work in its thread (not creating a new thread for each connection as some examples do), but i'm worried since i've been told winsock will only support max 64 client connectios :S Is this 64 connections true? What other choices do I have? It would be cool to have a c++ example for a similar implementation. Thanks
Alternative library: You should consider using boost asio. It is a cross platform networking library which simplifies many of the tasks you may have to do. You can find the example source code you seek here. About the 64 limit: There is no hard 64 connection limit that you will experience with a good design. Basically if you use some kind of threading model you will not experience this limitation. Here's some information on the limit you heard about: 4.9 - What are the "64 sockets" limitations? There are two 64-socket limitations: The Win32 event mechanism (e.g. WaitForMultipleObjects()) can only wait on 64 event objects at a time. Winsock 2 provides the WSAEventSelect() function which lets you use Win32's event mechanism to wait for events on sockets. Because it uses Win32's event mechanism, you can only wait for events on 64 sockets at a time. If you want to wait on more than 64 Winsock event objects at a time, you need to use multiple threads, each waiting on no more than 64 of the sockets. The select() function is also limited in certain situations to waiting on 64 sockets at a time. The FD_SETSIZE constant defined in winsock.h determines the size of the fd_set structures you pass to select(). It's defined by default to 64. You can define this constant to a higher value before you #include winsock.h, and this will override the default value. Unfortunately, at least one non-Microsoft Winsock stack and some Layered Service Providers assume the default of 64; they will ignore sockets beyond the 64th in larger fd_sets. You can write a test program to try this on the systems you plan on supporting, to see if they are not limited. If they are, you can get around this with threads, just as you would with event objects. Source
411,422
411,429
Pointer to void in C++?
I'm reading some code in the Ogre3D implementation and I can't understand what a void * type variable means. What does a pointer to void mean in C++?
A pointer to void, void* can point to any object: int a = 5; void *p = &a; double b = 3.14; p = &b; You can't dereference, increment or decrement that pointer, because you don't know what type you point to. The idea is that void* can be used for functions like memcpy that just copy memory blocks around, and don't care about the type that they copy.
411,823
414,870
How do I implement QHoverEvent in Qt?
I'm just learning Qt with C++. I have successfully implemented signals and slots to trap standard events like ButtonPushed(), etc. However, I want to have a function called when I mouse over and mouse out of a QLabel. It looks like QHoverEvent will do what I need, but I can't seem to find any tutorials or examples on how to implement this. Is it done the same way as signals and slots?. I tried: connect(ui.lbl_test, SIGNAL(QHoverEvent), this, SLOT(TestFunc(QEvent::Type type, const QPoint & pos, const QPoint & oldPos))); .. but the function didn't get called when I hovered over the label. Here is the function, listed in the header file as a public slot: void MyDialog::TestFunc(QEvent::Type type, const QPoint & pos, const QPoint & oldPos) { QMessageBox::information(this, tr("Hey"), tr("Listen!")); } Can anyone help me figure this out or point me to a good example? EDIT: After reading a post below, I found no setFlag() member to call for my label widget, but I did try: ui.lbl_test->setMouseTracking(true); connect(ui.lbl_test, SIGNAL(ui.lbl_test->mouseMoveEvent()), this, SLOT(TestFunc(QMouseEvent *event))); And updated TestFunc() accordingly. But still nothing happens when I mouse over. After looking I am not sure QLabel even inherits the mouseMoveEvent() even from QWidget. If this is true, is there a widget that does, or a list of objects that inherit it somewhere?. All I can tell from the documentation on their site is how many inherited functions an object has..
Using signals and slots for this purpose isn't going to work. mouseMoveEvent() is not a signal or meta-method and cannot be connected to a slot. Subclassing the widget class and overriding mouseMoveEvent() will allow you to get mouse-move-events, but that is a very heavyweight way to accomplish this (and adds one more class to your source base). Instead, consider implementing an eventFilter() method on your MyDialog class and installing it on the QLabel. With this event filter method, you can intercept all the events for a given QObject instance. Here is the documentation on Event Filters. http://doc.qt.io/qt-4.8/eventsandfilters.html#event-filters Additionally, through looking at the code sample, I'd recommend you take a moment to investigate what the SIGNAL() and SLOT() macros do. You can see how they are defined in $QTDIR/src/corelib/kernel/qobjectdefs.h
412,165
412,200
C++ Service Providers
I've been learning C++, coming from C#, where I've gotten used to using service providers: basically a Dictionary<Type, object>. Unfortunately, I can't figure out how to do this in C++. So the questions are basically: How would I make a dictionary in C++. How would I use 'Type' with it, as far as I know there is no 'Type' in C++. Same as above, but with 'object'. Thanks!
I'm assuming that you're trying to map a type to a single object instance. You could try something along these lines: #include <typeinfo> #include <map> #include <string> using namespace std; class SomeClass { public: virtual ~SomeClass() {} // virtual function to get a v-table }; struct type_info_less { bool operator() (const std::type_info* lhs, const std::type_info* rhs) const { return lhs->before(*rhs) != 0; } }; class TypeMap { typedef map <type_info *, void *, type_info_less> TypenameToObject; TypenameToObject ObjectMap; public: template <typename T> T *Get () const { TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T)); if (iType == ObjectMap.end()) return NULL; return reinterpret_cast<T *>(iType->second); } template <typename T> void Set(T *value) { ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value); } }; int main() { TypeMap Services; Services.Set<SomeClass>(new SomeClass()); SomeClass *x = Services.Get<SomeClass>(); } In C++ types are not first-class objects in their own right, but at least the type-name is going to be unique, so you can key by that. Edit: The names aren't actually guaranteed to be unique, so hold on to the type_info pointers and use the before method to compare them.
412,183
412,199
On writing win32 api wrapper with C++, how to pass this pointer to static function
I want to convert function object to function. I wrote this code, but it doesn't work. #include <iostream> typedef int (*int_to_int)(int); struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } operator int_to_int () { return this->*&adder::operator(); } }; int main(void) { adder add_two(2); int_to_int add_fn = add_two; std::cout << add_two(3) << std::endl; // expect 5 std::cout << add_fn(3) << std::endl; // expect 5 add_fn = adder(5); std::cout << add_fn(3) << std::endl; // expect 8 return 0; } and I got message from g++, says invalid use of non-static member function. How do I get pointer to member function of instance? Edit:My original problem is about Win32 API. I'm forced to write windows program with old Win32 API at school. but I don't want to write horrible switch statement like some example codes on text. Then, I decided to write wrapper in C++. I want to write the window class like ... class Window { public: LRESULT update (HWND, UINT, WPARAM, LPARAM); void run(); // below methods are called by update() virtual void onclick(int, int); virtual void ondraw(); // ... and more methods }; and I'm willing to write my application class with deriving this class and overloading some methods. Finally, my actual probrem is how to do this in C++. // on initializing my window object, // I must register window class with callback which is // not a C++ function object. // I try to explain what I want to do with psudocode mixing C++ and javascript. WNDCLASS wndclass; Window *self = this; wndclass.lpfnWndProc = function () { return self.update.apply(self, argunemts); }; In other word, I have to make closure into function pointer. I don't know how to do this, but I can't believe this can't do in C++. Edit: The original title of this question was How to get pointer-to-member-function of instance. But this title and my question didn't tell my actual problem enough. Sorry to early answerers, and litb, thank you for suggestion and very useful answer!
Update: You told us what you want. I found this question here on SO: Best method for storing this pointer for use in WndProc . I'm not a Windows Programmer, but the Adam Rosenfield guy seem to be right in using SetWindowLongPtr and GetWindowLongPtr. So, you use it like this: LRESULT CALLBACK my_callback(HWND hwnd, UINT ui, WPARAM wp, LPARAM lp) { Window * self = reinterpret_cast<Window*>( GetWindowLongPtr(hwnd, 0)); return self->update(hwnd, ui, wp, lp); // handle it. } Register that function as the wnd-proc and store the this pointer of your Window object using SetWindowLongPtr. In the WNDCLASSEX structure, there is a cbWndExtra field that you assign sizeof(Window*) to, which is enough storage to just contain the this pointer. Then you can call SetWindowLongPtr(my_hwnd, 0, reinterpret_cast<LONG_PTR>(this)); to put the this pointer into that region. Then receive it like the above and delegate to the real member function. You could in theory also use a static member function. But you have to be careful. Calling a static member function from C code can cause bugs, because the calling convention might be different between C code and C++ code. For Windows, that may not be an issue - I don't know. So better check yourself in addition. The thing you try is invalid. You try to return a pointer to the function call operator, but there is no object provided when the call is made, beside that your conversion operator has the wrong type. The type that the conversion operator returns has function pointer type, but not member function pointer type. The closest you can get to is to use the proper type: struct adder; typedef int (adder::*int_to_int)(int); struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } operator int_to_int () { return &adder::operator(); } }; Now, your conversion operator is not even considered, because it has to be called like this: adder a(10); cout << (a.*(int_to_int)a)(2); // expected: 12 And manually like this: // note, we just get the member function pointer using the conversion operator. // Nothing is related to the actual temporary adder object. int_to_int i = adder(5); cout << (adder(10).*i)(2); // expected: 12 The usual function call syntax does not cope with that. In short, what you try is not possible. I think another question is, why the heck do you want to do that? I think we can help you better when we know what the original problem is. If you are trying to make it look and work like a function call, you don't need any conversion operators at all: struct adder { int n_; adder (int n) : n_(n) {} int operator() (int x) { return x + n_; } }; adder a(10); cout << a(2); // expected: 12
412,344
412,356
a better way than casting from a base class to derived class
I know downcasting like this won't work. I need a method that WILL work. Here's my problem: I've got several different derived classes all from a base class. My first try was to make an array of base class. The program has to select (more or less at random) different derived classes. I had tried casting from a base class to the derived class, putting it in the array of the base, but obviously that didn't work. I was sincerely hoping for another method than simply sticking arrays of all the derived classes, because there could be quite a few derived classes. Is there any better way to do this that I'm just brainfarting on? If y'all need code examples or more information, just let me know. It all makes sense to me, but It's late and it may not make sense to everybody else heh. Any help is very much appreciated, guys.
Not sure what you mean. Sounds like you store the objects by value, and you you have an array of Base. That won't work, because as soon as you assign a Derived, that object will be converted to a Base, and the Derived part of the object is sliced away. But i think you want to have a array of pointers to base: Base * bases[NUM_ITEMS]; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases[i] = new Derived1; else if(r == 1) bases[i] = new Derived2; // ... } If you ever haved worked with pointers, you will know it's a pain in the ass to manage them, espacially pass around and not lose them, since you will need to call delete on them to free the memory and call the destructor of the objects. You can use shared_ptr, and it will manage that for you: shared_ptr<Base> bases[NUM_ITEMS]; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases[i].reset(new Derived1); else if(r == 1) bases[i].reset(new Derived2); // ... } Now, you can pass bases[x] to another shared_ptr, and it will note you have got more than one reference - it will call automatically delete if the last reference to the objects go out of scope. Ideally, you would also replace the raw array by std::vector: std::vector< shared_ptr<Base> > bases; for(int i=0; i<NUM_ITEMS; i++) { int r = get_random_integer(); if(r == 0) bases.push_back(shared_ptr<Base>(new Derived1)); else if(r == 1) bases.push_back(shared_ptr<Base>(new Derived2)); // ... } Then you can pass the vector around, and don't lose the size of it, and you can dynamically add items to it on demand. Get the size of the vector using bases.size(). Read about shared_ptr here. Conversion from a Base class to a Derived class should only be done when absolutely necessary. Normally, you want to use a technique called polymorphism, which means you call a function on the base pointer, but it will actually call a function defined in the derived class, having the same signature (name and parameters are the same type) and is said to override it. Read the article on wikipedia about it. If you really need to cast, you can do it like this for a raw pointer: Derived1 * d = &dynamic_cast<Derived1&>(*bases[x]); Using dynamic_cast ensures, that when you cast to the wrong type (i.e the type you cast is not the type that was created and assigned to the base pointer), you get an exception thrown by the operator. For the shared_ptr case, there are ways too: shared_ptr<Derived1> d = dynamic_pointer_cast<Derived1>(bases[x]); if(d) { // conversion successful, it pointed to a derived. d and bases[x] point still // to the same object, thus share it. }
412,366
412,641
Read keyboard characters to determine shortcuts
I'm working on a document application and part of this application I've to add support to read the keyboard pressed events and replace the pre-defined characters set if that keyboard entry is match with the pre-defind short form/word.The actual application has implemented in C++. Please provide me your thoughts on how to implement this. Is there any sample C++ program for reference? algorithm/concepts?
Standard C++ doesn't support keypress events, so you'll have to look at either an OS function, or a framework function. Portable C++ frameworks like wxWidgets or Qt support keypress events on Windows, Mac and Linux.
412,378
412,549
How do people get mixin-style re-use in C#?
I come from a C++ background where I can use template mixins to write code that refers to FinalClass which is a template parameter that is passed in. This allows reusable functions to be "mixed-in" to any derived class, by simply inheriting from ReusableMixin with a template paramter of MyFinalClass. This all gets inlined into the class so it's as though I just wrote a big class that did everything -- ie very fast! Since mixins can chain, I can mix-in all sorts of behaviour (and state) into one object. If anyone wants clarification on the technique, please ask. My question is, how can I get reuse like that in C#? Note: C# generics don't allow inheriting from a generic parameter.
In C#, the closest you get to C++ style mixins is adding the mixins as fields of a class and add a bunch of forwarding methods to the class: public class MyClass { private readonly Mixin1 mixin1 = new Mixin1(); private readonly Mixin2 mixin2 = new Mixin2(); public int Property1 { get { return this.mixin1.Property1; } set { this.mixin1.Property1 = value; } } public void Do1() { this.mixin2.Do2(); } } This is usually enough, if you only want to import functionality & state of the mixins. A mixin can of course be implemented as you like, complete with (private) fields, properties, methods, etc. If your class also needs to express "is-a" relationships with the mixins then you need to do the following: interface IMixin1 { int Property1 { get; set; } } interface IMixin2 { void Do2(); } class MyClass : IMixin1, IMixin2 { // implementation same as before } (This is also the standard way how multiple inheritance is emulated in C#.) Of course, the mixin interfaces as well as the mixin classes can be generics, e.g. with a most-derived class parameter or whatever.
412,611
412,614
Struct with boolean field default initialization?
I have the following use case, a struct with some boolean and int variables struct a { int field1; bool field2; bool field3; }; I am refactoring this code, and writing a constructor for the struct , the problem is the default initialization of fields. I am not criticizing any language construct here, but ideally I would want null to be part of the language itself i mean I should be able to define for struct a as a : field1(null.int), field2(null.bool), field3(null.bool) {} C++ does not allow it since null.int or null.bool are not defined. Is the only way to do in C++ is a: field1(-1), field2(false), field3(false) {}
You can do struct a { a():field1(), field2(), field3() { } int field1; bool field2; bool field3; }; And all fields will be zero and false respectively. If you want to say that the fields have an indeterminate value, i'm afraid you have to use other techniques. One is to use boost::optional: struct a { a():field1(int()), field2(bool()) { } optional<int> field1; optional<bool> field2; optional<bool> field3; }; Leaves field3 indeterminate. Access the values with *field_name. Test for a none value with field == boost::none or if(field) { ... }.
412,615
438,867
create sql query in c++/java?
which method do you prefer for creating dynamic sql queries? formating or streaming? Is it just preference or there any reason one is better than other?Or any special library you use to it. EDIT: Please answer in case of c++.
There is some thing called SOCI - The C++ Database Access Library for C++
412,954
412,975
Converting binary data to printable hex
In this thread some one commented that the following code should only be used in 'toy' projects. Unfortunately he hasn't come back to say why it's not of production quality so I was hoping some one in the community may be able to either assure me the code is ok (because I quite like it) or identify what is wrong. template< class T1, class T2> void hexascii( T1& out, const T2& in ) { out.resize( in.size() * 2 ); const char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7','8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; T1::iterator outit = out.begin(); for( T2::const_iterator it = in.begin(); it != in.end(); ++it ) { *outit++ = hexDigits[*it >> 4]; *outit++ = hexDigits[*it & 0xF]; } } template<class T1, class T2> void asciihex( T1& out, const T2& in ) { size_t size = in.size; assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); for( T2::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit ) { *outit = ((( (*it > '9' ? *it - 0x07 : *it) - 0x30) << 4) & 0x00f0) + (((*(it+1) > '9' ? *(it+1) - 0x07 : *(it+1)) - 0x30) & 0x000f); } } Edit: Thanks for your help guys, you've made some big improvements. I've written functions in the two suggested styles from your answers. Some rough testing suggests the second method is marginally faster than the first, but IMO this is outweighed by the improved readability of the first. template<class T1> void asciihex2( T1& out, const std::string& in ) { dassert( sizeof(T1::value_type)==1 ); size_t size = in.size(); assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); for( size_t i = 0; i < in.size(); i += 2 ) { int tmp; sscanf( in.c_str() + i, "%02X", &tmp ); *outit++ = tmp; } } template<class T1> void asciihex3( T1& out, const std::string& in ) { dassert( sizeof(T1::value_type)==1 ); size_t size = in.size(); assert( !(size % 2) ); out.resize( size / 2 ); T1::iterator outit = out.begin(); const char hexDigits[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F}; for( std::string::const_iterator it = in.begin(); it != in.end(); it += 2, ++outit ) { *outit = (hexDigits[(*it - 0x30) & 0x1f] << 4) + hexDigits[((*(it+1) - 0x30) & 0x1f)]; } } Some of the assumptions surronding this code: 1: They are not intended as a generic, but are used in an anonymous name space to translate data for a specific class. 2: The templating is required as two separate container types are being used (one being std::vector, the other a similar byte array type container from a third party library. 3: The purpose is to be able to convert binary data of indeterminate length into strings and back again (0x1234abcd <-> "1234abcd") 4: assert traps errors in both debug and release modes 5: by the time these functions are called the size of the string will already have been checked, assert is used to terminate processing if something serious has gone wrong 6: It needs some commenting Any other ideas appreciated.
It seems like a lot of templated code to achieve very little, given you have direct hex conversion in the standard C scanf and printf functions. why bother?
413,425
420,521
How do I get the HWND for an ActiveX control after the control has been initialised/activated?
I am creating an ATL 8.0 based ActiveX control in C++ using Visual Studio 2008. I need to create a sub-window and attach it to the ActiveX control. How do I get access to the HWND that is owned by the ActiveX control? Which ATL function can I override in order to use the HWND after the control's window has been created?
After some trial and error and I found the answer I was after. In the constructor of your ATL ActiveX control you to add the following line of code: m_bWindowOnly = true; This causes the window for the control to be created (rather than just reusing the HWND of the parent window). After this the m_hWnd member of the control class can be used to access the HWND for the control's window.
413,473
413,520
dlopen on library with static member that throws exception in constructor - results in Abort
I am trying to load a dynamic library using dlopen function. This library contains a static object, which throws an exception in its constructor. I have a "try-catch(...)" block around the dlopen call, but it doesn't catch the exception, and I just see "Abort" printed. How am I able to catch this exception?
Short Answer: You Can't Thinking about it again. The original statements holds, but you must also remember that dlopen() is a C library function. C does not support exceptions. Thus throwing an exception that crosses from C++ code to C ( Your global object back upto dlopen() ) code will also cause application termination. See here:Why destructor is not called on exception? These are the situations under which throwing an exception will terminate the application. Your specific situation is covered by: An exception escapes the constructor/destructor of a non local static (ie global)
414,243
414,260
Lazy evaluation in C++
C++ does not have native support for lazy evaluation (as Haskell does). I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it? EDIT: I like Konrad Rudolph's answer. I'm wondering if it's possible to implement it in a more generic fashion, for example by using a parametrized class lazy that essentially works for T the way matrix_add works for matrix. Any operation on T would return lazy instead. The only problem is to store the arguments and operation code inside lazy itself. Can anyone see how to improve this?
I'm wondering if it is possible to implement lazy evaluation in C++ in a reasonable manner. If yes, how would you do it? Yes, this is possible and quite often done, e.g. for matrix calculations. The main mechanism to facilitate this is operator overloading. Consider the case of matrix addition. The signature of the function would usually look something like this: matrix operator +(matrix const& a, matrix const& b); Now, to make this function lazy, it's enough to return a proxy instead of the actual result: struct matrix_add; matrix_add operator +(matrix const& a, matrix const& b) { return matrix_add(a, b); } Now all that needs to be done is to write this proxy: struct matrix_add { matrix_add(matrix const& a, matrix const& b) : a(a), b(b) { } operator matrix() const { matrix result; // Do the addition. return result; } private: matrix const& a, b; }; The magic lies in the method operator matrix() which is an implicit conversion operator from matrix_add to plain matrix. This way, you can chain multiple operations (by providing appropriate overloads of course). The evaluation takes place only when the final result is assigned to a matrix instance. EDIT I should have been more explicit. As it is, the code makes no sense because although evaluation happens lazily, it still happens in the same expression. In particular, another addition will evaluate this code unless the matrix_add structure is changed to allow chained addition. C++0x greatly facilitates this by allowing variadic templates (i.e. template lists of variable length). However, one very simple case where this code would actually have a real, direct benefit is the following: int value = (A + B)(2, 3); Here, it is assumed that A and B are two-dimensional matrices and that dereferencing is done in Fortran notation, i.e. the above calculates one element out of a matrix sum. It's of course wasteful to add the whole matrices. matrix_add to the rescue: struct matrix_add { // … yadda, yadda, yadda … int operator ()(unsigned int x, unsigned int y) { // Calculate *just one* element: return a(x, y) + b(x, y); } }; Other examples abound. I've just remembered that I have implemented something related not long ago. Basically, I had to implement a string class that should adhere to a fixed, pre-defined interface. However, my particular string class dealt with huge strings that weren't actually stored in memory. Usually, the user would just access small substrings from the original string using a function infix. I overloaded this function for my string type to return a proxy that held a reference to my string, along with the desired start and end position. Only when this substring was actually used did it query a C API to retrieve this portion of the string.
414,274
414,568
The latest version of gcc to use libstdc++.so.5
What is the latest version of gcc that still uses libstdc++.so.5 (as opposed to libstdc++.so.6)?
After searching all over for the answer, and failing to find it. I compiled several different versions and the last version to use libstdc++.so.5 is version 3.3 (more specifically 3.3.6). Version 3.4.X uses libstdc++.so.6.
414,714
414,725
Compiling with g++ using multiple cores
Quick question: what is the compiler flag to allow g++ to spawn multiple instances of itself in order to compile large projects quicker (for example 4 source files at a time for a multi-core CPU)?
You can do this with make - with gnu make it is the -j flag (this will also help on a uniprocessor machine). For example if you want 4 parallel jobs from make: make -j 4 You can also run gcc in a pipe with gcc -pipe This will pipeline the compile stages, which will also help keep the cores busy. If you have additional machines available too, you might check out distcc, which will farm compiles out to those as well.
415,199
415,226
const_cast for vector with object
I understand that const_cast to remove constness of objects is bad, I have the following use case, //note I cannot remove constness in the foo function foo(const std::vector<Object> & objectVec) { ... int size = (int) objectVec.size(); std::vector<Object> tempObjectVec; //Indexing here is to just show a part of the vector being //modified for (int i=0; i < (int) size-5; ++i) { Object &a = const_cast<Object&> objectVec[i]; tempObjectVec.push_back(a); } foo1(tempObjectVec); } If i change tempObjectVec objects in foo1, will the original objects in ObjectVec change, I say yes since I am passing references, further is this efficient. Can you suggest alternatives.
Well, that depends on Object. But the Objects are being copied, when you pass them to push_back. You can check this by adding some debug code to the copy constructor. So if Object is well-behaved and keeps distinct copies separate, then foo1 can change the vector it gets all it likes. A more efficient way to do this would be to have foo1 accept a start and end iterators: void foo1(std::vector<Object>::const_iterator start, std::vector<Object>::const_iterator end); ... foo1(objectVec.begin(), objectVec.end() - 5); If you don't use const_cast, then the type system will ensure that foo1 does not change any elements, as these are const_iterators.
415,515
415,575
How can I read and manipulate CSV file data in C++?
Pretty self-explanatory, I tried google and got a lot of the dreaded expertsexchange, I searched here as well to no avail. An online tutorial or example would be best. Thanks guys.
If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model: struct Customer { int id; std::string first_name; std::string last_name; struct { std::string street; std::string unit; } address; char state[2]; int zip; }; Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer> or std::set<Customer>. With that in mind, think of your CSV handling as two operations: // if you wanted to go nuts, you could use a forward iterator concept for both of these class CSVReader { public: CSVReader(const std::string &inputFile); bool hasNextLine(); void readNextLine(std::vector<std::string> &fields); private: /* secrets */ }; class CSVWriter { public: CSVWriter(const std::string &outputFile); void writeNextLine(const std::vector<std::string> &fields); private: /* more secrets */ }; void readCustomers(CSVReader &reader, std::vector<Customer> &customers); void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers); Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits: Your data is represented in a form that makes sense for your problem (customers), rather than the current solution (CSV files). You can trivially add adapters for other data formats, such as bulk SQL import/export, Excel/OO spreadsheet files, or even an HTML <table> rendering. Your memory footprint is likely to be smaller (depends on relative sizeof(Customer) vs. the number of bytes in a single row). CSVReader and CSVWriter can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.
415,941
415,960
VisualStudio *.obj files size (513Mb objs and 534Mb lib)
I'm a C++ developer and using Visual Studio 2008. How can I reduce *.obj files size? I've read why are my visual studio .obj files are massive in size compared to the output .exe? but didn't find the answer. When I build project to a static lib total size of all *.obj files is 513Mb and resulting lib is 534Mb. Each obj file is 1-13Mb. Debug exe file is 11Mb. Link-time code generation (/Gm) is turned off. Thanks in advance.
Object files tend to get large because of large amounts of duplicated code and symbols placed into multiple object files. Typically this is caused by copies of inline functions and instantiated template code. The resulting executable is much, much smaller than the sum of all the object files as duplicated weak symbols and unreferenced symbols can be discarded. Personally, I wouldn't worry about object file size, but if you want to reduce it then minimize the use of inline functions and consider keeping template code in separate files from the other code and using explicit instantiation to generate the required instantiations in only one place. Example Suppose that you have this in a header file. template< class T > inline void F( T* t ) { // ... some code } If you use F for a handful of types, then every translation unit will generate copies of the function for the types that it uses. If you replace it with just a declaration: template< class T > void F( T* t ); then you can generate just the instantations that you need in a separate source file: template< class T > void F( T* t ) { // definition } template void F< int >( int* ); template void F< char >( char* ); template void F< MyType >( MyType* ); Of course, you now have to manual manage which types you need a template instantiation for.
416,162
416,195
Assignment inside function that is passed as pointer?
ClassA* pa = NULL; ClassA* pb = NULL; void assignObject(ClassA* pa, ClassB* pb) { pa = new ClassA; pb = new ClassB; } What will be the value of pa and pb after executing the function? EDIT how to pass as pointer is the return if pa,pb is NULL
As pointed out in other answers - both will still be NULL after the call. However, there are two possible solutions to this problem: 1) references void assignObject(ClassA*& pa, ClassB*& pb) { pa = new ClassA; pb = new ClassB; } ClassA* pa = NULL; ClassA* pb = NULL; assignObject(pa, pb); // both will be assigned as expected. 2) pointers void assignObject(ClassA** pa, ClassB** pb) { assert(pa != NULL); assert(pb != NULL); *pa = new ClassA; *pb = new ClassB; } ClassA* pa = NULL; ClassA* pb = NULL; assignObject(&pa, &pb); // both will be assigned as expected. Most programmers would probably choose references because then they don't need to assert anything (references can never be NULL).
416,345
416,354
Is f(void) deprecated in modern C and C++?
I'm currently refactoring/tidying up some old C code used in a C++ project, and regularly see functions such as: int f(void) which I would tend to write as: int f() Is there any reason not to replace (void) with () throughout the codebase in order to improve consistency, or is there a subtle difference between the two that I am unaware of? More specifically, if a virtual member function in C++ is described as: virtual int f(void) and a derived class includes a member function: int f() is this a valid override? Additionally, am I likely to encounter any linker problems based on almost identical signatures?
In C, the declaration int f(void) means a function returning int that takes no parameters. The declaration int f() means a function returning int that takes any number of parameters. Thus, if you have a function that takes no parameters in C, the former is the correct prototype. In C++, I believe int f(void) is deprecated, and int f() is preferred, as it specifically means a function that takes no parameters.
416,436
416,622
What to put in a binary data file's header
I have a simulation that reads large binary data files that we create (10s to 100s of GB). We use binary for speed reasons. These files are system dependent, converted from text files on each system that we run, so I'm not concerned about portability. The files currently are many instances of a POD struct, written with fwrite. I need to change the struct, so I want to add a header that has a file version number in it, which will be incremented anytime the struct changes. Since I'm doing this, I want to add some other information as well. I'm thinking of the size of the struct, byte order, and maybe the svn version number of the code that created the binary file. Is there anything else that would be useful to add?
In my experience, second-guessing the data you'll need is invariably wasted time. What's important is to structure your metadata in a way that is extensible. For XML files, that's straightforward, but binary files require a bit more thought. I tend to store metadata in a structure at the END of the file, not the beginning. This has two advantages: Truncated/unterminated files are easily detected. Metadata footers can often be appended to existing files without impacting their reading code. The simplest metadata footer I use looks something like this: struct MetadataFooter{ char[40] creatorVersion; char[40] creatorApplication; .. or whatever } struct FileFooter { int64 metadataFooterSize; // = sizeof(MetadataFooter) char[10] magicString; // a unique identifier for the format: maybe "MYFILEFMT" }; After the raw data, the metadata footer and THEN the file footer are written. When reading the file, seek to the end - sizeof(FileFooter). Read the footer, and verify the magicString. Then, seek back according to metadataFooterSize and read the metadata. Depending on the footer size contained in the file, you can use default values for missing fields. As KeithB points out, you could even use this technique to store the metadata as an XML string, giving the advantages of both totally extensible metadata, with the compactness and speed of binary data.
416,451
416,637
Symbian C++ - Load and display image from .mbm file
I have a .mbm file that I copy to my device using this line in the .pkg file "$(EPOCROOT)epoc32\data\z\resource\apps\MyApp.mbm" -"!:\resource\apps\MyApp.mbm" Then in the draw function of my container I do this.. _LIT(KMBMFile , "\\resource\\apps\\MyApp.mbm" ); CFbsBitmap* iBitmap; iBitmap->Load(KMBMFile, 0); gc.BitBlt(Rect().iTl, iBitmap); However the line iBitmap->Load(KMBMFile, 0); raises a KERN-EXEC:0 PANIC "This panic is raised when the Kernel cannot find an object in the object index for the current process or current thread using the specified object index number (the raw handle number)." Can anyone spot where I am going wrong? Thanks!
You were dereferencing an uninitialized pointer, you could also use this: // remember to include the EIK environemnt include file #include <eikenv.h> _LIT(KMBMFile , "\\resource\\apps\\MyApp.mbm" ); CFbsBitmap* iBitmap; iBitmap = iEikonEnv->CreateBitmapL( KMBMFile, 0 ); gc.BitBlt( Rect().iTl, iBitmap );
416,464
416,521
Is it possible to exit a for before time in C++, if an ending condition is reached?
I want to know if it is possible to end a for loop in C++ when an ending condition (different from the reacheing right number of iterations) is verified. For instance: for (int i = 0; i < maxi; ++i) for (int j = 0; j < maxj; ++j) // But if i == 4 < maxi AND j == 3 < maxj, // then jump out of the two nested loops. I know that this is possible in Perl with the next LABEL or last LABEL calls and labeled blocks, is it possible to do it in C++ or I should use a while loop? Thank you.
You can use the return keyword: move the nested loop into a subroutine, invoke the subroutine to run the nested loops, and 'return' from the subroutine to exit [all] the loops.
416,739
416,758
Difference between WinMain,main and DllMain in C++
What is the difference between the three functions and when to use them??
WinMain is used for an application (ending .exe) to indicate the process is starting. It will provide command line arguments for the process and serves as the user code entry point for a process. WinMain (or a different version of main) is also a required function. The OS needs a function to call in order to start a process running. DllMain is used for a DLL to signify a lot of different scenarios. Most notably, it will be called when The DLL is loaded into the process: DLL_PROCESS_ATTACH The DLL is unloaded from the process: DLL_PROCESS_DETACH A thread is started in the process: DLL_THREAD_ATTACH A thread is ended in the process: DLL_THREAD_DETACH DllMain is an optional construct and has a lot of implicit contracts associated with it. For instance, you should not be calling code that will force another DLL to load. In general it's fairly difficult function to get right and should be avoided unless you have a very specific need for it.
416,904
416,943
C++ ATL Member Variable access help
I am not familiar with this, and can use a kick start. I am using ATL (unmanaged C++) user control and would like to use the ShockWave ActiveX object. I need to know how to declare it so that I can set a property or call a method. For instance, if I could assign a variable to it, then I would like to call 'variable->LoadMovie()' I know this is super ridiculous... almost embarrassed to ask it here. ;) (almost)
If you #import the dll (which I recommend when working with COM because it makes your life SO much easier), you can use a smart pointer paired with the CLSID of the object. Remember that smart pointer classes have the post-fix 'Ptr' after the interface name. For instance: ISomeInterfacePtr pSomeInterface( CLSID_SomeComponent ); HRESULT hr = pSomeInterface->SomeMethod(); Hope that helps. EDIT: If you want to check the HRESULT of the allocation, you can do the following: ISomeInterfacePtr pSomeInterface = 0; HRESULT hr = pSomeInterface.CreateInstance( CLSID_SomeComponent );
416,974
416,982
What is the definitive link for C and C++ programming languages?
Lately all modern programming languages have a definitive web site to support, distribute, learn the programming language, as well as community forums, e-mail lists and so on. Java has java.sun.com, python has python.org, etc. However C/C++ does not seem to have such a site. Which site do you use, say in a document, to link for C or C++ programming language? Wikipedia entries don't count, although they might be perfect fit. Founder's web sites? Or any other ideas?
The C Programming Language
417,146
417,263
Need to 'wrap up' a C++ dll/h/lib/xml/exe based SDK into a COM to use in a C# 2.0 project
I just got handed an SDK made of C++ dll, lib, exe, and various .h files. I presume it is meant for C++ developers. The sample projects they provide with their documentation are all written in C++. I am able to spin them up with Visual Studio 8 (2005) and run them. They do control the device as advertised. However the project this needs to be used by is in C# .Net 2.0 and that is unchangeable. My boss was a C++ developer and says all I need to do is to compile it as a COM object and then import the COM object into my C# solution. My boss says it should take less than an hour to "wrap" there SDK up as a COM object, even for me with no knowledge of C++ compiling. I've used COM objects in C# solutions before so once this is made, I can continue on from there without a problem. However, I don't know what to do to make the COM object from the 2 .dll files, 1 .exe, 1 .lib file, 1 .xml file, and the 12 .h files. Is there a resource available to tell me what to do to make this happen?
My boss was a C++ developer and says all I need to do is to compile it as a COM object and then import the COM object into my C# solution. That's true, however compiling it as a COM object is "difficult" (by which, I mean that you can't do it) unless it already implements the COM APIs (if it doesn't then you need to implement the COM APIs before you can build it as a COM object). There are books (for example, Essential COM) which explain how to to create COM objects using C++, but it's non-trivial (for building COM objects there may be better books than Essential COM, and better/easier tools than C++). I think you and/or your boss have 3 options: Ask the vendor to give them to you as COM objects Design a COM API that would wrap the SDK's API. Create a COM project (in the language of your choice) which exports this API. Implement these APIs by invoking the underlying SDK methods. To do this you may need someone who knows C++, or be willing to spend much, much longer than "an hour" on this project. Forget about using COM; instead, build the SDK as a DLL, and use PInvoke to invoke it from .NET code. My boss says it should take less than an hour to "wrap" there SDK up as a COM object, even for me with no knowledge of C++ compiling. Based on what you've said I don't know of any way to make that happen.
417,446
417,509
Managing C++ objects in a buffer, considering the alignment and memory layout assumptions
I am storing objects in a buffer. Now I know that I cannot make assumptions about the memory layout of the object. If I know the overall size of the object, is it acceptible to create a pointer to this memory and call functions on it? e.g. say I have the following class: [int,int,int,int,char,padding*3bytes,unsigned short int*] 1) if I know this class to be of size 24 and I know the address of where it starts in memory whilst it is not safe to assume the memory layout is it acceptible to cast this to a pointer and call functions on this object which access these members? (Does c++ know by some magic the correct position of a member?) 2) If this is not safe/ok, is there any other way other than using a constructor which takes all of the arguments and pulling each argument out of the buffer one at a time? Edit: Changed title to make it more appropriate to what I am asking.
You can create a constructor that takes all the members and assigns them, then use placement new. class Foo { int a;int b;int c;int d;char e;unsigned short int*f; public: Foo(int A,int B,int C,int D,char E,unsigned short int*F) : a(A), b(B), c(C), d(D), e(E), f(F) {} }; ... char *buf = new char[sizeof(Foo)]; //pre-allocated buffer Foo *f = new (buf) Foo(a,b,c,d,e,f); This has the advantage that even the v-table will be generated correctly. Note, however, if you are using this for serialization, the unsigned short int pointer is not going to point at anything useful when you deserialize it, unless you are very careful to use some sort of method to convert pointers into offsets and then back again. Individual methods on a this pointer are statically linked and are simply a direct call to the function with this being the first parameter before the explicit parameters. Member variables are referenced using an offset from the this pointer. If an object is laid out like this: 0: vtable 4: a 8: b 12: c etc... a will be accessed by dereferencing this + 4 bytes.
417,481
417,635
Pointers, smart pointers or shared pointers?
I am programming with normal pointers, but I have heard about libraries like Boost that implement smart pointers. I have also seen that in Ogre3D rendering engine there is a deep use of shared pointers. What exactly is the difference between the three, and should I stick on using just a type of them?
Sydius outlined the types fairly well: Normal pointers are just that - they point to some thing in memory somewhere. Who owns it? Only the comments will let you know. Who frees it? Hopefully the owner at some point. Smart pointers are a blanket term that cover many types; I'll assume you meant scoped pointer which uses the RAII pattern. It is a stack-allocated object that wraps a pointer; when it goes out of scope, it calls delete on the pointer it wraps. It "owns" the contained pointer in that it is in charge of deleteing it at some point. They allow you to get a raw reference to the pointer they wrap for passing to other methods, as well as releasing the pointer, allowing someone else to own it. Copying them does not make sense. Shared pointers is a stack-allocated object that wraps a pointer so that you don't have to know who owns it. When the last shared pointer for an object in memory is destructed, the wrapped pointer will also be deleted. How about when you should use them? You will either make heavy use of scoped pointers or shared pointers. How many threads are running in your application? If the answer is "potentially a lot", shared pointers can turn out to be a performance bottleneck if used everywhere. The reason being that creating/copying/destructing a shared pointer needs to be an atomic operation, and this can hinder performance if you have many threads running. However, it won't always be the case - only testing will tell you for sure. There is an argument (that I like) against shared pointers - by using them, you are allowing programmers to ignore who owns a pointer. This can lead to tricky situations with circular references (Java will detect these, but shared pointers cannot) or general programmer laziness in a large code base. There are two reasons to use scoped pointers. The first is for simple exception safety and cleanup operations - if you want to guarantee that an object is cleaned up no matter what in the face of exceptions, and you don't want to stack allocate that object, put it in a scoped pointer. If the operation is a success, you can feel free to transfer it over to a shared pointer, but in the meantime save the overhead with a scoped pointer. The other case is when you want clear object ownership. Some teams prefer this, some do not. For instance, a data structure may return pointers to internal objects. Under a scoped pointer, it would return a raw pointer or reference that should be treated as a weak reference - it is an error to access that pointer after the data structure that owns it is destructed, and it is an error to delete it. Under a shared pointer, the owning object can't destruct the internal data it returned if someone still holds a handle on it - this could leave resources open for much longer than necessary, or much worse depending on the code.
417,745
417,846
OS X equivalent to OutputDebugString()?
I'm examining the feasibility of porting an existing Windows MFC control to OS X/Carbon. My test bed is a C++ Carbon application generated using the XCode 3 Wizard. I'm looking for a quick way to dump some trace info to the debugger or the OS X equivalent of DbgView. On Win32 I'd use OutputDebugString() - what's the deal on OS X? Is there a way to view test written to std::cout from a Carbon app? Thanks Jerry
There is no real equivalent. Xcode uses GDB under the hood, so you're basically dealing with that. You could, however, implement it yourself. The code sample below will produce output to standard out only when the debugger is present. You could further protect this by wrapping it in preprocessor directives as a macro and compile it out (or into an inline nil function) if NDEBUG is present at compile time. Any output produced by an application will be directed to the debugging console in Xcode. extern "C" { bool IsDebuggerPresent() { int mib[4]; struct kinfo_proc info; size_t size; info.kp_proc.p_flag = 0; mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); size = sizeof(info); sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0); return ((info.kp_proc.p_flag & P_TRACED) != 0); } void OutputDebugString(const char *restrict fmt, ...) { if( !IsDebuggerPresent() ) return; va_list args; va_start(args, fmt); vprintf(fmt, args); va_end(args); } }
417,788
417,804
Help to correct source code, with template
I tried to compile the example posted (C++ Service Providers) and failed to VS8 VC9. I have little experience with template. Any suggestions? Tanks. These are the errors : dictionarystl.cpp(40) : error C2663: 'std::_Tree<_Traits>::find' : 2 overloads have no legal conversion for 'this' pointer dictionarystl.cpp(48) : error C2679: binary '[' : no operator found which takes a right-hand operand of type 'const type_info *__w64 ' (or there is no acceptable conversion) #include <typeinfo> #include <map> #include <string> using namespace std; class SomeClass { public: virtual ~SomeClass() {} // virtual function to get a v-table }; struct type_info_less { bool operator() (const std::type_info* lhs, const std::type_info* rhs) const { return lhs->before(*rhs) != 0; } }; class TypeMap { typedef map <type_info *, void *, type_info_less> TypenameToObject; TypenameToObject ObjectMap; public: template <typename T> T *Get () const { TypenameToObject::const_iterator iType = ObjectMap.find(&typeid(T)); if (iType == ObjectMap.end()) return NULL; return reinterpret_cast<T *>(iType->second); } template <typename T> void Set(T *value) { ObjectMap[&typeid(T)] = reinterpret_cast<void *>(value); } }; int main() { TypeMap Services; Services.Set<SomeClass>(new SomeClass()); SomeClass *x = Services.Get<SomeClass>(); }
For this code to compile, the following line: typedef map<type_info *, void *, type_info_less> TypenameToObject; should be: typedef map<const type_info *, void *, type_info_less> TypenameToObject;
417,876
417,973
How do I source/link external functions in C or C++?
EDIT: I suppose I should clarify, in case it matters. I am on a AIX Unix box, so I am using VAC compilers - no gnu compilers. End edit I am pretty rusty in C/C++, so forgive me if this is a simple question. I would like to take common functions out of a few of my C programs and put them in shared libraries or shared objects. If I was doing this in perl I would put my subs in a perl module and use that module when needed. For the sake of an example, let's say I have this function: int giveInteger() { return 1034; } Obviously this is not a real world example, but if I wanted to share that function, how would I proceed? I'm pretty sure I have 2 options: Put my shared function in a file, and have it compile with my main program at compile time. If I ever make changes to my shared function, I would have to recompile my main program. Put my shared function in a file, and compile it as a shared library (if I have my terms correct), and have my main program link to that shared library. Any changes I make to my shared library (after compiling it) would be integrated into my main program at runtime without re-compiling my main program. Am I correct on that thinking? If so, how can I complish either/both of those methods? I've searched a lot and I seem to find information how how I could have my own program link to someone else's shared library, but not how to create my own shared functions and compile them in a way I can use them in my own program. Thanks so much! Brian EDIT: Conclusion Thanks everyone for your help! I thought I would add to this post what is working for me (for dynamic shared libraries on AIX) so that others can benefit: I compile my shared functions: xlc -c sharedFunctions.c -o sharedFunctions.o Then make it a shared object: xlc -qmkshrobj -qexpfile=exportlist sharedFunctions.o xlc -G -o libsharedFunctions.so sharedFunctions.o -bE:exportlist Then link it another program: xlc -brtl -o mainProgram mainProgram.c -L. -lsharedFunctions And another comment helped me find this link, which also helped: http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/topic/com.ibm.vacpp7a.doc/proguide/ref/compile_library.htm Thanks again to all who helped me out!
Yeah you are correct. The first is called a static library, while the second is called a shared library, because the code is not bound to the executable at compile time, but everytime again when your program is loaded. Static library Compile your library's code as follows: gcc -c *.c The -c tells the program not to link the object file, but just leaves you with object files for each .c file that was compiled. Now, archive them into one static library: ar rcs libmystuff.a *.o man ar will tell you what the rcs options mean. Now, libmystuff.a is a archive file (you can open it with some zip-file viewers) which contain those object files, together with an index of symbols for each object file. You can link it to your program: gcc *.c libmystuff.a -o myprogram Now, your program is ready. Note that the order of where the static libraries appear in the command matter. See my Link order answer. Shared library For a shared library, you will create your library with gcc -shared -o libmystuff.so *.c That's all it takes, libmystuff.so is now a shared object file. If you want to link a program to it, you have to put it into a directory that is listed in the /etc/ld.so.conf file, or that is given by the -L switch to GCC, or listed in the LD_LIBRARY_PATH variable. When linking, you cut the lib prefix and .so suffix from the library name you tell gcc. gcc -L. -lmystuff *.c -o myprogram Internally, gcc will just pass your arguments to the GNU linker. You can see what arguments it pass using the -### option: Gcc will print the exact arguments given to each sub process. For details about the linking process (how some stuff is done internally), view my Linux GCC linker answer.
418,039
418,766
CPU Utilization of Service DLL?
I need to find out the CPU utilization of a service DLL. I have looked in existing samples and we can find CPU utilization for processes. I think DLL will be loaded by services.exe. So is it possible to find out CPU utilization by DLL. I am working in C++ on the Windows platform.
Make a copy of svchost.exe and call it dbgsrvc.exe; then, go into the service entry in the registry (HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog for example), and change the ImagePath to use dbgsrvc instead of services. That way, you've isolated your service into its own process so you can get perf counters on it.
418,121
418,155
Compiler error for modifying a non-const object
#include "iostream" #include "vector" class ABC { private: bool m_b; public: ABC() : m_b(false) {} ABC& setBool(bool b) { m_b = b; return *this; } bool getBool() const { return m_b; } }; void foo(const std::vector<ABC> &vec) { vec[0].setBool(true); } int main(int argc, char*argv[]) { std::vector<ABC> vecI; ABC i; vecI.push_back(i); foo(vecI); } When I compile it I get this error: passing const ABC as this argument of ABC& ABC::setBool(bool) discards qualifiers Any ideas why this would happen since the object itelf is not a constant.
foo takes vec by reference-to-const, and you cannot change a const. So either remove the line that calls setBool, or if you really want to set the bool, change the argument type to std::vector&. Or to be more strict about the implementation... You see, these two functions exist: T& vector<T>::operator[](int); T const& vector<T>::operator[](int) const; When you call "vec[i]" on a const object, only the second one is valid, so it gets selected. But this overload obviously returns T const&, and that's the thing you can't change.
418,545
418,555
A random number generator that can get different numbers in < a second
I'm in need of a C++ (pseudo, i don't care) random number generator that can get me different numbers every time I call the function. This could be simply the way I seed it, maybe there's a better method, but every random generator I've got doesn't generate a new number every time it's called. I've got a need to get several random numbers per second on occasion, and any RNG i plug in tends to get the same number several times in a row. Of course, I know why, because it's seeded by the second, so it only generates a new number every second, but I need to, somehow, get a new number on every call. Can anyone point me in the right direction?
Sounds like you do it like this: int get_rand() { srand(time(0)); return rand(); } Which would explain why you get the same number within one second. But you have to do it like this: int get_rand() { return rand(); } And call srand once at program startup.
418,887
428,253
Array over written with last value assigned?
I have a pointer to pointer array. I am assigning each row in the while loop below and the printf inside the while loop shows each is assigned my id number 1-20. After, out side of the while loop I iterate through the array and every element is written with id 20? Any help is greatly appreciated. (FYI- I am using the Template2doc library and example1.c, at the bottom here- http://www.algonet.se/~thunberg/template2doc/c_version/docs/index.htm) Below code only shows problem area, I took out the rest. char **tableData[500]={NULL}; char *myData[500][2]; while(rc == SQLITE_ROW){ tableData[r] = myData[r]; printf(*tableData[r]); <-- Displays id 1-20 fine r=r+1; }//end while tableData[r+1] = NULL;//null terminated array for (a=0; a<r; a++){ printf("\n"); printf(*tableData[a]); <--Displays 20 elements all of id 20? } outputFile=insertTableData(outputFile, dataMarker, fieldMarker, tableData);
You should create something that actually compiles and reproduces the problem. Not only will it help people help you, but in doing so you may very well find the problem yourself. In your code excerpts we have no idea: What rc is, how its value is set, or how its value is ever going to change and therefore terminate the loop What the initial value of r is What the actual contents of myData are I created this code based on what you posted, which produces the same output from both loops. So either I've missed something in what you did post, or you left something important out. int main( int argc, char** argv ) { #define STRING char * STRING dummy = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()"; STRING *tableData[500]={0}; STRING myData[500][2]; int r=0; while(r < 20){ myData[r][0] = dummy+2*r; myData[r][1] = dummy+r; tableData[r] = myData[r]; printf(*tableData[r]); printf("\n"); r=r+1; }//end while int a; for (a=0; a<r; a++){ printf(*tableData[a]); printf("\n"); } }
419,045
419,053
How to add padding bytes to a bitmap?
Lets say I have some raster data I want to write to a file.. Now I want to write it as a bmp file.. This data happens to be not DWORD aligned, which, if I understand correctly, needs to be padded with enough bytes to reach the next DWORD.. However, when I try to pad it with this code: bmFile.Write(0x0, (4-(actualWidth%4))); I get an error.. If I try to debug (I'm using MSVC++ 6.0), the next statement points to an ASSERT in CFile::Write that asserts the first parameter is NULL.. So this fails.. How should I pad it? should I write out: bmFile.Write("0x0"(4-(actualWidth%4))); instead? or would this be treated literally...? Thanks..
Perhaps try: bmFile.Write("\0\0\0\0", (4-(actualWidth%4))); Your first example is, as you say, trying to write data pointed to by a null pointer. Your second example would write from the bytes '0', 'x', '0' which have ASCII values 0x30, 0x78, 0x30, which is probably not what you intend.
419,096
419,099
What is the best open source example of a lightweight Windows Application?
I would like to learn how a program can be written and installed without the use of the .net framework. I'm looking for a project that is known to be lightweight and robust. Something like the uTorrent client.
chromium, the open-source project behind Google Chrome, is chalk full of clean, robust (and unit-tested) code. If you choose to dive in, keep the map handy.
419,328
506,243
How to record keystrokes when keyboard journaling is not available?
Having setup C++ app originally using MS specific keyboard journaling hook (WH_JOURNALRECORD) we find that it does not work on Vista unless run as administrator with uiAccess enabled. MSDN Question - Journaling hooks on Vista? We want to record a key sequence from the user in a friendly way that will be repeated at some later date. The user presses a record button, a dialog is displayed with a stop button and the recorded keys. One advantage of using the journaling hook was that you only got keystrokes which did something. Holding down shift didn't report 100 shift keys, but did report usage when you hit a letter. Another advantage was that you could set the focus to an area outside of the application, say another applications window, and record the action as the user interacted. Asides from making the keyboard capture part of the existing app a separate executable which runs as administrator with uiAccess, I'm seeking other ideas on how to record keystrokes that work on windows for 2K, 2K3, 2K8, XP, Vista. Edit: I know there is a security concern with just recording anything, obviously if you could do such a thing without the users notice you have your typical keystroke logger for hacking purposes. Soooooo..... Is there a way to make journaling work, for this user, and their apps, running at the same level (or lower) and capture keystrokes? having it popup the vista security are you sure dialog would be allright, but the process cannot be marked with uiAccess (otherwise it won't interact properly with the rest of the system) and it will in 98% of cases be run by users without rights to elevate to administrator.
We have worked around the main issues by using SetWindowsHook instead. const HMODULE hDLL = ::GetModuleHandle(DLL_NAME); ::SetWindowsHookEx(WH_KEYBOARD_LL, myKeyboardProcCallback, hDLL, 0); The callback now has to manage the keystroke information and translating it into usable sequences - ie don't record multiple ctrl presses when heeld down to press ctrl+key.
419,344
419,377
C++ 'GET' request or how do you download files to work with in C++?
Alright I've spent a good three days trying this, here's the scenario: I want to download a '.csv' file from Google and then do stuff with the data from the file. It's for a Win32 Console Application. I have the latter down, I just cannot for the life of me figure out how to download the file. I've heard of libcurl, curlpp, ptypes, rolling my own, just using the .NET api, and been told a bunch of times: ...it's just a GET request Well that's all well and good, but I must be missing something because it seems like everyone was just born knowing how to do this. I have been combing through books looking to figure this out and even had a huge problem with LNKerrors after traveling down the road with "The Art of C++" for a while. All that being said, I have learned a LOT from this, but at this point I just want to know how to do it. The API for C++ is seriously lacking, no example code to be found. Tutorials online are almost non-existent. And no book out there seems to think this is important. Can someone please throw me a life raft? I'm a man on the edge here. edit By "from Google" I mean that I want to download a .csv file that they host. An example can be found here.
You should be able to bend this to your will. Now that I have kinda answered your question. Why C++? Nothing against the language, but pick the best language for the job. Perl, PHP, and Python(and I am sure more) all have great documentation and support on this kind of operation. In perl(the one I am familiar with) it's just about 3-5 lines of code. Here is the code snippet previously available in (from WayBackMachine): /* * This is a very simple example of how to use libcurl from within * a C++ program. The basic idea is that you want to retrieve the * contents of a web page as a string. Obviously, you can replace * the buffer object with anything you want and adjust elsewhere * accordingly. * * Hope you find it useful.. * * Todd Papaioannou */ #include <string> #include <iostream> #include "curl/curl.h" using namespace std; // Write any errors in here static char errorBuffer[CURL_ERROR_SIZE]; // Write all expected data in here static string buffer; // This is the writer call back function used by curl static int writer(char *data, size_t size, size_t nmemb, std::string *buffer) { // What we will return int result = 0; // Is there anything in the buffer? if (buffer != NULL) { // Append the data to the buffer buffer->append(data, size * nmemb); // How much did we write? result = size * nmemb; } return result; } // You know what this does.. void usage() { cout < < "curltest: \n" << endl; cout << " Usage: curltest url\n" << endl; } /* * The old favorite */ int main(int argc, char* argv[]) { if (argc > 1) { string url(argv[1]); cout < < "Retrieving " << url << endl; // Our curl objects CURL *curl; CURLcode result; // Create our curl handle curl = curl_easy_init(); if (curl) { // Now set up all of the curl options curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, errorBuffer); curl_easy_setopt(curl, CURLOPT_URL, argv[1]); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writer); curl_easy_setopt(curl, CURLOPT_WRITEDATA, &buffer); // Attempt to retrieve the remote page result = curl_easy_perform(curl); // Always cleanup curl_easy_cleanup(curl); // Did we succeed? if (result == CURLE_OK) { cout << buffer << "\n"; exit(0); } else { cout << "Error: [" << result << "] - " << errorBuffer; exit(-1); } } } }
419,406
419,553
Are assertions always bad?
I used to work for a company where some of the lead architect/developers had mandated on various projects that assertions were not to be used, and they would routinely be removed from code and replaced with exceptions. I feel they are extremely important in writing correct code. Can anyone suggest how such a mandate could be justified? If so, what's wrong with assertions?
We use a modified version of assert, as per JaredPar's comment, that acts like a contract. This version is compiled into the release code so there is a small size overhead, but disabled unless a diagnostics switch is set, such that performance overhead is minimized. Our assert handler in this instance can be set to disabled, silent mode (e.g. log to file), or noisy mode (e.g. display on screen with abort / ignore, where abort throws an exception). We used automated regression testing as part of our pre-release testing, and asserts are hugely important here as they allow us to find potential internal errors that cannot be picked up at a GUI level, and may not be initially fatal at a user level. With automation, we can run the tests both with and without diagnostics, with little overhead other than the execution time, so we can also determine if the asserts are having any other side effects. One thing to be careful of with asserts is side effects. For example, you might see something like assert(MyDatabasesIsOk()), which inadvertently corrects errors in the database. This is a bug, as asserts should never change the state of the running application.
419,559
419,805
Is this possible use ellipsis in macro? Can it be converted to template?
Having implemented CLogClass to make decent logging I also defined macro, but it works only with one parameter... class CLogClass { public: static void DoLog(LPCTSTR sMessage, ...); }; #define DebugLog(sMessage, x) ClogClass::DoLog(__FILE__, __LINE__, sMessage, x) Well, it fails when called with more than 2 parameters :( ... Is it possible at all to avoid it? Can it be translated to templates somehow? EDIT: Variadic macros were introduced in VS 2005 (But i'm currently in VS 2003...). Any advices?
You could have a MYLOG macro returning a custom functor object which takes a variable number of arguments. #include <string> #include <cstdarg> struct CLogObject { void operator()( const char* pFormat, ... ) const { printf( "[%s:%d] ", filename.c_str(), linenumber ); va_list args; va_start( args, pFormat ); vfprintf( stderr, pFormat, args ); va_end( args ); } CLogObject( std::string filename, const int linenumber ) : filename( filename ), linenumber( linenumber ) {} std::string filename; int linenumber; }; #define MYLOG CLogObject( __FILE__, __LINE__ ) int _tmain(int argc, _TCHAR* argv[]) { MYLOG( "%s, %d", "string", 5 ); return 0; } Note that it's not so hard to step over to the type-safe variant touched by this answer: you don't need any variadic arguments due to the chaining effect of operator<<. struct CTSLogObject { template< typename T > std::ostream& operator<<( const T& t ) const { return std::cout << "[" << filename << ":" << linenumber << "] "; } CTSLogObject( std::string filename, const int linenumber ) : filename( filename ), linenumber( linenumber ) {} std::string filename; int linenumber; }; #define typesafelog CTSLogObject( __FILE__, __LINE__ ) int _tmain(int argc, _TCHAR* argv[]) { typesafelog << "typesafe" << ", " << 5 << std::endl; return 0; }
419,775
420,017
DirectDraw question - running the application as a regular Windows application
I am developing an application for video recording and I want to overlay the video preview with a logo and recording timer. I tried to run the full-screen application and everything worked fine. Then I tried to run the application as a regular Windows application and it returned an error. Could anyone take a look at the code below if there's a way to modify it to run the application as a regular Windows app? HRESULT CViewfinderRenderer::OnStartStreaming() { HRESULT hr = S_OK; DDSURFACEDESC ddsd; m_pDD = NULL; //full screen settings hr = DirectDrawCreate(NULL, &m_pDD, NULL); hr = m_pDD->SetCooperativeLevel(m_hWnd, DDSCL_FULLSCREEN); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; ddsd.ddsCaps.dwCaps = DDSCAPS_FLIP | DDSCAPS_PRIMARYSURFACE; ddsd.dwBackBufferCount = 1; //end full screen settings //normal settings /*hr = DirectDrawCreate(NULL, &m_pDD, NULL); hr = m_pDD->SetCooperativeLevel(m_hWnd, DDSCL_NORMAL); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_BACKBUFFERCOUNT; ddsd.dwBackBufferCount = 1;*/ //end normal settings hr = m_pDD->CreateSurface(&ddsd, &m_pSurface, NULL); if (hr != DD_OK) { return hr; } // Get backsurface hr = m_pSurface->EnumAttachedSurfaces(&m_pBackSurface, EnumFunction); return S_OK; }
Even when running windowed, you need to create a primary surface, only it is not a flippable surface. //full screen settings hr = DirectDrawCreate(NULL, &m_pDD, NULL); hr = m_pDD->SetCooperativeLevel(m_hWnd, DDSCL_NORMAL); ddsd.dwSize = sizeof(ddsd); ddsd.dwFlags = DDSD_CAPS; ddsd.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; Besides of creating a surface, most likely you will want to create a clipper for the window. For a complete sample see paragraph Running windowed in this GameDev article.
420,099
420,225
Is this' type variableofType()' function or object?
#include<iostream> class name { public: int a; name():a(0){}; }; void add(name * pname) { pname = NULL; } int main() { name varName(); name * pName = new name(); add(pName); add(&varName);//error C2664: 'add' : cannot convert parameter 1 from 'name __cdecl *)(void)' to 'name *' }
I think it's worth telling you about a similar problem, that also causes trouble: struct foo { }; struct bar { bar(foo f); }; int main() { // does *not* create a bar object initialized by a default constructed // foo object. bar b(foo()); } What b really is is a function that returns a bar and takes as first argument a pointer to a function that returns a foo taking no arguments. It's the same as: bar b(foo(*)()); If you want to create a bar object initialized by a default constructed foo, put parentheses around the argument. That makes it doesn't look like a function declaration anymore, and the compiler will interpret it like you want: bar b((foo())); There are also non-obvious cases where a compiler error should be risen. GCC gets this wrong, but Comeau gets it right again. Consider the following snippet struct foo { static bool const value = false; }; int main() { int v(int(foo::value)); } You will probably expect that this takes the static constant, and casts it to int, initializing the v variable to 0? No, it won't according to the Standard, because the initializer can be interpreted as a declaration, according to pure syntax analysis, as the following shows struct foo { static int value; }; // valid, parentheses are redundant! Defines `foo::value`. int (foo::value); Whenever the initializer can be interpreted as a declaration, in such a situation whole the declaration will declare a function. So, the line in main declares a function like the following, omitting the redundant and meaningless parentheses int v(int foo::value); And this will cause a compiler error when parsing the function declaration, because a function parameter name may not be qualified.
420,109
420,274
Symbian C++ - Remove or hide component (ie. CEikLabel)
Seemingly a simple enough question, but I cannot work it out. I want to hide a CEikLabel at a certain point. I want a function like.. myLabel->SetVisible(EFalse); or.. myLabel->RemoveFromView(); I realise I could just use myLabel->SetTextL(_L("")); but that is not what I want to do. Thanks :)
What about MakeVisible(TBool aVisible); Also read about it in Symbian forum
420,151
420,176
Get the value from a fixed memory offset : Visual C++ Programming
I would like to write an simple application able to retrieve some certain data from another process(application)'s allocated memory. Say I already know a process' id and I would like to obtain a value in this process' memory always from a fixed offset (like 0x523F1C), is this doable in the user-mode, or it has to be in kernel-mode? Any hints or info are highly appreciated. My environment is Windows XP, and I am using Visual C++ and Qt for GUI. Thanks in advance :) EDIT: (a) thanks guys. basically it's working (when setting a break point and hook over the value it's correct), but when doing a normal release build the value obtained is always the initialized :( will have to work more to figure it out... (b) Since the application I am trying to obtain value from isn't written by me, can I still do the interprocess communications / shared memory techniques? EDIT 2: thanks again for the quick response! :D
Use ReadProcessMemory - you'll need a handle with PROCESS_VM_READ access to the other process[1], but if you're an administrator (or possibly, if you have SE_DEBUG privs) it should be straightforward. BOOL WINAPI ReadProcessMemory( __in HANDLE hProcess, __in LPCVOID lpBaseAddress, __out LPVOID lpBuffer, __in SIZE_T nSize, __out SIZE_T* lpNumberOfBytesRead ); [1] HANDLE hProc = OpenProcess(PROCESS_VM_READ, false, pid); Edit: b) No, unless you use CreateRemoteThread - but you normally need to have shimmed your own DLL into the remote process before you can meaningfully create threads in that process. This is advanced, fun and dangerous :)
420,185
420,314
How to get the version information of a DLL file in C++
I need to get the version information of a DLL file I created in Visual Studio 2008 C++. How do I get it?
Thanks for the answers. This worked for me: WCHAR fileName[_MAX_PATH]; DWORD size = GetModuleFileName(g_dllHandle, fileName, _MAX_PATH); fileName[size] = NULL; DWORD handle = 0; size = GetFileVersionInfoSize(fileName, &handle); BYTE* versionInfo = new BYTE[size]; if (!GetFileVersionInfo(fileName, handle, size, versionInfo)) { delete[] versionInfo; return; } // we have version information UINT len = 0; VS_FIXEDFILEINFO* vsfi = NULL; VerQueryValue(versionInfo, L"\\", (void**)&vsfi, &len); aVersion[0] = HIWORD(vsfi->dwFileVersionMS); aVersion[1] = LOWORD(vsfi->dwFileVersionMS); aVersion[2] = HIWORD(vsfi->dwFileVersionLS); aVersion[3] = LOWORD(vsfi->dwFileVersionLS); delete[] versionInfo;
420,261
420,277
Using boost shared_ptr
I have to use a smart pointer and I found "shared_ptr" from boost looks good. I downloaded the boost library and I can see many files and libraries there. Is there any way to use only the shared_ptr ?
boost bcp is your friend. It allows extracting individual boost libraries out of its tree. I used it with success in the past. shared_ptr consists only of headers, so that will be especially good for you.
420,612
420,649
Is there around a straightforward way to invert a triangular (upper or lower) matrix?
I'm trying to implement some basic linear algebra operations and one of these operations is the inversion of a triangular (upper and/or lower) matrix. Is there an easy and stable algorithm to do that? Thank you.
Yes, use back substitution. A standard algorithm to invert a matrix is to find its LU decomposition (decomposition into a lower-triangular and an upper-triangular matrix), use back subsitution on the triangular pieces, and then combine the results to obtain the inverse of the original matrix.
420,726
420,804
How to cast member variable pointer to generic type in C++
I have code similar to this in my application: class A { public: int b; } class C { public: int d; } void DoThings (void *arg1, MYSTERYTYPE arg2); A obj_a; C obj_c; DoThings(&obj_a, &A::b); DoThings(&obj_c, &C::d); The question is - What should MYSTERYTYPE be? neither void* nor int work, despite the value &A::b being printed just fine if you output it through a printf. Clarifications: Yes, &A::b is defined under C++. Yes, I am trying to get the offset to a class member. Yes, I am being tricky. Edit: Oh I can use offsetof(). Thanks anyway.
You have a data member pointer to two unrelated classes. Well, you can't find a common type that can hold both pointers. It will only work if the function parameter is a data member pointer to a member of the derived, because it's guaranteed to contain the member too, if a base contains it: struct a { int c; }; struct b : a { }; int main() { int b::*d = &a::c; } Update: I think i should write why the above converts from a::* to b::* implicitly. After all, we usually have b* to a* ! Consider: struct a { }; struct b : a { int c; }; struct e : a { }; int main() { int a::*d = &b::c; e e_; (e_.*d) = 10; /* oops! */ } If the above would be valid, you would really much screw up. The above is not valid, because conversion from b::* to a::* is not implicit. As you see, we assigned a pointer to b::c, and then we could dereference it using a class that doesn't contain it at all! (e). The compiler enforces this order: int main() { int b::*d = &b::c; e e_; (e_.*d) = 10; /* bug! */ } It fails to compile now, because e is not derived from b, the class the member pointer pointer belongs to. Good! The following, however, is very valid and compiles, of course (changed classes a and b): struct a { int c; }; struct b : a { }; struct e : a { }; int main() { int e::*d = &a::c; e e_; (e_.*d) = 10; /* works! */ } To make it work for your case, you have to make your function a template: template<typename Class> void DoThings (int Class::*arg) { /* do something with arg... */ } Now, the compiler will auto-deduce the right class that the given member pointer belongs too. You will have to pass the instance alongside of the member pointer to actually make use of it: template<typename Class> void DoThings (Class & t, int Class::*arg) { /* do something with arg... */ (t.*arg) = 10; } If you just want to set some member you already know at the time you write DoThings, the following suffices: template<typename Class> void DoThings (Class & t) { t.c = 10; }
420,852
422,063
reading an application's manifest file?
Is there an easy way to read an application's already embedded manifest file? I was thinking along the lines of an alternate data stream?
Windows manifest files are Win32 resources. In other words, they're embedded towards the end of the EXE or DLL. You can use LoadLibraryEx, FindResource, LoadResource and LockResource to load the embedded resource. Here's a simple example that extracts its own manifest... BOOL CALLBACK EnumResourceNameCallback(HMODULE hModule, LPCTSTR lpType, LPWSTR lpName, LONG_PTR lParam) { HRSRC hResInfo = FindResource(hModule, lpName, lpType); DWORD cbResource = SizeofResource(hModule, hResInfo); HGLOBAL hResData = LoadResource(hModule, hResInfo); const BYTE *pResource = (const BYTE *)LockResource(hResData); TCHAR filename[MAX_PATH]; if (IS_INTRESOURCE(lpName)) _stprintf_s(filename, _T("#%d.manifest"), lpName); else _stprintf_s(filename, _T("%s.manifest"), lpName); FILE *f = _tfopen(filename, _T("wb")); fwrite(pResource, cbResource, 1, f); fclose(f); UnlockResource(hResData); FreeResource(hResData); return TRUE; // Keep going } int _tmain(int argc, _TCHAR* argv[]) { const TCHAR *pszFileName = argv[0]; HMODULE hModule = LoadLibraryEx(pszFileName, NULL, LOAD_LIBRARY_AS_DATAFILE); EnumResourceNames(hModule, RT_MANIFEST, EnumResourceNameCallback, NULL); FreeLibrary(hModule); return 0; } Alternatively, you can use MT.EXE from the Windows SDK: >mt -inputresource:dll_with_manifest.dll;#1 -out:extracted.manifest
421,203
421,208
Can you make Visual Studio 2005 provide command line arguments for your startup program?
For testing purposes, is there some place in the Visual Studio IDE where you can specify the command line parameters that you want sent to your startup project when it's launched from the IDE? Thanks in advance for all your help!
Yes - click on Properties for your project, then Debugging, then Command Arguments. You can type in your command line arguments there, and they will be passed to your application on startup.
421,234
421,252
Convert MYSQL_TIME data type to char * or C++ string
I am using the MySQL C API within a C++ application. I have a column in my result set that is of the type MYSQL_TIME (part of mysql.h). Is there a way to convert MYSQL_TIME to a char* or to a C++ string?
I figured it out: fprintf(stdout, " %04d-%02d-%02d %02d:%02d:%02d (%ld)\n", ts.year, ts.month, ts.day, ts.hour, ts.minute, ts.second, length[3]); where length[3] contains the length of ts.
421,282
423,313
What make g++ include GLIBCXX_3.4.9?
I compiled 2 different binaries on the same GNU/Linux server using g++ version 4.2.3. The first one uses: GLIBC_2.0 GLIBC_2.2 GLIBC_2.1 GLIBCXX_3.4 GLIBC_2.1.3 The second one uses: GLIBC_2.0 GLIBC_2.2 GLIBC_2.1 GLIBCXX_3.4.9 GLIBCXX_3.4 GLIBC_2.1.3 Why the second binary uses GLIBCXX_3.4.9 that is only available on libstdc++.so.6.0.9 and not in libstdc++.so.6.0.8 What is the new feature generated by g++ that require an ABI break and force the system to have GLIBCXX_3.4.9? Is there a way to disable this new feature to not require GLIBCXX_3.4.9?
To find out which of the listed GLIBCXX_3.4.9 symbol(s) your binary actually depends on, do this: readelf -s ./a.out | grep 'GLIBCXX_3\.4\.9' | c++filt Once you know which symbols to look for, you can trace back to the object which needs them: nm -A *.o | grep _ZN<whatever> Finally, to tie this back to source, you can do: objdump -dS foo.o and see which code is referencing the 3.4.9 symbol(s).
421,530
421,603
Is endian conversion required for wchar_t data?
In C/C++, if a multi-byte wide character (wchar_t) value is transmitted from a big-endian system to a little-endian system (or vice-versa), will it come out the same value on the other side? Or will the bytes need to be swapped?
Yes you will need to swap them. The bytes will be retrieved from the transport in the same order they were put in. Just at the other end the ordering of these bytes has a different meaning. So you need to convert them to the correct endian-ness (is that a word?). The tried and true method is to convert to network byte order before transport. Then convert back to host specific byte order (from network byte order) on receipt. A set of function to help with endian conversion: ntohs Convert a 16-bit quantity from network byte order to host byte order ntohl Convert a 32-bit quantity from network byte order to host byte order htons Convert a 16-bit quantity from host byte order to network byte order htonl Convert a 32-bit quantity from host byte order to network byte order Just to add another note of caution. Different systems use different size for wchar_t so do not assume sizeof(wchar_t) == 2. Additionally each host may use a different representational format for wchar_t. To help deal with this most systems convert the text to a known format for transport (UTF-8 or UTF-16 are good choices). The convert the text back to the host specific format at the other end. You could look at IBM's icu this has all this functionality.
421,573
421,615
Best way to extract a subvector from a vector?
Suppose I have a std::vector (let's call it myVec) of size N. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, myVec [100000] through myVec [100999] in a vector of size 150000. If this cannot be done efficiently with a vector, is there another STL datatype that I should use instead?
vector<T>::const_iterator first = myVec.begin() + 100000; vector<T>::const_iterator last = myVec.begin() + 101000; vector<T> newVec(first, last); It's an O(N) operation to construct the new vector, but there isn't really a better way.
421,860
421,871
Capture characters from standard input without waiting for enter to be pressed
I can never remember how I do this because it comes up so infrequently for me. But in C or C++, what is the best way to read a character from standard input without waiting for a newline (press enter). Also ideally it wouldn't echo the input character to the screen. I just want to capture keystrokes with out effecting the console screen.
That's not possible in a portable manner in pure C++, because it depends too much on the terminal used that may be connected with stdin (they are usually line buffered). You can, however use a library for that: conio available with Windows compilers. Use the _getch() function to give you a character without waiting for the Enter key. I'm not a frequent Windows developer, but I've seen my classmates just include <conio.h> and use it. See conio.h at Wikipedia. It lists getch(), which is declared deprecated in Visual C++. curses available for Linux. Compatible curses implementations are available for Windows too. It has also a getch() function. (try man getch to view its manpage). See Curses at Wikipedia. I would recommend you to use curses if you aim for cross platform compatibility. That said, I'm sure there are functions that you can use to switch off line buffering (I believe that's called "raw mode", as opposed to "cooked mode" - look into man stty). Curses would handle that for you in a portable manner, if I'm not mistaken.
422,081
429,430
CEditView not showing text
I have a view which is derived from CEditView. It is read only. I would like to set the text as a kind of logging, but nothing shows up on the screen. If I inspect temp in the debugger after GetEditCtrl().GetWindowText(temp); I can see that the text is indeed changing internally, but I see nothing on the screen. // HistoryView.cpp : implementation file // #include "stdafx.h" #include "HistoryView.h" // CHistoryView IMPLEMENT_DYNCREATE(CHistoryView, CEditView) CHistoryView::CHistoryView() { } CHistoryView::~CHistoryView() { } BEGIN_MESSAGE_MAP(CHistoryView, CEditView) END_MESSAGE_MAP() // CHistoryView diagnostics #ifdef _DEBUG void CHistoryView::AssertValid() const { CEditView::AssertValid(); } #ifndef _WIN32_WCE void CHistoryView::Dump(CDumpContext& dc) const { CEditView::Dump(dc); } #endif #endif //_DEBUG // CHistoryView message handlers void CHistoryView::OnInitialUpdate() { CEditView::OnInitialUpdate(); // TODO: Add your specialized code here and/or call the base class GetEditCtrl().SetReadOnly(TRUE); } //! /*! */ void CHistoryView::AddRow(CString message) { CString temp; GetEditCtrl().GetWindowText(temp); if(temp.IsEmpty()) { GetEditCtrl().SetWindowText(message); } else { GetEditCtrl().SetWindowText(temp + "\r\n" + message); } GetEditCtrl().LineScroll(2, 0); //GetEditCtrl().UpdateWindow(); // no effect }
Turns out that a third-party UI toolkit was reconstructing the View (who knows why?) so my pointer to it was stale. Thus, I was actually refreshing a different view!
422,389
422,405
Memory Allocation in Recursive C++ Calls
I'm having problems allocating and deallocating my memory in a recursive C++ program. So without using an automatic memory management solution, I wonder if anyone can help me resolve the memory leak I am experiencing. The following code essentially explains the problem (although it's a contrived example, please correct any mistakes or simplifications I've made). A number class to hold the value of a number: class Number { public: Number() { value = 1; }; Number& operator + (const Number& n1) const { Number result = value + n1.value; return result; }; int value; }; Two functions to perform the recursion: Number& recurse(const Number& v1) { Number* result = new Number(); Number one = Number(); *result = *result + recurse(one); return *result; } int main(...) { Number answer = Number(); answer = recurse(result); } As you can see the memory allocated in the recurse function is leaked, but I'm not sure where I can free up this memory from based on the nature of the recursion?
The problem is here: Number& operator + (const Number& n1) const { Number result = value + n1.value; return result; }; You're returning a local variable (result) by reference, and that's a big NO-NO. Local variables are allocated on the stack, and when the function exits, the variables are gone. Returning a reference to a local variable is returning a pointer into the stack that's now being used for something else, and that's going to cause lots of badness. What you should instead do is return by value (just change the return type from Number& to Number). Make sure you have an appropriate copy constructor, or that the compiler's automatically generated copy constructor suits your needs. This means when operator+ returns, it makes a copy (which can often by optimized away), and since there's no pointers or references involved, you can't get a corrupted return value. To fix your memory leak, you can use smart pointers such as boost::shared_ptr. Alternatively, ditch pointers and dynamic memory altogether, and just return your results by value from recurse().
422,600
422,688
Canonical operator overloading?
Is there a canonical or recommended pattern for implementing arithmetic operator overloading in C++ number-like classes? From the C++ FAQ, we have an exception-safe assignment operator that avoids most problems: class NumberImpl; class Number { NumberImpl *Impl; ... }; Number& Number::operator=(const Number &rhs) { NumberImpl* tmp = new NumberImpl(*rhs.Impl); delete Impl; Impl = tmp; return *this; } But for other operators (+, +=, etc..) very little advice is given other than to make them behave like the operators on built-in types. Is there a standard way of defining these? This is what I've come up with - are there pitfalls I'm not seeing? // Member operator Number& Number::operator+= (const Number &rhs) { Impl->Value += rhs.Impl->Value; // Obviously this is more complicated return *this; } // Non-member non-friend addition operator Number operator+(Number lhs, const Number &rhs) { return lhs += rhs; }
In Bjarne Stroustrup's book "The C++ Programming Language", in chapter 11 (the one devoted to Operator Overloading) he goes through witting a class for a complex number type (section 11.3). One thing I do notice from that section is that he implements mixed type operations... this is probably expected for any numeric class. In general, what you've got looks good.
422,738
422,753
Visual Studio _CrtDumpMemoryLeaks always skipping object dump
I'm trying to use the CRT memory leak detection but I keep getting the following message in Microsoft Visual Studio: "Detected memory leaks - skipping object dump." I can never get the it to actually do and object dump. I followed the directions in the Microsoft article on Memory Leak Detection (http://msdn.microsoft.com/en-us/library/e5ewb1h3(VS.80).aspx) with no luck. In my stdafx.h I have (rebuilt the entire project): #define _CRTDBG_MAP_ALLOC #include <stdlib.h> #include <crtdbg.h> In the entry point of my application I have: _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); I'm also hoping that it will display the file name and line number in the Microsoft advertised format: Detected memory leaks! Dumping objects -> C:\PROGRAM FILES\VISUAL STUDIO\MyProjects\leaktest\leaktest.cpp(20) : {18} normal block at 0x00780E80, 64 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete. While I've NEVER been able to even get an object dump, but I've noticed that other people say they see something along these lines (even with _CRTDBG_MAP_ALLOC defined): Detected memory leaks! Dumping objects -> {18} normal block at 0x00780E80, 64 bytes long. Data: < > CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD CD Object dump complete. I don't really want to spend time overriding the new and delete operators, so I was hoping that the CRT debugging would help me. If this doesn't work out I might end up overriding the new and delete operators, but I really want to get the allocation information with a file name and line number (crosses fingers). Thanks, Kiril
I don't have it here on my machine, but when you instal MSVC you have the option of installing (most of the) source code for the C run-time library (i.e. for MSVCRTxx.xxx). If you look in that source code for "skipping object dump" then you might be able to work out why the object dump is being skipped.
422,774
422,800
C++ How can I get a return a reference and save the refence as a local variable in a function?
I have a function inside a class that returns a reference to a member variable. std::vector<uint8> & getBuffer() const { return m_myBuffer; } Now say in another class I call this method: int someFunction() { std::vector<uint8> myFileBuffer = myFile.getBuffer(); } This line calls the copy constructor of vector and makes me a local buffer. I do not want this, how can I instead set myFileBuffer to reference the myFile.getBuffer(). I know I can do this via pointers but wanted to use references if it is possible. Thanks.
Note since your member method is const you should be returning a const reference. // Note the extra const on this line. std::vector<uint8> const& getBuffer() const { return m_myBuffer; } So to use the returned value by reference do this: std::vector<uint8> const& myFileBuffer = myFile.getBuffer();
422,830
423,355
Structure of a C++ Object in Memory Vs a Struct
If I have a class as follows class Example_Class { private: int x; int y; public: Example_Class() { x = 8; y = 9; } ~Example_Class() { } }; And a struct as follows struct { int x; int y; } example_struct; Is the structure in memory of the example_struct simmilar to that in Example_Class for example if I do the following struct example_struct foo_struct; Example_Class foo_class = Example_Class(); memcpy(&foo_struct, &foo_class, sizeof(foo_struct)); will foo_struct.x = 8 and foo_struct.y = 9 (ie: the same values as the x,y values in the foo_class) ? The reason I ask is I have a C++ library (don't want to change it) that is sharing an object with C code and I want to use a struct to represent the object coming from the C++ library. I'm only interested in the attributes of the object. I know the ideal situation would be to have Example_class wrap arround a common structure between the C and C++ code but it is not going to be easy to change the C++ library in use.
The C++ standard guarantees that memory layouts of a C struct and a C++ class (or struct -- same thing) will be identical, provided that the C++ class/struct fits the criteria of being POD ("Plain Old Data"). So what does POD mean? A class or struct is POD if: All data members are public and themselves POD or fundamental types (but not reference or pointer-to-member types), or arrays of such It has no user-defined constructors, assignment operators or destructors It has no virtual functions It has no base classes About the only "C++-isms" allowed are non-virtual member functions, static members and member functions. Since your class has both a constructor and a destructor, it is formally speaking not of POD type, so the guarantee does not hold. (Although, as others have mentioned, in practice the two layouts are likely to be identical on any compiler that you try, so long as there are no virtual functions). See section [26.7] of the C++ FAQ Lite for more details.
423,128
423,130
Is this dynamic memory allocation?
Simple question: do I have to delete or delete [] c? Does the language matter? char c[] = "hello"
In c++ that is not dynamic memory allocation. No delete[] will be needed. Your example is basically a short-cut for this: char c[6]={'h','e','l','l','o','\0'};
423,166
480,380
Flash ActiveX: How to Load Movie from memory or resource or stream?
I'm embedding a Flash ActiveX control in my C++ app (Flash.ocx, Flash10a.ocx, etc depending on your Flash version). I can load an SWF file by calling LoadMovie(0, filename), but the file needs to physically reside in the disk. How to load the SWF from memory (or resource, or stream)? I'm sure there must be a way, because commercial solutions like f-in-box's feature Load flash movies from memory directly also uses Flash ActiveX control.
Appearantly I a going to need to supply details for a vote 'up'.. OK. The internal flash buffer when first initiailized indicates if a movie is loaded or if the buffer hold properties in the buffer fisrt four bytes. gUfU -- no movie loaded. properties to follow .... fUfU -- .. [4bytes] size as integer. then the UNCOMPRESSED movie or SWF as it were. Write a IStream class. fill with above. save as szFile TFlashStream *fStream = new TFlashStream(szFile); // QI flash player IPersistStreamInit * psStreamInit = 0; shock->QueryInterface(::IID_IPersistStreamInit, (LPVOID*)&psStreamInit); if(psStreamInit) { psStreamInit->InitNew(); psStreamInit->Load(fStream); psStreamInit->Release(); } delete fStream; Things to note : When psStreamInit->Load(fStream); will call IStream::Read looking for the header 'fUfU'. if the return is correct psStreamInit then calls IStream::Read for the buffer size. If everthing looks good so far, psStreamInit then reads in 1024 byte chunks until the read is exhausted. However. for the header and file size. STDMETHOD(Read)(void *pv, ULONG cb, ULONG *pcbRead) pcbRead is invalid. you may want to use something like IsBadReadPtr -- Michael
423,298
423,594
Use of CoGetClassObject() in C - access COM Object interface
Instruction on accessing a interface to an application, in plain C/C++ without: MFC ATL WTL Basically, I would like to make use of a COM object. Working sample source code or guidance - to using (functionality) a COM object, not creating a COM server. Regards
Here is a simple example in plain C++: CoInitialize(NULL); // absolutely essential: initialize the COM subsystem IMyInterface* pIFace; // create the object and obtain a pointer to the sought interface CoCreateInstance(CLSID_MyObject, NULL, CLSCTX_ALL, IID_IMyInterface, &pIFace); pIFace->MethodIReallyNeed(); // use the object pIFace->Release(); // free the object CoUninitialize(); // cleanup COM after you're done using its services Copied from here: COM Basics