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 castin... | 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 ... |
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 differe... |
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... | 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 ... |
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 sho... | 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++ c... |
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... | 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 c... | 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> myCon... | 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> vo... |
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( statu... |
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() {retu... | 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 writ... |
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 n... | 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 : ... |
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, ... | 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 derive... |
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() {
... }
... | 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 (Add... |
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 ... | 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 c... |
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 a... | 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 (Wh... |
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 star... | 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... |
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 concu... | 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 a... |
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... | 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, bu... |
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 comp... | 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 resourc... |
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... | 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& oth... |
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 ... | 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.valu... | 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 acces... |
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_DI... | 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 pr... |
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 ... | 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_membe... |
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
{
pu... | 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 in... |
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 a... | 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 particul... |
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 alrea... | 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... |
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 tol... | 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. Basi... |
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 car... |
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 h... | 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 ... |
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 'T... | 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
{
boo... |
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();
}
... | 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... |
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 cla... | 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 * ba... |
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 ... | 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 in... | 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 t... |
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, bu... | 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 {... |
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.
templ... | 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 crea... | 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 ... |
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 terminati... |
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 ... |
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 f... |
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 addition... |
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 ... | 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... |
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;
... |
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... | 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 ... |
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 assign... |
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 tw... | 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 depreca... |
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 w... | 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 beginn... |
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.BitBl... | 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 tw... | 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... |
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->Lo... | 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_SomeCo... |
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, t... | 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 t... |
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 ... |
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 sh... | 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)]; ... |
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 use... |
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 d... | 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 a... |
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) : e... | 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... | 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 l... |
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 co... |
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]... | 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 con... |
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 se... | 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 T... | 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 t... |
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%... | 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 som... | 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... |
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, cu... | 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'... |
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... | 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 d... |
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 pa... | 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, pForma... |
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 th... | 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_PRI... |
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 a... |
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... | 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,
__... |
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, versionI... |
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::... | 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 ... |
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 h... |
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 li... | 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 ca... |
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 ... |
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 th... | 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 ... | 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 fo... |
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.
// ... | 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... | 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 ... |
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 &r... | 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... |
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.c... | 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 a... | 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_... | 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 fundame... |
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, beca... | 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 UNCOM... |
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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.