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 |
|---|---|---|---|---|
2,751,316 | 2,751,340 | Boost lambda: Invoke method on object | I'm looking at boost::lambda as a way to to make a generic algorithm that can work with any "getter" method of any class.
The algorithm is used to detect duplicate values of a property, and I would like for it to work for any property of any class.
In C#, I would do something like this:
class Dummy
{
public String GetId() ...
public String GetName() ...
}
IEnumerable<String> FindNonUniqueValues<ClassT>
(Func<ClassT,String> propertyGetter) { ... }
Example use of the method:
var duplicateIds = FindNonUniqueValues<Dummy>(d => d.GetId());
var duplicateNames = FindNonUniqueValues<Dummy>(d => d.GetName());
I can get the for "any class" part to work, using either interfaces or template methods, but have not found yet how to make the "for any method" part work.
Is there a way to do something similar to the "d => d.GetId()" lambda in C++ (either with or without Boost)?
Alternative, more C++ian solutions to make the algorithm generic are welcome too.
I'm using C++/CLI with VS2008, so I can't use C++0x lambdas.
| Assuming, I understand what you're looking for, you can use boost::bind:
FindNonUniqueValues<Dummy>(boost::bind(&Dummy::GetId, _1));
Actually, you just need boost::mem_fn or even std::mem_fun, but boost::bind will allow you a bit more generality.
In this case, you would define FindNonUniqueValues as something like:
template <typename T>
/* ? */ FindNonUniqueValues(boost::function<std::string (const T&)> getter) { ... }
Here, I'm not really sure how your FindNonUniqueValues gets its list of objects (or exactly what it's supposed to return - is an IEnumerable like an iterator?), so you could fill that in.
|
2,751,458 | 2,751,509 | Fibonacci Function Question | I was calculating the Fibonacci sequence, and stumbled across this code, which I saw a lot:
int Fibonacci (int x)
{
if (x<=1) {
return 1;
}
return Fibonacci (x-1)+Fibonacci (x-2);
}
What I don't understand is how it works, especially the return part at the end: Does it call the Fibonacci function again? Could someone step me through this function?
| Yes, the function calls itself. For example,
Fibonacci(4)
= Fibonacci(3) + Fibonacci(2)
= (Fibonacci(2) + Fibonacci(1)) + (Fibonacci(1) + Fibonacci(0))
= ((Fibonacci(1) + Fibonacci(0)) + 1) + (1 + 1)
= ((1 + 1) + 1) + 2
= (2 + 1) + 2
= 3 + 2
= 5
Note that the Fibonacci function is called 9 times here. In general, the naïve recursive fibonacci function has exponential running time, which is usually a Bad Thing.
|
2,751,487 | 2,751,749 | Why there is no scoped locks for multiple mutexes in C++0x or Boost.Thread? | C++0x thread library or Boost.thread define non-member variadic template function that lock all lock avoiding dead lock.
template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...);
While this function avoid help to deadlock, the standard do not includes the associated scoped lock to write exception safe code.
{
std::lock(l1,l2);
// do some thing
// unlock li l2 exception safe
}
That means that we need to use other mechanism as try-catch block to make exception safe code or define our own scoped lock on multiple mutexes ourselves or even do that
{
std::lock(l1,l2);
std::unique_lock lk1(l1, std::adopted);
std::unique_lock lk2(l2, std::adopted);
// do some thing
// unlock li l2 on destruction of lk1 lk2
}
Why the standard doesn't includes a scoped lock on multiple mutexes of the same type, as for example
{
std::array_unique_lock<std::mutex> lk(l1,l2);
// do some thing
// unlock l1 l2 on destruction of lk
}
or tuples of mutexes
{
std::tuple_unique_lock<std::mutex, std::recursive_mutex> lk(l1,l2);
// do some thing
// unlock l1 l2 on destruction of lk
}
Is there something wrong on the design?
Updated: description from the standard
template <class L1, class L2, class... L3> void lock(L1&, L2&, L3&...);
Requires: Each template parameter type shall meet the Mutex requirements, except that a call to try_- lock() may throw an exception. [ Note: The unique_lock class template meets these requirements when suitably instantiated. —end note ]
Effects: All arguments are locked via a sequence of calls to lock(), try_lock(), or unlock() on each argument. The sequence of calls shall not result in deadlock, but is otherwise unspecified. [ Note: A deadlock avoidance algorithm such as try-and-back-off must be used, but the specific algorithm is not specified to avoid over-constraining implementations. —end note ] If a call to lock() or try_lock() throws an exception, unlock() shall be called for any argument that had been locked by a call to lock() or try_lock().
I have accept the answer. I understand that the main reason is because there is no enough time to make the C++0x Thread library better. I hope that TR2 will include much more things.
| I think that by providing defer_lock_t (and adopt_lock_t) the expectation is that usage will be like your second example, or probably more like:
std::unqiue_lock ul1(l1, std::deferred);
std::unique_lock ul2(l2, std::deferred);
std::lock(ul1, ul2);
This is exception safe and all that good stuff.
I certainly can't pretend to know the minds of the designers, but my guess is they are making an effort to provide a minimal set of portable, safe, primitives. A scoped multiple lock type is just so much icing, and it's icing that if in the standard needs to be specified and designed, or in boost.thread, icing that needs to be implemented (and of course ultimately the standard has to be concerned about implementation too, look what happened with export).
|
2,751,528 | 2,751,611 | Scope quandary with namespaces, function templates, and static data | This scoping problem seems like the type of C++ quandary that Scott Meyers would have addressed in one of his Effective C++ books.
I have a function, Analyze, that does some analysis on a range of data. The function is called from a few places with different types of iterators, so I have made it a template (and thus implemented it in a header file). The function depends on a static table of data, AnalysisTable, that I don't want to expose to the rest of the code.
My first approach was to make the table a static const inside Analysis.
namespace MyNamespace {
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end) {
static const int AnalysisTable[] = { /* data */ };
... // implementation uses AnalysisTable
return result;
}
} // namespace MyNamespace
It appears that the compiler creates a copy of AnalysisTable for each instantiation of Analyze, which is wasteful of space (and, to a small degree, time).
So I moved the table outside the function like this:
namespace MyNamespace {
const int AnalysisTable[] = { /* data */ };
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end) {
... // implementation uses AnalysisTable
return result;
}
} // namespace MyNamespace
There's only one copy of the table now, but it's exposed to the rest of the code. I'd rather keep this implementation detail hidden, so I introduced an unnamed namespace:
namespace MyNamespace {
namespace { // unnamed to hide AnalysisTable
const int AnalysisTable[] = { /* data */ };
} // unnamed namespace
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end) {
... // implementation uses AnalysisTable
return result;
}
} // namespace MyNamespace
But now I again have multiple copies of the table, because each compilation unit that includes this header file gets its own. If Analyze weren't a template, I could move all the implementation detail out of the header file. But it is a template, so I seem stuck.
My next attempt was to put the table in the implementation file and to make an extern declaration within Analyze.
// foo.h ------
namespace MyNamespace {
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end) {
extern const int AnalysisTable[];
... // implementation uses AnalysisTable
return result;
}
} // namespace MyNamespace
// foo.cpp ------
#include "foo.h"
namespace MyNamespace {
const int AnalysisTable[] = { /* data */ };
}
This looks like it should work, and--indeed--the compiler is satisfied. The linker, however, complains, "unresolved external symbol AnalysisTable." Drat! (Can someone explain what I'm missing here?)
The only thing I could think of was to give the inner namespace a name, declare the table in the header, and provide the actual data in an implementation file:
// foo.h -----
namespace MyNamespace {
namespace PrivateStuff {
extern const int AnalysisTable[];
} // unnamed namespace
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end) {
... // implementation uses PrivateStuff::AnalysisTable
return result;
}
} // namespace MyNamespace
// foo.cpp -----
#include "foo.h"
namespace MyNamespace {
namespace PrivateStuff {
const int AnalysisTable[] = { /* data */ };
}
}
Once again, I have exactly one instance of AnalysisTable (yay!), but other parts of the program can access it (boo!). The inner namespace makes it a little clearer that they shouldn't, but it's still possible.
Is it possible to have one instance of the table and to move the table beyond the reach of everything but Analyze?
| You could use a class with a static member to hold the data if it's really important that nothing but specializations of your function template can access the data.
class AnalysisTable
{
static const int data[];
template <typename InputIterator>
friend int Analyze(InputIterator begin, InputIterator end);
};
template <typename InputIterator>
int Analyze(InputIterator begin, InputIterator end)
{
// ...
x = AnalysisTable::data[n];
// ...
}
|
2,751,670 | 2,751,699 | What does this C++ construct do? | Somewhere in lines of code, I came across this construct...
//void* v = void* value from an iterator
int i = (int)(long(v))
What possible purpose can this contruct serve?
Why not simply use int(v) instead? Why the cast to long first?
| It most possibly silences warnings.
Assuming a 32bit architecture with sizeof(int) < sizeof(long) and sizeof(long) == sizeof(void *) you possibly get a warning if you cast a void * to an int and no warning if you cast a void * to a long as you're not truncating. You then get a warning assigning a long to an int (possible truncation) which is removed by then explicitly casting from a long to an int.
Without knowing the compiler it's hard to say, but I've certainly seen multi-step casts required to prevent warnings. Why not try converting the construct to what you think it should be and see what the compiler says (of course that only helps you to work out what was in the mind of the original programmer if you're using the same compiler and same warning level as they were).
|
2,751,761 | 2,751,785 | Polygonal gradients with OpenGL | I'm wondering how I could create a gradient wuth multiple stops and a direction if I'm making polygons. Right now I'm creating gradients by changing the color of the verticies but this is limiting. Is there another way to do this?
Thanks
| One option you may have is to render a simple polygon with a gradient to a texture, which you then use to texture your actual polygon.
Then you can rotate the source polygon and anything textured with its image will have its gradient rotate as well, without the actual geometry changing.
|
2,751,819 | 2,751,893 | How do I make Boost multithreading? | I am trying to compile the latest Boost c++ libraries for Centos. I 've used bjam install and it has placed the libraries in /usr/lib and /usr/lib64.
The problem is I need the -mt variants for a specific application to run. I cannot understand in the documentation how to create the multithreading variants. :(
Please give me a hint!
Thanks!
| -mt is just distribution specific extension.
either edit your config file or create symbolic link to libboost_thread
andrey@localhost:~$ ls -l /usr/lib/libboost_thread*
-rw-r--r-- 1 root root 174308 2010-01-25 10:36 /usr/lib/libboost_thread.a
lrwxrwxrwx 1 root root 41 2009-11-04 10:10 /usr/lib/libboost_thread-gcc41-mt-1_34_1.so.1.34.1 -> libboost_thread-gcc42-mt-1_34_1.so.1.34.1
-rw-r--r-- 1 root root 49912 2008-11-01 02:55 /usr/lib/libboost_thread-gcc42-mt-1_34_1.so.1.34.1
lrwxrwxrwx 1 root root 17 2010-01-27 18:32 /usr/lib/libboost_thread-mt.a -> libboost_thread.a
lrwxrwxrwx 1 root root 25 2010-01-27 18:32 /usr/lib/libboost_thread-mt.so -> libboost_thread.so.1.40.0
lrwxrwxrwx 1 root root 25 2010-01-27 18:32 /usr/lib/libboost_thread.so -> libboost_thread.so.1.40.0
-rw-r--r-- 1 root root 89392 2010-01-25 10:36 /usr/lib/libboost_thread.so.1.40.0
|
2,751,820 | 2,751,962 | Download File from Web C++ (with winsock?) | I need to download files/read strings from a specified url in C++. I've done some research with this, cURL seems to be the most popular method. Also, I've used it before in PHP. The problem with cURL is that the lib is huge, and my file has to be small. I think you can do it with winsock, but I can't find any simple examples. If you have a simple winsock example, a light cURL/Something else, or anything that could get the job done. I would greatly appreciated. Also, I need this to work with native C++.
| I can repeat me answer Is it possible to handle proxies at socket level? (see also comments) about two important interfaces Windows Internet (WinINet) API and Windows HTTP Services (WinHTTP). An important restriction of WinINet is that WinINet should be not used in a service (only in GUI app.) because of possible dialogs.
|
2,751,874 | 2,751,914 | Make openGL lines connected | Right now I'v created a polygon, then I do the same thing but with line_loop to draw the outline. My issue right now is if I set the line thickness to high, the lines arn't connected. Their ends would need to be (linewidth) longer... is there a way to fix this?
Thanks
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
glOrtho (0, 600, 600, 0, 0, 1);
glMatrixMode (GL_MODELVIEW);
......
glLineWidth(5.0);
glTranslatef(250,250,0);
glRotated(x,0,0,50.0);
glBegin(GL_POLYGON); //Begin quadrilateral coordinates
//Trapezoid
glColor3f(255,0,0);
glVertex2f(0,0);
glVertex2f(100,0);
glVertex2f(100,100);
glVertex2f(50,50);
glVertex2f(0,100);
glEnd(); //End quadrilateral coordinates
glBegin(GL_LINE_LOOP); //Begin quadrilateral coordinates
//Trapezoid
glColor3f(0,255,0);
glVertex2f(0,0);
glVertex2f(100,0);
glVertex2f(100,100);
glVertex2f(50,50);
glVertex2f(0,100);
glEnd(); //End quadrilateral coordinates
| The article here shows how to achieve rounded line caps and antialised lines using a texture trick.
|
2,751,900 | 2,752,609 | Why timed lock doesn't throw a timeout exception in C++0x? | C++0x allows to lock on a mutex until a given time is reached, and return a boolean stating if the mutex has been locked or not.
template <class Clock, class Duration>
bool try_lock_until(const chrono::time_point<Clock,
Duration>& abs_time);
In some contexts, I consider an exceptional situation that the locking fails because of timeout. In this case an exception should be more appropriated.
To make the difference a function lock_until could be used to get a timeout exception when the time is reached before locking.
template <class Clock, class Duration>
void lock_until(const chrono::time_point<Clock,
Duration>& abs_time);
Do you think that lock_until should be more adequate in some contexts? if yes, on which ones? If no, why try_lock_until will always be a better choice?
| Can't you just check the return value and throw your own exception?
if ( ! my_lock.try_lock_until( my_start_time ) ) {
throw realtime_error( "Couldn't start in time!" );
}
Also, a quick look through the threading and exceptions libraries in the FCD doesn't show any time-related exception classes, so there's no type in std:: for lock_until to naturally throw.
|
2,752,006 | 2,752,080 | Generate texture from polygon (openGL) | I have a quad and I would like to use the gradient it produces as a texture for another polygon.
glPushMatrix();
glTranslatef(250,250,0);
glBegin(GL_POLYGON);
glColor3f(255,0,0);
glVertex2f(10,0);
glVertex2f(100,0);
glVertex2f(100,100);
glVertex2f(50,50);
glVertex2f(0,100);
glEnd(); //End quadrilateral coordinates
glPopMatrix();
glBegin(GL_QUADS); //Begin quadrilateral coordinates
glVertex2f(0,0);
glColor3f(0,255,0);
glVertex2f(150,0);
glVertex2f(150,150);
glColor3f(255,0,0);
glVertex2f(0,150);
glEnd(); //End quadrilateral coordinates
My goal is to make the 5 vertex polygon have the gradient of the quad (maybe a texture is not the best bet)
Thanks
| Keep it simple!
It is very simple to create a gradient texture in code, e.g.:
// gradient white -> black
GLubyte gradient[2*3] = { 255,255,255, 0,0,0 };
// WARNING: check documentation, I am not quite sure about syntax and order:
glTexture1D( GL_TEXTURE_1D, 0,3, 2, 0, GL_RGB, GL_UNSIGNED_BYTE, gradient );
// setup texture parameters, draw your polygon etc.
The graphics hardware and/or the GL will create a sweet looking gradient from color one to color two for you (remember: that's one of the basic advantages of having hardware accelerated polygon drawing, you don't have to do interpolation work in software).
Your real problem is: which texture coordinates do you use on the 5 vertex polygon. But that was not your question... ;-)
|
2,752,144 | 2,752,179 | Why doesn't this for-loop execute? | I'm writing a program for an exercise that will read data from a file and format it to be readable. So far, I have a bit of code that will separate a header from the data that goes under it. Here it is:
int main() {
ifstream in("records.txt");
ofstream out("formatted_records.txt");
vector<string> temp;
vector<string> headers;
for (int i = 0; getline(in,temp[i]); ++i) {
static int k = -1;
if (str_isalpha(temp[i])) {
headers[++k] = temp[i];
temp.erase(temp.begin() + i);
}
else {
temp[i] += "," + headers[k];
}
}
}
(str_isalpha() is just a function that applies isalpha() to every character in a string.) Now, the for-loop in this program doesn't execute, and I can't figure out why. Does anybody know?
EDIT: As suggested, I changed it to
string line;
for (int i = 0; getline(in,line); ++i) {
temp.push_back(line);
Still skips the for-loop altogether.
| If the loop still doesn't run after ensuring that you're reading into a valid string reference, then you should check that the stream you're reading from is valid. The stream will be invalid if the file doesn't exist or if you lack permission to read it, for instance. When the stream isn't valid, getline won't read anything. Its return value is the same stream, and when converted to bool, it evaluates as false. Check the stream's status before proceeding.
ifstream in("records.txt");
if (!in.is_open()) {
std::cerr << "Uh-oh.\n";
return EXIT_FAILURE;
}
|
2,752,175 | 2,752,271 | Getting the vector points of a letter in a truetype font | Since True Type fonts are just vectors, I was wondering if there was a way to get the vectors (array of points) for a letter given that i'm using the WinAPI.
Thanks
| Use the GetGlyphOutline function with the GGO_NATIVE option.
http://msdn.microsoft.com/en-us/library/dd144891%28v=VS.85%29.aspx
Actually, True Type fonts are defined by Bezier curves, not vectors, so you get back a list of curves. Most graphics libraries have a way of drawing Bezier curves anyway so you can get by just knowing that a curve is defined by several control points.
The font will be pre-fitted to a grid (eg, hinting).
|
2,752,229 | 2,774,591 | F# performance in scientific computing | I am curious as to how F# performance compares to C++ performance? I asked a similar question with regards to Java, and the impression I got was that Java is not suitable for heavy numbercrunching.
I have read that F# is supposed to be more scalable and more performant, but how is this real-world performance compares to C++? specific questions about current implementation are:
How well does it do floating-point?
Does it allow vector instructions
how friendly is it towards optimizing
compilers?
How big a memory foot print does it have? Does it allow fine-grained control over memory locality?
does it have capacity for distributed
memory processors, for example Cray?
what features does it have that may be of interest to computational science where heavy number processing is involved?
Are there actual scientific computing
implementations that use it?
Thanks
|
F# does floating point computation as fast as the .NET CLR will allow it. Not much difference from C# or other .NET languages.
F# does not allow vector instructions by itself, but if your CLR has an API for these, F# should not have problems using it. See for instance Mono.
As far as I know, there is only one F# compiler for the moment, so maybe the question should be "how good is the F# compiler when it comes to optimisation?". The answer is in any case "potentially as good as the C# compiler, probably a little bit worse at the moment". Note that F# differs from e.g. C# in its support for inlining at compile time, which potentially allows for more efficient code which rely on generics.
Memory foot prints of F# programs are similar to that of other .NET languages. The amount of control you have over allocation and garbage collection is the same as in other .NET languages.
I don't know about the support for distributed memory.
F# has very nice primitives for dealing with flat data structures, e.g. arrays and lists. Look for instance at the content of the Array module: map, map2, mapi, iter, fold, zip... Arrays are popular in scientific computing, I guess due to their inherently good memory locality properties.
For scientific computation packages using F#, you may want to look at what Jon Harrop is doing.
|
2,752,295 | 2,752,304 | C++ LPTSTR to int (but memory overwrite problem using atoi) | I have the following code, m_edit is a MFC CEdit (I know I would never use MFC but project demanded it).
It's a simple loop, that gets the text from a text edit, converts it to integer after getting the first line, then stores it in m_y vector.
LPTSTR szTemp;
vector<int> m_y;
for(int i = 0; i < m_edit->GetLineCount(); i++){
szTemp = s_y.GetBuffer(0);
m_edit->GetLine(i, szTemp); // get line text store in szTemp
y = atoi(szTemp);
m_y.push_back(y);
szTemp = "";
y = 0;
}
IMPORTANT EXAMPLE: So let's say the CEdit has 6 numbers:
0
5
2
5
18
6
If you use Visual Studio's debugger you will notice an anomaly!!
Here's what it shows:
y = 0
y = 5
y = 2
y = 5
y = 18
y = 68
Do you see that? szTemp when inserted into atoi, it returns the number 6, but concatenates the 2nd digit of the last number!!! This is why I did szTemp = "";, but the problem persists. Also, let's say the last number was 17 (not 18), then this time debugger would say y = 67, so it is definitely this problem.
However, Visual Studio debugger, when you hover over szTemp during this iteration, it says '6' <--- not '68' inside szTemp. So somehow atoi is ruining it.
Am I suppose to concatenate a \0 into szTemp before putting it into atoi? How do I solve this easily?
| From the MFC CEdit::GetLine documentation:
Remarks:
The copied line does not contain a null-termination character.
So you need to pay attention to GetLine's return value to determine how many bytes were copied into the buffer and then add your own NUL-terminator.
Also, I would recommend that you pass in the buffer size to make sure you don't have a potential buffer overflow.
|
2,752,349 | 2,752,387 | Fast rectangle to rectangle intersection | What's a fast way to test if 2 rectangles are intersecting?
A search on the internet came up with this one-liner (WOOT!), but I don't understand how to write it in Javascript, it seems to be written in an ancient form of C++.
struct
{
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT;
bool IntersectRect(const RECT * r1, const RECT * r2)
{
return ! ( r2->left > r1->right
|| r2->right < r1->left
|| r2->top > r1->bottom
|| r2->bottom < r1->top
);
}
| This is how that code can be translated to JavaScript. Note that there is a typo in your code, and in that of the article, as the comments have suggested. Specifically r2->right left should be r2->right < r1->left and r2->bottom top should be r2->bottom < r1->top for the function to work.
function intersectRect(r1, r2) {
return !(r2.left > r1.right ||
r2.right < r1.left ||
r2.top > r1.bottom ||
r2.bottom < r1.top);
}
Test case:
var rectA = {
left: 10,
top: 10,
right: 30,
bottom: 30
};
var rectB = {
left: 20,
top: 20,
right: 50,
bottom: 50
};
var rectC = {
left: 70,
top: 70,
right: 90,
bottom: 90
};
intersectRect(rectA, rectB); // returns true
intersectRect(rectA, rectC); // returns false
|
2,752,469 | 2,752,476 | Help with these warnings. [inheritance] | I have a set of code, which mimics a basic library cataloging system. There is a base class named items, in which the the general id,title and year variables are defined and 3 other derived classes (DVD,Book and CD).
Base [Items]
Derived [DVD,Book,CD].
The programs runs, however I get the following warnings, I'm not sure how to fix these.
>"C:\Program Files\gcc\bin/g++" -Os -mconsole -g -Wall -Wshadow -fno-common mainA4.cpp -o mainA4.exe
In file included from mainA4.cpp:5:
a4.h: In constructor `DVD::DVD(int, std::string, int, std::string)':
a4.h:28: warning: `DVD::director' will be initialized after
a4.h:32: warning: base `Items'
a4.h:32: warning: when initialized here
a4.h: In constructor `Book::Book(int, std::string, int, std::string, int)':
a4.h:48: warning: `Book::numPages' will be initialized after
a4.h:52: warning: base `Items'
a4.h:52: warning: when initialized here
a4.h: In constructor `CD::CD(int, std::string, int, std::string, int)':
a4.h:66: warning: `CD::numSongs' will be initialized after
a4.h:70: warning: base `Items'
a4.h:70: warning: when initialized here
>Exit code: 0
| When you declare member variables in a class, they're initialized in the order you declare them. But you may write them in any order in your constructor's initializer list. For example,
struct foo {
int a;
int b;
foo(): b(5), a(3) {}
};
will construct a and then b, even though it appears that you're initializing them in the other order.
The compiler issues a warning because you can trick yourself into writing incorrect code. For example,
struct foo {
int a;
int b;
foo(): b(5), a(b) {}
};
the value of a will be undefined.
|
2,752,499 | 2,752,512 | floating exception using icc compiler | I'm compiling my code via the following command:
icc -ltbb test.cxx -o test
Then when I run the program:
time ./mp6 100 > output.modified
Floating exception
4.871u 0.405s 0:05.28 99.8% 0+0k 0+0io 0pf+0w
I get a "Floating exception". This following is code in C++ that I had before the exception and after:
// before
if (j < E[i]) {
temp += foo(0, trr[i], ex[i+j*N]);
}
// after
temp += (j < E[i])*foo(0, trr[i], ex[i+j*N]);
This is boolean algebra... so (j < E[i]) is either going to be a 0 or a 1 so the multiplication would result either in 0 or the foo() result. I don't see why this would cause a floating exception.
This is what foo() does:
int foo(int s, int t, int e) {
switch(s % 4) {
case 0:
return abs(t - e)/e;
case 1:
return (t == e) ? 0 : 1;
case 2:
return (t < e) ? 5 : (t - e)/t;
case 3:
return abs(t - e)/t;
}
return 0;
}
foo() isn't a function I wrote so I'm not too sure as to what it does... but I don't think the problem is with the function foo(). Is there something about boolean algebra that I don't understand or something that works differently in C++ than I know of? Any ideas why this causes an exception?
Thanks,
Hristo
| You are almost certainly dividing by zero in foo.
A simple program of
int main()
{
int bad = 0;
return 25/bad;
}
also prints
Floating point exception
on my system.
So, you should check whether e is 0 when s % 4 is zero, or whether t is 0 when s % 4 is 2 or 3. Then return whatever value makes sense for your situation instead of trying to divide by zero.
@hristo: C++ will still evaluate the right-hand-side of a multiplication even if the left-hand-side is zero. It doesn't matter that the result should be zero; it matters that foo was called and evaluated and caused an error.
Sample source:
#include <iostream>
int maybe_cause_exception(bool cause_it)
{
int divisor = cause_it ? 0 : 10;
return 10 / divisor;
}
int main()
{
std::cout << "Do not raise exception: " << maybe_cause_exception(false) << std::endl;
int x = 0;
std::cout << "Before 'if' statement..." << std::endl;
if(x)
{
std::cout << "Inside if: " << maybe_cause_exception(true) << std::endl;
}
std::cout << "Past 'if' statement." << std::endl;
std::cout << "Cause exception: " << x * maybe_cause_exception(true) << std::endl;
return 0;
}
Output:
Do not raise exception: 1
Before 'if' statement...
Past 'if' statement.
Floating point exception
|
2,752,549 | 2,752,558 | Why can't I pass const map structure to a function in c++? | I tried to pass const with vector it works:
Ex:
void damn(const vector <bool> &bb)
{
for (int i=0; i<bb.size(); i++)
cout<<bb[i]<<endl;
}
But when trying with map, it does not:
void pas(const map <string, float> &mm)
{
cout<<mm["a"];
cout<<mm["b"];
}
I wonder why it doesn't.
| I believe that it is because [] in map isn't const, as it creates new pair with default value, if you address to nonexisting one. Try
void pas(const map <string, float> &mm)
{
cout<<mm.find("a")->second;
cout<<mm.find("b")->second;
}
|
2,752,869 | 2,752,883 | How to remove an item from a structure array in C++? | I have the following array structure (linked list):
struct str_pair
{
char ip [50] ;
char uri [50] ;
str_pair *next ;
} ;
str_pair *item;
I know to create a new item, I need to use
item = new str_pair;
However, I need to be able to loop through the array and delete a particular item. I have the looping part sorted. But how do I delete an item from an array of structures?
| What you've shown is not an array of struct, but a linked list of struct containing arrays (of type char).
An array of struct would look like this:
str_pair array_of_structs[10];
// or:
str_pair* dynamically_allocated_array_of_structs = new str_pair[10];
If you actually have something like this, you don't need to delete single items from an array. Let's say you've initialized your array as follows:
str_pair* array_of_structs = new str_pair[10];
Then you delete the whole array (including all of its items) using:
delete[] array_of_structs;
Again, you can't delete single items in an array allocated with new[]; you perform a delete[] on the whole array.
If, on the other hand, you intended to say "linked list of struct", then you'd generally delete an item similarly to the following:
str_pair* previous_item = ...;
str_pair* item_to_delete = previous_item->next;
if (item_to_delete != 0)
{
previous_item->next = item_to_delete->next; // make the list "skip" one item
delete item_to_delete; // and delete the skipped item
}
Or, in English: Find the item (A) preceding the item which you want to delete (B), then adjust A's "next" pointer so that B will be skipped in the list, then delete B.
You need to be careful with special cases, i.e. when the item to be removed from the list is the first item or the last one. The above code is not sufficient when you want to delete the first item in the list, because there will be no previous_item. In this case, you'd need to change the pointer to the list's first element to the second element.
Your code:
void deleteitem(char *uri)
{
str_pair *itemtodelete;
curr = head;
while (curr->next != NULL) {
if ((strcmp(curr->uri, uri)) == 0) {
itemtodelete = curr;
curr = itemtodelete->next;
delete itemtodelete;
curr = head;
return;
}
curr = curr->next;
}
}
Some things are wrong here:
If head is null, the test curr->next != NULL will cause a segfault. (You must never dereference a null pointer!)
Your code for removing an item from the list is completely incorrect. Worst of all, you delete a node without changing the previous item's next pointer. The previous item will thus reference an item that's no longer there.
A detail: curr = head; before the return statement doesn't do anything useful at all.
Suggested code:
Do it in two steps: One function to find the node to be deleted via its attached uri, and one function to remove the node. You could separate it even better than the code below does, but it should be a starting point:
str_pair* finditemwithuri(char* uri)
{
str_pair* current = head;
while (current)
{
if (strcmp(current->uri, uri) == 0) return current;
current = current->next;
}
return 0;
}
void deleteitem(char* uri)
{
// find linked list node with that uri; abort if uri not in list
str_pair* itemtodelete = finditemwithuri(uri);
if (!itemtodelete) return;
// special case: node to be deleted is the list's head
if (itemtodelete == head)
{
head = itemtodelete->next;
delete itemtodelete;
return;
}
// else, iterate over list nodes
// up to the one preceding the node to be deleted
str_pair* current = head;
while (current)
{
if (itemtodelete == current->next)
{
current->next = itemtodelete->next;
delete itemtodelete;
return;
}
current = current->next;
}
}
|
2,752,893 | 2,753,091 | Is there a way to implement OnReady() callback in Qt4? | I want to do something which will access network when a QMainWindow is ready.
I suppose I should not do it in the constructor, so I try to find a signal the widget will get and try to implement something like a OnReady() call back in other UI library. But I still can not find a way to do this.
Thanks a lot in advance.
| If I understand correctly, you need to do something as soon as the application's event loop is ready to process events.
The reason you can't do it in the constructor because the application's event loop isn't ready until some time after the constructor has finished running.
What you can do is create a slot in your MainWindow class containing the code you want to run, set up a single-shot timer in the constructor, and have that timer call your slot. For example:
mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void doStuff(); // This slot will contain your code
// ...
// ...
// ...
}
mainwindow.cpp:
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
QTimer::singleShot(0, this, SLOT(doStuff())); // This will call your slot when the event loop is ready
// ...
// ...
// ...
}
void MainWindow::doStuff()
{
// This code will run as soon as the event loop is ready
}
|
2,752,925 | 2,752,954 | how to write any custom data type to file using ifstream? | as question says, i want to write custom data type data of a class maybe to a file using ifstream in c++. Need help.
| For an arbitrary class, say, Point, here's a fairly clean way to write it out to an ostream.
#include <iostream>
class Point
{
public:
Point(int x, int y) : x_(x), y_(y) { }
std::ostream& write(std::ostream& os) const
{
return os << "[" << x_ << ", " << y << "]";
}
private:
int x_, y_;
};
std::ostream& operator<<(std::ostream& os, const Point& point)
{
return point.write(os);
}
int main() {
Point point(20, 30);
std::cout << "point = " << point << "\n";
}
|
2,752,974 | 2,752,994 | Invoking MSYS bash from Windows cmd | I'm using GCC on Windows 7 (using the TDM's build). I installed MSYS to be able to execute Make and compile using makefiles. However, it is tedious to every time start up the MSYS Bash shell, navigate to the directory of the project and run make.
What I want is to automate this process. I prefer to have a batch file in Windows, or something similar, from which I then invoke the MSYS Bash shell. It should navigate to the directory the batch file resides in and call make.
Is this possible? Can I send commands to MSYS Bash from cmd (like navigation/invoking make)? Or can I let the MSYS Bash run a "Bash script", which sets the commands to be executed much like batch scripts?
PS: This is something similar to Stack Overflow question Executing MSYS from cmd.exe with arguments.
| Not an MSYS expert, but does something like this work for you:
rem Call this something like compile-project.bat
c:
cd \src\project
bash -c "make"
|
2,752,987 | 2,752,996 | C++ macros explanation | Can somebody explain the following code please?
#if 1
// loop type
#define FOR_IS_FASTER 1
#define WHILE_IS_FASTER 0
// indexing type
#define PREINCREMENT_IS_FASTER 1
#define POSTINCREMENT_IS_FASTER 0
#else
// loop type
#define FOR_IS_FASTER 1
#define WHILE_IS_FASTER 0
// indexing type
#define PREINCREMENT_IS_FASTER 0
#define POSTINCREMENT_IS_FASTER 1
#endif
#if PREINCREMENT_IS_FASTER
#define ZXP(z) (*++(z))
#define ZX(z) (*(z))
#define PZ(z) (++(z))
#define ZP(z) (z)
#define ZOFF (1)
#elif POSTINCREMENT_IS_FASTER
#define ZXP(z) (*(z)++)
#define ZX(z) (*(z))
#define PZ(z) (z)
#define ZP(z) ((z)++)
#define ZOFF (0)
#endif
I can understand what the functions are doing but for example
how does the pre-processor choose which ZXP will be execute if we call it later?
What do the 1 and 0 stand for?
| The #if 1 triggers the first group of #defines, which set PREINCREMENT_IS_FASTER to 1. Because of this, #if PREINCREMENT_IS_FASTER triggers the first #define ZXP....
There is nothing exceptional about 1 and 0 in this context. The #if preprocessor directive succeeds if its argument is non-zero.
You can switch to the alternate form by changing the #if 1 at the top of the file with #if 0. (Thank you @rabidmachine for the tip.)
|
2,752,999 | 2,753,020 | How do I define an implicit typecast from my class to a scalar? | I have the following code, which uses a Unicode string class from a library that I'm writing:
#include <cstdio>
#include "ucpp"
main() {
ustring a = "test";
ustring b = "ing";
ustring c = "- -";
ustring d;
d = "cafe\xcc\x81";
printf("%s\n", (a + b + c[1] + d).encode());
}
The encode method of the ustring class instances converts the internal Unicode into a UTF-8 char *. However, because I don't have access to the char class definition, I am unsure on how I can define an implicit typecast (so that I don't have to manually call encode when using with printf, etc).
| First, I would recommend that you consider not providing an implicit conversion. You may find that the situations where unexpected conversions are not caught as errors outweighs the cost of calling encode when you want a char*.
If you do decide to provide an implicit conversion you declare it like this (inside your class definition.
operator char*();
You might be able to make the method const, in which case you can use:
operator char*() const;
Usually you would also want to return a pointer to a non-modifiable buffer:
operator const char*() const;
In the body of your function you should return an appropriate pointer. As an implicit conversion clients wouldn't expect to have to free the returned buffer so if you need to make a special buffer for your return value you will have to maintain a pointer to this buffer until a suitable point to free it. Typically such a suitable moment might be the next mutating operation on your class object.
Note that as printf takes any number and type of optional arguments you would still need to cast your class object in any case.
printf("%s\n", static_cast<const char*>(a + b + c[1] + d));
or
printf("%s\n", (const char*)(a + b + c[1] + d));
Both of these are more verbose than an explicit call to encode.
|
2,753,060 | 2,753,099 | Who architected / designed C++'s IOStreams, and would it still be considered well-designed by today's standards? | First off, it may seem that I'm asking for subjective opinions, but that's not what I'm after. I'd love to hear some well-grounded arguments on this topic.
In the hope of getting some insight into how a modern streams / serialization framework ought to be designed, I recently got myself a copy of the book Standard C++ IOStreams and Locales by Angelika Langer and Klaus Kreft. I figured that if IOStreams wasn't well-designed, it wouldn't have made it into the C++ standard library in the first place.
After having read various parts of this book, I am starting to have doubts if IOStreams can compare to e.g. the STL from an overall architectural point-of-view. Read e.g. this interview with Alexander Stepanov (the STL's "inventor") to learn about some design decisions that went into the STL.
What surprises me in particular:
It seems to be unknown who was responsible for IOStreams' overall design (I'd love to read some background information about this — does anyone know good resources?);
Once you delve beneath the immediate surface of IOStreams, e.g. if you want to extend IOStreams with your own classes, you get to an interface with fairly cryptic and confusing member function names, e.g. getloc/imbue, uflow/underflow, snextc/sbumpc/sgetc/sgetn, pbase/pptr/epptr (and there's probably even worse examples). This makes it so much harder to understand the overall design and how the single parts co-operate. Even the book I mentioned above doesn't help that much (IMHO).
Thus my question:
If you had to judge by today's software engineering standards (if there actually is any general agreement on these), would C++'s IOStreams still be considered well-designed? (I wouldn't want to improve my software design skills from something that's generally considered outdated.)
| Several ill-conceived ideas found their way into the standard: auto_ptr, vector<bool>, valarray and export, just to name a few. So I wouldn't take the presence of IOStreams necessarily as a sign of quality design.
IOStreams have a checkered history. They are actually a reworking of an earlier streams library, but were authored at a time when many of today's C++ idioms didn't exist, so the designers didn't have the benefit of hindsight. One issue that only became apparent over time was that it is almost impossible to implement IOStreams as efficiently as C's stdio, due to the copious use of virtual functions and forwarding to internal buffer objects at even the finest granularity, and also thanks to some inscrutable strangeness in the way locales are defined and implemented. My memory of this is quite fuzzy, I'll admit; I remember it being the subject of intense debate some years ago, on comp.lang.c++.moderated.
|
2,753,197 | 2,755,211 | Any free memory leak detector for Qt? | I'm looking for free memory leak detector for Qt. I use Qt Creator 1.3 with Qt version 4.6 (32 bit). The platform is Windows 7 Ultimate.
Thanks.
| Although this question is not Qt-specific, the answers do refer to various general-purpose memory leak detection tools which are available on Windows. The two which are mentioned in the accepted answer are commercial tools, but there are some free alternatives referred to in other answers.
|
2,753,349 | 2,753,357 | C++ Class Static variable problem - C programmer new to C++ | I am a C programmer, but had learnt C++ @school longtime back. Now I am trying to write code in C++ but getting compiler error. Please check and tell me whats wrong with my code.
typedef class _filter_session
{
private:
static int session_count; /* Number of sessions count -- Static */
public:
_filter_session(); /* Constructor */
~_filter_session(); /* Destructor */
}FILTER_SESSION;
_filter_session::_filter_session(void)
{
(this->session_count)++;
return;
}
_filter_session::~_filter_session(void)
{
(this->session_count)--;
return;
}
The error that I am getting is
"error LNK2001: unresolved external symbol "private: static int _filter_session::session_count" (?session_count@_filter_session@@0HA)"
I am using Visual Studio 2005 by the way.
Plz plz help me.
Regards,
Microkernel
| static variables need to be defined outside of the class body somewhere. The declaration inside the class body is just a declaration.
E.g. at global scope:
int _filter_session::session_count;
You need to ensure that this definition occurs only once in the program so usually you would place it in a source file (.cc or .cpp) and not a header file which is included in more than once translation unit.
For portability you should avoid class names that start with an _. There is also little need to typedef your class name. class Name { //... introduces a type name in C++, you wouldn't have to use class Name to refer to the type.
|
2,753,381 | 2,753,637 | Performance of vector::size() : is it as fast as reading a variable? | I have do an extensive calculation on a big vector of integers. The vector size is not changed during the calculation. The size of the vector is frequently accessed by the code. What is faster in general: using the vector::size() function or using helper constant vectorSize storing the size of the vector?
I know that compilers usually able to inline the size() function when setting the proper compiler flags, however, making a function inline is something that a compiler may do but can not be forced.
| Interesting question.
So, what's going to happened ? Well if you debug with gdb you'll see something like 3 member variables (names are not accurate):
_M_begin: pointer to the first element of the dynamic array
_M_end: pointer one past the last element of the dynamic array
_M_capacity: pointer one past the last element that could be stored in the dynamic array
The implementation of vector<T,Alloc>::size() is thus usually reduced to:
return _M_end - _M_begin; // Note: _Mylast - _Myfirst in VC 2008
Now, there are 2 things to consider when regarding the actual optimizations possible:
will this function be inlined ? Probably: I am no compiler writer, but it's a good bet since the overhead of a function call would dwarf the actual time here and since it's templated we have all the code available in the translation unit
will the result be cached (ie sort of having an unnamed local variable): it could well be, but you won't know unless you disassemble the generated code
In other words:
If you store the size yourself, there is a good chance it will be as fast as the compiler could get it.
If you do not, it will depend on whether the compiler can establish that nothing else is modifying the vector; if not, it cannot cache the variable, and will need to perform memory reads (L1) every time.
It's a micro-optimization. In general, it will be unnoticeable, either because the performance does not matter or because the compiler will perform it regardless. In a critical loop where the compiler does not apply the optimization, it can be a significant improvement.
|
2,753,590 | 2,753,657 | signature output operator overload | do you know, how to write signature of a function or method for operator<< for template class in C++? I want something like:
template <class A> class MyClass{
public:
friend ostream & operator<<(ostream & os, MyClass<A> mc);
}
ostream & operator<<(ostream & os, MyClass<A> mc){
// some code
return os;
}
But this just won't compile. Do anyone know, how to write it correctly?
| All the below said, if you don't need an operator to be a friend, then don't make it a friend. For output operators in particular, in my opinion you should not make them friends. That is because if your class can be output to a stream, it should have equivalent get functions that provide the same data programmatically. And in that event, you can write a operator<< as a non-friend in terms of those get functions.
In case you have some good reason for making them friends, you can do a friend definition
template <class A> class MyClass {
public:
friend ostream & operator<<(ostream & os, MyClass<A> const& mc) {
// ...
}
};
That way you don't need the template<...> clause that gets you the type A. It's alreay known if you define the operator inside the template. Note that even though you defined it inside the template, it's not a member function. It's still a non-member, but has access to the names declared in the class (like the template parameter). For each instance of MyClass you create, a different non-template operator function is created out of that friend function that prints things.
If you want to define the template outside, you have to predeclare it to be able to declare a given specialization of it as a friend.
// predeclare it so you can make it a friend.
template <class A> class MyClass;
template <class A> ostream &operator<<(ostream &os, MyClass<A> const&);
template <class A> class MyClass{
public:
/* the "<A>" is needed - it says that a given instantiation of
that template is a friend, and not a non-template function. */
friend ostream & operator<< <A>(ostream & os, MyClass<A> const& mc);
};
template <class A>
ostream & operator<<(ostream & os, MyClass<A> const& mc){
// some code
return os;
}
That makes operator<< <Foo> a friend of MyClass<Foo>. If you were to omit the <A> or an also possible empty <>, the compiler would understand that as saying you made a non-template operator having concrete instead of templated parameters as friend.
The more easy but less "correct" solution is to make MyClass <Foo> have as friend all the operator << instantiations. So theoretically operator << <Bar> could access private members of MyClass <Foo>. It's not what is wanted, but it works too, gaining more access than needed. It gets rid of the need for forward declaring:
template <class A> class MyClass{
public:
/* make all instantiations friends. */
template<typename T>
friend ostream & operator<<(ostream & os, MyClass<T> const& mc);
};
template <class T>
ostream & operator<<(ostream & os, MyClass<T> const& mc){
// some code
return os;
}
|
2,753,670 | 2,753,723 | What's the best way to resolve this scope problem? | I'm writing a program in python that uses genetic techniques to optimize expressions.
Constructing and evaluating the expression tree is the time consumer as it can happen
billions of times per run. So I thought I'd learn enough c++ to write it and then incorporate it
in python using cython or ctypes.
I've done some searching on stackoverflow and learned a lot.
This code compiles, but leaves the pointers dangling.
I tried this_node = new Node(... . It didn't seem to work. And I'm not at all sure how I'd
delete all the references as there would be hundreds.
I'd like to use variables that stay in scope, but maybe that's not the c++ way.
What is the c++ way?
class Node
{
public:
char *cargo;
int depth;
Node *left;
Node *right;
}
Node make_tree(int depth)
{
depth--;
if(depth <= 0)
{
Node tthis_node("value",depth,NULL,NULL);
return tthis_node;
}
else
{
Node this_node("operator" depth, &make_tree(depth), &make_tree(depth));
return this_node;
}
};
| The Node object returned by make_tree() is just a temporary object, it will automatically be destroyed again at the end of the expression in which the function is called. When you create a pointer to such a temporary object, like in &make_tree(depth), this pointer will not point to anything useful anymore once the temporary object got destroyed.
You should use real dynamic memory allocation with new and delete to build the tree, so that you don't end up with pointers to not longer existing objects. Probably this construction of the tree should be done in a constructor of the Node class, the destructor should then take care of the deletes needed to release the used memory. For example:
class Node {
public:
const char *cargo;
int depth;
Node *left;
Node *right;
Node(int a_depth);
~Node();
};
// constructor
Node::Node(int a_depth) {
depth = a_depth;
a_depth--;
if(a_depth <= 0)
{
cargo = "value";
left = NULL;
right = NULL;
}
else
{
cargo = "operator";
left = new Node(a_depth);
right = new Node(a_depth);
}
}
// destructor
Node::~Node() {
delete left;
delete right;
}
|
2,753,774 | 2,753,823 | C++: Help with cin difference between Linux and Windows | I have a Win32 console program that I wrote and it works fine. The program takes input from the user and performs some calculations and displays the output - standard stuff. For fun, I am trying to get the program to work on my Fedora box but I am running into an issue with clearing cin when the user inputs something that does not match my variable type. Here is the code in question:
void CParameter::setPrincipal() {
double principal = 0.0;
cout << endl << "Please enter the loan principal: ";
cin >> principal;
while(principal <= 0)
{
if (cin.fail())
{
cin.clear();
cin.ignore(INT_MAX, '\n');
}
else
{
cout << endl << "Plese enter a number greater than zero. Please try again." << endl;
cin >> principal;
}
}
m_Parameter = principal;
}
This code works in Windows. For example, if the user tries to enter a char data type (versus double) then the program informs the user of the error, resets cin, and allows the user another opportunity to enter a valid value.
When I move this code to Fedora, it compiles fine. When I run the program and enter an invalid data type, the while loop never breaks to allow the user to change the input.
My questions are; how do I clear cin when invalid data is inputted in the Fedora environment? Also, how should I write this code so it will work in both environments (Windows & Linux)?
Thanks in advance for your help!
| I think it's a bad idea to use formatted input to read user responses. I'd use getline - something like this:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
template <typename T>
bool Read( T & t, istream & is ) {
string s;
if ( ! getline( is, s ) ) {
return false;
}
else {
istringstream ss( s );
return ss >> t;
}
}
int main() {
while(1) {
double d;
if ( ! Read( d, cin ) ) {
cout << "invalid\n";
}
else {
cout << "You entered " << d << "\n";
}
}
}
which works on Windows - I don't have my Linux box switched on at the moment.
|
2,753,857 | 2,753,933 | is there a simple timed lock algorithm avoiding deadlock on multiple mutexes? | C++0x thread library or Boost.thread define a non-member variadic template function that locks all mutex at once that helps to avoid deadlock.
template <class L1, class L2, class... L3>
void lock(L1&, L2&, L3&...);
The same can be applied to a non-member variadic template function try_lock_until, which locks all the mutex until a given time is reached that helps to avoid deadlock like lock(...).
template <class Clock, class Duration,
class L1, class L2, class... L3>
void try_lock_until(
const chrono::time_point<Clock,Duration>& abs_time,
L1&, L2&, L3&...);
I have an implementation that follows the same design as the Boost function boost::lock(...). But this is quite complex.
As I can be missing something evident I wanted to know if:
is there a simple timed lock algorithm avoiding deadlock on multiple mutexes?
If no simple implementation exists, can this justify a proposal to Boost?
P.S. Please avoid posting complex solutions.
Notes:
I don't want to add more constraints than the ones std::lock(...) imposes.
std::lock(...) doesn't avoid deadlock completely. It just avoid to have dead lock if two threads do std::lock(l1,l2) and the other std::lock(l2,l1). This is enough to avoid a lot of deadlock cases.
| The classic (and best) approach is to define an order in which mutexes are to be locked, and make sure that any code that holds more than one locked mutex at a time always locks its mutexes in that order. Is that approach insufficient here?
|
2,753,996 | 2,761,450 | Is there a way to access the locale used by gettext under windows? | I have a program where i18n is handled by gettext. The program works fine, however for some reason I need to know the name of the locale used by gettext at runtime (something like 'fr_FR') under win32.
I looked into gettext sources, and there is a quite frightening function that computes it on all platforms (gl_locale_name, in a C file called "localename.h/c"). However, this file does not seem to be installed alongside gettext or libintl, so I can't seem to call the function. Is there another function provided by gettext to get this value ? Or in another package (boost, glib, anything ?)
(On a related note, there is a thing called std::locale in the C++ standard library, and according to the doc calling std::locale("") should create a locale with the settings of the system, unless I am mistaken ... but then the name is 'C' under windows. Is it a viable way of getting the locale name ? What I am doing wrong ?)
| Turns out the "gl_locale_name" function was not part of gettext directly, but rather part of gnulib - http://www.gnu.org/software/gnulib. I just discovered the package today.
So getting the infamous localename.h header in my project was a matter of
gnulib-tool --import localename
Then the gl_locale_name function works just fine when cross-compiling.
Thanks to everyone for the answers !
|
2,754,073 | 2,757,463 | Writing a program which uses voice recogniton... where should I start? | I'm a design student currently dabbling with Arduino code (based on c/c++) and flash AS3. What I want to do is to be able to write a program with a voice control input.
So, program prompts user to spell a word. The user spells out the word. The program recognizes if this is right, adds one to a score if it's correct, and corrects the user if it's wrong. So I'm seeing a big list of words, each with an audio file of the word being read out, with the voice recognition part checking to see if the reply matches the input.
Ideally i'd like to be able to interface this with an Arduino microcontroller so that a physical output with a motor could be achieved in reaction also.
Thing is i'm not sure if I can make this program in flash, in Processing (associated with arduino) or if I need another C program-making-program. I guess I need to download a good voice recognizing program, but how can I interface this with anything else? Also, I'm on a mac. (not sure if this makes a difference)
I apologize for my cluelessness, any hints would be great!
-Susan
| What you need is most likely not a speech recognition program. You are looking for a speech recognition library. You're probably not that familiar with programming yet, so the term may be unfamiliar. Basically, a library is an intermediate step between source code and a whole program.
In your case, you are really asking for a library that (1) does vocie recognition and (2) works with Adobe Flash. Unfortunately, I can't find one of them with Google. Furthermore, I've found people who've tried, and their experiments (while short of what you need) are described by others as impressive. That suggests the technology isn't there yet.
It is probably easier to move the voice recognition to the Arduino. "Voice recognition Arduino" provides a lot of good hits in Google.
|
2,754,150 | 2,754,156 | += Overloading in C++ problem | I am trying to overload the += operator for my rational number class, but I don't believe that it's working because I always end up with the same result:
RationalNumber RationalNumber::operator+=(const RationalNumber &rhs){
int den = denominator * rhs.denominator;
int a = numerator * rhs.denominator;
int b = rhs.numerator * denominator;
int num = a+b;
RationalNumber ratNum(num, den);
return ratNum;
}
Inside main
//create two rational numbers
RationalNumber a(1, 3);
a.print();
RationalNumber b(6, 7);
b.print();
//test += operator
a+=(b);
a.print();
After calling a+=(b), a is still 1/3, it should be 25/21. Any ideas what I am doing wrong?
| operator+= is supposed to modify the object itself and return a reference. You are instead creating a new object and returning that. Something like this might work (untested code):
RationalNumber &RationalNumber::operator+=(const RationalNumber &rhs){
int den = denominator * rhs.denominator;
int a = numerator * rhs.denominator;
int b = rhs.numerator * denominator;
int num = a+b;
numerator = num;
denominator = den;
return *this;
}
Likewise operator+ should return a new object and can almost always be implemented in terms of operator+=:
RationalNumber RationalNumber::operator+(const RationalNumber &rhs){
RationalNumber tmp(*this);
tmp += rhs;
return tmp;
}
Finally, (now i'm getting off topic) it is usually considered best practice to use free functions instead of members where you can for things like binary operators.
|
2,754,152 | 2,754,253 | Question about Virtual Inheritance hierarchy | I encounter this problem when tackling with virtual inheritance. I remember that in a non-virtual inheritance hierarchy, object of sub-class hold an object of its direct super-class. What about virtual inheritance? In this situation, does object of sub-class hold an object of its super-class directly or just hold a pointer pointing to an object of its super-class?
By the way, why the output of the following code is:
sizeof(A): 8
sizeof(B): 20
sizeof(C): 20
sizeof(D): 36
Code:
#include <iostream>
using namespace std;
class A{
char k[ 3 ];
public:
virtual void a(){};
};
class B : public virtual A{
char j[ 3 ];
public:
virtual void b(){};
};
class C : public virtual A{
char i[ 3 ];
public:
virtual void c(){};
};
class D : public B, public C{
char h[ 3 ];
public:
virtual void d(){};
};
int main( int argc, char *argv[] ){
cout << "sizeof(A): " << sizeof( A ) << endl;
cout << "sizeof(B): " << sizeof( B ) << endl;
cout << "sizeof(C): " << sizeof( C ) << endl;
cout << "sizeof(D): " << sizeof( D ) << endl;
return 0;
}
Thanks in advance.
Kind regards.
| The virtual base object is somewhere in the memory block that belongs to the object (the memory with size = sizeof(object)). Because several sub objects of different types can be combined in various ways but must share the same base object, a offset pointer is needed for each sub object to find out the virtual base object. Without virtual inheritance, the offset to find out the corresponding base object is fixed at compile time for each class type.
The sizeof values depend on your compiler and machine, but the following assumptions are very common:
assumption: pointer size is 4 bytes
assumption: class size is rounded up to multiple of 4 bytes
sizeof(A): 8 -> 1 pointer to vtable (virtual method)
+ 3 chars -> 4+3=7
-> round up to 8
sizeof(B): 20 -> 8 + 1 pointer to vtable (virtual method)
+ 1 offset pointer to virtual base
+ 3 chars -> 8 + 4 + 4 + 3 = 19
-> round up to 20
sizeof(C): 32 -> 20 + 1 pointer to vtable (virtual method)
+ 1 offset pointer to virtual base
+ 3 chars
-> 20 + 4 + 4 + 3 = 31 // this calculation refers to an older
-> round up to 32 // version of the question's example
// where C had B as base class
The calculations are guessed because the real calculation must exactly know how the compiler works.
Regards,
Oliver
More details why an extra offset pointer is needed:
Example:
class B : virtual public A {...};
class C : virtual public A {...};
class D1 : public B {...};
class D2 : public B, C {...};
possible memory layout for D1:
A
B
D1
possible memory layout for D2:
A
C
B
D2
in the second case sub object B needs another offset to find its base A
An object of type D2 consists of a memory block, where all the parent object parts are contained, i.e. the memory block for an object of type D2 has a section for the A member variables, the C member variables, the B member variables and the D2 member variables. The order of these sections is compiler dependent, but the example shows, that for multiple virtual inheritance a offset pointer is needed, that points within the object's total memory block to the virtual base object. This is needed because the methods of class B know only one this pointer to B and must somehow calculate where the A memory part is relative to the this pointer.
Calculation sizeof(D):
sizeof(D): 36 -> A:3 chars + A:vtable
+ B:3 chars + B:vtable + B:virtual base pointer
+ C:3 chars + C:vtable + C:virtual base pointer
+ D:3 chars + D:vtable
= 3 + 4
+ 3 + 4 + 4
+ 3 + 4 + 4
+ 3 + 4
= 36
The above calculation is probably wrong ;-) ...
I'm not sure whether the D part has its own vtable pointer or not (this is all highly compiler dependent).
I now think that it could be that the D part use the vtable pointer entry of its parent classes and that the 4 extra bytes are used for alignment each part (multiple of 8 bytes):
So this calculation is probably more correct:
sizeof(D): 36 -> A:3 chars + A:vtable + A:alignment
+ B:3 chars + B:vtable + B:virtual base pointer + B:alignment
+ C:3 chars + C:vtable + C:virtual base pointer + C:alignment
+ D:3 chars + D:alignment
= 3 + 4 + 1
+ 3 + 4 + 4 + 1
+ 3 + 4 + 4 + 1
+ 3 + 1
= 36
|
2,754,176 | 2,754,201 | Virtual class problem | What i think about virtual class is, if a derived class has a public base, let's say, class base, then a pointer to derived can be assigned to a variable of type pointer to base without use of any explicit type conversion. But what if, we are inside of base class then how can we call derived class's functions. I will give an example:
class Graph{
public:
Graph(string);
virtual bool addEdge(string,string);
}
class Direct:public Graph{
public:
Direct(string);
bool addEdge(string,string);
}
Direct::Direct(string filename):Graph(filename){};
When i call constructor of Direct class then it calls Graph. Now lets think Graph function calls addedge.
Graph(string str){
addedge(str,str);
}
When it calls addedge, even if the function is virtual, it calls Graph::edge. What i want is, to call Direct::addedge. How can it be done?
| It can't be done. Virtual functions cannot be called whithin constructors -- at least they cannot be called with virtual behavior. The problem is that the derived class constructor is responsible for setting up the vtbl to point to it's particular instance of the virtual functions. The base class' constructor is executed first, before the derived constructor, so a direct solution to this is not possible.
You can work around this using either some form of "init" function on your base class, or you can use a factory method.
|
2,754,235 | 2,847,296 | Lua + SWIG Monkey Patching | I have used SWIG to bind a set of classes to lua. I know C++ itself doesn't support monkey patching, and I'm not trying to modify my C++ objects, merely their lua representations. The problem comes if I want to start monkey patching the lua tables and objects exported by SWIG, so that I can modify the API presented on the lua side.
e.g. the following lua code:
game.GetEnemies1 = game.GetEnemies2
does not work as expected. The behaviour after that line is still consistent with the original GetEnemies1 not GetEnemies2.
how do I combat this problem?
| I've successfully monkeypatched lua userdata by adding and replacing existing methods. It involved modifying their metatables.
Here's a sample of what I had to do in order to add a couple methods to an existing userdata object.
As you can see, instead of modifying the object iself, I had to modify its metatable.
This solution will only work if your userdata objects are set up so their metatables "point to themselves": mt.__index = mt.
Regards!
|
2,754,342 | 2,754,468 | printing double in binary | In 'Thinking in C++' by Bruce Eckel, there is a program given to print a double value
in binary. (Chapter 3, page no. 189)
int main(int argc, char* argv[])
{
if(argc != 2)
{
cout << "Must provide a number" << endl;
exit(1);
}
double d = atof(argv[1]);
unsigned char* cp = reinterpret_cast<unsigned char*>(&d);
for(int i = sizeof(double); i > 0 ; i -= 2)
{
printBinary(cp[i-1]);
printBinary(cp[i]);
}
}
Here while printing cp[i] when i=8 (assuming double is of 8 bytes), wouldn't it be undefined behaviour?
I mean this code doesn't work as it doesn't print cp[0].
| A1: Yes, it would be undefined behaviour when it accesses cp[8].
A2: Yes, it also does not print cp[0].
As shown, it prints bytes 7, 8, 5, 6, 3, 4, 2, 1 of the valid values 0..7. So, if you have copied the code correctly from the book, there is a bug in the book's code. Check the errata page for the book, if there is one.
It is also odd that it unwinds the loop; a simpler formulation is:
for (int i = sizeof(double); i-- > 0; )
printBinary(cp[i]);
There is also, presumably, a good reason for printing the bytes in reverse order; it is not obvious what that would be.
|
2,754,386 | 2,754,409 | Using delete[] (Heap corruption) when implementing operator+= | I've been trying to figure this out for hours now, and I'm at my wit's end. I would surely appreciate it if someone could tell me when I'm doing wrong.
I have written a simple class to emulate basic functionality of strings. The class's members include a character pointer data (which points to a dynamically created char array) and an integer strSize (which holds the length of the string, sans terminator.)
Since I'm using new and delete, I've implemented the copy constructor and destructor. My problem occurs when I try to implement the operator+=. The LHS object builds the new string correctly - I can even print it using cout - but the problem comes when I try to deallocate the data pointer in the destructor: I get a "Heap Corruption Detected after normal block" at the memory address pointed to by the data array the destructor is trying to deallocate.
Here's my complete class and test program:
#include <iostream>
using namespace std;
// Class to emulate string
class Str {
public:
// Default constructor
Str(): data(0), strSize(0) { }
// Constructor from string literal
Str(const char* cp) {
data = new char[strlen(cp) + 1];
char *p = data;
const char* q = cp;
while (*q)
*p++ = *q++;
*p = '\0';
strSize = strlen(cp);
}
Str& operator+=(const Str& rhs) {
// create new dynamic memory to hold concatenated string
char* str = new char[strSize + rhs.strSize + 1];
char* p = str; // new data
char* i = data; // old data
const char* q = rhs.data; // data to append
// append old string to new string in new dynamic memory
while (*p++ = *i++) ;
p--;
while (*p++ = *q++) ;
*p = '\0';
// assign new values to data and strSize
delete[] data;
data = str;
strSize += rhs.strSize;
return *this;
}
// Copy constructor
Str(const Str& s)
{
data = new char[s.strSize + 1];
char *p = data;
char *q = s.data;
while (*q)
*p++ = *q++;
*p = '\0';
strSize = s.strSize;
}
// destructor
~Str() { delete[] data; }
const char& operator[](int i) const { return data[i]; }
int size() const { return strSize; }
private:
char *data;
int strSize;
};
ostream& operator<<(ostream& os, const Str& s)
{
for (int i = 0; i != s.size(); ++i)
os << s[i];
return os;
}
// Test constructor, copy constructor, and += operator
int main()
{
Str s = "hello"; // destructor for s works ok
Str x = s; // destructor for x works ok
s += "world!"; // destructor for s gives error
cout << s << endl;
cout << x << endl;
return 0;
}
EDIT: Accelerated C++ problem 12-1.
| Following chunk of code makes p pointed beside the array.
while (*p++ = *q++) ;
*p = '\0';
Better (and safe) solution you have used in copy constructor:
while (*q)
*p++ = *q++;
*p = '\0';
|
2,754,586 | 2,754,592 | Reading function pointer syntax | Everytime I look at a C function pointer, my eyes glaze over. I can't read them.
From here, here are 2 examples of function pointer TYPEDEFS:
typedef int (*AddFunc)(int,int);
typedef void (*FunctionFunc)();
Now I'm used to something like:
typedef vector<int> VectorOfInts ;
Which I read as
typedef vector<int> /* as */ VectorOfInts ;
But I can't read the above 2 typedefs. The bracketing and the asterisk placement, it's just not logical.
Why is the * beside the word AddFunc..?
| The actual type of the first one is
int (*)(int,int);
(that is, a pointer to a function that takes two parameters of type int and returns an int)
The * identifies it as a function pointer. AddFunc is the name of the typedef.
cdecl can help with identifying particularly complex type or variable declarations.
|
2,754,600 | 2,754,639 | Use C function in C++ program; "multiply-defined" error | I am trying to use this code for the Porter stemming algorithm in a C++ program I've already written. I followed the instructions near the end of the file for using the code as a separate module. I created a file, stem.c, that ends after the definition and has
extern int stem(char * p, int i, int j) ...
It worked fine in Xcode but it does not work for me on Unix with gcc 4.1.1--strange because usually I have no problem moving between the two. I get the error
ld: fatal: symbol `stem(char*, int, int)' is multiply-defined:
(file /var/tmp//ccrWWlnb.o type=FUNC; file /var/tmp//cc6rUXka.o type=FUNC);
ld: fatal: File processing errors. No output written to cluster
I've looked online and it seems like there are many things I could have wrong, but I'm not sure what combination of a header file, extern "C", etc. would work.
| That error means that the symbol (stem) is defined in more than one module.
You can declare the symbol in as many modules as you want. A declaration of a function looks like this:
int stem(char * p, int i, int j);
You don't need the "extern" keyword, although it doesn't hurt anything. For functions declarations, it's implied.
A definition of a function looks like this:
int stem(char * p, int i, int j)
{
/* body of your function */
}
The "multiply-defined" error indicates that you have two modules with a definition for the same function. That usually means that you have two files that define the function, or two files that #include a file that defines the function. Normally, you should not put function definitions in files that you #include. Put the definition in a .c, .cpp, or .cc file and just put a declaration in a .h file that you #include.
For example, you could create a stem.h file with this in it:
int stem(char * p, int i, int j);
Then, #include "stem.h".
|
2,754,650 | 2,754,656 | Getting value of std::list<>::iterator to pointer? | How can i loop thru a stl::List and store the value of one of the objects for use later in the function?
Particle *closestParticle;
for(list<Particle>::iterator p1 = mParticles.begin(); p1 != mParticles.end(); ++p1 )
{
// Extra stuff removed
closestParticle = p1; // fails to compile (edit from comments)
}
| Either
Particle *closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it)
{
// Extra stuff removed
closestParticle = &*it;
}
or
list<Particle>::iterator closestParticle;
for(list<Particle>::iterator it=mParticles.begin(); it!=mParticles.end(); ++it )
{
// Extra stuff removed
closestParticle = it;
}
or
inline list<Particle>::iterator findClosestParticle(list<Particle>& pl)
{
for(list<Particle>::iterator it=pl.begin(); it!=pl.end(); ++it )
{
// Extra stuff removed
return it;
}
return pl.end();
}
or
template< typename It >
inline It findClosestParticle(It begin, It end)
{
while(begin != end )
{
// Extra stuff removed
return begin;
++begin;
}
return end;
}
These are sorted in increasing personal preference. :)
|
2,754,673 | 2,754,732 | Drawing connected lines with OpenGL | I'm drawing convex polygons with OpenGL. I then do the same thing but use GL_LINE_LOOP.
The problem I have is the lines are not always connected. How could I ensure that the lines are always connected?
In the photo below, Iv highlighted in green, the corners that are connected and in red, those that are not. I would like for them to be all like the green ones.
http://img249.imageshack.us/i/notconnected.png/
Thanks
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
x ++;
glLineWidth(50.0);
glPushMatrix();
glTranslatef(250,250,0);
glBegin(GL_POLYGON); //Begin quadrilateral coordinates
//Trapezoid
glColor3f(255,0,0);
glVertex2f(-10,0);
glVertex2f(50,0);
glColor3f(255,100,0);
glVertex2f(100,50);
glVertex2f(mouse.x - 250,mouse.y - 250);
glVertex2f(-30,50);
glEnd(); //End quadrilateral coordinates
glBegin(GL_LINE_LOOP); //Begin quadrilateral coordinates
//Trapezoid
glColor3f(0,0,255);
glVertex2f(-10,0);
glVertex2f(50,0);
glVertex2f(100,50);
glVertex2f(mouse.x - 250,mouse.y - 250);
glVertex2f(-30,50);
glEnd(); //End quadrilateral coordinates
glPopMatrix();
glBegin(GL_QUADS); //Begin quadrilateral coordinates
glVertex2f(0,0);
glColor3f(0,255,0);
glVertex2f(150,0);
glVertex2f(150,150);
glColor3f(255,0,0);
glVertex2f(0,150);
glEnd(); //End quadrilateral coordinates
| What you're looking for is called endpoint capping / mitering. OpenGL doesn't support this natively, see 14.100
Using wide lines (line width 50) amplifies the problem. You might want to try using OpenGL tesselation. This example might seem a bit much, but I think there is some valuable interfacing between Java2D shapes and OpenGL tesselation that might fix your problem at the cost of some rewriting / rethinking.
|
2,754,707 | 2,754,974 | Moving from Windows to Ubuntu | I used to program in Windows with Microsoft Visual C++ and I need to make some of my portable programs (written in portable C++) to be cross-platform, or at least I can release a working version of my program for both Linux and Windows.
I am total newcomer in Linux application development (and rarely use the OS itself).
So, today, I installed Ubuntu 10.04 LTS (through Wubi) and equipped Code::Blocks with the g++ compiler as my main weapon. Then I compiled my very first Hello World linux program, and I confused about the output program.
I can run my program through the "Build and Run" menu option in Code::Blocks, but when I tried to launch the compiled application externally through a File Browser (in /media/MyNTFSPartition/MyProject/bin/Release; yes, I saved it in my NTFS partition), the program didn't show up.
Why? I ran out of idea.
I need to change my Windows and Microsoft Visual Studio mindset to Linux and Code::Blocks mindset.
So I came up with these questions:
How can I execute my compiled linux programs externally (outside IDE)?
In Windows, I simply run the generated executable (.exe) file
How can I distribute my linux application?
In Windows, I simply distribute the executable files with the corresponding DLL files (if any)
What is the equivalent of LIBs (static library) and DLLs (dynamic library) in linux and how to use them?
In Windows/Visual Studio, I simply add the required libraries to the Additional Dependencies in the Project Settings, and my program will automatically link with the required static library(-ies)/DLLs.
Is it possible to use the "binary form" of a C++ library (if provided) so that I wouldn't need to recompile the entire library source code?
In Windows, yes. Sometimes precompiled *.lib files are provided.
If I want to create a wxWidgets application in Linux, which package should I pick for Ubuntu? wxGTK or wxX11? Can I run wxGTK program under X11?
In Windows, I use wxMSW, Of course.
If question no. 4 is answered possible, are precompiled wxX11/wxGTK library exists out there? Haven't tried deep google search.
In Windows, there is a project called "wxPack" (http://wxpack.sourceforge.net/) that saves a lot of my time.
Sorry for asking many questions, but I am really confused on these linux development fundamentals.
Any kind of help would be appreciated =)
Thanks.
|
How can I execute my compiled linux
programs externally (outside IDE)? In
Windows, I simply run the generated
executable (.exe) file
On Linux you do the same. The only difference is that on Linux the current directory is by default not in PATH, so typically you do:
./myapp
If you add current dir to the path
PATH=".:$PATH"
then windows-like way
myapp
will do, but this is not recommended due to security risks, at least in shared environments (you don't want to run /tmp/ls left by somebody).
How can I distribute my linux application?
In Windows, I simply distribute the executable files with the corresponding DLL files (if any)
If you are serious about distributing, you should probably learn about .deb (Ubuntu, Debian) and .rpm (RedHat, CentOS, SUSE). Those are "packages" which make it easy for the user to install the application using distribution-specific way.
There are also a few installer projects which work similarly to windows installer generators, but I recommend studying the former path first.
What is the equivalent of LIBs (static library) and DLLs (dynamic library) in linux and how to use them?
.a (static) and .so (dynamic). You use them in more or less the same way as on Windows, of course using gcc-specific compilation options. I don't use Code::Blocks so I don't know how their dialogs look like, in the end it is about adding -llibrary to the linking options (guess what: on windows it is about adding /llibrary ;-))
Is it possible to use the "binary form" of a C++ library (if provided) so that I wouldn't need to recompile the entire library source code?
Yes. And plenty of libraries are already present in distributions.
Note also that if you use .deb's and .rpm's for distribution, you can say "my app needs such and such libraries installed" and they will be installed from the distribution archives. And this is recommended way, in general you should NOT distribute your copy of the libraries.
If I want to create a wxWidgets application in Linux, which package should I pick for Ubuntu? wxGTK or wxX11? Can I run wxGTK program under X11?
Try wxGTK first, dialogs may look better, gnome themes should be used etc.
If question no. 4 is answered possible, are precompiled wxX11/wxGTK library exists out there? Haven't tried deep google search.
Try
apt-cache search wx
(or spawn your Ubuntu Software Center and search for wx)
In short: you will find everything you need in distribution archives.
|
2,754,925 | 2,754,951 | C++ User-Defined Vector | How do you declare a vector in c++ while allowing user input to define the vector's name?
Okay, after reviewing your responses, here is more detail; Here is the error message from VS08 C++ console application -
Error 2 error C2664: 'std::basic_istream<_Elem,_Traits> &std::basic_istream<_Elem,_Traits>::get(_Elem *,std::streamsize)' : cannot convert parameter 1 from 'std::istream' to 'char *' e:\c++\project 5\project 5\project 5.cpp 58 project 5
Here is the code:
void addRecord()
{
vector<char>recordName;
vector<inventory>recordNameUser;
cout << "Name the record you want to store it as\n";
cin.get(cin, recordName);
cout << "Enter the item description\n";
cin.get(cin, recordNameUser.itemDescription);
cout << "Enter the quanity on hand\n";
cin >> recordNameUser.quanityOnHand;
cout << "Enter the wholesale cost\n";
cin >> recordNameUser.wholesaleCost;
cout << "Enter the retail cost\n";
cin >> recordNameUser.retailCost;
cout << "Enter the date of the inventory (mm/dd/yyyy)\n";
cin >> recordNameUser.inventoryDate;
}
| You want to have users give you a name and to be able to associate that with a vector of things? That's what a std::map is for, with a std::string as the key type and a std::vector as the payload type.
|
2,755,242 | 3,328,899 | Passing around objects to network packet handlers? | I've been writing a networking server for a while now in C++ and have come to the stage to start looking for a way to properly and easily handle all packets.
I am so far that I can figure out what kind of packet it is, but now I need to figure out how to get the needed data to the handler functions.
I had the following in mind:
Have a map of function pointers with the opcode as key and the function pointer as value
Have all these functions have 2 arguments, packet and ObjectAccessor
ObjectAccessor class contains various functions to fetch various items such as users and alike
Perhaps pass the user's guid too so we can fetch it from the objectaccessor
I'd like to know the various implementations others have come up with, so please comment on this idea and reply with your own implementations.
Thanks, Xeross
| I have implemented a handler class in conjunction with an array of function pointers, works beautifully.
|
2,755,258 | 2,916,036 | How to use folders in VC10 | When making a .NET project, then you can create folders in your solution explorer and these are real folders on the hard drive. When using C++ however they are only filters. Is there a way to set filters to be actually folders?
| There's a button to show the hard-drive in the solution explorer.
|
2,755,298 | 2,755,464 | Good style for handling constructor failure of critical object | I'm trying to decide between two ways of instantiating an object & handling any constructor exceptions for an object that is critical to my program, i.e. if construction fails the program can't continue.
I have a class SimpleMIDIOut that wraps basic Win32 MIDI functions. It will open a MIDI device in the constructor and close it in the destructor. It will throw an exception inherited from std::exception in the constructor if the MIDI device cannot be opened.
Which of the following ways of catching constructor exceptions for this object would be more in line with C++ best practices
Method 1 - Stack allocated object, only in scope inside try block
#include <iostream>
#include "simplemidiout.h"
int main()
{
try
{
SimpleMIDIOut myOut; //constructor will throw if MIDI device cannot be opened
myOut.PlayNote(60,100);
//.....
//myOut goes out of scope outside this block
//so basically the whole program has to be inside
//this block.
//On the plus side, it's on the stack so
//destructor that handles object cleanup
//is called automatically, more inline with RAII idiom?
}
catch(const std::exception& e)
{
std::cout << e.what() << std::endl;
std::cin.ignore();
return 1;
}
std::cin.ignore();
return 0;
}
Method 2 - Pointer to object, heap allocated, nicer structured code?
#include <iostream>
#include "simplemidiout.h"
int main()
{
SimpleMIDIOut *myOut;
try
{
myOut = new SimpleMIDIOut();
}
catch(const std::exception& e)
{
std::cout << e.what() << std::endl;
delete myOut;
return 1;
}
myOut->PlayNote(60,100);
std::cin.ignore();
delete myOut;
return 0;
}
I like the look of the code in Method 2 better, don't have to jam my whole program into a try block, but Method 1 creates the object on the stack so C++ manages the object's life time, which is more in tune with RAII philosophy isn't it?
I'm still a novice at this so any feedback on the above is much appreciated. If there's an even better way to check for/handle constructor failure in a siatuation like this please let me know.
| Personally, I prefer the first style you've used - Method 1 - that of allocating the SimpleMIDIOut object as local to the scope of the try-catch block.
For me, one of the benefits of a try-catch block is that is provides a neat, tidy place for that error handling code - the catch block - that allows you to specify your business logic in one nice, readable, unbroken flow.
Secondly, the try-catch block you've specified is generic enough to deal with any exception that derives from std::exception - so having the bulk of your program code within the try-catch block isn't a bad thing. It'll prevent your program from terminating unexpectedly if the worst happens and an exception gets thrown. Potentially that could be an exception that you don't expect, like an index out of bounds, or a memory allocation exception.
If you dislike having lots of code within the try-catch block for readability reasons, that's OK, because it's good design practice to refactor big lumps of code into functions. By doing this, you can keep the main function itself to a minimal number of lines.
Looking at Method 2:
You don't need that delete in the catch block. If an exception was thrown during construction then there's no object there to delete anyway.
Have you considered how you plan to cater for any std::exception that could be thrown by myOut->PlayNote? It's outside the scope of your try-catch, so an exception here would kill the program unexpectedly. This is what I was getting at with my second bullet, above.
If you were to decide to wrap most of the program in that try-catch block, but would still like to dynamically allocate the SimpleMIDIOut object, you could make the memory management a bit easier by using an auto_ptr to manage the memory for you in the event of an exception:
try
{
std::auto_ptr<SimpleMIDIOut> myOut(new SimpleMIDIOut());
myOut->PlayNote(60,100);
std::cin.ignore();
} // myOut goes out of scope, SimpleMIDIOut object deleted
catch(const std::exception& e)
{
std::cout << e.what() << std::endl;
return 1;
}
return 0;
...but you may as well just create the SimpleMIDIOut object as local rather than dynamic.
|
2,755,351 | 2,755,889 | How to list all installed ActiveX controls? | I need to display a list of ActiveX controls for the user to choose. It needs to show the control name and description.
How do I query Windows on the installed controls?
Is there a way to differentiate controls from COM automation servers?
| Googling for "enumerate activex controls" give this as the first result:
http://www.codeguru.com/cpp/com-tech/activex/controls/article.php/c5527/Listing-All-Registered-ActiveX-Controls.htm
Although I would add that you don't need to call AddRef() on pCatInfo since CoCreateInstance() calls that for you.
This is how I would do it:
#include <cstdio>
#include <windows.h>
#include <comcat.h>
int main()
{
// Initialize COM
::CoInitializeEx(NULL, COINIT_MULTITHREADED);
// Obtain interface for enumeration
ICatInformation* catInfo = NULL;
HRESULT hr = ::CoCreateInstance(CLSID_StdComponentCategoriesMgr,
NULL, CLSCTX_INPROC_SERVER, IID_ICatInformation, (void**)&catInfo);
// Obtain an enumerator for classes in the CATID_Control category.
IEnumGUID* enumGuid = NULL;
CATID catidImpl = CATID_Control;
CATID catidReqd = CATID_Control;
catInfo->EnumClassesOfCategories(1, &catidImpl, 0, &catidReqd, &enumGuid);
// Enumerate through the CLSIDs until there is no more.
CLSID clsid;
while((hr = enumGuid->Next(1, &clsid, NULL)) == S_OK)
{
BSTR name;
// Obtain full name
::OleRegGetUserType(clsid, USERCLASSTYPE_FULL, &name);
// Do something with the string
printf("%S\n", name);
// Release string.
::SysFreeString(name);
}
// Clean up.
enumGuid->Release();
catInfo->Release();
::CoUninitialize();
return 0;
}
|
2,755,352 | 2,756,425 | wrapping boost::ublas with swig | I am trying to pass data around the numpy and boost::ublas layers. I
have written an ultra thin wrapper because swig cannot parse ublas'
header correctly. The code is shown below
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/lexical_cast.hpp>
#include <algorithm>
#include <sstream>
#include <string>
using std::copy;
using namespace boost;
typedef boost::numeric::ublas::matrix<double> dm;
typedef boost::numeric::ublas::vector<double> dv;
class dvector : public dv{
public:
dvector(const int rhs):dv(rhs){;};
dvector();
dvector(const int size, double* ptr):dv(size){
copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0]));
}
~dvector(){}
};
with the SWIG interface that looks something like
%apply(int DIM1, double* INPLACE_ARRAY1) {(const int size, double* ptr)}
class dvector{
public:
dvector(const int rhs);
dvector();
dvector(const int size, double* ptr);
%newobject toString;
char* toString();
~dvector();
};
I have compiled them successfully via gcc 4.3 and vc++9.0. However
when I simply run
a = dvector(array([1.,2.,3.]))
it gives me a segfault. This is the first time I use swigh with numpy
and not have fully understanding between the data conversion and
memory buffer passing. Does anyone see something obvious I have
missed? I have tried to trace through with a debugger but it crashed within the assmeblys of python.exe. I have no clue if this is a swig problem or of my simple wrapper. Anything is appreciated.
| You may want to replace
copy(ptr, ptr+sizeof(double)*size, &(dv::data()[0]));
by
copy(ptr, ptr+size, &(dv::data()[0]));
Remember that in C/C++ adding or subtracting from a pointer moves it by a multiple of the size of the datatype it points to.
Best,
|
2,755,395 | 2,755,912 | How to return the handle of a window when we click on it, without any DLL injection? | For one of my projects, I need to create a function that will return a handle to a window when the user click on it (any window displayed on screen, and anywhere inside that window).
I know it is possible to use a global hook, but I think there must be a more simple way of doing that, without using any DLL injection.
In fact, I could intercept the left mouse click or intercept when a window is activated.
Can I use one of those 2 solutions without any DLL injection?
| You could use a LowLevelMouseProc hook to intercept the click, and then use WindowFromPoint to determine the window. (I haven't actually tried this.)
|
2,755,447 | 2,755,496 | Importing a C DLL's functions into a C++ program | I have a 3rd party library that's written in C. It exports all of its functions to a DLL.
I have the .h file, and I'm trying to load the DLL from my C++ program.
The first thing I tried was surrounding the parts where I #include the 3rd party lib in
#ifdef __cplusplus
extern "C" {
#endif
and, at the end
#ifdef __cplusplus
} // extern "C"
#endif
But the problem there was, all of the DLL file function linkage looked like this in their header files:
a_function = (void *)GetProcAddress(dll, "a_function");
While really a_function had type int (*a_function) (int *). Apparently MSVC++ compiler doesn't like this, while MSVC compiler does not seem to mind.
So I went through (brutal torture) and fixed them all to the pattern
typedef int (*_x_a_function) (int *); // using _a_function will not work, C uses it!
_x_a_function a_function ;
Then, to link it to the DLL code, in main():
a_function = (_x_a_function)GetProcAddress(dll, "a_function");
This SEEMS to make the compiler MUCH, MUCH happier, but it STILL complains with this final set of 143 errors, each saying for each of the DLL link attempts:
error LNK2005: _x_a_function already defined in main.obj main.obj
Multiple symbol definition errors.. sounds like a job for extern! SO I went and made ALL the function pointer declarations as follows:
function_pointers.h
typedef int (*_x_a_function) (int *);
extern _x_a_function a_function ;
And in a cpp file:
function_pointers.cpp
#include "function_pointers.h"
_x_a_function a_function ;
ALL fine and dandy.. except for linker errors now of the form:
error LNK2001: unresolved external symbol _a_function main.obj
Main.cpp includes "function_pointers.h", so it should know where to find each of the functions..
I am bamboozled. Does any one have any pointers to get me functional? (Pardon the pun..)
| Linker errors like that suggest you've defined all the functions in function_pointers.cpp, but forgotten to add it to the project/makefile.
Either that, or you've forgotten to "extern C" the functions in function_pointers.cpp too.
|
2,755,497 | 2,755,585 | Can't Include winhttp.h (with code::blocks/mingw) c++ | I've been trying to include winhttp.h and I get this error:
Winhttp.h: No such file or directory
Mingw doesn't have it, how would I add it?
| You can use runtime dynamic linking to link to the function(s) you want directly. You can't use the plain winhttp.h that ships with the Windows SDK because it contains Microsoft-specific features. You could also compile with Visual C++ 2010 Express Edition which would include the header you want.
Hope that helps :)
|
2,755,652 | 2,758,124 | How to generate one large dependency map for the whole project that builds with makefiles? | I have a gigantic project that is built using makefiles. Running make at the root of the project takes over 20 minutes when no files have changed (i.e. just traversing the project and checking for updated files).
I'd like to create a dependency map that will tell me which directories I need to run 'make' in based on the file(s) changed. I already have a list of updated files that I can get from my version control system, and I'd like to skip the 20 minutes of traversing and get straight to the locations that do need to be recompiled.
The project has a mix of several languages and custom tools, so this would ideally be language-independent (i.e. it would only process all makefiles to generate dependencies). I'll settle for a C/C++-specific solution, too, as the majority of the project is in C++. The project is built on Linux.
[Edit - clarifications, responses to comments]
The project truly is gigantic, it's taking 20 minutes simply because of the size and because of all things described in the link below ("recursive makes consider harmful"). Unfortunately, the project is put together from many pieces coming from many different places, and there's little flexibility in what I can do with low-level Makefiles... the top-level ones putting the pieces together are the ones I have control over.
| One thing you could look for is "makefile graph" -- there are a few projects out there to make dependency trees from large makefile projects. Here's one: http://sailhome.cs.queensu.ca/~bram/makao/index.html . I think it will both create a pretty graph, and actually build things.
If you want to roll your own Makefile parser, and essentially replace make with your own custom script, my advice would be "don't". But there is a collection of Perl modules: Makefile::Parser. It claims to "pass 51% of the GNU Make test suite".
If you want to just look at what's taking so long, you can turn on Make's debugging output. Bits of it are usually sort of useless, like the pages and pages of Make deciding whether or not to apply implicit rules, but maybe there will be some obvious thing that happens that doesn't need to happen. If you want to do this, you could look at remake, "GNU Make with comprehensible tracing and a debugger".
|
2,755,670 | 2,755,810 | How to attach boost::shared_ptr (or another smart pointer) to reference counter of object's parent? | I remember encountering this concept before, but can't find it in Google now.
If I have an object of type A, which directly embeds an object of type B:
class A {
B b;
};
How can I have a smart pointer to B, e. g. boost::shared_ptr<B>, but use reference count of A? Assume an instance of A itself is heap-allocated I can safely get its shared count using, say, enable_shared_from_this.
| D'oh!
Found it right in shared_ptr documentation. It's called aliasing (see section III of shared_ptr improvements for C++0x).
I just needed to use a different constructor (or a corresponding reset function overload):
template<class Y> shared_ptr( shared_ptr<Y> const & r, T * p );
Which works like this (you need to construct shared_ptr to parent first):
#include <boost/shared_ptr.hpp>
#include <iostream>
struct A {
A() : i_(13) {}
int i_;
};
struct B {
A a_;
~B() { std::cout << "B deleted" << std::endl; }
};
int
main() {
boost::shared_ptr<A> a;
{
boost::shared_ptr<B> b(new B);
a = boost::shared_ptr<A>(b, &b->a_);
std::cout << "ref count = " << a.use_count() << std::endl;
}
std::cout << "ref count = " << a.use_count() << std::endl;
std::cout << a->i_ << std::endl;
}
|
2,755,797 | 2,771,883 | How to determine Scale of Line Graph based on Pixels/Height? | I have a problem due to my terrible math abilities, that I cannot figure out how to scale a graph based on the maximum and minimum values so that the whole graph will fit onto the graph-area (400x420) without parts of it being off the screen (based on a given equation by user).
Let's say I have this code, and it automatically draws squares and then the line graph based on these values. What is the formula (what do I multiply) to scale it so that it fits into the small graphing area?
vector<int> m_x;
vector<int> m_y; // gets automatically filled by user equation or values
int HeightInPixels = 420;// Graphing area size!!
int WidthInPixels = 400;
int best_max_y = GetMaxOfVector(m_y);
int best_min_y = GetMinOfVector(m_y);
m_row = 0;
m_col = 0;
y_magnitude = (HeightInPixels/(best_max_y+best_min_y)); // probably won't work
x_magnitude = (WidthInPixels/(int)m_x.size());
m_col = m_row = best_max_y; // number of vertical/horizontal lines to draw
////x_magnitude = (WidthInPixels/(int)m_x.size())/2; Doesn't work well
////y_magnitude = (HeightInPixels/(int)m_y.size())/2; Doesn't work well
ready = true; // we have values, graph it
Invalidate(); // uses WM_PAINT
////////////////////////////////////////////
/// Construction of Graph layout on WM_PAINT, before painting line graph
///////////////////////////////////////////
CPen pSilver(PS_SOLID, 1, RGB(150, 150, 150) ); // silver
CPen pDarkSilver(PS_SOLID, 2, RGB(120, 120, 120) ); // dark silver
dc.SelectObject( pSilver ); // silver color
CPoint pt( 620, 620 ); // origin
int left_side = 310;
int top_side = 30;
int bottom_side = 450;
int right_side = 710; // create a rectangle border
dc.Rectangle(left_side,top_side,right_side,bottom_side);
int origin = 310;
int xshift = 30;
int yshift = 30;
// draw scaled rows and columns
for(int r = 1; r <= colrow; r++){ // draw rows
pt.x = left_side;
pt.y = (ymagnitude)*r+top_side;
dc.MoveTo( pt );
pt.x = right_side;
dc.LineTo( pt );
for(int c = 1; c <= colrow; c++){
pt.x = left_side+c*(magnitude);
pt.y = top_side;
dc.MoveTo(pt);
pt.y = bottom_side;
dc.LineTo(pt);
} // draw columns
}
// grab the center of the graph on x and y dimension
int top_center = ((right_side-left_side)/2)+left_side;
int bottom_center = ((bottom_side-top_side)/2)+top_side;
| You are using ax^2 + bx + c (quadratic equation). You will get list of (X,Y) values inserted by user.
Let us say 5 points you get are
(1,1)
(2,4)
(4,1)
(5,6)
(6,7)
So, here your best_max_y will be 7 and best_min_y will be 1.
Now you have total graph area is
Dx = right_side - left_side //here, 400 (710 - 310)
Dy = bottom_side - top_side //here, 420 (450 - 30)
So, you can calculate x_magnitude and y_magnitude using following equation :
x_magnitude = WidthInPixels / Dx;
y_magnitude = HeightInPixels / Dy;
|
2,756,153 | 2,823,616 | Why would GDI+ colours vary based off whether a tooltip is visible? | I'm displaying a bitmap using GDI+. After loading the bitmap from a DLL resource I set the background colour (blue - #0000FF) to transparent using TransparentBlt. On Windows Vista and later this works as expected.
However, on a Windows XP system we're testing on this only works when any tooltip (e.g. the "title" property in IE, or Windows Explorer's tooltip shown when hovering the mouse over a file, etc) is displayed. The rest of the time the background colour is still blue.
Has anyone encountered this before, or know of a way to stop this occurring and for the blue to be properly made transparent?
Edit: After further investigation I found that setting colour depth in Windows XP to 16 bit colours instead of 32 bit colours caused TransparentBlt to start working normally again. Obviously this isn't an ideal solution, specifying what colour depth must be used, but does this give any hint to what might be happening?
Edit2: Code sample included.
m_pGDIBitmap = new Gdiplus::Bitmap(_Module.m_hInst, MAKEINTRESOURCE(lImageResource));
m_hMemDC = CreateCompatibleDC(hdc);
Gdiplus::Graphics myGraphics(m_hMemDC);
myGraphics.DrawImage(m_pGDIBitmap,
Gdiplus::Rect(0, 0, m_pGDIBitmap->GetWidth(), m_pGDIBitmap->GetHeight()),
0,
0,
m_pGDIBitmap->GetWidth(),
m_pGDIBitmap->GetHeight(),
Gdiplus::UnitPixel, &imAtt);
SetStretchBltMode(hdc, HALFTONE);
SetBrushOrgEx(hdc, rcBounds.left, rcBounds.top, NULL);
TransparentBlt(hdc, rcBounds.left, rcBounds.top, iScaledWidth, iScaledHeight, m_hMemDC, 0, 0, iBitmapWidth, iBitmapHeight, GetPixel(m_hMemDC, 0, 0));
| What I ended up doing was more of a workaround, but it did work. I changed the background colour to black and added the following code before the DrawImage call:
Gdiplus::ImageAttributes imAtt;
imAtt.SetColorKey(Gdiplus::Color(0, 0, 0), Gdiplus::Color(0, 0, 0), Gdiplus::ColorAdjustTypeBitmap);
For some reason using this with blue as the background didn't work and using TransparentBlt on its own with either colour didn't work, but the combination applied the transparency correctly on the various OSes and colour depths that I tried.
If I had access to a paint program that supported bitmap files with an alpha channel, i.e. 32 bit bitmaps, I suspect making the background explicitly transparent and then using AlphaBlend would have worked as well but I didn't have the ability to try that at the time.
|
2,756,233 | 2,756,265 | Why should pop() take an argument? | Quick background
I'm a Java developer who's been playing around with C++ in my free/bored time.
Preface
In C++, you often see pop taking an argument by reference:
void pop(Item& removed);
I understand that it is nice to "fill in" the parameter with what you removed. That totally makes sense to me. This way, the person who asked to remove the top item can have a look at what was removed.
However, if I were to do this in Java, I'd do something like this:
Item pop() throws StackException;
This way, after the pop we return either: NULL as a result, an Item, or an exception would be thrown.
My C++ text book shows me the example above, but I see plenty of stack implementations taking no arguments (stl stack for example).
The Question
How should one implement the pop function in C++?
The Bonus
Why?
| To answer the question: you should not implement the pop function in C++, since it is already implemented by the STL. The std::stack container adapter provides the method top to get a reference to the top element on the stack, and the method pop to remove the top element. Note that the pop method alone cannot be used to perform both actions, as you asked about.
Why should it be done that way?
Exception safety: Herb Sutter gives a good explanation of the issue in GotW #82.
Single-responsibility principle: also mentioned in GotW #82. top takes care of one responsibility and pop takes care of the other.
Don't pay for what you don't need: For some code, it may suffice to examine the top element and then pop it, without ever making a (potentially expensive) copy of the element. (This is mentioned in the SGI STL documentation.)
Any code that wishes to obtain a copy of the element can do this at no additional expense:
Foo f(s.top());
s.pop();
Also, this discussion may be interesting.
If you were going to implement pop to return the value, it doesn't matter much whether you return by value or write it into an out parameter. Most compilers implement RVO, which will optimize the return-by-value method to be just as efficient as the copy-into-out-parameter method. Just keep in mind that either of these will likely be less efficient than examining the object using top() or front(), since in that case there is absolutely no copying done.
|
2,756,243 | 2,756,277 | Network programming and Packets interactions | Greeting,
This month I will start working on my master thesis. My thesis's subject is about network security.
I need to deal with network interfaces and packets.
I've used shappcap before to interact with packets but I'm not sure if C# is the most powerful language to deal with network programing and packets.
I worked a bit with wireshark and I saw how powerful it is and as you know winsharp is open source developed using C++.
I'm not sure if I should use C# or C++ for network security programming and I want your through about the best language might be for network programming and packets interaction.
should I use C#, C++, or java or some thing else?
please give me your advice.
Thank you,
UPDATE
..........................
I'm going to do different packet mining by taking each packet and read each field on it then use these values and in same stages I would modify some of the packets value then resend them back.
I want to control the packet since it received by the network interface until it passes to the application layer.
also
| You'd be able to do network programming using almost any language you want to. If you are equally comfortable in all of the languages you've mentioned, you should determine what system libraries or APIs will you be interfacing with. For example, if you will be doing packet-level network programming on a Unix system, C would probably be your best best. If you want to integrate with Wireshark, go with C++. If you want to use an Apache Commons component, use Java. I suggest you come up with a more specific set of requirements for your actual program before trying to decide which language to use.
|
2,756,273 | 2,756,304 | Does OpenGL stencil test happen before or after fragment program runs? | When I set glStencilFunc( GL_NEVER, . . . ) effectively disabling all drawing, and then run my [shader-bound] program I get no performance increase over letting the fragment shader run. I thought the stencil test happened before the fragment program. Is that not the case, or at least not guaranteed? Replacing the fragment shader with one that simply writes a constant to gl_FragColor does result in a higher FPS.
| Take a look at the following outline for the DX10 pipeline, it says that the stencil test runs before the pixel shader:
http://3.bp.blogspot.com/_2YU3pmPHKN4/Sz_0vqlzrBI/AAAAAAAAAcg/CpDXxOB-r3U/s1600-h/D3D10CheatSheet.jpg
and the same is true in DX11:
http://4.bp.blogspot.com/_2YU3pmPHKN4/S1KhDSPmotI/AAAAAAAAAcw/d38b4oA_DxM/s1600-h/DX11.JPG
I don't know if this is mandated in the OpenGL spec but it would be detrimental for an implementation to not do the stencil test before running the fragment program.
|
2,756,415 | 2,756,439 | Console output window in DLL | I am trying to redirect the output from my DLL to an external console window for easy debugging.
I have been told about AllocConsole but I am not able to reproduce it, i.e. the console window does not appear.
My current environment is Visual Studio 2005.
I tried the following example which is gotten off the Internet,
AllocConsole();
HANDLE han = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsole(han,"hello",6,new DWORD,0);
yet nothing happens. Can someone point me in the right direction if creating a console window via DLL is possible in the first place.
Thanks in advance!
| The proper way to output debug strings is via OutputDebugString(), with an appropriate debugging tool listening for output strings.
|
2,756,859 | 2,756,878 | Transfer data between C++ classes efficiently | Need help...
I have 3 classes, Manager which holds 2 pointers. One to class A another to class B . A does not know about B and vise versa.
A does some calculations and at the end it puts 3 floats into the clipboard.
Next, B pulls from clipboard the 3 floats, and does it's own calculations.
This loop is managed by the Manager and repeats many times (iteration after iteration).
My problem:
Now class A produces a vector of floats which class B needs. This vector can have more than 1000 values and I don't want to use the clipboard to transfer it to B as it will become time consumer, even bottleneck, since this behavior repeats step by step.
Simple solution is that B will know A (set a pointer to A).
Other one is to transfer a pointer to the vector via Manager
But I'm looking for something different, more object oriented that won't break the existent separation between A and B
Any ideas ?
Many thanks
David
| It kind of sounds like you are writing a producer / consumer pair, who may communicate more easily over a (probably thread-safe) queue of floats.
In other words: the "queue" is like the vector you are currently using. Both A and B will have a reference to this queue. A runs calculations, and writes floats to the queue (possibly three at a time, if that's what you need). B checks the queue, or possibly is "signaled" by A that the queue is ready, and grabs the floats from the queue to process them.
For more info, google (or search Stack Overflow) for "producer consumer" and/or "queue", you'll probably find a lot of useful info.
(e.g. Multithreaded Work Queue in C++)
|
2,757,424 | 2,757,479 | Discrepancy between the values computed by Fortran and C++ | I would have dared say that the numeric values computed by Fortran and C++ would be way more similar. However, from what I am experiencing, it turns out that the calculated numbers start to diverge after too few decimal digits. I have come across this problem during the process of porting some legacy code from the former language to the latter. The original Fortran 77 code...
INTEGER M, ROUND
DOUBLE PRECISION NUMERATOR, DENOMINATOR
M = 2
ROUND = 1
NUMERATOR=5./((M-1+(1.3**M))**1.8)
DENOMINATOR = 0.7714+0.2286*(ROUND**3.82)
WRITE (*, '(F20.15)') NUMERATOR/DENOMINATOR
STOP
... outputs 0.842201471328735, while its C++ equivalent...
int m = 2;
int round = 1;
long double numerator = 5.0 / pow((m-1)+pow(1.3, m), 1.8);
long double denominator = 0.7714 + 0.2286 * pow(round, 3.82);
std::cout << std::setiosflags(std::ios::fixed) << std::setprecision(15)
<< numerator/denominator << std::endl;
exit(1);
... returns 0.842201286195064. That is, the computed values are equal only up to the sixth decimal. Although not particularly a Fortran advocator, I feel inclined to consider its results as the 'correct' ones, given its legitimate reputation of number cruncher. However, I am intrigued about the cause of this difference between the computed values. Does anyone know what the reason for this discrepancy could be?
| In Fortran, by default, floating point literals are single precision, whereas in C/C++ they are double precision.
Thus, in your Fortran code, the expression for calculating NUMERATOR is done in single precision; it is only converted to double precision when assigning the final result to the NUMERATOR variable.
And the same thing for the expression calculating the value that is assigned to the DENOMINATOR variable.
|
2,757,492 | 2,759,822 | Display using QtWebKit, whilst parsing xml | I wish to use QtWebKit to load a url for display, but, that's the easy part, I can do that. What I wish to do is record / log xml as I go. My attention here is to record and database certain details on the fly, by recording those details.
My problem is, how to do this all on the fly, without requesting the same url from the server twice, once for the xml, and the second time to view the url.
My hope here, is to implement a very fast way of recording set data as the user passes over it. Take for example, rather then have to type out details displayed by a website, I wish to have those details chucked into a database as I the user views the website.
Now, I am using QtWebKit, and I have everything pretty much solved viewing wise. I have a loadUrl() routine which calls load(url) inside the qwebview.h
The problem is, how do I piggyback xml parsing on top of this?
| In your loadUrl do the download of the url yourself using the HTTP download facilities Qt already provides (QNetworkRequest and friends).
Once you got the data, parse and log it and use:
void QWebView::setHtml ( const QString & html, const QUrl & baseUrl = QUrl() )
To set it into the QWebView manually. The second url parameter is the url you have, which will be used as a base url for the elements that are referenced from the page.
If you are not sure you downloaded html, then use:
void QWebView::setContent ( const QByteArray & data, const QString & mimeType = QString(), const QUrl & baseUrl = QUrl() )
You can also do the inverse. Just call QWebView::load(url) in your method, and once the transfer is complete, use QWebView::mainFrame() to get the main frame and then QWebFrame::toHtml() to get the content, which you can parse and log as you wish.
|
2,757,713 | 2,759,347 | Optimizing C++ Tree Generation | I'm generating a Tic-Tac-Toe game tree (9 seconds after the first move), and I'm told it should take only a few milliseconds. So I'm trying to optimize it, I ran it through CodeAnalyst and these are the top 5 calls being made (I used bitsets to represent the Tic-Tac-Toe board):
std::_Iterator_base::_Orphan_me
std::bitset<9>::test
std::_Iterator_base::_Adopt
std::bitset<9>::reference::operator bool
std::_Iterator_base::~_Iterator_base
void BuildTreeToDepth(Node &nNode, const int& nextPlayer, int depth)
{
if (depth > 0)
{
//Calculate gameboard states
int evalBoard = nNode.m_board.CalculateBoardState();
bool isFinished = nNode.m_board.isFinished();
if (isFinished || (nNode.m_board.isWinner() > 0))
{
nNode.m_winCount = evalBoard;
}
else
{
Ticboard tBoard = nNode.m_board;
do
{
int validMove = tBoard.FirstValidMove();
if (validMove != -1)
{
Node f;
Ticboard tempBoard = nNode.m_board;
tempBoard.Move(validMove, nextPlayer);
tBoard.Move(validMove, nextPlayer);
f.m_board = tempBoard;
f.m_winCount = 0;
f.m_Move = validMove;
int currPlay = (nextPlayer == 1 ? 2 : 1);
BuildTreeToDepth(f,currPlay, depth - 1);
nNode.m_winCount += f.m_board.CalculateBoardState();
nNode.m_branches.push_back(f);
}
else
{
break;
}
}while(true);
}
}
}
Where should I be looking to optimize it? How should I optimize these 5 calls (I don't recognize them=.
| The tic-tac-toe game tree is very redundant. Eliminating rotated and mirrored boards will reduce the final ply of the game tree by 3 or 4 orders of magnitude. No amount of optimizations will make bubblesort as fast as introsort.
struct Game_board;
struct Node
{
Game_board game_board;
Node* parent;
std::vector<Node*> children;
enum { X_Win, Y_Win, Draw, Playing } outcome;
};
// returns the same hash value for all "identical" boards.
// ie boards that can be rotated or mirrored to look the
// same will have the same hash value
int hash( const Game_board& game_board );
// uses hash() function to generate hashes from Node*
struct Hash_functor;
// nodes yet to be explored.
std::hash_set<Node*,Hash_functor> open;
//nodes already explored.
std::hash_set<Node*,Hash_functor> closed;
while( ! open.empty() )
{
Node* node_to_expore = get_a_node( open );
assert( node_to_expore not in close or open sets )
if( node_to_expore is win lose or draw )
{
Mark node as win lose or draw
add node to closed set
}
loop through all children of node_to_expore
{
if( child in close )
{
add node from closed set to children list of node_to_expore
}
else if( child in open )
{
add node from open set to children list of node_to_explore
}
else
{
add child to open set
add child to children list of node_to_expore
}
}
}
|
2,757,816 | 2,798,382 | Class template specializations with shared functionality | I'm writing a simple maths library with a template vector type:
template<typename T, size_t N>
class Vector {
public:
Vector<T, N> &operator+=(Vector<T, N> const &other);
// ... more operators, functions ...
};
Now I want some additional functionality specifically for some of these. Let's say I want functions x() and y() on Vector<T, 2> to access particular coordinates. I could create a partial specialization for this:
template<typename T>
class Vector<T, 3> {
public:
Vector<T, 3> &operator+=(Vector<T, 3> const &other);
// ... and again all the operators and functions ...
T x() const;
T y() const;
};
But now I'm repeating everything that already existed in the generic template.
I could also use inheritance. Renaming the generic template to VectorBase, I could do this:
template<typename T, size_t N>
class Vector : public VectorBase<T, N> {
};
template<typename T>
class Vector<T, 3> : public VectorBase<T, 3> {
public:
T x() const;
T y() const;
};
However, now the problem is that all operators are defined on VectorBase, so they return VectorBase instances. These cannot be assigned to Vector variables:
Vector<float, 3> v;
Vector<float, 3> w;
w = 5 * v; // error: no conversion from VectorBase<float, 3> to Vector<float, 3>
I could give Vector an implicit conversion constructor to make this possible:
template<typename T, size_t N>
class Vector : public VectorBase<T, N> {
public:
Vector(VectorBase<T, N> const &other);
};
However, now I'm converting from Vector to VectorBase and back again. Even though the types are the same in memory, and the compiler might optimize all this away, it feels clunky and I don't really like to have potential run-time overhead for what is essentially a compile-time problem.
Is there any other way to solve this?
| I think you can use CRTP to solve this problem. This idiom is used in boost::operator.
template<typename ChildT, typename T, int N>
class VectorBase
{
public:
/* use static_cast if necessary as we know that 'ChildT' is a 'VectorBase' */
friend ChildT operator*(double lhs, ChildT const &rhs) { /* */ }
friend ChildT operator*(ChildT const &lhs, double rhs) { /* */ }
};
template<typename T, size_t N>
class Vector : public VectorBase<Vector<T,N>, T, N>
{
};
template<typename T>
class Vector<T, 3> : public VectorBase<Vector<T, 3>, T, 3>
{
public:
T x() const {}
T y() const {}
};
void test()
{
Vector<float, 3> v;
Vector<float, 3> w;
w = 5 * v;
w = v * 5;
v.x();
Vector<float, 5> y;
Vector<float, 5> z;
y = 5 * z;
y = z * 5;
//z.x(); // Error !!
}
|
2,758,080 | 2,758,100 | How to sort an STL vector? | I would like to sort a vector
vector<myClass> object;
Where myclass contains many int variables. How can I sort my vector on any specific data variable of myClass.
| Overload less than operator, then sort. This is an example I found off the web...
class MyData
{
public:
int m_iData;
string m_strSomeOtherData;
bool operator<(const MyData &rhs) const { return m_iData < rhs.m_iData; }
};
std::sort(myvector.begin(), myvector.end());
Source: here
|
2,758,158 | 2,758,164 | Which casting technique is better for doing casting from upper class to lower class in C++ | i want to cast from upper class pointer to lower class i.e from the base class pointer to derived class pointer.
Should i use "Dynamic_cast" or "reinterpret_cast"? please advice me
| Don't use reinterpret_cast - either use static_cast or dynamic_cast. If you're sure that the pointer is to exactly that derived class object use static_cast, otherwise use dynamic_cast (that will require the base class to be polymorhic) and check the result to ensure that the pointer is indeed to the class you want.
|
2,758,259 | 2,758,304 | How can I know the jpeg quality of the read image using graphicsmagick | When I read a jpeg image using Magick::readImages(...) function.
How can I know the estimated jpeg quality of the image?
I know how to set the quality when I wanna write the image, but it is not relevant to the quality of the original image, so for example:
when I read a jpeg image that its quality is 80% and I write it using 90% quality I will get a bigger image than the original one, since the 90% is not 90% out of the original 80%.
How can I know the jpeg quality of the read image?
| This is impossible, period. The JPEG quality settings is just a number that is passed to the encoder and affects how the encoder treats the data.
It's not even percentage of anything - it is just some setting that affects how aggressively the encoder manipulates and transforms data. Wherever you see the percent sign near JPEG quality just ignore it - it's meaningless there.
So regardless of the encoder it is impossible to find which JPEG quality settings value the enocder used to produce this very image. The only way would be to obtain the original and try all reasonably possible setting values until you hit the same result.
|
2,758,449 | 2,758,833 | Is my method for avoiding dynamic_cast<> faster than dynamic_cast<> itself? | I was answering a question a few minutes ago and it raised to me another one:
In one of my projects, I do some network message parsing. The messages are in the form of:
[1 byte message type][2 bytes payload length][x bytes payload]
The format and content of the payload are determined by the message type. I have a class hierarchy, based on a common class Message.
To instantiate my messages, i have a static parsing method which gives back a Message* depending on the message type byte. Something like:
Message* parse(const char* frame)
{
// This is sample code, in real life I obviously check that the buffer
// is not NULL, and the size, and so on.
switch(frame[0])
{
case 0x01:
return new FooMessage();
case 0x02:
return new BarMessage();
}
// Throw an exception here because the mesage type is unknown.
}
I sometimes need to access the methods of the subclasses. Since my network message handling must be fast, I decived to avoid dynamic_cast<> and I added a method to the base Message class that gives back the message type. Depending on this return value, I use a static_cast<> to the right child type instead.
I did this mainly because I was told once that dynamic_cast<> was slow. However, I don't know exactly what it really does and how slow it is, thus, my method might be as just as slow (or slower) but far more complicated.
What do you guys think of this design ? Is it common ? Is it really faster than using dynamic_cast<> ? Any detailed explanation of what happen under the hood when one use dynamic_cast<> is welcome !
--- EDIT ---
Since some people asked why:
Basically, when I receive a frame, I do two things:
I parse the message and build a corresponding instance of a subclass of Message if the content of the frame is valid. There is no logic except for the parsing part.
I receive a Message and depending on a switch(message->getType()), I static_cast<> to the right type and do whatever has to be done with the message.
| Implementations of dynamic_cast will of course vary by compiler.
In Visual C++, the vtable points to a structure which contains all of the RTTI about a structure. A dynamic_cast therefore involves dereferencing this pointer, and checking the "actual" type against the requested type, and throwing an exception (or returning NULL) if they are not compatible. It is basically equivalent to the system you describe. It's not particularity slow.
Your design also sounds a bit off - you have a factory method which forgets the true type of an object, then you immediately want to un-forget that information. Perhaps you should move that logic you do when unforgetting a type into the factory method, or into virtual methods on the base class itself.
|
2,758,848 | 2,758,889 | boost timer usage question | I have a really simple question, yet I can't find an answer for it. I guess I am missing something in the usage of the boost timer.hpp. Here is my code, that unfortunately gives me an error message:
#include <boost/timer.hpp>
int main() {
boost::timer t;
}
And the error messages are as follows:
/usr/include/boost/timer.hpp: In member function ‘double boost::timer::elapsed_max() const’:
/usr/include/boost/timer.hpp:59: error: ‘numeric_limits’ is not a member of ‘std’
/usr/include/boost/timer.hpp:59: error: ‘::max’ has not been declared
/usr/include/boost/timer.hpp:59: error: expected primary-expression before ‘double’
/usr/include/boost/timer.hpp:59: error: expected `)' before ‘double’
The used library is boost 1.36 (SUSE 11.1).
Thanks in advance!
| It should be fine, on a side note, are you sure you are typing #include instead of include?
You shouldn't need to, but you can try to also include:
#include <limits>
Before the boost include as it seems that may fix at least some of your problems.
|
2,758,863 | 2,758,906 | C++ instantiation question | Want to verify that my understanding of how this works.
Have a C++ Class with one public instance variable:
char* character_encoding;
and whose only constructor is defined as:
TF_StringList(const char* encoding = "cp_1252");
when I use this class in either C++/CLI or C++, the first thing I do is declare a pointer to an object of this class:
const TF_StringList * categories;
Then later I instantiate it:
categories = new TF_StringList();
this gives me a pointer to an object of type TF_StringList whose variable character_encoding is set to "cp_1252";
So, is all that logic valid?
Jim
| The one problem i see, is that your constructor takes a const char*, but you're storing it in a char*. That's going to cause the compiler to complain unless you cast away the constness. (Alternatively, is there any reason not to make your field a const char* ? i don't see you needing to edit the chars of the name...)
|
2,758,994 | 2,759,087 | text from a file turned into a variable? | If I made a program that stores strings on a text file using the "list"-function(#include ), and then I want to copy all of the text from that file and call it something(so I can tell the program to type in all of the text I copied somewhere by using that one variable to refer to the text), do I use a string,double,int or what do I declare that chunk of text as?
I'm making the program using c++ in a simple console application.
Easier explanation for PoweRoy:
I have a text in a .txt file,I want to copy everything in it and then all this that I just copied, I want to call it "int text" or "string text" or whatever.But I don't know which one of those "int","string","double" etc. to use.
| To take some pity on you, this is about the simplest C++ program that reads a file into memory and then does something with it:
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
using namespace std;
int main() {
ifstream input( "foo.txt" );
if ( ! input.is_open() ) {
cerr << "could not open input file" << endl;
return 1;
}
vector <string> lines;
string line;
while( getline( input, line ) ) {
lines.push_back( line );
}
for ( unsigned int i = 0; i < lines.size(); i++ ) {
cout << (i+1) << ": " << lines[i] << "\n";
}
}
|
2,759,205 | 2,759,235 | Cryptic C++ "thing" (function pointer) | What is this syntax for in C++? Can someone point me to the technical term so I can see if I find anything in my text?
At first I thought it was a prototype but then the = and (*fn) threw me off...
Here is my example:
void (*fn) (int&,int&) = x;
| It can be rewritten to
typedef void (*T) (int&, int&);
T fn = x;
The 2nd statement is obvious, which should have solved that = x; question. In the 1st statement, we make T as a synonym as the type void(*)(int&, int&), which means:
a pointer to a function ((*…))
returning void
and taking 2 arguments: int&, int&.
|
2,759,350 | 2,759,596 | Can I use const in vectors to allow adding elements, but not modifications to the already added? | My comments on this answer got me thinking about the issues of constness and sorting. I played around a bit and reduced my issues to the fact that this code:
#include <vector>
int main() {
std::vector <const int> v;
}
will not compile - you can't create a vector of const ints. Obviously, I should have known this (and intellectually I did), but I've never needed to create such a thing before. However, it seems like a useful construct to me, and I wonder if there is any way round this problem - I want to add things to a vector (or whatever), but they should not be changed once added.
There's probably some embarrassingly simple solution to this, but it's something I'd never considered before.
I probably should not have mentioned sorting (I may ask another question about that, see this for the difficulties of asking questions). My real base use case is something like this:
vector <const int> v; // ok (i.e. I want it to be OK)
v.push_back( 42 ); // ok
int n = v[0]; // ok
v[0] = 1; // not allowed
| Well, in C++0x you can...
In C++03, there is a paragraph 23.1[lib.containers.requirements]/3, which says
The type of objects stored in these components must meet the requirements of CopyConstructible types (20.1.3), and the additional requirements of Assignable types.
This is what's currently preventing you from using const int as a type argument to std::vector.
However, in C++0x, this paragraph is missing, instead, T is required to be Destructible and additional requirements on T are specified per-expression, e.g. v = u on std::vector is only valid if T is MoveConstructible and MoveAssignable.
If I interpret those requirements correctly, it should be possible to instantiate std::vector<const int>, you'll just be missing some of its functionality (which I guess is what you wanted). You can fill it by passing a pair of iterators to the constructor. I think emplace_back() should work as well, though I failed to find explicit requirements on T for it.
You still won't be able to sort the vector in-place though.
|
2,759,702 | 2,759,712 | class member access specifiers and binary code | I understand what the typical access specifiers are, and what they mean. 'public' members are accessible anywhere, 'private' members are accessible only by the same class and friends, etc.
What I'm wondering is what, if anything, this equates to in lower-level terms. Are their any post-compilation functional differences between these beyond the high-level restrictions (what can access what) imposed by the language (c++ in this case) they're used in.
Another way to put it - if this were a perfect world where programmers always made good choices (like not accessing members that may change later and using only well defined members that should stay the same between implementations), would their be any reason to use these things?
| Access specifiers only exist for compilation purposes. Any memory within your program's allocation can be accessed by any part of the executable; there is no public/private concept at runtime
|
2,759,725 | 2,768,023 | Preventing symbols from being stripped in IBM Visual Age C/C++ for AIX | I'm building a shared library which I dynamically load (using dlopen) into my AIX application using IBM's VisualAge C/C++ compiler. Unfortunately, it appears to be stripping out necessary symbols:
rtld: 0712-002 fatal error: exiting.
rtld: 0712-001 Symbol setVersion__Q2_3CIF17VersionReporterFRCQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc__ was referenced
from module ./object/AIX-6.1-ppc/plugins/plugin.so(), but a runtime definition
of the symbol was not found.
Both the shared library and the application which loads the shared library compile/link against the static library which contains the VersionReporter mentioned in the error message.
To link the shared library I'm using these options: -bM:SRE -bnoentry -bexpall
To link the application, I'm using this option: -brtl
Is there an option I can use to prevent this symbol from being stripped in the application? I've tried using -nogc as stated in the IBM docs, but that causes the shared library to be in an invalid format or the application to fail to link (depending on which one I use it with).
| I figured this out. The trick is to use an export list so that symbols used in the plugin but not used in the binary aren't stripped out.
# version.exp:
setVersion__Q2_3CIF17VersionReporterFRCQ2_3std12basic_stringXTcTQ2_3std11char_traitsXTc_TQ2_3std9allocatorXTc__
And then when linking the application use: -brtl -bexpfull -bE:version.exp
There's more information here: Developing and Porting C and C++ Applications on AIX.
|
2,759,738 | 2,760,860 | Navigation graphics overlayed over video | Imagine I have a video playing.. Can I have some sort of motion graphics being played 'over' that video.. Like say the moving graphics is on an upper layer than the video, which would be the lower layer..
I am comfortable in a C++ and Python, so a solution that uses these two will be highly appreciated..
Thank you in advance,
Rishi..
| I'm not sure I understand the question correctly but a video file is a sequence of pictures that you can extract (for instance with the opencv library C++ interface) and then you can use it wherever you want. You can play the video on the sides of an opengl 3D cube (available in all opengl tutorials) and other 3D elements around it.
Of course you can also displays it in a conventional 2D interface and draw stuff on top of it, but for this you need a graphical ui.
Is it what you thought or am I completely lost?
|
2,759,845 | 2,759,875 | Why is address zero used for the null pointer? | In C (or C++ for that matter), pointers are special if they have the value zero: I am adviced to set pointers to zero after freeing their memory, because it means freeing the pointer again isn't dangerous; when I call malloc it returns a pointer with the value zero if it can't get me memory; I use if (p != 0) all the time to make sure passed pointers are valid, etc.
But since memory addressing starts at 0, isn't 0 just as a valid address as any other? How can 0 be used for handling null pointers if that is the case? Why isn't a negative number null instead?
Edit:
A bunch of good answers. I'll summarize what has been said in the answers expressed as my own mind interprets it and hope that the community will correct me if I misunderstand.
Like everything else in programming it's an abstraction. Just a constant, not really related to the address 0. C++0x emphasizes this by adding the keyword nullptr.
It's not even an address abstraction, it's the constant specified by the C standard and the compiler can translate it to some other number as long as it makes sure it never equals a "real" address, and equals other null pointers if 0 is not the best value to use for the platform.
In case it's not an abstraction, which was the case in the early days, the address 0 is used by the system and off limits to the programmer.
My negative number suggestion was a little wild brainstorming, I admit. Using a signed integer for addresses is a little wasteful if it means that apart from the null pointer (-1 or whatever) the value space is split evenly between positive integers that make valid addresses and negative numbers that are just wasted.
If any number is always representable by a datatype, it's 0. (Probably 1 is too. I think of the one-bit integer which would be 0 or 1 if unsigned, or just the signed bit if signed, or the two bit integer which would be [-2, 1]. But then you could just go for 0 being null and 1 being the only accessible byte in memory.)
Still there is something that is unresolved in my mind. The Stack Overflow question Pointer to a specific fixed address tells me that even if 0 for null pointer is an abstraction, other pointer values aren't necessarily. This leads me to post another Stack Overflow question, Could I ever want to access the address zero?.
| 2 points:
only the constant value 0 in the source code is the null pointer - the compiler implementation can use whatever value it wants or needs in the running code. Some platforms have a special pointer value that's 'invalid' that the implementation might use as the null pointer. The C FAQ has a question, "Seriously, have any actual machines really used nonzero null pointers, or different representations for pointers to different types?", that points out several platforms that used this property of 0 being the null pointer in C source while represented differently at runtime. The C++ standard has a note that makes clear that converting "an integral constant expression with value zero always yields a null pointer, but converting other expressions that happen to have value zero need not yield a null pointer".
a negative value might be just as usable by the platform as an address - the C standard simply had to chose something to use to indicate a null pointer, and zero was chosen. I'm honestly not sure if other sentinel values were considered.
The only requirements for a null pointer are:
it's guaranteed to compare unequal to a pointer to an actual object
any two null pointers will compare equal (C++ refines this such that this only needs to hold for pointers to the same type)
|
2,760,167 | 2,760,215 | C++ to bytecode compiler for CLR? | I'd like to be able to compile a C/C++ library so that it runs within a managed runtime in the CLR. There are several tools for doing this with the JVM (NestedVM, LLJVM, etc) but I can't seem to find any for the CLR. Has anyone tried doing this?
| Microsoft already provides such a tool with Visual Studio. The C++ compiler cl.exe accepts the /clr option to tell it to generate managed code instead of native code. See the MSDN document How To: Migrate to /clr for information on changing your native project to support managed code.
|
2,760,180 | 2,760,204 | Is it possible to change a exe's icon without recompiling it? | I have lot of executable that I have compiled (long time back) for many of which I don't have sourcecode now. But when I compiled them I didn't put any icons for them, so they all look like same dull, bald default icon. So my questions are,
(1) is it possible for me to write a software that can change the resources section of the exe and change its looks? If so, can anyone plz point me to the location where its explained? (I am a beginner, I have no idea on the exe format and all)
Also its fun to keep changing Icons without having the pain of recompiling everything just for the icon change...
(2) This is raises a natural converse question, Is it similarly possible to zap out the icon used by some file and use it for some other file? (If so, plz point me to location where I can get some details.
I am a C/C++ developers and I am looking for solution on Windows Platform...
Regards,
MicroKernel
| It is possible to read and write resoures from an exe or DLL file. Reading the resources is easy(ish) - just use LoadLibraryEx(LOAD_AS_DATA_FILE) to load it, then you can enumerate the resources using the standard resource API's. All of this is documented on MSDN.
Writing the resources can also be done using the UpdateResource API and related functions.
You should bear in mind though that changing the resources of someone elses EXE file will invalidate any signing. Also, depending on OS resources is risky - windows has been known to remove resources without warning (since they are undocumented). Copying resources may not be legal too (although IANAL).
|
2,760,310 | 2,760,329 | How to resolve location of %UserProfile% programmatically in C++? | I'd like to find the directory of the current user profile programmatically in C++.
| SHGetSpecialFolderLocation is the best way to get at most of the special paths on Windows. Passed CSIDL_PROFILE it should retrieve the folder you are interested in.
If you are actually interested in the contents of the %UserProfile% environment variable you could try ExpandEnvironmentStrings
|
2,760,549 | 2,760,573 | C++ to bytecode compiler for Silverlight CLR? | I'd like to be able to compile a C/C++ library so that it runs within a safe managed runtime in the Silverlight CLR.
There are several tools for doing this with the JVM that allows C++ code to run within a CRT emulation layer (see NestedVM, LLJVM, etc), which effectively allows C++ code to be run within a Java Applet. There's even a tool for this for the Adobe Flash VM (see Alchemy).
However, I can't seem to find any tools like this for the CLR. fyi, the MSVC tools don't seem to allow for this: The /clr:pure flag will create C++ code that runs in the CLR, but it isn't safe (because the CRT isn't safe) and /clr:safe requires massive code changes (no native types, etc).
| Then I think you are plain out of luck. If your code can't use the /clr:safe flag then it won't be compilable into something that can run in Silverlight. If the C++ is doing something that the CLR does not allow or support, then there is no way around this directly.
Depending what your code does, you could possibly execute it on the server and call that from Silverlight via a web service?
|
2,760,692 | 2,760,798 | Sorting and displaying a custom QVariant type | I have a custom type I'd like to use with QVariant but I don't know how to get the QVariant to display in a table or have it sort in a QSortFilterProxyModel.
I register the type with Q_DECLARE_METATYPE and wrote streaming operators registered via qRegisterMetaTypeStreamOperators but for whatever reason when I use the type with a table model, it doesn't display anything and it doesn't sort.
I should specify that this custom type can not be modified. It has a copy and default constructor, but I can not go in and modify the source code to get it to work with QVariant. Is there a way of non-intrusively getting the behaviour I'd like?
| Display:
It sounds like your model isn't returning sensible content for the DisplayRole. The QAbstractItemDelegate (often a QStyledItemDelegate) that is used to display all content from the model needs to understand how to render the content of returned by data() for the Qt::DisplayRole.
You have two main options:
Modify your model so that it returns a sensible Qt::DisplayRole, OR
Subclass one of the existing delegates and modify it so that it can display your custom variant type correctly.
If you want to edit items of that type, you'll need to call registerEditor so you can associate your custom type to an editor. See the QItemEditorFactory documentation.
Sorting:
You can't rely on the comparison operator for QVariant as it doesn't work with custom types, so you'll need to implement QSortFilterProxyModel::lessThan to have custom sorting.
|
2,760,716 | 2,760,876 | Avoiding stack overflows in wrapper DLLs | I have a program to which I'm adding fullscreen post-processing effects. I do not have the source for the program (it's proprietary, although a developer did send me a copy of the debug symbols, .map format). I have the code for the effects written and working, no problems.
My issue now is linking the two.
I've tried two methods so far:
Use Detours to modify the original program's import table. This works great and is guaranteed to be stable, but the user's I've talked to aren't comfortable with it, it requires installation (beyond extracting an archive), and there's some question if patching the program with Detours is valid under the terms of the EULA. So, that option is out.
The other option is the traditional DLL-replacement. I've wrapped OpenGL (opengl32.dll), and I need the program to load my DLL instead of the system copy (just drop it in the program folder with the right name, that's easy).
I then need my DLL to load the Cg framework and runtime (which relies on OpenGL) and a few other things. When Cg loads, it calls some of my functions, which call Cg functions, and I tend to get stack overflows and infinite loops. I need to be able to either include the Cg DLLs in a subdirectory and still use their functions (not sure if it's possible to have my DLLs import table point to a DLL in a subdirectory) or I need to dynamically link them (which I'd rather not do, just to simplify the build process), something to force them to refer to the system's file (not my custom replacement).
The entire chain is: Program loads DLL A (named opengl32.dll). DLL A loads Cg.dll and dynamically links (GetProcAddress) to sysdir/opengl32.dll. I now need Cg.dll to also refer to sysdir/opengl32.dll, not DLL A.
How would this be done?
Edit: How would this be done easily without using GetProcAddress? If nothing else works, I'm willing to fall back to that, but I'd rather not if at all possible.
Edit2: I just stumbled across the function SetDllDirectory in the MSDN docs (on a totally unrelated search). At first glance, that looks like what I need. Is that right, or am I misjudging? (off to test it now)
Edit3: I've solved this problem by doing thing a bit differently. Instead of dropping an OpenGL32.dll, I've renamed my DLL to DInput.dll. Not only does it have the advantage of having to export one function instead of well over 120 (for the program, Cg, and GLEW), I don't have to worry about functions running back in (I can link to OpenGL as usual). To get into the calls I need to intercept, I'm using Detours. All in all, it works much better. This question, though, is still an interesting problem (and hopefully will be useful for anyone else trying to do crazy things in the future). Both the answers are good, so I'm not sure yet which to pick...
| SetDllDirectory probably won't work. Cg.dll likely just links to OpenGL.dll. When the OS loads Cg.dll, it sees that there's already a module loaded with that name (yours), so it links Cg with that instead of going off to find some other copy. That is, the search order that SetDllDirectory modifies never even comes into play because the OS doesn't do any searching.
I suspect your best bet will indeed be to detect re-entrant calls to your library. When you detect one, instead of doing your custom handling, forward the call directly to the real OpenGL library, which you have a reference to due to calling LoadLibrary and then GetProcAddress for each of the library's functions.
|
2,760,875 | 2,760,894 | How to use class templates as function arguments? | I have a class declared along the lines of
template<int a, int b>
class C {
public:
array[a][b];
}
and I want to use it as argument in a function like this:
bool DoSomeTests(C &c1, C &c2);
but when I compile, it tells me 'use of class template requires template argument list.' I tried
template<int a, int b>
bool DoSomeTests(C &c1, C &c2);
but I get the same error. How can I fix this?
| You need to provide arguments to the class template C in the declaration of DoSomeTests:
template<int a, int b>
bool DoSomeTests(C<a, b> &c1, C<a, b> &c2);
Both the class template C and your function template DoSomeTests take two int template parameters but the fact that you want to map them from the function template to C can't be inferred by the compiler.
|
2,761,045 | 2,761,061 | c++ strings and file input | Ok, its been a while since I've done any file input or string manipulation but what I'm attempting to do is as follows
while(infile >> word) {
for(int i = 0; i < word.length(); i++) {
if(word[i] == '\n') {
cout << "Found a new line" << endl;
lineNumber++;
}
if(!isalpha(word[i])) {
word.erase(i);
}
if(islower(word[i]))
word[i] = toupper(word[i]);
}
}
Now I assume this is not working because >> skips the new line character?? If so, whats a better way to do this.
| There is getline function.
|
2,761,242 | 2,761,307 | Test for external undefined references in Linux | Is there a built in linux utility that I can use to test a newly compiled shared library for external undefined references? Gcc seems to be intelligent enough to check for undefined symbols in my own binary, but if the symbol is a reference to another library gcc does not check at link time. Instead I only get the message when I try to link to my new library from another program.
It seems a little silly to get undefined reference messages in a library when I am compiling a different project so I want to know if I can do a check on all references internal and external when I build the library not when I link to it.
Example error:
make -C UnitTests debug
make[1]: Entering directory `~/projects/Foo/UnitTests`
g++ [ tons of objects ] -L../libbar/bin -lbar -o UnitTests
libbar.so: undefined reference to `DoSomethingFromAnotherLibrary`
collect2: ld returned 1 exit status
make[1]: *** [~/projects/Foo/UnitTests] Error 1
| Usually, undefined references are allowed when linking shared objects, but you can make the linker generate an error if there are undefined symbols in the object files that you are linking to create the shared library by supplying -z defs to the linker (or equivalently -Wl,-z,defs in the gcc command that calls the linker).
|
2,761,266 | 2,761,308 | Writing a C++ wrapper for a C library | I have a legacy C library, written in an OO type form. Typical functions are like:
LIB *lib_new();
void lib_free(LIB *lib);
int lib_add_option(LIB *lib, int flags);
void lib_change_name(LIB *lib, char *name);
I'd like to use this library in my C++ program, so I'm thinking a C++ wrapper is required.
The above would all seem to map to something like:
class LIB
{
public:
LIB();
~LIB();
int add_option(int flags);
void change_name(char *name);
...
};
I've never written a C++ wrapper round C before, and can't find much advice about it. Is this a good/typical/sensible approach to creating a C++/C wrapper?
| A C++ wrapper is not required - you can simply call the C functions from your C++ code. IMHO, it's best not to wrap C code - if you want to turn it into C++ code - fine, but do a complete re-write.
Practically, assuming your C functions are declared in a file called myfuncs.h then in your C++ code you will want to include them like this:
extern "C" {
#include "myfuncs.h"
}
in order to give them C linkage when compiled with the C++ compiler.
|
2,761,360 | 2,761,494 | Could I ever want to access the address zero? | The constant 0 is used as the null pointer in C and C++. But as in the question "Pointer to a specific fixed address" there seems to be some possible use of assigning fixed addresses. Is there ever any conceivable need, in any system, for whatever low level task, for accessing the address 0?
If there is, how is that solved with 0 being the null pointer and all?
If not, what makes it certain that there is not such a need?
| Neither in C nor in C++ null-pointer value is in any way tied to physical address 0. The fact that you use constant 0 in the source code to set a pointer to null-pointer value is nothing more than just a piece of syntactic sugar. The compiler is required to translate it into the actual physical address used as null-pointer value on the specific platform.
In other words, 0 in the source code has no physical importance whatsoever. It could have been 42 or 13, for example. I.e. the language authors, if they so pleased, could have made it so that you'd have to do p = 42 in order to set the pointer p to null-pointer value. Again, this does not mean that the physical address 42 would have to be reserved for null pointers. The compiler would be required to translate source code p = 42 into machine code that would stuff the actual physical null-pointer value (0x0000 or 0xBAAD) into the pointer p. That's exactly how it is now with constant 0.
Also note, that neither C nor C++ provides a strictly defined feature that would allow you to assign a specific physical address to a pointer. So your question about "how one would assign 0 address to a pointer" formally has no answer. You simply can't assign a specific address to a pointer in C/C++. However, in the realm of implementation-defined features, the explicit integer-to-pointer conversion is intended to have that effect. So, you'd do it as follows
uintptr_t address = 0;
void *p = (void *) address;
Note, that this is not the same as doing
void *p = 0;
The latter always produces the null-pointer value, while the former in general case does not. The former will normally produce a pointer to physical address 0, which might or might not be the null-pointer value on the given platform.
|
2,761,542 | 2,779,052 | Changes to data inside class not being shown when accessed from outside class | I have two classes, Car and Person. Car has as one of its members an instance of Person, driver. I want to move a car, while keeping track of its location, and also move the driver inside the car and get its location. However, while this works from inside the class (I have printed out the values as they are calculated), when I try to access the data from main, there's nothing there. I.e. the array position[] ends up empty. I am wondering if there is something wrong with the way I have set up the classes -- could it be a problem of the scope of the object?
I have tried simplifying the code so that I only give what is necessary. Hopefully that covers everything that you would need to see. The constructer Car() fills the offset array of driver with nonzero values.
class Car{
public:
Container(float=0,float=0,float=0);
~Container();
void move(float);
void getPosition(float[]);
void getDriverPosition(float[]);
private:
float position[3];
Person driver;
float heading;
float velocity;
};
class Person{
public:
Person(float=0,float=0,float=0);
~Person();
void setOffset(float=0,float=0,float=0);
void setPosition(float=0,float=0,float=0);
void getOffset(float[]);
void getPosition(float[]);
private:
float position[3];
float offset[3];
};
Some of the functions:
void Car::move(float time){
float distance = velocity*time;
location[0] += distance*cos(PI/2 - heading);
location[1] += distance*sin(PI/2 - heading);
float driverLocation [3];
float offset[3];
driver.getOffset(offset);
for (int i = 0; i < 3; i++){
driverLocation[i] = offset[i] + location[i];
}
driver.setPosition(driverLocation[0],driverLocation[1],driverLocation[2]);
}
void Car::getDriverPosition(float p[]){
driver.getPosition(p);
}
void Person::getPosition(float p[]){
for (int i = 0; i < 3; i++){
p[i] = position[i];
}
}
void Person::getOffset(float o[]){
for (int i = 0; i < 3; i++){
o[i] = offset[i];
}
}
In Main:
Car * car = new Car();
car->move();
float p[3];
car->getDriverPosition(p);
When I print driverLocation[] inside the move() function, I have actual nonzero values. When I print p[] inside main, all I get are zeros.
Newly found problem: Through some debugging, I've discovered every time that I call move() the destructor for Person class is called, and thus deletes all the data. Anyone have an idea about how this could happen? I don't call the destructor anywhere, how do I prevent it from happening.
| So I think that I figured it out. I think the problem was that I was passing the object by value into the move() function. I switched to passing it as a pointer to the object, and it worked!
|
2,761,570 | 2,761,601 | C++ std::vector memory/allocation | From a previous question about vector capacity, Mr. Bailey said:
In current C++ you are guaranteed that no reallocation occurs after a call to reserve until an insertion would take the size beyond the value of the previous call to reserve. Before a call to reserve, or after a call to reserve when the size is between the value of the previous call to reserve and the capacity the implementation is allowed to reallocate early if it so chooses.
So, if I understand correctly, in order to assure that no reallocation happens until capacity is exceeded, I must do reserve twice? Can you please clarify it?
I am using vector as a memory stack like this:
std::vector<double> memory;
memory.reserve(size);
memory.insert(memory.end(), matrix.data().begin(), matrix.data().end()); // smaller than size
memory.resize(memory.capacity(), 0);
I need to guarantee that reallocation does not happen in the above.
thank you.
ps: I would also like to know if there is a better way to manage memory stack in similar manner other than vector
| I think you're reading the statement wrong. Reserve is allowed to set capacity to a larger amount than what you reserved. The special language is to allow an implementation to reallocate if you're reserving more than you did the last time, but before you've reached the current capacity.
|
2,761,591 | 2,761,611 | error in assigning a const character to an unsigned char array in C++ | #include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
typedef unsigned long int WORD; /* Should be 32-bit = 4 bytes */
#define w 32 /* word size in bits */
#define r 12 /* number of rounds */
#define b 16 /* number of bytes in key */
#define c 4 /* number words in key */
/* c = max(1,ceil(8*b/w)) */
#define t 26 /* size of table S = 2*(r+1) words */
WORD S [t],L[c]; /* expanded key table */
WORD P = 0xb7e15163, Q = 0x9e3779b9; /* magic constants */
/* Rotation operators. x must be unsigned, to get logical right shift*/
#define ROTL(x,y) (((x)<<(y&(w-1))) | ((x)>>(w-(y&(w-1)))))
#define ROTR(x,y) (((x)>>(y&(w-1))) | ((x)<<(w-(y&(w-1)))))
void RC5_DECRYPT(WORD *ct, WORD *pt) /* 2 WORD input ct/output pt */
{
WORD i, B = ct[1], A = ct[0];
for (i = r; i > 0; i--)
{
B = ROTR(B - S[2 * i + 1], A)^A;
A = ROTR(A - S[2 * i], B)^B;
}
pt[1] = B - S[1]; pt[0] = A - S[0];
}
void RC5_SETUP(unsigned char *K) /* secret input key K 0...b-1] */
{
WORD i, j, k, u = w/8, A, B, L[c];
/* Initialize L, then S, then mix key into S */
for (i = b - 1, L[c - 1] = 0; i != -1; i--)
L[i/u] = (L[i/u] << 8) + K[i];
for (S[0] = P, i = 1; i < t; i++)
S[i] = S[i - 1] + Q;
for (A=B=i=j=k=0; k<3*t; k++,i=(i+1)%t,j=(j+1)%c) /* 3*t > 3*c */
{
A = S[i] = ROTL(S [i]+(A+B),3);
B = L[j] = ROTL(L[j]+(A+B),(A+B));
}
}
void printword(WORD A)
{
WORD k;
for (k=0 ;k<w; k+=8)
printf("%02.2lX",(A>>k)&0xFF);
}
int main()
{
WORD i, j, k, pt [2], pt2 [2], ct [2] = {0,0};
unsigned char key[b];
ofstream out("cpt.txt");
ifstream in("key.txt");
if (!in)
{
cout << "Cannot open file.\n";
return 1;
}
if (!out)
{
cout << "Cannot open file.\n";
return 1;
}
key="111111000001111";
RC5_SETUP(key);
ct[0]=2185970173;
ct[1]=3384368406;
for (i=1; i<2; i++)
{
RC5_DECRYPT(ct,pt2);
printf("\n plaintext ");
printword(pt[0]);
printword(pt[1]);
}
return 0;
}
When I compile this code i get two warnings and also an error saying that I cant assign a char value to my character array. Why is that?
| Change:
key="111111000001111";
to
strncpy((char *)key, "111111000001111", sizeof(key));
|
2,761,605 | 2,761,749 | Getting website source with C++ - content is repeated | So, I have this source:
#include <winsock2.h>
#include <windows.h>
#include <iostream>
#pragma comment(lib,"ws2_32.lib")
using namespace std;
int main (){
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2,2), &wsaData) != 0) {
cout << "WSAStartup failed.\n";
system("pause");
return 1;
}
SOCKET Socket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
struct hostent *host;
host = gethostbyname("www.newegg.com");
SOCKADDR_IN SockAddr;
SockAddr.sin_port=htons(80);
SockAddr.sin_family=AF_INET;
SockAddr.sin_addr.s_addr = *((unsigned long*)host->h_addr);
cout << "Connecting...\n";
if(connect(Socket,(SOCKADDR*)(&SockAddr),sizeof(SockAddr)) != 0){
cout << "Could not connect";
system("pause");
return 1;
}
cout << "Connected.\n";
send(Socket,"GET / HTTP/1.1\r\nHost: www.newegg.com\r\nConnection: close\r\n\r\n", strlen("GET / HTTP/1.1\r\nHost: www.newegg.com\r\nConnection: close\r\n\r\n"),0);
char buffer[10000];
int nDataLength;
while ((nDataLength = recv(Socket,buffer,10000,0)) > 0){
int i = 0;
while (buffer[i] || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
}
closesocket(Socket);
WSACleanup();
system("pause");
return 0;
}
Now, it works getting the source, however, it keeps repeating afterwards. For example:
Notice how it says , then continues? I was wondering how I can avoid that. I know I can limit the buffer, however is there a better solution? Thanks
| Try changing
while (buffer[i] || buffer[i] == '\n' || buffer[i] == '\r') {
cout << buffer[i];
i += 1;
}
to
for(; i != nDataLength; ++i)
cout << buffer[i];
It looks like you are reading past the end of the buffer into garbage data used by recv and friends. Nobody said the data returned had to be null terminated which is what the while loop assumes for correct behavior.
|
2,761,679 | 2,761,692 | Can anyone explain C++ exception specifications to me? | Can anyone explain Exception Specifications as used in C++ ?
When are they used (I have rarely seen it used in code)
What are the pros and cons (benefits/disadvantages) of using exception specifications?
| When are they used (I have rarely seen it used in code)
Hopefully never as they are deprecated in the next version of C++ due for standardization next year.
What are the pros and cons (benefits/disadvantages) of using exception specifications?
They provide a way for readers of your code to know exactly what exceptions a function is allowed to throw. The problem is, that if an unexpected exception (one not in the specification) is thrown, then the program will be terminated (by default).
|
2,761,918 | 2,761,921 | How do I use "this" in a member function? | I've written a member function of class Node to read a tree of Nodes in postfix order.
It will be called by the Node instance which is the root node of the tree.
So: N.postfix();
these appear to be illeagal:
*this->left.postfix();
*this->right.postfix();
What is the proper way to do this?
class Node
{
public:
const char *cargo;
int depth;
Node *left;
Node *right
void Node::postfix()
{
if (this==__nullptr)
{
return;
}
else
{
*this->left.postfix();
*this->right.postfix();
out<<*this->cargo<<"\n";
return;
}
};
| In a member function, you don't generally need to use this to access class members; you can simply use:
left->postfix();
etc.
If you have function parameters or other local variables that have the same name as a class member variable, you can use this to refer to the member variable, e.g.,
this->left->postfix();
The reason that your code is illegal is that it does not correctly treat left as a pointer. You need to dereference left using -> in order to access its members, as shown in the correct code here. (You could also use the equivalent (*left).postfix(), but that just makes you use more parentheses for no real benefit.)
The use of the indirection operator * at the start of the expression is also incorrect, because it is applied to the result of postfix() (i.e., it dereferences whatever is returned by postfix()). postfix() doesn't return anything, so it's an error. It is important to remember that the . and -> operators both have higher precedence than *.
|
2,762,017 | 2,762,022 | C++ Singleton Constructor and Destructor | Does it matter if the constructor/destructor implementation is provided in the header file or the source file? For example, which way is preferred and why?
Way 1:
class Singleton
{
public:
~Singleton() { }
private:
Singleton() { }
};
Way 2:
class Singleton
{
public:
~Singleton();
private:
Singleton();
};
In the source .cc file:
Singleton::Singleton()
{
}
Singleton::~Singleton()
{
}
Initially, I have the implementation in a source file, but I was asked to remove it. Does anyone know why?
| It does not matter, but usually it's better (in my humblest of opinions) to define them in the .cpp file, in order to hide the implementation from users of the class.
|
2,762,078 | 2,762,099 | Why is C++0x's `noexcept` checked dynamically? | I am curious about the rationale behind noexcept in the C++0x FCD. throw(X) was deprecated, but noexcept seems to do the same thing. Is there a reason that noexcept isn't checked at compile time? It seems that it would be better if these functions were checked statically that they only called throwing functions within a try block.
| If I remember throw has been deprecated because there is no way to specify all the exceptions a template function can throw. Even for non-template functions you will need the throw clause because you have added some traces.
On the other hand the compiler can optimize code that doesn't throw exceptions. See "The Debate on noexcept, Part I" (along with parts II and III) for a detailed discussion. The main point seems to be:
The vast experience of the last two decades shows that in practice, only two forms of exceptions specifications are useful:
The lack of an overt exception specification, which designates a function that can throw any type of exception:
int func(); //might throw any exception
A function that never throws. Such a function can be indicated by a throw() specification:
int add(int, int) throw(); //should never throw any exception
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.