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 |
|---|---|---|---|---|
4,017,343 | 4,017,382 | Shouldn't this code crash | int *p;
while(true)
{
p = new int;
}
Due to running out of memory space, shouldn't this code crash. I have tried printing out the value of p, that is the address of memory located for p, and it seems to increase yet there is no crashing.
Why is this so?
| This solution is like trying to crash a car at a telephone pole down the street while driving 1MPH. It will happen eventually but if you want fast results you need to up the speed a bit.
int *p;
while (true) {
p = new int[1024*1024*1024];
}
My answer though is predicated on your code base using the standard STL al... |
4,017,414 | 4,017,450 | Argument of type '(Foo::)(int,int)' does not match 'void (*)(int,int)' in main.cpp | I want to pass Resize method of my Foo class object as the argument of glutReshapeFunc() but I get that error.
How should I pass it?
This is my definition of Resize:
class Foo{
public:
void Resize(int w, int h);
...
}
and this is how I try to call it
glutReshapeFunc(foo->Resize);
It was ok when foo was no... | Non-static functions take an additional hidden parameter (this) so they're not compatible with a global, non-member, function with apparently similar signature.
You could make Resize a static, but you'll have problem figuring out on what object to act. glutReshapeFunc mentions that
Before the callback, the current
... |
4,017,511 | 4,024,475 | reference to function std::get<1> in tuple header | How do I get a reference to a "get"-function for a specific tuple instance?
My best try is given below but does not compile against g++4.5.1
#include <tuple>
#include <string>
typedef std::tuple<int,std::string> Tuple;
auto t=(std::string& (Tuple&))(std::get<1,Tuple>);
The compiler error is:
a.cc:5: error: invalid ca... | The code below works for me. The trick is to use a function-pointer typedef and not a function reference typedef.
I am impressed that the compiler does not need all template parameters, but can optionally work out missing ones through the overloaded function type.
#include <tuple>
#include <string>
typedef std::tuple... |
4,017,548 | 4,020,223 | recursive c++ template problem | Say I have a template class that takes msgs from source, does something smart to them, and then sends them to a sink:
template <typename Source, typename Sink>
class MsgHandler
{
MsgHandler(Source* pSource)
: m_pSource(pSource)
{
m_pSource->setHandler(this);
}
};
//Now the definition of the Source:
template <typena... | You could use a templated parameter for the source parameter of your handler:
class MySink;
template <template<typename Handler> class Source, typename Sink>
class MsgHandler
{
Source<MsgHandler>* m_pSource;
MsgHandler(Source<MsgHandler>* pSource)
: m_pSource(pSource)
{
m_pSource->setHandler(this... |
4,017,621 | 4,018,265 | How to do portable 64 bit arithmetic, without compiler warnings | I occasionally use 64 bit arithmetic in an open source C++ library of mine. I discovered that long long serves my purpose quite nicely. Even some 10 year old solaris box could compile it. And it works without messing around with #defines on Windows too.
Now the issue is I get complaints from my users because they compi... | When your library is provided as source, one option is to provide a "porting" header, in which it is your users' responsibility to provide a 64 bit type (you'd specify the name). It's then also naturally their responsibility to deal with any compiler warnings that their choice of type provokes, either avoid them, suppr... |
4,017,756 | 4,171,504 | Sending a processed video from C# program to C++ program | I am capturing video from my webcam and it is processed by a C# program then i want to stream it to a C++ program. this C++ program can be configured to get a video stream from a webcam so is it possible to send/stream my processed video to this program where the C++ program detect that stream as a video which is comin... | I could simply overcome my problem using SplitCam Thank you everyone.
|
4,017,892 | 4,018,047 | In an STL Map of structs, why does the "[ ]" operator cause the struct's dtor to be invoked 2 extra times? | I've created a simple test case exhibiting a strange behavior I've noticed in a larger code base I'm working on. This test case is below. I'm relying on the STL Map's "[ ]" operator to create a pointer to a struct in a map of such structs. In the test case below, the line...
TestStruct *thisTestStruct = &testStructMap[... | The functionality of std::map<>::operator[] is equivalent to
(*((std::map<>::insert(std::make_pair(x, T()))).first)).second
expression, as specified in the language specification. This, as you can see, involves default-constructing a temporary object of type T, copying it into a std::pair object, which is later copied... |
4,017,954 | 4,017,974 | Expression evaluation in C/C++ doesnt follow BODMAS rule? | When a expression is evaluated in C/C++, does it follow BODMAS [Bracket open Division Multiply Addition Substraction] rule? If not then how they are evaluated?
EDIT: More clearly, If the following expression is evaluated according to BODMAS rule,
(5 + 3)/8*9
First what is in brackets is processed.
8/8*9.
Then Division... | There are far more operators than that. You can find a precedence tables for C++ and C.
But yes, you'll find it respects that. (Though I'm not sure it's exactly what you've said...)
|
4,018,011 | 4,018,270 | Generate .cpp source from a .h file | The barebones version of a .cpp file is often not much more than a copy of the related header file with some braces instead of semicolons, ClassName:: inserted in a few places, and removing the virtual keyword. Much of it could be generated with a one-line sed command, but it wouldn't be very robust for all the languag... | Most graphical editors have some plugins available to do that like vim, gedit or Eclipse.
But I am not aware of a shell or perl script to do that.
|
4,018,069 | 4,018,094 | Writing DLL for C# and C++ Applications | I need to write a couple DLLs that will both be accessed from a C# application and a C++ application. Initially, I was thinking that I could save time/effort by writing the DLLs in C# and linking to them from the C# and C++ applications. Is this approach wise, or should the DLLs be written using C++?
| My advice would be to implement the code where you are most comfortable, but don't forget the interop requirement as you go. Know upfront what your interface is and what glue is required in the end product. Write the interface and test the interop before you fill out the implementation.
If the complexity of your re... |
4,018,196 | 4,018,226 | What is the best way to wrap our software library to serve both C++ and C# client apps? | I am starting work on a new project where the core product is a Software Library. There is existing code we will be wrapping, written in C++ because it is very numerically intensive; we own and compile this core code.
I believe we will have two prominent client types:
1. App written in C++, probably MFC
2. App written ... | Interesting question, I'm looking forward to other answers.
One possible solution, if probably not the best: If your library code follows object-oriented practices, you could write the core functionality in C++ and then provide separate COM wrapper classes around the core classes (also in C++). This would allow you to ... |
4,018,350 | 4,019,675 | hash_map: why it defines less, rather than equal_to | C++, using Visual Studio 2010. A question about why a user-defined trait of hash_map actually requires total ordering.
I have a simple structure, say FOO, which only has a number of integers. I'd like to use hash_map, which is a hash table whose keys are unordered, to store the structure of FOO. I just need a fast sea... |
For any value _Key1 of type Key that precedes _Key2 in the sequence and has the same hash value (value
returned by the hash function), hash_comp(_Key2, _Key1) is false. The function must impose a
total ordering on values of type Key.
A total ordering of keys with the same hash value guarantees a total ordering of... |
4,018,384 | 4,025,951 | STL and UTF-8 file input/output. How to do it? | I use wchar_t for internal strings and UTF-8 for storage in files. I need to use STL to input/output text to screen and also do it by using full Lithuanian charset.
It's all fine because I'm not forced to do the same for files, so the following example does the job just fine:#include <io.h>
#include <fcntl.h>
#include ... | Use std::codecvt_facet template to perform the conversion.
You may use standard std::codecvt_byname, or a non-standard codecvt_facet implementation.
#include <locale>
using namespace std;
typedef codecvt_facet<wchar_t, char, mbstate_t> Cvt;
locale utf8locale(locale(), new codecvt_byname<wchar_t, char, mbstate_t> ("en_U... |
4,018,501 | 4,018,609 | Valgrind used in C++ development? | I'm quite new to C++ but have some basic C knowledge. In my past C (university) projects, I used Valgrind to check for memleaks.
Now, with C++, is Valgrind a valid tool? Does C++ suffer the same problems concerning memleaks like C? Or are there even better tools to use in conjunction with C++?
| I never use new and delete (or other forms of manual memory management) and I very rarely even use pointers. And I still have to wrestle with memory leaks invalid memory accesses.1 Valgrind is an indispensable tool for me. Even more important than gdb.
1 As Viktor pointed out in a comment, producing memory leaks witho... |
4,018,775 | 4,072,969 | What's the fastest C++ class or C library to convert latitude and longitude from decimal degrees to string and back | I'm looking for the best C or C++ code to encode and decode decimal latitude and longitude values from/to double/char. I'd prefer the code convert from double to char[] and vice-versa
rather than c++ strings.
If you have a code snippet that would be great too.
To clarify: I need to convert from a string Degrees/Minute... | Working with the OP(amanda) via email, we've developed a fast function based on a large switch-case statement.
amanda reports that is runs somewhere around 15x faster than the code they had been using.
Considering this is run over 300 million records, that should be a pretty substantial time savings.
I found the probl... |
4,018,816 | 4,018,850 | Circular Dependency in C++ | The facts:
I have two predominant classes: Manager and Specialist.
There are several different types of Specialists.
Specialists often require the help of other Specialists in order to get their job done.
The Manager knows all of the Specialists, and initially each Specialist knows only their Manager. (This is the ... | In both cases, forward declare the other class:
Manager.h
class Specialist;
class Manager
{
std::list<Specialist*> m_specialists;
};
Specialist.h
class Manager;
class Specialist
{
Manager* m_myManager;
};
The only time you need to bring in the header file for a class is when you need to use a member functio... |
4,018,840 | 4,019,436 | Finding all shortest paths and distances using Floyd-Warshall | First, a little background: I'm working on building a simple graph class with basic graph algorithms (Dijkstra, Floyd-Warshall, Bellman-Ford, etc) to use as a reference sheet for an upcoming programing competition.
So far I have a functioning version of Floyd-Warshall, but the downside is that so far it's only getting ... | Huzzah!
I had a good hard stare at the results from adding Wikipedia's code snippet and I came up with an adapter to convert it's results into my results without the need of calling a separate function:
// Time to clean up the path graph...
for (int st_node = 0; st_node < this->size; st_node++)
{
for (int end_node ... |
4,018,935 | 4,026,281 | Valgrind won't return source lines! | I've tried running valgrind (memcheck and massif) on an app I wrote, but all I get back are addresses for the functions that executed.
---------------------------------
Context accounted for 0.6% of measured spacetime
0x805F29A: (within prog_name)
0x8141740: (within prog_name)
Called from:
0.6% : 0x812E077: (w... | I discovered that I passed in both the -g and -ggdb flags to g++ at compile time. Omitting the -g flag caused this issue to go away.
|
4,019,109 | 4,019,376 | GMP and smart pointers | I'm working with gnump and have a function that must return mpz_t. So I have to use raw pointers to return a value. I allocate space with new for pointer and send it as a parameter in my function.
I think it is better to use smart pointers. But I didn't work with them before. I read the manual but still can't underst... | The use of shared pointers in this context does not help you. The type mpz_t itself is pointer-like. Such a pointer is initialised by calling any of the mpz_init_... functions. However, you need to call a mpz_clear to free the space allocated by the init function you've used.
Storing the pointer-like in a shared_ptr do... |
4,019,141 | 4,019,392 | HtmlHelp() closes my MFC application | I am updating an old MFC application that used WinHelp so that it now uses HtmlHelp. I've changed the constructor of CWinApp-based class so that it calls EnableHtmlHelp(). Then I've changed the old calls from WinHelp( IDH_CONTENTS, HELP_CONTEXT) to HtmlHelp( IDH_CONTENTS, HH_HELP_CONTEXT). Unfortunately, whenever I try... | Ok. I found it. I finally paid attention to this statement in the MSDN documentation:
When using the HTML Help API, set the
stack size of the hosting executable
to at least 100k. If the defined stack
size is too small, then the thread
created to run HTML Help will also be
created with this stack size, and
... |
4,019,268 | 4,019,439 | iterating over a list, each item consisting of a struct within a struct, difficulty getting values | I have a list which contains a number of _MEMORY_BASIC_INFORMATION structs nested within mb structs (defs below). What I am having problems with is getting the info from the nested _MEMORY_BASIC_INFORMATION out. I am using an iterator to traverse the list. From below I know the error is g->mbi; but I don't know how ... | When posting such a problem, it is always extremely helpful to include the specific error message that you get from your compiler.
At the first sight I can't see why your code does not compile. However, you should be aware that your assignment of mbi2 does create a copy of the whole _MEMORY_BASIC_INFORMATION structure.... |
4,019,295 | 4,019,537 | How to parse through a C/C++/C# project and write all packages/classes/methods into a database? | For my new application I would like to parse another C, C++ or C# project, so that i can later display the graphical representation of all the classes in this project.
So I thought that its a good approach to use a database with the following tables to store the necessary information:
TablePackages:
id | name | parentI... | For C#, you can compile it and use reflection to get the list of all classes/properties/methods. For C/C++, you would perhaps need to implement a parser in some form yourself.
|
4,019,733 | 4,019,827 | Which API should I use for playing audio on Windows? | There are many ways of playing sounds on Windows. Which are the differences, advantages and disavantages of each method?
I know there are at least 5 methods:
1991 WinMM.dll/mmsys.dll PlaySound
1995 MCIWnd (as suggested by @casablanca)
1996 DirectSound
1998 WaveOut
1999 ASIO
1999 Windows Media Player ActiveX control?
2... | Really depends on what you want to do. For most common scenarios, I've found that the MCIWnd functions work well: they're really easy to use and can play any format for which a codec is installed.
DirectSound is somewhat more difficult to use but gives you much more control over the output; it lets you add special effe... |
4,019,742 | 4,019,776 | Xcode: multiple projects, more than one main executable | Hi I'm new to Xcode. I'm trying to learn c++ and I was wondering if it is possible to have multi projects and choose which project should run. I used ms visual studios before and I like how under a solution I can create multiple projects and choose which one is the executable one. Xcode also has targets not exactly sur... | Xcode targets are probably what you are looking for. You can have many targets in a single project, and whichever one you select as active will be used when you tell Xcode to compile or run. If you are having problems with duplicate mains, you probably have all of your .cpp files in all of your targets. If you have mai... |
4,019,770 | 4,019,800 | Regarding C++ preprocessor while using #define to conditionally exclude a main function | Here's the situation:
I have three files, Test1.cpp and Test2.cpp. Test1.cpp can be compiled as-is into a stand-alone application. Test1.cpp also contains some functions that I would like to re-use in Test2.cpp. I'm using an #ifndef #endif block to conditionally exclude the main function of Test1.cpp so that when I ... | The preprocessor runs sequentially through each source file. Macros defined in one .cpp file do not affect macros defined in another .cpp file.
One option is to define FN_MAIN in the header: then when Test1.cpp includes that header the macro will still be defined. However, I think it's probably cleaner to define t... |
4,019,914 | 4,020,369 | How do we modify OpenCV and generate new DLLs | The OpenCV library is great. Most functions have the required functionality, however, I would like to modify some of the functions and recompile so that it fits my specific needs. how would we recompile the dlls and other files? is there a built-in script or do we need to write all the scripts ourselves?
| According to the install guide, you'll need CMake to compile it on Windows.
I found this tutorial that shows step-by-step how to compile OpenCV 2.0 on Windows, but I believe the instructions also apply for compiling OpenCV 2.1.
This thread is directly related to what you aim.
|
4,020,062 | 4,020,078 | Question on reuse of pointers after passing to functions | So, when I pass a const char * to a function once, can I use it again? It appears to end up spitting out crap to me.
const char *config_file = "file.txt";
function(int x, config_file);
cout << "Number" << x;
secondfunction(int y, config_file);
Do I need to make another pointer to config_file?
If so, how do I do th... | No, your can use it just fine. Despite the fact that the code you gave is uncompilable, I think I understand what you're asking.
A code segment like:
const char *x = "Hello";
fnA (x);
fnB (x);
should be just fine.
If you find that fnB is not getting what it expects then either:
fnA is changing what x points to (norma... |
4,020,391 | 4,020,496 | glGenLists(1) return 0 outside OnPaint() with wxThread | Currently, I am trying to separate the display list from the OnPaint(), but glGenLists(1) return 0.
Is there any prerequisite on using display list?
Is function glGenLists(1) only survive inside OnXxx() event thread?
Thank you!
| The only requirement is having a valid OpenGL context made current. You probably don't have one. If you use multiple threads, you need to use multiple GL contexts which share objects.
|
4,020,445 | 4,021,738 | Communicating over telnet | I can't use Boost ASIO (reasons not related to programming) and I looked around and libcurl looks good. I'm building the binaries at the moment and decided to get some feedback from the community.
Any comments regarding libcurl/alternatives?
UPDATE:
libcurl's not great for telnet. It's 2010! Shouldn't there be a simple... | Telnet is a very simple protocol. Some wonky stuff to negotiate the terminal type but I'm sure your robot doesn't care where the cursor ends up. Just use a socket to open a TCP/IP connection on port 23 and send the command strings, terminated with a '\n'.
|
4,020,582 | 4,020,595 | Treating double variable as boolean | Which is the better way(efficiency/best practice wise) to test if a double variable is equal to 0?
1. if(a_double)
.....
else
.....
OR
2. if(a_double == 0)
.....
else
.....
| The second is generally better (more explicit about what you're doing). I'd normally prefer if (a_double == 0.0) though. Also note that with floating point, it's often useful to do an approximate comparison to account for the possibility of rounding in the calculations (though doing this well can be non-trivial).
Edit:... |
4,020,664 | 4,020,790 | DoModal() not bringing up dlg box as modal | I have a window with the following properties set int he .rc file:
STYLE DS_SETFONT | DS_MODALFRAME | DS_FIXEDSYS | WS_POPUP | WS_CAPTION | WS_SYSMENU
It has an associated class (derived from CDialog) and when I instantiate it, then call that object's DoModal() on
it it is not really modal - I can click on the "paren... | I don't see that you're specifying a parent window for your modal dialogs.
Perhaps that's what's lacking.
|
4,020,715 | 4,020,736 | How to generate a exe program through programming? | I want to write a application which can use to generate .exe program automatically from some word and txt files.
How can I implement this ? Is it possible to generate a exe program with programming ?
| You can use the CodeDOM namespace to create a .NET Framework EXE. Generating Source Code and Compiling a Program from a CodeDOM Graph
|
4,020,791 | 4,020,795 | C++ initialize anonymous struct | I'm still earning my C++ wings; My question is if I have a struct like so:
struct Height
{
int feet;
int inches;
};
And I then have some lines like so:
Height h = {5, 7};
Person p("John Doe", 42, "Blonde", "Blue", h);
I like the initialization of structs via curly braces, but I'd prefer the above be on one li... | You can't, at least not in present-day C++; the brace initialization is part of the initializer syntax and can't be used elsewhere.
You can add a constructor to Height:
struct Height
{
Height(int f, int i) : feet(f), inches(i) { }
int feet, inches;
};
This allows you to use:
Person p("John Doe", 42, "Blonde", ... |
4,020,995 | 4,021,005 | long lines of integer arithmetic | Two Parts two my question. Which is more efficient/faster:
int a,b,c,d,e,f;
int a1,b1,c1,d1,e1,f1;
int SumValue=0; // oops forgot zero
// ... define all values
SumValue=a*a1+b*b1+c*c1+d*d1+e*e1*f*f1;
or
Sumvalue+=a*a1+b*b1+c*c1;
Sumvalue+=d*d1+e*e1*f*f1;
I'm guessing the first one is. My second question is why.
I gue... | Did you measure that? The optimized machine code for both approaches will probably be very similar, if not the same.
EDIT: I just tested this, the results are what I expected:
$ gcc -O2 -S math1.c # your first approach
$ gcc -O2 -S math2.c # your second approach
$ diff -u math1.s math2.s
--- math1.s 2010-10-26 19:35... |
4,021,061 | 4,041,612 | What is the Equivalent of "object of C# " in VC++? | In C# we have a datatype object which can hold any type of data. Same thing I want to achieve in VC++. Can anyone kindly let me know VC++ equivalent of "Object of C#".
IN C#, in the calling appl program (say call.cs)
object ob=null;
ob=(object)str;
funct(ref ob);
Here str is empty string.
This thing I want to a... | As other commentators have said, C++ does not have a common base-class for every object. Theoretically, you could create your own and derive everything from it:
class Object
{
protected:
Object(){};
virtual ~Object(){};
public:
virtual std::string toString() const {return("");};
}; // eo class Object
Thi... |
4,021,078 | 4,021,305 | Drawing polygon with more than one hole? | I'm trying to draw a polygon with more than one holes. I tried the following code and it does not work correctly. Please advise.
PointF[] mypoly = new PointF[6 + 5 + 5];
mypoly[0] = new PointF(0, 0);
mypoly[1] = new PointF(100, 0);
mypoly[2] = new PointF(100, 100);
mypoly[3] = new PointF(0, 100);
... | Use a GraphicsPath instead. You can draw it with Graphics.FillPath, like this:
using System.Drawing.Drawing2D;
...
using (var gp = new GraphicsPath()) {
PointF[] outer = new PointF[] { new PointF(0, 0), new PointF(100, 0),
new PointF(100, 100), new PointF(0, 100), new PointF(10, 80),new PointF... |
4,021,125 | 4,021,378 | Memory Management in Qt | I have small doubt about Qt memory management.
Let's take an example of Listview, in listview we add each item by allocating memory dynamically. So in this case do we need to delete all the "new"ed items manually.
E.g:
Qlistview *list = new Qlistview;
QStandardItemModel *mModel = new QStandardItemModel();
list ->setMo... | QStandardItemModel takes ownership of items, so they will be automatically deleted when model is destroyed. You still need to delete the model itself (setModel() doesn't transfer ownership of model to the view, because one model can be used by multiple views).
|
4,021,307 | 4,023,272 | EnumProcesses() vs CreateToolhelp32Snapshot() | I was wondering if there are any differences - mostly performance wise - between the two Win32 API functions EnumProcesses() and CreateToolhelp32Snapshot() for enumerating all active processes and loaded modules. Or if one is better than the other to use and why.
| I think they are pretty much the same in terms of performance (and results) as they both call the same underlying NT API, though CreateToolhelp32Snapshot() may have a slight overhead as it creates a section object and copies all the information to it whereas EnumProcesses()/EnumProcessModules() works directly with user... |
4,021,457 | 4,021,654 | C++ code to indent XML line | I am looking for C++ code to indent an xml line. I don't want to link with a library.
I have my stream in one line like this
<root><a>value_a</a><b>value_b</b></root>
and I want to print it in a multi-line way (with tabs).
<root>
<a>value_a</a>
<b>value_b</b>
</root>
does it ring a bell to anybody?
| If you do not want to use a library, you will have to write it yourself. That should not be too hard. You will first have to tokenize the stream into tags and values. This is the hardest part I guess. Then you have to write the tokens to a stream. For every opening tag that follows an opening tag, you increase the inde... |
4,021,819 | 4,021,936 | Linkage of class names |
$3.5 - "In addition, a member
function, static data member, class or
enumeration of class scope has
external linkage if the name of the
class has external linkage."
Any inputs on what does it mean by 'if the name of the class has external linkage'?
Is the hint on 'local classes' (which probably don't have any... | Local classes (but not necessarily nested classes) don't have linkage. A class can't be defined with static specifier. So this equivalently could be stated as follows:
$3.5 - "In addition, a member function, static data member, class or enumeration of class scope has external linkage unless the containing class is a lo... |
4,021,873 | 4,022,832 | Base class's destructor called without destroying the base class! | #include<iostream>
using namespace std;
class A
{
public:
int i;
A() {cout<<"A()"<<endl;}
~A() {cout<<"~A()"<<endl;}
};
class B:public A
{
public:
int j;
B(): j(10)
{
this->i=20;
this->~A();
}
};
int main()
{
B abc;
... | @Nav: no, your understanding of "destroyed" is just wrong. When an object's destructor is called, the object is destroyed. You seem to believe that the memory it resided in evaporates entirely, but that never happens. The object no longer exists, but some garbage data is typically left over by the object, and if you're... |
4,021,981 | 4,029,310 | Use static_assert to check types passed to macro | I unfortunately have several macros left over from the original version of my library that employed some pretty crazy C. In particular, I have a series of macros that expect certain types to be passed to them. Is it possible to do something along the lines of:
static_assert(decltype(retval) == bool);
And how? Are ther... | I found this to be the cleanest, using @UncleBens suggestion:
#include <type_traits>
static_assert(std::is_same<decltype(retval), bool>::value, "retval must be bool");
|
4,022,001 | 4,022,026 | How to print bold string in C++? | I got an old application which was written in a C++. I have 0 experience with it but I am suppose to make some changes in app. One of them is to change some text. Problem is that part of updated text needs to be bold, but i have no idea how to do that. I googled but with no much success. Only think I now is to go to ne... | There is no concept of bold text in C++, there may be in a particular device that displays character text, for example rich-text-format or HTML tagging or a terminal screen. The latter usually involves sending some "escape sequence" relevant to that particular terminal.
|
4,022,163 | 4,022,191 | Is stack-only variable possible in C++? | Currently I want to make wrapper accessor class in multithreaded environment. The purpose of the class is simple - Grab a lock on its construction and release a lock on its destruction. Other than that, it's identical to a normal pointer. Moreover, I want to prevent it from being created on heap area to ensure that the... | Well, what about you overload operator new for your class and delcare it private?
|
4,022,348 | 4,022,358 | Software package for calculation of intersections of polyhedra in C/C++ | There are many good packages for calculating the intersection of polygons. I have found the GPC library useful.
I would like to compute intersections of polyhedra (piecewise linear boundaries) in 3D. Are there any good libraries in C/C++ for this?
| So far, I've found CGAL, but I haven't tried it out yet.
|
4,022,984 | 4,023,018 | Function definition and function type | I have the following code which works as expected:
#include <iostream>
using namespace std;
typedef int (TMyFunc)(int);
TMyFunc* p;
int x(int y)
{
return y*2;
}
int main()
{
p = &x;
cout << (*p)(5) << endl;
}
What I want to do is skip defining x and define p there straight. Something like
TMyFunc p; ... | It's possible in C++1x, the next C++ standard, generally expected next year (which would make it C++11, then). It allows this:
auto p = [](int y){return y*2;};
This relies on auto been given a new meaning ("automatically deduce the type of this variable from the expression that initializes it") and the new lambda fun... |
4,023,002 | 4,023,048 | How transport to dev team software crash'es from remote clients machines? | I searching people who know some experience with bug tracking on client machines,
if my application works on many client machines who i don't have to it any access.
I have in my application very huge debug logging feature, but in many cases this is
to less to good detect problem of crash without very bigs and unreadabl... | See this blog post about minidumps. It should do what you want (I think).
|
4,023,011 | 4,023,030 | Delete element from C++ array | Please tell me how to delete an element from a C++ array.
My teacher is setting its value to 0, is that correct?
| You can't really "delete" an element from a C++ array.
However, if the array consists of pointers, you can delete the object that a specific element points to.
In your teacher's case, it will be important to make note of whether the objects of the array are dynamically allocated (using the new operator in C++) or not. ... |
4,023,125 | 4,074,999 | C++ Class instantiation problem | I have included the proper
Header Files ,
Header Gard
but i cannot instantiate a specific class
Getting Error
error C2065: 'ClassName' : undeclared identifier
Sample Code
Class A{
//instantiate class B
}
Class B {
//need to instantiate Class A
}
| Since you haven't posted any real code for us to actually make use of, I'll take a guess as to what your code actually looks like:
A.h:
#ifndef HEADER_A
#define HEADER_A
#include "B.h"
class A {
private:
B someMember;
};
B.h:
#ifndef HEADER_B
#define HEADER_B
#include "A.h"
class B {
public:
doSomething(A param)... |
4,023,222 | 10,475,937 | List of all hosts on LAN network | How can I get all the IP addresses and associated host names in a LAN?
| To get the list of interfaces and IP addresses, use getifaddrs().
Search for interfaces with ifa_addr->sa_family == AF_INET
The IP address is in sin_addr.s_addr.
You can then use gethostbyaddr() to look up the DNS name for that IP address.
Update:
It was pointed out to me that the OP was probably asking about discoveri... |
4,023,283 | 4,023,315 | Default Constructors | I know that default constructors initialize objects to their default values, but how do we view these values? If there's a variable of type int, it is supposed to be initialized to 0. But how do we actually view these default values of the constructors? Can anyone please provide a code snippet to demonstrate the same?
| Good coding practice: write your own constructor, so you know how it will be initialized. This is portable and guaranteed to always have the same behaviour. Your code will be easier to read and the compiler knows how to make that efficient, especially when using the special notation:
class Foo
{
public:
Foo() : i... |
4,023,343 | 4,023,361 | where is socket header in linux | I compile my simple prog with #include <sys/socket.h> but there's none of this file.
Where is it, I just start coding in linux and I have no idea where is it . Or do we need to download it online .
| In case you have installed manual pages, the first stop should be man socket.
Without manual pages you could call
find /usr/include -name socket.h
which outputs
/usr/include/asm/socket.h
/usr/include/sys/socket.h
/usr/include/bits/socket.h
/usr/include/linux/socket.h
on my system, the one to include is sys/socket.h .... |
4,023,503 | 4,023,546 | C++: Datatypes, which to use and when? | I've been told that I should use size_t always when I want 32bit unsigned int, I don't quite understand why, but I think it has something to do with that if someone compiles the program on 16 or 64 bit machines, the unsigned int would become 16 or 64 bit but size_t won't, but why doesn't it? and how can I force the bit... | size_t is not always 32-bit. E.g. It's 64-bit on 64-bit platforms.
For fixed-size integers, stdint.h is best. But it doesn't come with VS2008 or earlier - you have to download it separately. (It comes as a standard part of VS2010 and most other compilers).
Since you're using VS2008, you can use the MS-specific __i... |
4,023,794 | 4,023,878 | Forward declaration just won't do | Below are two fragments (ready to compile) of code. In first fragment in which I'm using only forward declaration for a struct while deleting pointer to this struct from a Base class dtor for a Guest class isn't invoked.
In the second fragment when instead of forward declaration I use full definition of this Guest clas... | Informally: the compiler needs the class definition in order to delete the object correctly, because it needs to know how to call the destructor and/or operator delete for that class.
Formally, 5.3.5/5:
If the object being deleted has
incomplete class type at the point of
deletion and the complete class has a
no... |
4,024,328 | 4,024,437 | symbol table for debug in windows | I want to compile and use Visual studio for checking an unmanaged C++ on windows program.
I am using ADPlus and WinDBG. For doing this I need a .pdb file amd to configure the symbols of my debugging.
How u can configure it (to local machine and not the net) ?
| Set _NT_SYMBOL_PATH in the environment to include the location of your PDB file(s). See here for detailed info, esp. if you want to get symbol info for the NT libs in your debug sessions.
You can also modify the symbol path dynamically in the Windbg GUI from the File menu, but this does not persist after you close Win... |
4,024,476 | 4,024,516 | Should methods that implement pure virtual methods of an interface class be declared virtual as well? | I read different opinions about this question. Let's say I have an interface class with a bunch of pure virtual methods. I implement those methods in a class that implements the interface and I do not expect to derive from the implementation.
Is there a need for declaring the methods in the implementation as virtual as... | No - every function method declared virtual in the base class will be virtual in all derived classes.
But good coding practices are telling to declare those methods virtual.
|
4,024,632 | 4,024,659 | How to get the number of elements in a struct? | I declared a struct for some options that shall be filled by command line arguments or by reading an input file:
struct options {
int val1;
int val2;
bool val3;
}
Now I want to check for the correct number of arguments at execution of the program. Sure thing a
const int optionsSize = 3;
would do. But is there ... | Why not add the options as specified into an std::vector<string> options and use the options.size() method to check the correct number. Then convert them to the proper datatype.
A more robust way of doing this kind of thing would be to use Boost Program Options
|
4,024,718 | 4,027,163 | JNI C++ Debugging Techniques? | I have a Linux C++ application that creates a JVM and makes JNI calls. I am new to JNI, and so far I the only effective way I have found to debug my application during development is by trial and error. What are some techniques to use to debug the infamous "A fatal error has been detected by the Java Runtime Environm... | Ok, so here's how I approached the problem I mentioned above. Somewhat tedious, but, given enough time and effort, it eventually paid off.
Don't assume that env->CallMethod(jobj, meth_id, ...) is being passed correct values. If this is where it is crashing, chances are high that some hard-to-find but fundamental iss... |
4,024,806 | 4,024,839 | How to convert from const char* to unsigned int c++ | I am new in c++ programming and I have been trying to convert from const char* to unsigned int with no luck.
I have a:
const char* charVar;
and i need to convert it to:
unsigned int uintVar;
How can it be done in C++?
Thanks
| #include <iostream>
#include <sstream>
const char* value = "1234567";
stringstream strValue;
strValue << value;
unsigned int intValue;
strValue >> intValue;
cout << value << endl;
cout << intValue << endl;
Output:
1234567
1234567
|
4,025,051 | 4,076,118 | Simplest way to interrupt a thread that is blocked on running a process | I need to execute some commands via "/bin/sh" from a daemon. Some times these commands takes too long to execute, and I need to somehow interrupt them. The daemon is written in C++, and the commands are executed with std::system(). I need the stack cleaned up so that destructors are called when the thread dies. (Catchi... | I did not try boost::process, as it is not part of boost. I did however try ACE_Process, which showed some strange behavior (the time-outs sometimes worked and sometimes did not work). So I wrote a simple std::system replacement, that polls for the status of the running process (effectively removing the problems with p... |
4,025,458 | 4,032,019 | How does Microsoft handle the fact that UTF-16 is a variable length encoding in their C++ standard library implementation | Having a variable length encoding is indirectly forbidden in the standard.
So I have several questions:
How is the following part of the standard handled?
17.3.2.1.3.3 Wide-character sequences
A wide-character sequence is an array object (8.3.4) A that can be declared as T A[N], where T is type wchar_t (3.9.1), option... | Here's how Microsoft's STL implementation handles the variable-length encoding:
basic_string<wchar_t>::operator[])( can return a low or a high surrogate, in isolation.
basic_string<wchar_t>::size() returns the number of wchar_t objects. A surrogate pair (one Unicode character) uses two wchar_t's and therefore adds two ... |
4,025,616 | 4,025,693 | C++ project compiles as static library but not dynamic (Visual Studio) | I'm a little new to c++ in visual studio, and I'm trying to compile a massive C++ project with Visual Studio. I've gone through and added all source and header files to my project and also updated all of the include paths in the project properties.
If I have the type of project set to "Static Library (.Lib)" the proje... | Check if you defined the following member function
char const* Project::toString(Project::compMode)
When you compile as a static library an unresolved symbol is not an error, because it can be resolved later when you link with other code.
You may have forgotten to add some .cpp file to your project.
|
4,025,869 | 4,025,907 | Using/Mixing C in C++ code? | Is using C in C++ bad?
Many people have told me that using C in C++ is bad because it's not as safe, and it requires more memory management. I keep telling them that as long as you know what you're doing, and you delete your "new"s and free your "malloc"s then C isn't a problem.
I'm currently on a forum where an argume... |
I keep telling them that as long as you know what your doing, and you delete your new's and free your malloc's then C isn't a problem.
This is true; if you are extraordinarily careful and ensure that you manually clean things up, then it isn't a problem. But do you really have the time to do that? Every call to new... |
4,025,891 | 4,028,974 | Create a function to check for key press in Unix using ncurses | I have been looking for an equivalent to kbhit() and I have read several forums on this subject, and the majority seem to suggest using ncurses.
How should I go about checking if a key is pressed in C++ using ncurses?
The function getch() provided by ncurses reads a character from the window.
I would like to write a fu... | You can use the nodelay() function to turn getch() into a non-blocking call, which returns ERR if no key-press is available. If a key-press is available, it is pulled from the input queue, but you can push it back onto the queue if you like with ungetch().
#include <ncurses.h>
#include <unistd.h> /* only for sleep() ... |
4,025,913 | 4,026,017 | Differences Between Python and C++ Constructors | I've been learning more about Python recently, and as I was going through the excellent Dive into Python the author noted here that the __init__ method is not technically a constructor, even though it generally functions like one.
I have two questions:
What are the differences between how
C++ constructs an object and... | The distinction that the author draws is that, as far as the Python language is concerned, you have a valid object of the specified type before you even enter __init__. Therefore it's not a "constructor", since in C++ and theoretically, a constructor turns an invalid, pre-constructed object into a "proper" completed ob... |
4,026,305 | 4,026,382 | C++ Function Conventions? | Just had a 'Fundamentals of Programming' lecture at uni and was told that the convention for using/declaring functions is to have the main() function at the top of the program, with functions/procedures below it and to use forward declarations to prevent compiler errors.
However, I've always done it the other way - fun... | There could be the case when your functions are related to each other. If you simply write them above the main() without forward-declaration you have to order them so they'll know the functions they depend on. In some cases (circular references) it won't even be possible to compile without forward declaration.
When for... |
4,026,318 | 4,029,251 | Creating web service app for enterprise Java vs C++? | So we want to develop a service app (web Service with post/get API). What is language to go for secure, fast, enterprise app for about 2000 employers to use with about 20~40 services for interacting with DB server (which in my case will be Oracle) Dev time a year Dev team of 3. All capable of righting C++ code as well... | The question is not what language to choose but which "architecture" or paradigm.
If you want/need to use SOAP then C++ might be fine, go and google for "gsoap". However I would recomend Java and REST as architecture paradigm, well we would need to know more what you really want to do. Perhaps some RMI or CORBA would b... |
4,026,427 | 4,026,468 | How to incorporate this script into build process using VC++ | I'm using VC++ and want to write a script that can scan my source-code and at some places where it sees a text like "abc" then extract characters of that text and generate a selective piece of code like ones below at build time:
first example of a piece of code :
Func1(a);
Func2(b);
Func3(c);
second example of a piece... | In the project properties of Visual Studio, you will have the option "Pre-Build Event" and "Post-Build Event".
At these configurations you can input programs that should be executed before and after your build. You can use project variables to identify your solution folder, project folder, binary, etc. If you are using... |
4,026,460 | 4,026,550 | Simple shared library |
Is the STD library a shared library or what is it ? out of curiosity .
Are there any books describe in detail the shared , static libraries development ?
Are there any tutorial ?
p.s (i'm using netbeans , eclipse, anjuta) and the tutorials aren't useful as I'm trying to understand what's actually going on.
| On my platform (Ubuntu Maverick) it is:
g++ test.cpp
ldd a.out
linux-vdso.so.1 => (0x00007fffee1ff000)
libstdc++.so.6 => /usr/lib/libstdc++.so.6 (0x00007f18755fd000)
libm.so.6 => /lib/libm.so.6 (0x00007f187537a000)
libgcc_s.so.1 => /lib/libgcc_s.so.1 (0x00007f1875163000)
libc.so.6 => /lib/libc.so.6 (0x00007f1874de000... |
4,026,703 | 4,026,871 | c++ how to write code the compiler can easily optimize for SIMD? | i'm working in Visual Studio 2008 and in the project settings I see the option for "activate Extended Instruction set" which I can set to None, SSE or SSE2
So the compiler will try to batch instructions together in order to make use of SIMD instructions?
Are there any rules one can follow in how to optimize code such t... |
i'm working in Visual Studio 2008 and in the project settings I see the option for "activate Extended Instruction set" which I can set to None, SSE or SSE2
So the compiler will try to batch instructions together in order to make use of SIMD instructions?
No, the compiler will not use vector instructions on its own. I... |
4,026,747 | 4,026,770 | Setting Up a Win32 DLL in Visual Studio 2008 | I would like to make a Win32 DLL (unmanaged code) using Visual Studio 2008. After selecting New Project, in Project types -> Other Languages -> Visual C++ -> Win32 I selected Win32 Project as the project type. Then I gave it a name and specified the location, and clicked OK. In the Win32 Application Wizard, I have t... | You only need ATL for COM, generally (so might be marginally useful if you do use WMI for this task). WMI is what underpins System.Management in the .Net Framework.
MFC is a general-purpose class library built to wrap Win32 APIs, if there is WMI support (I don't think so - list is here) you might find it useful.
There... |
4,026,887 | 4,026,908 | What is the difference between '\n' or "\n" in C++? | I've seen the new line \n used 2 different ways in a few code examples I've been looking at. The first one being '\n' and the second being "\n". What is the difference and why would you use the '\n'?
I understand the '\n' represents a char and "\n" represents a string but does this matter?
| '\n'is a character constant.
"\n" is a pointer to character array equivalent to {'\n', '\0'} (\n plus the null terminator)
EDIT
I realize i explained the difference, but didn't answer the question.
Which one you use depends on the context. You use '\n' if you are calling a function that expects a character, and "\n", ... |
4,027,154 | 4,027,336 | Why can't I downcast pointer to members in template arguments? | If I make a pointer-to-base-member, I can convert it to a pointer-to-derived-member usually, but not when used within a template like Buzz below, where the first template argument influences the second one. Am I fighting compiler bugs or does the standard really mandate this not work?
struct Foo
{
int x;
};
struct... | It simply isn't allowed. According to §14.3.2/5:
The following conversions are performed on each expression used as a non-type template-argument. If a non-type template-argument cannot be converted to the type of the corresponding template-parameter then the program is ill-formed.
— for a non-type template-parameter... |
4,027,317 | 4,033,935 | Ensuring column visibility in wxListCtrl | I want wxListCtrl in report mode and I want to lock one or more columns such that when you scroll left and right those columns remain visible at all times. For example:
| name | field1 | field2 | field3 |....|
When scrolled to the left I want it to be like:
| name | field3 | field 4 | ... |
I can't find a way to ge... | I suggest faking it by using two controls side by side. One would hold the the non-scrolling column(s), the other would scroll. By carefully aligning them with minimal margins, they would look, at a glance, like one control. By handling the vertical scroll events in the parent, the vertical scrolling of both can be ... |
4,027,428 | 4,027,447 | Getting Spaces to Play Nicely with C++ Input Streams | First consider this sample C++ code:
std::string input1, input2, input3;
std::cout << "Enter Input 1: ";
std::cin >> input1;
std::cout << std::endl << "Enter Input 2: ";
std::cin >> input2;
std::cout << std::endl << "Enter Input 3: ";
std::cin >> input3;
If for input1 I enter something like "Good day neighbors" then i... | You can use std::getline:
std::getline(std::cin, input1);
...
std::getline(std::cin, input2);
...
std::getline(std::cin, input3);
|
4,027,604 | 4,027,676 | C->C++ Automatically cast void pointer into Type pointer in C++ in #define in case of type is not given (C-style) [MSVS] | Hi!
I've used the following C macro, But in C++ it can't automatically cast void* to type*.
#define MALLOC_SAFE(var, size) { \
var = malloc(size); \
if (!var) goto error; \
}
I know, I can do something like this:
#define MALLOC_SAFE_CPP(var, type, size) { \
var = (type)malloc(size); \
if (!var) goto er... | I do not recommend doing this; this is terrible code and if you are using C you should compile it with a C compiler (or, in Visual C++, as a C file)
If you are using Visual C++, you can use decltype:
#define MALLOC_SAFE(var, size) \
{ \
var = st... |
4,027,917 | 4,028,049 | Converting HLOCAL to LPTSTR | How is should a HLOCAL data type be converted to a LPTSTR data type? I'm trying to get a code snippet from Microsoft working, and this is the only error, of which I'm not sure how to resolve:
// Create a HDEVINFO with all present devices.
hDevInfo = SetupDiGetClassDevs(NULL,
0, // Enumerator
0,
DIGCF_PRESE... | LocalLock() returns the pointer. But this is 18 year old silliness, just use
// Change the buffer size.
delete buffer;
// Double the size to avoid problems on
// W2k MBCS systems per KB 888609.
buffer = new TCHAR[buffersize * 2];
Ignoring the ~7 year old silliness of still u... |
4,027,986 | 4,028,007 | C++ -- Why I can return an int for class Month | Saw the following code snippet and I have problems to understand how it works.
class Month {
public:
static const Month Jan() { return 1; }
...
static const Month Dec() { return 12; }
int asInt() const { return monthNumber; }
private:
Month(int number) : monthNumber(number) {}
const int monthNu... | The Month object is created automatically using the Month(int) constructor. It could/should have been written this way to be explicit:
static const Month Jan() { return Month(1); }
Note that good practice is to declare constructors that take one parameter as explicit. Indeed, these constructors can be used to perform ... |
4,028,169 | 4,029,386 | Parsing escaped strings with boost spirit | I´m working with Spirit 2.4 and I'd want to parse a structure like this:
Text{text_field};
The point is that in text_field is a escaped string with the symbols '{', '}' and '\'.
I would like to create a parser for this using qi. I've been trying this:
using boost::spirit::standard::char_;
using boost::spirit::stand... | Your grammar could be written as:
qi::rule< IteratorT, std::string(), ascii::space_type > text;
qi::rule< IteratorT, std::string() > content;
qi::rule< IteratorT, char() > escChar;
text = "Text{" >> content >> "};";
content = +(~char_('}') | escChar);
escChar = '\\' >> char_("\\{}");
i.e.
text is Text{ fo... |
4,028,221 | 4,028,247 | A C++ Equivalent to PHP's fgets()? | Essentially what I'm looking for is a function with the following prototype: string getln(istream);
All I need it to do is work like PHP's fgets(), that is, take an input stream as a parameter and return the next line from the stream.
I feel like my current approach is somewhat bulky for creating a temporary variable e... | You're being picky. Any function that returns a string is going to have a string variable that's declared, filled, and returned, just like the function you've already written.
Besides, the "named return-value optimization" allows the compiler to elide the extra variable sometimes. The caller will allocate space for the... |
4,028,413 | 4,028,462 | Out parameters and pass by reference | I have joined a new group that has coding guidelines that (to me) seem dated.
But just rallying against the machine without valid backup is not going to get me anywhere.
So I am turning to SO to see if we can up with rational reasons for/against (hey I may be wrong in my option so both sides of the argument would be ap... |
When you use a reference, it looks the same as a value.
Only if you really aren't paying attention to what you are doing. Ok, sometimes that happens, but really... no amount of coding standards can correct for people not paying attention or not knowing what they are doing.
The caller may be surprised that his value... |
4,028,463 | 4,033,554 | Detecting an unplugged capture device (OpenCV) | I'm attempting to detect if my capture camera gets unplugged. My assumption was that a call to cvQueryFrame would return NULL, however it continues to return the last valid frame.
Does anyone know of how to detect camera plug/unplug events with OpenCV? This seems so rudimentary...what am I missing?
| There is no API function to do that, unfortunately.
However, my suggestion is that you create another thread that simply calls cvCaptureFromCAM() and check it's result (inside a loop). If the camera get's disconnected then it should return NULL.
I'll paste some code just to illustrate my idea:
// This code should be ex... |
4,028,571 | 4,028,586 | Python and win32 API - using a C file | With ActiveState Python comes a win32api module. I need to implement something that monitors directories recursively for file-changes. Actually there's an example in the MSDN library using C. I don't know whether the win32api bindings are sufficient for something like this.
Can I import this into a Python project? Beca... | Why not try some of the python win32 examples here. It uses pywin32 and does what you want.
http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html
The "C" code that you have mentioned with link to MSDN uses FindFirstChangeNotification. Tim Golden's example uses the same through python win32 bin... |
4,028,681 | 4,028,885 | How do I run a python file that is read into a std::string using PyRun | I am embedding Python into my C++ program, and have used PyRun_SimpleString quite effectively but now am having trouble.
What I have done is loaded a python.py file a std::string but am now having troubles running it. PyRun_SimpleFileEx didn't seem to do the trick either so some help would be great!
std::string con... | I solved my problem by using a string vector and reading each line of the file into the vector, then executing each one using PyRun_SimpleString.
Here's the finished code, no error checking though.
std::vector string_vector;
std::string content;
if(python_script.empty())
return true;... |
4,028,691 | 4,028,739 | C# calling C++ method that returns a pointer. Explain memory management | Can someone explain what exactly is happening at a low level / memory management perspective on the 2 C# lines in "Main" in the following?
C++ Code (unmanaged):
#define DLLEXPORT extern "C" __declspec(dllexport)
DLLEXPORT MyClass* MyClass_MyClass()
{
return new MyClass();
}
DLLEXPORT void M... | .NET knows nothing about MyClass type, it only stores a pointer to it. Size of the pointer is always known and fixed - 4 bytes for 32bit processes and 8 bytes for 64bit processes. All memory allocation and management in this particular case happens in unmanaged C++ code here:
return new MyClass();
and here:
myClass->s... |
4,028,785 | 4,028,801 | C++ friend function references | I have this situation (two classes with two different header files):
b.h
#include "a.h"
class B {
friend void B* A::create(void);
private:
int x;
};
a.h
#include "b.h"
class A {
public:
void B* create(void);
...
};
basically class A creates "B" objects. I want to give the creation function... | What you need is a "forward declaration". Basically you don't include the classes' headers in other classes' headers (unless you want to use composition, then you have to). In your case, it'd look like this:
// B.h
class A;
class B {
// declare pointers to A freely
};
And the other way round in A.h.
You'd probably... |
4,029,227 | 4,029,264 | How does the compiler determine the location of a member when accessing through a base pointer | This just jumped into my head and I can't figure it out.
If I have a code like this:
struct A { char x[100]; };
struct B { int data; };
struct C : A, B {};
#include <iostream>
using namespace std;
B* get_me_some_stuff()
{
static int x = 0;
if (++x % 2 == 0)
return new B();
el... | Try this:
C* x = new C();
B* y = x;
cout << x << " " << y << endl;
Output for me:
0x1ae2010 0x1ae2074
The act of casting from C* to B* (or in the other direction) includes the necessary pointer arithmetic.
|
4,029,265 | 4,029,278 | Determining calling line without macro | Is it possible to determine the line number that calls a function without the aid of a macro?
Consider this code:
#include <iostream>
#define PrintLineWithMacro() \
std::cout << "Line: " << __LINE__ << std::endl; // Line 4
void PrintLine()
{
std::cout << "Line: " << __LINE__ << std::endl; // Line 8
}
int mai... | I would do the following:
#define PrintLine() PrintLine_(__LINE__)
void PrintLine_(int line) {
std::cout << "Line: " << line << std::endl;
}
I know that this doesn't completely remove the preprocessor, but it does move most of the logic into an actual function.
|
4,029,381 | 4,029,418 | Input after cin.getline() fails? | I am new to programming. In my textbook, the problem presented it to write a program that asks a user for the rainfall for three months and calculates the average.
I used the cin.getline() function to read the user input into an array. The text states that there is no worry of the array being overflowed using the cin... | It's because getline will read up to the size you specify (minus 1), and it leaves the remaining characters in the stream. When you use (>>) to extract the rainfall, since there are non numerical characters in the stream, cin errors. You need to account for that.
|
4,029,524 | 4,029,577 | USB RF Receiver Mouse Hacking | How do wireless mice work, as in technically, the RF Receiver you plug in via USB (PnP)? I want to know how I would go about accessing the data section of the receiver and see either the actual code involved in sending information to the OS driver, or see the drivers involved to go about decompilation.
| Do you want to know how the receiver talks to the mouse, or how the receiver talks to the PC?
The former interface is proprietary and will vary from device to device. For the latter, see here
http://www.usb.org/developers/devclass_docs/HID1_11.pdf
|
4,029,628 | 4,040,418 | what is the media player uid in symbian^3 (N8 device) | in my application,i just wanna open a url contain media,e.g. http://www.test.com/test.mp3,or rstp://www.test.com/test.3gp,so i need the symbian embeded media player's uid to open it.
| This is what I use for showing links:
_LIT( KTestUrlPrefix,"4 " );
HBufC* parameter = HBufC::NewLC( KTestUrlPrefix().Length() + aLink.Length() );
parameter->Des().Copy( KTestUrlPrefix );
parameter->Des().Append( aLink );
if(iLauncher)
{
delete iLauncher;
iLauncher = NULL;
}
iLauncher = CBrowserLauncher::NewL();... |
4,029,801 | 4,029,851 | How to turn on STL backward compatability? | I am trying to compile something that uses Google's sparsehash include files.
libs/include/google/dense_hash_map:93:60: error: ext/hash_fun.h: No such file or directory
^Cmake: *** [all] Interrupt
I know that hash_fun.h exists in /usr/include/c++/4.3/backward/hash_fun.h.
I am just not sure how to make google sparse ha... | When you compiled sparsehash, did you build it with the same compiler that you are using now? When I build it, it finds hash_fun in tr1/functional, not in ext/hash_fun.h.
In m4/stl_hash_fun.m4, you can see the list of places that it searches.
|
4,029,870 | 4,029,897 | How to create a dynamic array of integers | How to create a dynamic array of integers in C++ using the new keyword?
| int main()
{
int size;
std::cin >> size;
int *array = new int[size];
delete [] array;
return 0;
}
Don't forget to delete every array you allocate with new.
|
4,029,970 | 4,030,203 | C++: What are scenarios where using pointers is a "Good Idea"(TM)? |
Possible Duplicate:
Common Uses For Pointers?
I am still learning the basics of C++ but I already know enough to do useful little programs.
I understand the concept of pointers and the examples I see in tutorials make sense to me. However, on the practical level, and being a (former) PHP developer, I am not yet con... | Pointers are commonly used in C++. Becoming comfortable with them, will help you understand a broader range of code. That said if you can avoid them that is great, however, in time as your programs become more complex, you will likely need them even if only to interface with other libraries.
Primarily pointers are use... |
4,030,049 | 4,030,199 | Curious question : What algorithm does STL set_intersect implement? | I spent a considerable amount of time coding in Baeza-Yates' fast set intersection algorithm for one of my apps. While I did marginally out-do the STL set_intersect, the fact that I required the resultant set to be sorted removed any time I had gained from implementing my own algorithm after I sorted the output. Given ... | At least in the implementations I've looked at, the implementation is fairly simplistic -- something on this general order:
template <class inIt, class outIt>
outIt set_intersection(inIt start1, inIt end1, inIt start2, inIt end2, outIt out) {
while (start1 != end1 && start2 != end2) {
if (*start1 < *start2)
... |
4,030,067 | 4,031,231 | State of static variable in DLL | Scenario:
My Application bind a library X which has static class. I initialize it in my process.
After some time when I load a dll which also use same library X.
I see content of static variable in dll is not initialized. Where I already initialized it in process before loading DLL.
I added initialization code in DLL... | library x is clearly linked as a static library against both the exe, and the dll :- in order to get the behavior you want, library X itself needs to be built as a shared library. So then "my application.exe" and "a.dll" would both use "libraryx.dll" as a result there would only by one instance of the static value.
|
4,030,224 | 4,030,238 | What's the use of the derived class as a template parameter? | What's the purpose of this pattern? What is it called? It looked very strange when I saw it the first time, though I have now seen it many times.
template<typename Derived>
struct Base {
//...
};
struct Example : Base<Example> {
//...
};
| I think you are reffering to CRTP. Also refer here
|
4,030,237 | 4,030,251 | Problem with STL map iterator copying | I have an STL map that I want to iterate through, and can't seem to get the code to work. The code is:
//PowerupInfo is a struct defined in this class's header file
std::map<std::string, PowerupInfo> powerups;
...populate powerups
std::map<std::string, PowerupInfo>::iterator iter;
for (iter = powerups.begin(); iter !... | Your map name is poweruplist not powerups (You are using this name in the for loop). If this is not the cause of the error, then it looks like you are for loop is in a function which accepts the map by const reference (or is a const member function of a class). In that case your type of iterator should be const_iterato... |
4,030,337 | 4,030,402 | How to validate a valid integer and floating number in VC++ CString | Can some one tell me a valid way to validate a number present in CString object as either a valid integer or floating number?
| Use _tcstol() and _tcstod():
bool IsValidInt(const CString& text, long& value)
{
LPCTSTR ptr = (LPCTSTR) text;
LPTSTR endptr;
value = _tcstol(ptr, &endptr, 10);
return (*ptr && endptr - ptr == text.GetLength());
}
bool IsValidFloat(const CString& text, double& value)
{
LPCTSTR ptr = (LPCTSTR) text;... |
4,030,511 | 4,030,812 | Convert a QDateTime in UTC to local system time | I construct a QDateTime from a string like this:
QDateTime date = QDateTime::fromString("2010-10-25T10:28:58.570Z", "yyyy-MM-ddTHH:mm:ss.zzzZ");
I know that date is in UTC because that is the way it's stored. But when I want to display this date to the user, it should be in the user's local time zone. date.toLocalTime... | QDateTime knows whether it is UTC or local time. For example:
QDateTime utc = QDateTime::currentDateTimeUtc();
QDateTime local = QDateTime::currentDateTime();
local.secsTo(utc) // zero; these dates are the same even though I am in GMT-7
We need to tell date that it is a UTC date time with date.setTimeSpec(Qt::UTC):
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.