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 |
|---|---|---|---|---|
1,824,245 | 1,824,283 | scope of local variables of a function in C | I have heard about the following scenario right when I started programming in C.
"Trying to access from outside, a functions local variable will result in error (or garbage value). Since the stack gets cleared off when we return from the function"
But my below code sample prints a value of 50. I am compiling the code ... | Modify it to add a second call to printf and you'll see a different value from the first time. Compile it with optimizations turned on and you'll see another set of values. Do anything with the value and you're stepping into undefined territory, which means that the compiler is free to summon demons through your nasal ... |
1,824,279 | 1,824,293 | How to get IP address from sockaddr | I want to try and get the ip address of a client after calling accept. This is what I have so far, but I just end up getting some long number that is clearly not an ip address. What could be wrong?
int tcp_sock = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in client;
client.sin_family = AF_INET;
socklen_t c_len = size... | That long number is the IP address, in integer form (an IP address is just an integer, after all; it's just easier for people to use when we split the octets apart and put it into dot notation).
You can use inet_ntoa to convert the integer value to standard dot notation.
|
1,824,420 | 1,824,433 | Is there an string equivalent to LPTSTR? | Is there an string equivalent to LPTSTR? I know of string and wstring. Is there a tstring?
| You could define one:
typedef std::basic_string<TCHAR> mystring;
...
mystring test = _T("Hello World!");
|
1,824,533 | 1,824,550 | What does it mean by C++ runtime? | What are all the activities done by C++ runtime?
| It handles startup and shutdown of your application, and the core services it needs to run - things like initialising the stack and static variables, and providing the heap and default memory allocators.
|
1,824,685 | 8,964,016 | Eclipse-C++-Debugging: see content of an Array | Is it possible to see the content of a dynamically allocated array, as in:
int *array = new int[dimension];
I only see the value of the pointer.
edit: just found the option "display as an array", but I always have to manually enter the size of the array. Is it possible to get that automagically?
| In Eclipse, in order to see the content of a dynamically allocated array (for anyone else who stumbles over this question),
Make sure you are in the debugging perspective;
Look for the "Variables" window. if you don't see it, click "Window" > "Show view" > "Variables";
Right-click on the array variable;
Click "displa... |
1,824,772 | 1,824,834 | How many requests can SQL Server handle per second? | I am using JMeter to test our application 's performance. but I found when I send 20 requests from JMeter, with this the reason result should be add 20 new records into the sql server, but I just find 5 new records, which means that SQL server discard the other requests(because I took a log, and make sure that the inse... | I'm not convinced the nr of requests per seconds are directly releated to SQL server throwing away your inserts. Perhaps there's an application logic error that rolls back or fails to commit the inserts. Or the application fails to handle concurrency and inserts data violating the constraints. I'd check the server logs... |
1,824,787 | 1,836,580 | opencv multi channel element access | I'm trying to learn how to use OpenCV's new C++ interface.
How do I access elements of a multi channel matrix? For example:
Mat myMat(size(3, 3), CV_32FC2);
for (int i = 0; i < 3; ++i)
{
for (int j = 0; j < 3; ++j)
{
//myMat_at_(i,j) = (i,j);
}
}
What is the easiest way to do this? Something like ... | typedef struct elem_ {
float f1;
float f2;
} elem;
elem data[9] = { 0.0f };
CvMat mat = cvMat(3, 3, CV_32FC2, data );
float f1 = CV_MAT_ELEM(mat, elem, row, col).f1;
float f2 = CV_MAT_ELEM(mat, elem, row, col).f2;
CV_MAT_ELEM(mat, elem, row, col).f1 = 1212.0f;
CV_MAT_ELEM(mat, elem, row, col).f2 = 326... |
1,824,835 | 1,824,867 | How can I create a type based lookup table in order to implement multiple-dispatch in C++? | I'm attempting to make a messaging system in which any class derived from "Messageable" can receive messages based on how the function handleMessage() is overloaded. For example:
class Messageable {
public:
void takeMessage(Message& message) {
this->dispatchMessage(message);
}
protec... | You should look into the Double Dispatch pattern. See information here.
You should be able to implement VisualMessage as a class like such:
class VisualMessage : public Message
{
public:
virtual void dispatch(Messageable & inMessageable)
{
inMessageable.handleMessage(*this);
}
}... |
1,824,838 | 1,824,900 | Iterating over all pairs of elements in std-containers (C++) | What's the best way to iterate over all pairs of elements in std container like std::list, std::set, std::vector, etc.?
Basically to do the equivalent of this, but with iterators:
for (int i = 0; i < A.size()-1; i++)
for(int j = i+1; j < A.size(); j++)
cout << A[i] << A[j] << endl;
| The easiest way is just rewriting the code literally:
for (auto i = foo.begin(); i != foo.end(); ++i) {
for (auto j = i; ++j != foo.end(); /**/) {
std::cout << *i << *j << std::endl;
}
}
Replace auto with a const_iterator for C++98/03. Or put it in its own function:
template<typename It>
void for_each_pair(It... |
1,824,910 | 1,824,923 | Is there an occasion where using catch all clause : catch (...) is justified? | Each time I have seen the catch all statement:
try
{
// some code
}
catch (...)
{
}
it has always been an abuse.
The arguments against using cache all clauses are obvious. It will catch anything including OS generated exceptions such as access violations.
Since the exception handler can't know what it's deal... |
the arguments against using cache all clauses are obvious , it will catch anything including OS generated exceptions such as access violation. since the exception handler can't know what its dealing with, in most cases the exceptions will manifest as obscure log message or some incoherent message box.
And if those sa... |
1,825,065 | 1,825,183 | Is it OK for an abstract base class have non-abstract methods? | An abstract base class (interface class) usually has all its member functions abstract. However, I have several cases where member functions consisting of calls to the abstract methods of the interface are used. I can implement them in a derived-but-still-abstract class, or I can implemented the methods as non-abstrac... | If you're calling it an interface (i.e. which you seem to be by your use of the naming convention "IFoo") then it should be a pure interface (no implementations).
If it's merely an abstract class then a mix of pure virtual and implemented methods is perfectly reasonable.
|
1,825,089 | 1,825,223 | Using a C++ dll in C# | I'm attempting to consume a dll written in C++ from a C# application. I have 3rd party source code for the C++ dll (the Cyclone physics engine) and do not want to manually port it over to C#.
In the C++ project
I changed it to output a dll. I changed it to use the /clr flag. I changed it to use Multi-threaded Debug ... | The Particle class is not a managed class, hence it is treated as a struct. You need to use the ref keyword to make it managed and garbage collected. You also need to do the same to every other class that references it which might be a problem. The best solution I think, is to create a managed wrapper class that uses t... |
1,825,094 | 1,825,151 | Is there an automated program to find C++ linker errors? | I'm working in a Linux environment with C++, using the GCC compiler.
I'm currently working on modifying and upgrading a large pre-existing body of code. As part of this, it has been necessary to add quite a large number of small references throughout the code in a variety of places to link things together, and also to ... | Don't know your platform, but I spent sometime with linker problems in gcc till I realized that the static library (.a) linking requires specific ordering, its not the same to link gcc object.o first.a second.a than gcc object.o second.a first.a.
|
1,825,338 | 1,825,369 | Video streaming using c++ | I'm going to build an application in c++ that creates stream of photos and then sends them as video stream to another application. any ideas about how can i start? what I mean is, what libraries should i use and what the encoding? I'm thinking about MJPEG, and UDP or RTP as protocol.... any help would be greatly apprec... | If your input data is just a bunch of random images, not video, you're not going to do "video streaming". You're just going to be sending a bunch of full images. No need to involve video encoding technology, just do the simplest possible transmission of images. Video encoders rely on each frame having various relations... |
1,825,553 | 2,101,039 | C# pass int and string by reference to C++ ActiveX Control: type mismatch | I have a problem passing by reference int or string variables to C++ ActiveX Control.
Also I pass these variables by reference to C++ DLL and everything works fine.
C++ DLL:
__declspec (dllexport) void
Execute (LPCTSTR cmd, int& resultCode, LPCTSTR& message, long& receiptNumber)
{
message = _T("ReplyProblem");
... | SOLVED:
In MyCOMCtrl.cpp:
// Dispatch map
...
DISP_FUNCTION_ID(MyCOMCtrl, "Execute", DISPID_EXECUTE_METHOD, Execute, VT_EMPTY, VTS_PI4)
...
Must be:
DISP_FUNCTION_ID(MyCOMCtrl, "Execute", DISPID_EXECUTE_METHOD, Execute, VT_EMPTY, VTS_BSTR VTS_PI4) // two VTS arguments
|
1,825,653 | 1,825,698 | How to check code generated by C++ compiler? | just like in topic - is there any software to open (what?) and here I don't even know what to open - file with object code or exe?
My today's questions (if only todays ;)) may seem bit odd but I'm going through excersises in "The C++ Programming Language" by B.S. and sometimes I'm just stuck on particular question. I'm... | The debugger will help you. Most debuggers let you halt the program and look into disassembly. The nice thing is they point you right to disassembly of the line you set the breakpoint to, not to just all the compilation result.
Once in a while I do that in Visual Studio - compile the program, put a breakpoint onto the ... |
1,825,720 | 1,825,929 | C++ high precision time measurement in Windows | I'm interested in measuring a specific point in time down to the nanosecond using C++ in Windows. Is this possible? If it isn't, is it possible to get the specific time in microseconds at least?. Any library should do, unless I suppose it's possible with managed code.
thanks
| If you have a threaded application running on a multicore computer QueryPerformanceCounter can (and will) return different values depending on which core the code is executing on. See this MSDN article. (rdtsc has the same problem)
This is not just a theoretical problem; we ran into it with our application and had to ... |
1,825,794 | 1,825,813 | Passing pointer argument by reference under C? | #include <stdio.h>
#include <stdlib.h>
void
getstr(char *&retstr)
{
char *tmp = (char *)malloc(25);
strcpy(tmp, "hello,world");
retstr = tmp;
}
int
main(void)
{
char *retstr;
getstr(retstr);
printf("%s\n", retstr);
return 0;
}
gcc would not compile this file, but after adding #include <cstring> I could use ... | No, C doesn't support references. It is by design. Instead of references you could use pointer to pointer in C. References are available only in C++ language.
|
1,825,868 | 1,825,930 | How to prevent window resizing temporarily? | I have a window which can be resized, but there are some situations when resizing is not possible because of the application state. Is there a way to prevent resizing the window temporarily?
I want to disable resizing by all means available to the users, which include window menu, dragging edges by mouse, user initiate... | One way is to use GetWindowLong() with GWL_STYLE flag to get the window style and
reset/remove any styles you need, ie the WS_THICKFRAME style so that the window can't be resized.
You apply the new style with SetWindowLong.
|
1,825,964 | 1,825,996 | C/C++ maximum stack size of program on mainstream OSes | I want to do DFS on a 100 X 100 array. (Say elements of array represents graph nodes) So assuming worst case, depth of recursive function calls can go upto 10000 with each call taking upto say 20 bytes. So is it feasible means is there a possibility of stackoverflow?
What is the maximum size of stack in C/C++?
Please... | In Visual Studio the default stack size is 1 MB i think, so with a recursion depth of 10,000 each stack frame can be at most ~100 bytes which should be sufficient for a DFS algorithm.
Most compilers including Visual Studio let you specify the stack size. On some (all?) linux flavours the stack size isn't part of the ex... |
1,826,159 | 1,826,175 | Swapping two variable value without using third variable | One of the very tricky questions asked in an interview.
Swap the values of two variables like a=10 and b=15.
Generally to swap two variables values, we need 3rd variable like:
temp=a;
a=b;
b=temp;
Now the requirement is, swap values of two variables without using 3rd variable.
| Using the xor swap algorithm
void xorSwap (int* x, int* y) {
if (x != y) { //ensure that memory locations are different
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
}
Why the test?
The test is to ensure that x and y have different memory locations (rather than different values). This is because (p xo... |
1,826,165 | 1,826,361 | WM_ENTERSIZEMOVE / WM_EXITSIZEMOVE - when using menu, not always paired | To prevent my application changing the window content while user is moving its window around, I capture messages WM_ENTERSIZEMOVE / WM_EXITSIZEMOVE and I pause the application between the messages. However, sometimes it happens I receive WM_ENTERSIZEMOVE but no WM_EXITSIZEMOVE at all. One repro is:
open the window men... | As a temporary workaround, I now un-pause the application whenever I receive WM_ACTIVATE message. This seems to have a kind solved this particular case (you can recover the application by activating it again) and did not seem to break anything.
Such solution smells to me, though. I would rather understand how it should... |
1,826,172 | 1,826,188 | C++ type casting vector class | I have two vector classes:
typedef struct D3DXVECTOR3 {
FLOAT x;
FLOAT y;
FLOAT z;
} D3DXVECTOR3, *LPD3DXVECTOR3;
and
class MyVector3{
FLOAT x;
FLOAT y;
FLOAT z;
};
and a function:
void function(D3DXVECTOR3* Vector);
How is it possible (if it's possible) to achieve something like this:
MyVect... | function(reinterpret_cast<D3DXVECTOR3*>(&vTest));
Generally speaking you should avoid reinterpret_cast though.
|
1,826,203 | 1,826,373 | Swapping addresses of pointers in C++ | How can one swap pointer addresses within a function with a signature?
Let's say:
int weight, height;
void swap(int* a, int* b);
So after going out of this function the addresses of the actual parameters (weight and height) would be changed. Is it possible at all?
| If you want to swap the addresses that the pointers are pointing to, not just the values stored at that address, you'll need to pass the pointers by reference (or pointer to pointer).
#include <cassert>
void swap(int*& a, int*& b)
{
int* c = a;
a = b;
b = c;
}
int main()
{
int a, b;
int* pa = &a;
... |
1,826,464 | 1,826,505 | C-Style Strings as template arguments? | Can C-Style strings be used as template arguments?
I tried:
template <char *str>
struct X
{
const char *GetString() const
{
return str;
}
};
int main()
{
X<"String"> x;
cout<<x.GetString();
}
And although I get no complaints about the class definition, the instantiation yields 'X' : inval... | A string literal cannot be used as a template argument.
Update: Nowadays, a few years after this question was asked and answered, it is possible to use string literals as template arguments. With C++11, we can use characters packs as template arguments (template<char ...c>) and it is possible to pass a literal string t... |
1,826,534 | 1,826,644 | How to input realtime data to do realtime process in c/c++ | I dont project about process realtime data from cyber glove( Virtual Hand ) . So I need to write some application that get realtime data from glove and feed to some algorithm. I don't know how to deal with process realtime data; does anybody have some resources?
| I'm pretty sure the cyber glove you're using comes with an SDK as well as examples on how to get the data from the device.
From there, I'm afraid we can't tell you much. I see you tagged your question with "recognition" but what are you trying to recognize exactly?
Recognizing gestures would typically mean analyzing a... |
1,826,885 | 1,826,916 | Visual Studio 2008 C++ debugger drops out of single-step mode under Vista | I have a fairly large C++ project, and am trying to use the debugger to step through some code. Unfortunately, it sometimes decides to drop out of that mode, and just execute the code without paying attention to the fact that I pressed F10, and not breaking at subsequent breakpoints. I don't know when it's going to d... | I think I've encountered this before.
You can download hotfixes which will correct this and other issues (available here):
http://code.msdn.microsoft.com/Project/ProjectDirectory.aspx?TagName=Visual%20Studio%202008,Hotfix
I installed a bunch and have not since had the problem. After installing, you can see them listed... |
1,826,901 | 1,834,333 | Should I add .vcxproj.filter files to source control? | While evaluating Visual Studio 2010 Beta 2, I see that in the converted directory, my vcproj files became vcxproj files. There are also vcxproj.filter files alongside each project which appear to contain a description of the folder structure (\Source Files, \Header Files, etc.).
Do you think these filter files should b... | Previous versions of Visual Studio (at least versions 6.0 and 2008) store that information in their own project file (.dsp and .vcproj files respectively), which of course is good to add to SCC.
I cannot think of any reason to not include this .filter files in SCC
|
1,826,902 | 1,826,920 | How to avoid memory leak with shared_ptr? | Consider the following code.
using boost::shared_ptr;
struct B;
struct A{
~A() { std::cout << "~A" << std::endl; }
shared_ptr<B> b;
};
struct B {
~B() { std::cout << "~B" << std::endl; }
shared_ptr<A> a;
};
int main() {
shared_ptr<A> a (new A);
shared_ptr<B> b (new B);
a->b = b;
b->... | If you have circular references like this, one object should hold a weak_ptr to the other, not a shared_ptr.
From the shared_ptr introduction:
Because the implementation uses reference counting, cycles of shared_ptr instances will not be reclaimed. For example, if main() holds a shared_ptr to A, which directly or indi... |
1,826,934 | 1,827,049 | Copy Constructor Needed with temp object | The following code only works when the copy constructor is available.
When I add print statements (via std::cout) and make the copy constructor available it is not used (I assume there is so compiler trick happening to remove the unnecessary copy).
But in both the output operator << and the function plop() below (w... | From http://gcc.gnu.org/gcc-3.4/changes.html
When binding an rvalue of class type
to a reference, the copy constructor
of the class must be accessible. For
instance, consider the following code:
class A
{
public:
A();
private:
A(const A&); // private copy ctor
};
A makeA(void);
void foo(const A&);
voi... |
1,827,265 | 1,873,408 | error C2027 and error C2227 | I get
error C2027: use of undefined type 'Bridge'
and
error C2227: left of '->receive' must point to class/struct/union/generic type
on line *connection1->receive(newMessage,2);
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define MAXHOST 10
#define MAXPORT 5
#define MAXLAN 8
#define MAXBRIDGE 5
#define... | All the posts before are right, forward declaring is used to prevent circular includes in header files. The Bridge class is forward declared, so that you can specify pointers of that type within your class definition of LAN. Since pointers all have the same size this is ok.
When it comes to using this class the compile... |
1,827,406 | 1,827,545 | How much does the order of case labels affect the efficiency of switch statements? | Consider:
if (condition1)
{
// Code block 1
}
else
{
// Code block 2
}
If I know that condition1 will be true the majority of the time, then I should code the logic as written, instead of:
if (!condition1)
{
// Code block 2
}
else
{
// Code block 1
}
since I will avoid the penalty of the jump to the sec... | Some facts for modern hardware like x86 or x86_64:
A unconditionally taken branch has almost no additional costs, besides the decoding. If you want a number, it's about a quarter clock cycle.
A conditional branch, which was correctly predicted, has almost no additional costs.
A conditional branch, which was not correc... |
1,827,477 | 1,827,552 | How can I access my class instance from a boost thread? | I have the following code (this is some semi-sudo code, which may not compile):
class FooBar {
public:
void a();
void b();
boost::shared_ptr<boost::thread> m_thread;
std::string m_test;
};
void FooBar::a() {
m_test = "Foo bar"
m_thread = shared_ptr<thread>(new thread(bind(&FooBar::b, this)));
}... | Yes, that works. Here's the "real" version, which does in fact print "Foo bar":
#include <boost/make_shared.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
using namespace boost;
struct FooBar {
void a();
void b();
shared_ptr<thread> m_thread;
std::string m_test;
};
void FooBar::a() {
... |
1,827,522 | 1,827,695 | Default encoding for variant bstr to std::string conversion | I have a variant bstr that was pulled from MSXML DOM, so it is in UTF-16. I'm trying to figure out what default encoding occurs with this conversion:
VARIANT vtNodeValue;
pNode->get_nodeValue(&vtNodeValue);
string strValue = (char*)_bstr_t(vtNodeValue);
From testing, I believe that the default encoding is either Windo... | The operator char* method calls _com_util::ConvertBSTRToString(). The documentation is pretty unhelpful, but I assume it uses the current locale settings to do the conversion.
Update:
Internally, _com_util::ConvertBSTRToString() calls WideCharToMultiByte, passing zero for all the code-page and default character parame... |
1,827,705 | 1,852,359 | C++ Buildsystem with ability to compile dependencies beforehand | I'm in the middle of setting up an build environment for a c++ game project. Our main requirement is the ability to build not just our game code, but also its dependencies (Ogre3D, Cegui, boost, etc.). Furthermore we would like to be able build on Linux as well as on Windows as our development team consists of members ... | In the latest CMake 2.8 version there is the new ExternalProject module.
This allows to download/checkout code, configure and build it as part of your main build tree.
It should also allow to set dependencies.
At my work (medical image processing group) we use CMake to build all our own libraries and applications. We h... |
1,827,858 | 1,828,049 | How to mitigate class declaration being far from its owner namespace declaration in a file? | So, I've seen how useful namespaces can be to organize declarations into their respective groups, but now comes an issue with this.
The difference between making a library in C and a library in C++ is in C you must prefix your declarations with what they belong to, for example a library we'll dub MyMath might have a ve... | In chapter 8 of his book, Stroustrup recommends a style such as the following:
MyMath.h
namespace MyMath {
class Vector;
};
Vector.h
#include "MyMath.h"
class MyMath::Vector {
public:
Vector();
// ...
};
Vector.cc
#include "Vector.h"
MyMath::Vector::Vector() { /* ... */ }
Limiting open namespace-declarat... |
1,828,009 | 1,828,092 | Can you Hide a virtual method in c++? | I have a base class with a virtual function.
virtual CString& Foo();
I want to overload this in subclass like so
CString Foo();
is there a way to hide the base classes virtual function? Something like the new keyword in vb.net or C#
| Why anyone would do something like that? It breaks base class contract.
If you don't want to implement subclass that has the same interface as base class, why do you inherit at all?
Use composition.
There is no equivalent of C# new keyword in C++.
So you cannot cancel method's 'virtualness'.
If you really want to do th... |
1,828,021 | 1,828,183 | Storing variable sized strings in structures | I'm reading a file in C++ using streams, specifically, fstream, not ifstream.
blah blah blah\n
blah blah\n
blah blah blah blah \n
end
This repeats over and over with
varble number of blah's in each line,
constant number of lines between each end, end is the delimiter here
I want to read one set of data, then store i... | (My push_back utility described at the bottom.)
typedef std::vector<std::string> Block;
int main() {
using namespace std;
vector<Block> blocks;
string const end = "end";
// no real difference from using ifstream, btw
for (fstream file ("filename", file.in); file;) {
Block& block = push_back(blocks);
... |
1,828,037 | 1,828,048 | What's the point of g++ -Wreorder? | The g++ -Wall option includes -Wreorder. What this option does is described below. It is not obvious to me why somebody would care (especially enough to turn this on by default in -Wall).
-Wreorder (C++ only)
Warn when the order of member initializers given in the code does not
match the order in which they must... | Consider:
struct A {
int i;
int j;
A() : j(0), i(j) { }
};
Now i is initialized to some unknown value, not zero.
Alternatively, the initialization of i may have some side effects for which the order is important. E.g.
A(int n) : j(n++), i(n++) { }
|
1,828,132 | 1,828,224 | C++ text file pointer problems | I am writing a function which should (if the file already exists) increment the first number by one and append the parameters of the function to the end of the file.
Example:
append (4,9);
append (5,6);
File contents at 1:
1 \n 4 \n 9
File contents at 2:
2 \n 4 \n 9 \n 5 \n 6
int append (int obj, int objType) {
ifs... | Instead of closing and reopening file this way (I'm not sure if this operation will reset file position you require!) why not use std::fstream::seekg() and just "rewind" the file to beginning
infile.seekg(0, ios::beg)
|
1,828,452 | 1,828,572 | What on earth would compell C++ to call this function? | I'm working on a programming language that uses C++ as it's target language for now. I'm hitting an exceptionally strange backtrace.
#1 0x08048d09 in factorial (n=0x8052160) at ir.cpp:35
35 shore::builtin__int * __return = NULL;
(gdb) bt
#0 shore::builtin__int::__mul__ (this=0x8052160, other=0x8052288) at /home... | A bit of a guess: the initialization in the line shore::builtin__int * __return = NULL; does nothing, since it's always overwritten. The compiler would be perfectly entitled to (a) reorder it down to where __return is assigned, by the statement that does call __mul__ and then (b) remove the code entirely. But maybe it'... |
1,828,535 | 1,828,699 | Fastest socket method for a lot of data between a lot of files | I'm building a socket application that need to shuffle a lot of small/medium sized files, something like 5-100kb sized files to a lot of different clients (sort of like a web server, but still not quite).
Should I just go with the standard poll/epoll (linux) or async sockets in winsock (win32), or are there any methods... | On windows you may try using TransmitFile, which has a potential of boosting your performance by avoiding kernel space <-> user space data copying.
|
1,828,700 | 1,829,260 | Using C++ in xcode for image and video processing | I am studying in the area of image and video processing - specifically in the field of pattern recognition (objects, people etc.). I wish to use a programming language to apply the transformation to images and video (more importantly video). I am thinking of using C++ in Xcode to do this. The algorithms I wanna build I... | If you choose to use C++ (which seems sinsible for that scenario) you should check out these links:
IPP - Also usefull for non-Intel processors, especially in combination with the Intel C++ compiler, but it's expensive
Intel offers many tools that are usefull for parallelising high performance number crunching (CPU bo... |
1,829,013 | 1,829,034 | Trouble understanding C++ `virtual` | I'm having trouble understanding what the purpose of the virtual keyword in C++. I know C and Java very well but I'm new to C++
From wikipedia
In object-oriented programming, a
virtual function or virtual method is
a function or method whose behavior
can be overridden within an inheriting
class by a function... | Make the following changes and you will see why:
#include <iostream>
using namespace std;
class A {
public:
int a();
};
int A::a() {
return 1;
}
class B : public A { // Notice public added here
public:
int a();
};
int B::a() {
return 2;
}
int main() {
A* b = new B(); // Noti... |
1,829,119 | 1,829,158 | C++ -- Pointers to Arrays -- Arrays of Pointers | I notice this has caused confusion for several people, but after reading a couple of posts on here and the cplusplus tutorial my brain is still scrambled.
Suppose I have the following variables in a header file -
int numberOfLinePoints;
D3DXVECTOR3* line; //confused as to what it is
Then in the implementation C++ fi... | int numberOfLinePoints;
D3DXVECTOR3* line; //confused as to what it is
//both initialized in constructor
numberOfLinePoints = 25;
line = new D3DXVECTOR3[numPoints]; //array of pointers?
line is an array of D3DXVECTOR3. It would be an array of pointers if D3DVECTOR3 is itself a pointer, however. Since I don't kno... |
1,829,499 | 1,829,552 | How Does PHP's main.c Start Execution | I was poking around the PHP 5.3.1 source tree, and decided to take a look at main.c. I was curious what was happening behind the scenes whenever PHP runs.
I was under the impression that any C or C++ program starts execution in a function named main, but I don't see a function with that name in main.c.
Where does PHP ... | I don't think I've ever seen any clear answer to that kind of question on the Internet, but you might be interested by some paragraphs of the book Extending and Embedding PHP, which is probably the reference book when it comes to writting PHP extensions, and the internals of the PHP engine.
An interesting couple of sen... |
1,829,639 | 1,829,691 | How can I use a custom type for keys in a boost::unordered_map? | I'm using Boost's implementation of a hash map in a project right now, and I'm trying to implement a custom type for keys. I have four unsigned integers which I'd like to combine into a single 128-bit datatype to use as a key.
I've created a struct with a 32-bit integer array of four elements, which serves as my storag... | The involvement of unordered-map is almost incidental to the problem you're encountering. The real problem is that you're defining hash_value and operator== in every file that includes the header above.
You can cure this by either:
Defining both those as inline functions
Just declaring them in the header
If you do the... |
1,829,741 | 1,836,862 | Lightweight debugging on embedded Linux | I'm developing an application that runs on a small Linux-based SBC (~32MB RAM). Sadly, my app recently became too large to run under GDB anymore. Does anyone know of any good, lightweight debugging methods that I can use in embedded Linux? Even being able to view a thread's stack trace would be extremely helpful.
I ... | gdbserver definitely works with multi-threaded applications, I'm working on an embedded project right now with >25 threads and we use gdbserver all the time.
info threads
lists all the threads in the system
thread <thread number from info threads>
switches to that thread of execution.
thread apply XXX <command> ... |
1,829,898 | 1,829,917 | Drawing with c++ visual studio 2010 beta? | please tell me how to draw any shape (a small square e.g)
using visual studio 2010 with the c++ language ?
PUT THEM STEP BY STEP PLEASE
I don't know what type of file i have to choose nor how to check it out
| I think you mean drawing in win32? I would suggest you to check this out:
http://www.codeproject.com/KB/GDI/paint_beginner.aspx
|
1,829,905 | 1,831,813 | What is the copy constructor bug causing parsing errors? | I'm writing a compiler for a small language, and my Parser class is currently in charge of building an AST for use later. However, recursive expressions are not working correctly because the vector in each AST node that holds child nodes are not working correctly. Currently my AST's header file looks like this:
class A... | parent.children.push_back(expr) copies the expression. Hence, it calls AST::AST(AST const&). A bug in that could certainly cause the problem you see. However, without the code, we can't find bugs in it.
|
1,829,906 | 1,829,923 | Member value changes between successive calls of the same function | I have a CognitiveEntity class, defined this way:
class CognitiveEntity : public Object
{
public:
CognitiveEntity (FuzzyCognitiveMap fcm, SystemState s);
~CognitiveEntity ();
template <typename T> void RegisterChange (std::string context, T value);
bool operator!= (const CognitiveEntity& rhs) const;
private:... | If this was a multi-threaded system, I'd say it sounds like a classic case of shared, mutable state that wasn't properly synchronized.
If you don't have a multi-threaded situation, I'd say set a watch on that variable and see what changes it.
|
1,829,930 | 1,829,936 | Multi-statement Macros in C++ | In C++, is it possible to make a multi-statement macro with nested if statements inside of it like the one below? I've been attempting it for a while now and I'm getting a scope issue for the second if statement not being able to see 'symbol'. Maybe I need to understand macros further.
#define MATCH_SYMBOL( symbol, tok... | For a multi-line macro you need to add a \ character to the end of all but the last line to tell the macro processor to continue parsing the macro on the next line, like so:
#define MATCH_SYMBOL( symbol, token) \
if(something == symbol){ \
if( symbol == '-'){ \
}else if (symbol !=... |
1,830,043 | 1,830,089 | C++ pass pointer by reference and assign default value | I would like to pass a pointer by reference to a function, such that i can actually change the address the passed pointer is pointing to and i'd like to assign this argument a default value.
something like this:
in the declaration
void myFunc(SomeType* &var=NULL);
and the definition:
void MyClass::myFunc(SomeType* &va... | The error message says it all: you are passing an integer instead of a reference-to-a-pointer-to-SomeType. To do what you want, you can use a pointer-to-a-pointer-to-SomeType:
void myFunc(SomeType** var=NULL);
void MyClass::myFunc(SomeType** var){
if(var!=NULL && *var!=NULL)
(**var)=(*someOtherPointer);
... |
1,830,158 | 1,830,240 | How to call erase with a reverse iterator | I am trying to do something like this:
for ( std::list< Cursor::Enum >::reverse_iterator i = m_CursorStack.rbegin(); i != m_CursorStack.rend(); ++i )
{
if ( *i == pCursor )
{
m_CursorStack.erase( i );
break;
}
}
However erase takes an iterator and not a reverse iterator. is there a way to c... | After some more research and testing I found the solution. Apparently according to the standard [24.4.1/1] the relationship between i.base() and i is:
&*(reverse_iterator(i)) == &*(i - 1)
(from a Dr. Dobbs article):
So you need to apply an offset when getting the base(). Therefore the solution is:
m_CursorStack.erase... |
1,830,780 | 1,831,073 | How can I interface with a third party module that only provides JTAPI API From C++? | I'm supporting a large system written in C++ and we now have a requirement for our application to talk with a third party system which only provides a JTAPI interface. It would appear that I am stuck writing a JTAPI proxy in Java that talks JTAPI on one side and some more language-neutral API on the other. However, thi... | This article shows a way to call Java objects from C++.
You can also think of embedding the JVM in your C++ program. This page talks about a possible way to do this. Also see: Embed Java code into your native apps
If your C++ system provides an API, then the easier approach is to write a Java program that wraps the C++... |
1,831,290 | 1,832,693 | Static variable initialization? | I want to know why exactly static variables in C, C++ and Java are initialized by zero by default? And why this is not true for local variables?
| Why the static variables are deterministically initialized and local variables aren't?
See how the static variables are implemented. The memory for them is allocated at link time, and the initial value for them is also provided at link time. There is no runtime overhead.
On the other hand, the memory for local variable... |
1,831,316 | 1,832,051 | Is this "*ptr++ = *ptr + a" undefined behavior? | Well, I'm not really in serious need of this answer, I am just inquisitive.
Expressions like *ptr++ = a are perfectly valid since we are operating on two objects ptr and *ptr but if i write *ptr++ = *ptr + a is it still valid ?
For example consider the following snippet:
int main(void){
int a[] = {5,7,8,9,2};
in... | First let us assume that 'p' is a pointer type.
Otherwise all the operation are just syntactic sugar for function calls.
Lets us break the statement down into parts.
int* p = a;
*p++ = *p + 32;
<< Sequence Point >>
// Part 1: p++
// Note the definition of post increment in the standard is (5.2.6)
// The result of the... |
1,831,369 | 1,831,499 | Writing binary files using C++: does the default locale matter? | I have code that manipulates binary files using fstream with the binary flag set and using the unformatted I/O functions read and write. This works correctly on all systems I've ever used (the bits in the file are exactly as expected), but those are basically all U.S. English. I have been wondering about the potential ... | On Windows it should be fine, but on other OS you should check also the line endings (just as safety). The default C/C++ locale is "C" which is not dependent on the system's locale.
This is not a guarantee. As you know C/C++ compiler and their target machines vary greatly. So you're waiting for troubles to come if you ... |
1,831,529 | 2,308,294 | Is C++ code generation in ANTLR 3.2 ready? | I was trying hard to make ANTLR 3.2 generate parser/lexer in C++. It was fruitless. Things went well with Java & C though.
I was using this tutorial to get started: http://www.ibm.com/developerworks/aix/library/au-c_plusplus_antlr/index.html
When I checked the *.stg files, I found that:
CPP has only
./tool/src/main/res... | It sounds like you've answered your own question: ANTLR's C++ lexer/parser generators are not yet functional.
For what it's worth, it's still possible to use ANTLR for parsing from C++, via the C target. I use ANTLR to generate a C language lexer and parser, which I then compile and link to my C++ code.
I have one C++ ... |
1,831,635 | 1,831,688 | vptr - virtual tables | there is something i still don't get.
for every class i declare there is a hidden vptr member pointing to the class virtual table.
let's say i have this declaration :
class BASE
{
virtual_table* vptr; //that's hidden of course , just stating the obvious
virtual void foo();
}
class DERIVED : public BASE
{
vi... | first, yes, it is the same member. It is automaticaly assigned a first time when running base constructor, and assigned a second time when running the derived constructor. (In the case of default empty constructors, the useless assignements of base is optimized away.)
second, there is no real conversion. In fact, the d... |
1,831,991 | 1,832,104 | C++: Safe way to cast an integer to a pointer | I need to convert an integral type which contains an address to the actual pointer type. I could use reinterpret_cast as follows:
MyClass *mc1 = reinterpret_cast<MyClass*>(the_integer);
However, this does not perform any run-time checks to see if the address in question actually holds a MyClass object. I want to know ... | Type checking on dynamic_cast is implemented in different ways by different C++ implementations; if you want an answer for your specific implementation you should mention what implementation you are using. The only way to answer the question in general is to refer to ISO standard C++.
By my reading of the standard, cal... |
1,832,003 | 1,837,665 | Instantiating classes by name with factory pattern | Suppose I have a list of classes A, B, C, ... which all inherit from Base.
I get the class name as a string from the user, and I want to instantiate the right class and return a pointer to Base. How would you implement this?
I thought of using a hash-table with the class name as the key, and a function pointer to a fun... | Here is a generic factory example implementation:
template<class Interface, class KeyT=std::string>
struct Factory {
typedef KeyT Key;
typedef std::auto_ptr<Interface> Type;
typedef Type (*Creator)();
bool define(Key const& key, Creator v) {
// Define key -> v relationship, return whether this ... |
1,832,087 | 1,832,218 | Is Network Up? C++ Fedora/Unix | Does any one have a snippet of their code that, checks if the network is enabled on a machine and has an active IP Address.
I have a networking software that connects to other client machines, Although it works when the machine is connected but if i unplug the cable or disable the network, It throws a whole reem of exc... | Network is always in dynamic state, a simple check at beginning of the run is not enough for correct operation.
So unfortunately you have to check for any network operations succeess state.
As for not even starting program with network disconnected state... Consider if your program is automatically started after compu... |
1,832,160 | 1,832,206 | Can I use C++ templates to generate Unicode/ANSI variants of a function, rather than using the preprocessor? | We've got a bunch of legacy code that doesn't support Unicode, so a transitional pattern we use in our code is to move the function to a .inl file, change char to CHAR_TYPE, and then wrap it up like this:
#define CHAR_TYPE wchar_t
#define STRING_TYPE std::wstring
#define MyFunctionName MyFunctionNameW
#include "MyFunct... | Roger Pate is entire correct about the interface. You shouldn't bother with A and W suffixes. However, this still leaves the problem of implementation. As you supected, templates are the correct solution. And since you don't need the different names, you can leave out the typedefs. You would just have
template <typenam... |
1,832,504 | 1,832,574 | boost::any test code compiles with Sun CC but not g++ | The following noddy test code:
#include <iostream>
#include <list>
#include <boost/any.hpp>
#include <boost/foreach.hpp>
#include <typeinfo.h>
using boost::any_cast;
using std::cout;
using std::cerr;
typedef std::list<boost::any> many;
template <typename T>
inline bool is_any(const boost::any& op)
{
return (op.type... | Seems I only answered the second part of the question, so here I go with the first part as well:
Is this the reason why there isn't a 'is_any' template included with boost any?
There are no actual need to is_any, do the following instead:
if (const std::string* s = boost::any_cast<std::string>(&a))
{
std::cout << "s... |
1,832,521 | 1,832,570 | How do I avoid popping up an error dialog when my MSVS C++ app crashes | When my Visual Studio 2008 C++ command-line application crashes, it sometimes produces this dialog.
CommandProcessor.exe has encountered a problem and needs to close.
We are sorry for the inconvenience. If you were in the middle of something, the information you were working on might be lost. For more informaiton about... | With /EHa option you can use catch(...) to catch all exceptions included structured exceptions and write a console message. You can also use VC++ - specific __try for structured exception handling instead, but that's a bit harder to code.
However this will not protect you against situations when terminate() is called b... |
1,832,621 | 1,832,645 | C++ CPU Register Usage | In C++, local variables are always allocated on the stack. The stack is a part of the allowed memory that your application can occupy. That memory is kept in your RAM (if not swapped out to disk). Now, does a C++ compiler always create assembler code that stores local variables on the stack?
Take, for example, the foll... | Disclaimer: I don't know MIPS, but I do know some x86, and I think the principle should be the same..
In the usual function call convention, the compiler will push the value of n onto the stack to pass it to the function foo. However, there is the fastcall convention that you can use to tell gcc to pass the value throu... |
1,832,704 | 1,832,776 | Default assignment operator in inner class with reference members | I've run into an issue I don't understand and I was hoping someone here might provide some insight. The simplified code is as follows (original code was a custom queue/queue-iterator implementation):
class B
{
public:
B() {};
class C
{
public:
int get();
C(B&b) : b(b){};
private:
... | This problem has nothing to do with inner classes. In C++ you just can't (re)assign references - they need to be initialised when defined.
A simpler example is:
class B
{
public:
B(int& i) : ir(i) {};
int& ir;
};
int main()
{
int i;
B b(i); // Constructor - OK
int j;
B bb = B(j); // Cop... |
1,832,809 | 1,833,378 | How to catch divide-by-zero error in Visual Studio 2008 C++? | How can I catch a divide-by-zero error (and not other errors; and to be able to access exception information) in Visual Studio 2008 C++?
I tried this:
try {
int j=0;
int i= 1/j;//actually, we call a DLL here, which has divide-by-zero
} catch(std::exception& e){
printf("%s %s\n", e.what());
} catch(...){
print... | Assuming that you can't simply fix the cause of the exception generating code (perhaps because you don't have the source code to that particular library and perhaps because you can't adjust the input params before they cause a problem).
You have to jump through some hoops to make this work as you'd like but it can be d... |
1,833,224 | 1,833,237 | operator/ overloading | For learning purposes I'm creating big integer class in C++. There are 2 files:
big_int.h
#ifndef BIG_INT_H
#define BIG_INT_H
#include
class big_int
{
public:
big_int(void);
big_int(char*);
big_int(QString);
~big_int();
big_int operator+(big_int);
big_int operator-(big_int);
big_int o... | That's a typo, you forgot the class name :
big_int big_int::operator+(big_int b)
{
return big_int();
}
big_int big_int::operator-(big_int b)
{
return big_int();
}
big_int big_int::operator*(big_int b)
{
return big_int();
}
big_int big_int::operator/(big_int)
{
return big_int();
}
By the way, you sho... |
1,833,318 | 1,833,500 | Not able execute CreateProcess with PhotoViewer.dll | In my application there is an interface where user can select any file and open in its default application depending on the file association.
I am using FindExecutable and CreateProcessAsUser with Explorer token.
Now the problem is in the case of picture files say .jpg, FindExecutable returns "C:\Program Files\Window... | A Win32 executable has extension .EXE; a DLL is not an executable. CreateProcess cannot create a process with just a .DLL. The missing .EXE is "rundll32.exe".
However, that's not what you are after: you want the Shell behavior. ShellExecuteEx() is usually the most convenient function. AssocQueryString() may be appropr... |
1,833,356 | 1,833,381 | Detach a pointer from a shared_ptr? |
Possible Duplicate:
How to release pointer from boost::shared_ptr?
A function of my interface returns a pointer to an object. The user is supposed to take ownership of that object. I do not want to return a Boost.shared_ptr, because I do not want to force clients to use boost. Internally however, I would like to sto... | What you're looking for is a release function; shared_ptr doesn't have a release function. Per the Boost manual:
Q. Why doesn't shared_ptr provide a release() function?
A. shared_ptr cannot give away ownership unless it's unique() because the other copy will still destroy the object.
Consider:
shared_ptr<int> a(new ... |
1,833,362 | 1,833,389 | What is the correct way to initialize a Matrix in C++98? |
I'm not programmer
I want to compile Inkscape in win32, and stumbled on these error messages:
ui/dialog/filedialogimpl-win32.cpp:1379: error: in C++98 'matrix' must be initialized by constructor, not by '{...}'
make[1]: *** [ui/dialog/filedialogimpl-win32.o] Error 1
The suspected code of filedialogimpl-win32.cpp:... | Instead of
const Matrix matrix = {
scaleFactor, 0,
0, scaleFactor,
svgX, svgY };
there should be something like this:
const Matrix matrix(
scaleFactor, 0,
0, scaleFactor,
svgX, svgY );
|
1,833,379 | 1,835,894 | C macro to transform a SVN revision to an integer | I am looking for a C/C++ macro that can transform a random SVN revision like "$Revision: 9 $" or "$Revision: 9999999 $" into an integer or a string.
I know that simple functions exists to achieve this, but I want this to be made at compile time.
My wish is to write things like:unsigned int rev = SVN_TO_INT("$Revision$"... | I agree that it is not doable with macros, however, I found a trick using compiler optimizations.
The result is that the expression JL_SvnRevToInt("$Revision: 12345 $") is reduced to a single unsigned integer: 12345
inline unsigned int JL_SvnRevToInt(const char *r) {
if ( r == NULL || r[0] == '\0' || r[10] == '\0... |
1,833,447 | 1,833,499 | A good example for boost::algorithm::join | I recently wanted to use boost::algorithm::join but I couldn't find any usage examples and I didn't want to invest a lot of time learning the Boost Range library just to use this one function.
Can anyone provide a good example of how to use join on a container of strings? Thanks.
| #include <boost/algorithm/string/join.hpp>
#include <vector>
#include <iostream>
int main()
{
std::vector<std::string> list;
list.push_back("Hello");
list.push_back("World!");
std::string joined = boost::algorithm::join(list, ", ");
std::cout << joined << std::endl;
}
Output:
Hello, World!
|
1,833,484 | 1,833,628 | C++ frontend only compiler (convert C++ to C) | I'm currently managing some C++ code that runs on multiple platforms from a single source tree (Win32, Linux, Verifone CC terminals, MBED and even the Nintendo GBA/DS). However I need to build an app targetted at an embedded platform for which there is no C++ compiler (C only). I remmber that many of the early C++ comp... | If you use LLVM, llvm-g++ will compile your C++ code to LLVM bitcode, and llc has a backend which converts bitcode to C.
You could write commands like this:
llvm-g++ -emit-llvm -c foo.cpp -o foo.o
llc -march=c <foo.o >foo.c
|
1,833,683 | 1,839,660 | Boost: how to build Boost under MacOSX | I am trying to build MacOSX universal binaries (I need at least i386/ppc for >=macosx10.3) of Boost.
I tried a lot of different methods and options and versions and it all fails in the end with this crash:
Boost: what could be the reasons for a crash in boost::slot<>::~slot?
I guess this crash is because of a bad Boost... | It was already the correct command. I found out about the problem with my crash:
You must use exactly the same STL preprocessor definitions when you compiled Boost in your project. I.e. you cannot enable _GLIBCXX_DEBUG or _GLIBCXX_DEBUG_PEDANTIC in your project when Boost was compiled without those.
|
1,833,982 | 1,834,074 | In C++, is there a difference between “throw” and “throw ex”? | I'd like to ask this question (also here), but this time about C++.
What is the difference in C++ between
try { /*some code here*/}
catch(MyException& ex)
{ throw ex;} //not just throw
and
try { /*some code here*/}
catch(MyException& ex)
{ throw;} //not throw ex
Is it just in the stack trace (which in C++ is in any... | throw; rethrows the same exception object it caught while throw ex; throws a new exception. It does not make a difference other than the performance reasons of creating a new exception object. If you have a exception hierarchy where there some other exception classes derived from MyException class and while throwing a... |
1,834,164 | 1,834,274 | Access violation writing location | I have the following code:
#include <openssl/bn.h>
#include <openssl/rsa.h>
unsigned char* key;
RSA* rsa = RSA_new();
rsa = RSA_generate_key(1024,65537,NULL,NULL);
//init pubkey
key[BN_num_bytes(rsa->n)] = '\0';
BN_bn2bin(rsa->n, key);
printf("RSA Pub: %s\n", key);
RSA_free( rsa );
rsa = NULL;
The debugger is telling... | Since key is not pointing to anything and you have referenced it with array notation subscript, that is the source. How does key get the value. You are overwriting or trampling on some other memory block that is not yours hence the 'Access violation' as trapped by windows. Double check your code and make sure that the ... |
1,834,230 | 1,834,330 | How to encapsulate a std::set properly? | I have a class named Particle which has a std::set as a member. The class looks like this:
class Particle {
private:
std::set<vtkIdType> cells;
std::set<vtkIdType>::iterator ipc;
public:
Particle() {};
enum state {EXISTS = -1, SUCCESS = 0, ERROR = 1};
state addCell(const vtkIdType cell);
in... | I'm not sure why you do not want to expose the set itself, but if it is because you want to ensure that the content of the set cannot be altered outside class Particle just return const iterators which makes the set "read-only", e.g.
typedef std::set<vtkIdType>::const_iterator CellIterator;
CellIterator beginCell() con... |
1,834,434 | 1,834,577 | How to use protocol buffers? | Could someone please help and tell me how to use protocol buffers. Actually I want to exchange data through sockets between a program running on unix and anoother running on windows in order to run simulation studies.
The programs that use sockets to exchange data, are written in C/C++ and I would be glad if somneone... | You start by defining your message in a .proto file:
package foo;
message snd_data {
required string var= 1;
required int32 var1 = 2;
optional float var2 = 3;
optional double var3 = 4;
}
(I guess the float and double actually are different variables...)
Then you compile it using protoc and then you have code ... |
1,834,666 | 1,834,688 | In which header file c++ STL hash function object is declared? | If I want to use the hash function object provided in STL, which header file I should include on Linux? e.g. hash Hf;
| #include <hash_map>
on some Linux distros it's available here:
#include <ext/hash_map>
More info here. The hash_map is currently not part of the official STL but it's in TR1 as <unordered_map>.
|
1,834,769 | 1,834,783 | Character arrays question C++ | Is there any difference between the below two snippets?
One is a char array, whereas the other is a character array pointer, but they do behave the same, don't they?
Example 1:
char * transport_layer_header;
// Memory allocation for char * - allocate memory for a 2 character string
char * transport_layer_header = (cha... | Yes, there is a difference. In the first example, you dynamically allocate a two-element char array on the heap. In the second example you have a local two-element char array on the stack.
In the first example, since you don't free the pointer returned by malloc, you also have a memory leak.
They can often be used in... |
1,835,040 | 1,835,152 | C++ inheritance designing a linked list | I wanted to make a linked list class ListList that inherits from a class List.
ListList uses functions from List, but has its own functions. It has its own start pointer that points to the beginning of the list, and its own Node struct that holds a different amount of elements.
But, it looks like, when one of List's fu... | Edit: I see.
Ideally, you'd have just one linked list implementation that can hold any kind of value, including — and here's the kicker — a compound data structure that has a linked list as one of its fields. In the code you have right now, the inheritance is actually unnecessary as far as I can tell, you're generally ... |
1,835,106 | 1,835,181 | Lockless Deque in Win32 C++ | I'm pretty new to lockless data structures, so for an exercise I wrote (What I hope functions as) a bounded lockless deque (No resizing yet, just want to get the base cases working). I'd just like to have some confirmation from people who know what they're doing as to whether I've got the right idea and/or how I might ... | Looking at this I would think this would be a problem:
void PushBottom(ITask* task)
{
m_tasks[m_bottom] = task;
InterlockedIncrement(&m_bottom);
}
If this is used in an actual multithreaded environment I would think you'd collide when setting m_tasks[m_bottom]. Think of what would happen if you have two threads t... |
1,835,209 | 1,837,286 | How can I disable and gray the top level menu item using MFC | I have a dialog application in which I want to have clickable menu items at the top of the dialog. These items do not show a drop down menu but actually run the associated commands.
I did this by setting Popup=False in the dialogs properties and assigning a message-id but my problem is not having the ability to disabl... | I have not tried but in regular window (not dialog) CWnd::DrawMenuBar should do what you want. It might work with dialog based applications as well.
void CYourDlg::EnableMenuItem(UINT nCommand, BOOL bEnable)
{
CMenu* pMenu = GetMenu();
pMenu->EnableMenuItem(nCommand, bEnable ? 0 : MF_DISABLED | MF_GRAYED);
Dra... |
1,835,399 | 1,835,431 | Const correctness: const char const * const GetName const (//stuff); | Labelled as homework because this was a question on a midterm I wrote that I don't understand the answer to. I was asked to explain the purpose of each const in the following statement:
const char const * const GetName() const { return m_name; };
So, what is the explanation for each of these consts?
| Take them from the right. The one before the ; tells the client this is a design level const i.e. it does not alter the state of the object. (Think of this as a read-only method.)
Okay, now the return value:
const char const *const
This is a constant pointer to okay ... here we go boom! You have an extra const -- a s... |
1,835,489 | 1,835,566 | Linking an application to libbz2.so.1 rather than libbz2.so.1.0 | Here's the current situation I'm in:
I want to distribute a binary app on Linux that would run on several distros (not all of them, just the main ones matter at the moment, let's focus on Ubuntu and Fedora for the sake of this discussion). The app in question links to libbz2 for some of its work. A simple "Hello World"... | Why don't you just link statically instead?
I have done that in the past for builds on Ubuntu and deployment on RHEL which works just fine using static builds.
|
1,835,626 | 1,835,647 | C++ DLL fails when run from different drive letter | I've written a C++ DLL that connects to a Sybase database using the native C library for Sybase. I can build and run the program on my C drive, and others can run it from their C drives, and everything works. But in some situations both my DLL and the Sybase DLL are located on the F drive instead of the C drive. In tho... | Generally speaking absolute locations are not used inside DLLs. Only the name of the DLL is stored.
The places where system looks for DLLs are descrived here: http://msdn.microsoft.com/en-us/library/ms682586(VS.85).aspx
Though it IS possible to load a DLL by absolute path - with a techinique known as run-time DLL load... |
1,835,761 | 1,836,117 | Why does C# not have C++ style static libraries? | Lately I've been working on a few little .NET applications that share some common code. The code has some interfaces introduced to abstract away I/O calls for unit testing.
I wanted the applications to be standalone EXEs with no external dependencies. This seems like the perfect use case for static libraries. Come ... | .NET does in fact support the moral equivalent of a static
library. It's called a netmodule (file extension is usually
.netmodule). Read more about it in this blog post.
Beware that it isn't well supported by the Visual Studio
build tool chain. I think extension methods are a
problem as well. ILMerge is the better too... |
1,835,988 | 1,836,067 | Why can I not access a public function of a base class with a pointer of a subClass? | I am not sure why I am getting an "error C2660: 'SubClass::Data' : function does not take 2 arguments". when i try to compile my project.
I have a base class with a function called data. The function takes one argument, There is an overload of Data that takes 2 arguments.
In my subClass I override the data function tak... | The C++ Programming Language by Bjarne Stroustrup (p. 392, 2nd ed.):
15.2.2 Inheritance and Using-Declarations
Overload resolution is not applied across different class scopes (§7.4) …
You can access it with a qualified name:
void SomeOtherFunction()
{
SubClass* test = new SubClass();
test->Base::Data(1, 1);
}... |
1,836,253 | 1,836,612 | How To Remove Characters? | I'm start(really starting) an Assembly tool, at the time it only converts a decimal to a hexadecimal, but I want to remove the zeros from the result. Here is the code:
// HexConvert.cpp
#include <iostream>
using namespace std;
int main()
{
int decNumber;
while (true)
{
cout << "Enter the decimal num... | You can call this function directly from C++, but you may have to save some registers, dependig on the compiler. Have fun retranslating to C++.
;number to convert in [esp+4]
;pointer to string in [esp+8]
itoh: mov edi, [esp+8] ;pointer to c string
bsr ecx, eax ;calculate highest set b... |
1,836,622 | 1,837,422 | Surely there is a way to obtain the full View pulldown for the current folder view? | Motivation: Creating our own file dialog that looks & acts much like the std common dialog
Problem: How to obtain the view pull-down for the current folder/shell container
Apparent Dead Ends:
Query the IShellFolder for its IContextMenu < NULL interface pointer.
Query the IShellView for its IContextMenu < NULL interfac... | use SVGIO_BACKGROUND to get the background menu of the folder, which should have a view submenu. the index, name and the command id of the "view" menu item may vary between windows versions and local languages, so this is kind of hack.
|
1,836,671 | 1,837,945 | CSocket is not blocking on send | This function is called to serve each client in a new thread. in the consume function, these archives are read and written to but the function returns before the client finishes reading all the response so the socket goes out of scope and closed, creating an exception in client. I'm assuming that any write on the CArch... | I found the solution, In order to close the connection without loosing any none exchanged data you should basically use SO_LINGER option, it's a very long story you can see the details in this article
but the strange part is, MSDN seems very inaccurate when it comes to shutdown, in my experience, LINGER options had no ... |
1,837,024 | 1,837,336 | Problem with returning arguments that are const references | I know why the following does not work correclty, so I am not asking why. But I am feeling bad about it is that it seems to me that it is a very big programming hindrance.
#include <iostream>
#include <string>
using namespace std;
string ss("hello");
const string& fun(const string& s) {
return s;
}
int main(... | I think it is a slight weakness of C++. There's an unfortunate combination of two factors:
The function's return is only valid as long as its argument is.
Implicit conversion means that the function's argument is not the object it may appear to be.
I have no sympathy for people who fail to think about the lifetime of... |
1,837,092 | 1,837,140 | C++ destruction of temporary object in an expression | Given the following code:
#include <iostream>
struct implicit_t
{
implicit_t(int x) :
x_m(x)
{
std::cout << "ctor" << std::endl;
}
~implicit_t()
{
std::cout << "dtor" << std::endl;
}
int x_m;
};
std::ostream& operator<<(std::ostream& s, const implicit_t& x)
{
... |
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. [12.2/3]
|
1,837,159 | 1,837,186 | Encapsulating a private enum | Previously I've defined enumerated types that are intended to be private in the header file of the class.
private:
enum foo { a, b, c };
However, I don't want the details of the enum exposed anymore. Is defining the enum in the implementation similar to defining class invariants?
const int ClassA::bar = 3;
enum Clas... | C++ doesn't have forward declarations of enums, so you can't separate enum "type" from enum "implementation".
The following will be possible in C++0x:
// foo.h
class foo {
enum bar : int; // must specify base type
bar x; // can use the type itself, members still inaccessible
};
// foo.cpp
enum foo::bar : int { ... |
1,837,165 | 1,837,206 | can two classes see each other using C++? | So I have a class A, where I want to call some class B functions. So I include "b.h". But, in class B, I want to call a class A function. If I include "a.h", it ends up in an infinite loop, right? What can I do about it?
| Each class (A and B) should have a header file and an implementation file.
Each header file (e.g. A.h) should not include the other header file (e.g. B.h) but may include a forward reference to the other class (e.g. a statement like class B;), and may then use pointers and/or references to the other class in its declar... |
1,837,312 | 1,837,552 | Which version of boost should I use with c++ visual-studio-2005? | Does anyone know what version of the Boost Library to use with Visual Studio 2005?
| The latest version, 1.41.0.
If you're interested, Boost maintains a page with the current status of the regression tests on a variety of platforms, including Visual C++ 7.1, 8.0, and 9.0 (Visual Studio 2003, 2005, and 2008, respectively).
|
1,837,350 | 1,837,378 | Problem with cross casting in Visual Studio 2003 | I am using Visual Studio 2003 to compile and run following program.
There are 4 assignment operation where I expect 2 of them to run ok and 2 of them to raise exception. There is a dynamic casting inside overloaded = operator which expect to fail during non proper cross casting (Casting from Apple to Orange or Orange t... | You need to check Enable Run-time type information (RTTI) in Project Settings.
Category "C++ Language".
In VC6 at least it will not be enabled by default.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.