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 |
|---|---|---|---|---|
3,040,498 | 3,070,102 | Determine when using the VC90 compiler in VS2010 instead of VS2008? | Is there a (Microsoft-specific) CPP macro to determine when I'm using the VC9 compiler in Visual Studio 2010 as opposed to Visual Studio 2008? _MSC_VER returns the compiler version, so with VS2010 multi-targeting feature, I'll get the same result as with VS2008.
The reason for wanting to know the difference is that I created a new VS2010 project which contains code removed from a larger project. I just left the VS2008 stuff "as is" since we're moving away from VS2008 "soon" anyway and I didn't want to go through the hassle of creating a vcproj file along with the new vcxproj.
For now, I've just defined my own macro to indicate whether the code is compiled into its own DLL or not; it works just fine, but it would be nice if there were something slightly more elegant.
| It seems there is no solution, a custom macro works even if it isn't quite as elegant as I would like.
|
3,040,738 | 3,048,534 | Good OpenGL tutorial for Linux/Ubuntu? | I'm looking for a good Ubuntu OpenGL tutorial for a friend who already knows how to use OpenGL in Windows. Can anyone recommend any?
| OpenGL is the same in Linux, Windows and MacOSX, the difference is the windowing system. If you just want to get quickly into building multi-platform OpenGL applications, take a look at GLUT (open-source alternatives, Ubuntu comes with freeglut). GLUT is source-compatible between operating systems, so you can compile the same code, without modifications (theoretically), in Windows and Linux.
If you need something more elaborate, you should start using either GTK+ or Qt to build your application GUI. GTK+ has a GtkGLExt extension that creates a widget that contains a OpenGL context you can draw. Qt comes with the QtOpenGL module, which provides the QGLWidget widget.
|
3,040,750 | 3,040,767 | How to set C++ environment variable in Linux ubuntu? | I just installed Ubuntu on my Virtualbox on Windows.
I was trying to install cmake and the installation guide in the cmake website asked me to do the following steps
./bootstrap
make
make install
But when I just did the ./bootstrap command I get the following list of errors, can anyone suggest me how I can set the C++ compiler on my system. As I just installed Ubuntu perhaps the C++ is not set currently.
Kindly help.
CMake 2.8.1, Copyright 2000-2009 Kitware, Inc.
C compiler on this system is: cc
Error when bootstrapping CMake:
Cannot find appropriate C++ compiler on this system.
Please specify one using environment variable CXX.
See cmake_bootstrap.log for compilers attempted.
Log of errors: /home/vikboy/Downloads/cmake-2.8.1/Bootstrap.cmk/cmake_bootstrap.log
| Install the build-essential packages via apt.
sudo apt-get install build-essential
|
3,040,868 | 3,040,875 | question about copy constructor | I have this class:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
};
and I have function which contains this row:
A *pa1 = new A(a2);
can somebody please explain what exactly is going on, when I call A(a2) compiler calls copy constructor or constructor, thanks in advance
| Assuming a2 is an instance of A, this calls the copy constructor.
It will call operator new to get dynamic memory for the object, then it will copy-construct a new object into the memory, then return a pointer to that memory.
|
3,040,893 | 3,040,907 | Passing template into boost function | template <class EventType>
class IEvent;
class IEventable;
typedef boost::function<void (IEventable&, IEvent&)> behaviorRef;
What is the right way for passing template class IEvent into boost function? With this code I get:
error: functional cast expression list treated as compound expression
error: template argument 1 is invalid
error: invalid type in declaration before ‘;’ token
| boost::function needs a type, so you cannot pass it a template's name, it has to be a template instance. So either use a specific instance
typedef boost::function<void (IEventable&, IEvent<SomeEventType>&)> behaviorRef;
or put the whole thing itself into a template:
template< typename EventType >
struct foo {
typedef boost::function<void (IEventable&, IEvent<EventType >&)> behaviorRef;
};
|
3,040,951 | 3,040,995 | Drawing filled circles as one vertex array using OpenGL? | Is there a way to draw many filled circles using one vertex array. Is there a way to draw a circle with triangles? I basically have hundreds of circles far apart from each other that need to be drawn but I feeling calling the vertex pointer for each circle is inefficient. I'd rather make 1 call for all circles if possible. Thanks
| Take a look at Instancing, that is esp. GL_EXT_draw_instanced
For your convenience: http://www.opengl.org/registry/specs/EXT/draw_instanced.txt
(Note: This extension requires at least GeForce 8 series. As an EXT, it should be supported by ATI/Intel as well, but I do not know the requirements there - Probably hardware that supports at least OpenGL 2.0 and GL_EXT_gpu_shader4)
|
3,040,976 | 3,041,165 | Linking to a C library compiled as C++ | I'm in linker paradise now. I have a C library which only compiles in Visual C++ (it probably works in gcc) if:
I compile it as C++ code
Define __cplusplus which results in all the declarations being enclosed in extern "C" { }
So, by doing this I have a static library called, say, bsbs.lib
Now, I have a C++ project called Tester which would like to call function barbar in declared in bsbs.h. All goes fine, until I try to link to bsbs.lib where I get the all-too-familiar:
Tester.obj : error LNK2001: unresolved external symbol _foofoo
And it always seems to be foofoo which cannot be resolved regardless of which function I call in Tester (barbar or anything else).
Update: I've expanded on Point 2 as requested. Thanks a lot for the help guys!
#ifndef _BSBS_H
#define _BSBS_H
/* Prevent C++ programs from name mangling these definitions. */
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <setjmp.h>
.......
.......
#ifdef __cplusplus
}
#endif
#endif /* _BSBS_H */
This is the "main" header file, so to speak. All the important functions are here. But there are other header files called by the bsbs.c file which are not enclosed in extern "C" {}.
Solved:
OK, this is quite weird, but I removed the extern C bit from the header file in bsbs, compiled it as a C++ project (even though all the files are .c and removed the __cplusplus define) and it worked! I got the idea after looking at the symbol list. Everything was mangled except the ones enclosed in extern C (doh) and it was asking for an unmangled symbol so I figured something was amiss.
| If you declare them as extern C in the lib (which is unnecessary, if you're calling them from C++), then they must be extern C in your headers.
|
3,041,240 | 3,060,071 | telnet client connection stops receiveing data, server is still sending | I'm Working in an embedded linux environment.
it launches a telnet daemon on startup which watches on a particular port and launches a program when a connection is received.
i.e.
telnetd -l /usr/local/bin/PROGA -p 1234
PROGA - will output some data at irregular intervals. When it is not outputting data, every X period of time it sends out a 'heartbeat' type string to let the client know that we are still active i.e. "heartbeat\r\n"
After a random amount of time, the client (use a linux version of telnet, launched by: telnet xxx.xxx.xxx.xxx 1234) will fail to receive the 'heartbeat\r\n'
The data the client sees:
heartbeat
heartbeat
heartbeat
...
heartbeat
[nothing, should have received heartbeat]
[nothing forever]
heartbeat is sent:
result = printf("%s", heartbeat);
checking result, it is always the length of heartbeat. Logging to syslog shows us that the printf() is executing with success at the proper intervals
I've since added in a tcdrain and fflush which both return success, but do not seem to help the situation.
Any help would be appreciated.
**UDPATE: got a wireshark capture from the server side. Very Clearly the heartbeat is being sent continuously. No Hicups, no delays. Found something interesting on the client though. The client in this test case (telnet on Ubuntu 9.04) seems to suddenly stop receiving heartbeat (as describes above). Wireshark confirms this, big pause in packets. Well, once the client had stopped receiving the heartbeat, pressing any keystroke (on the client) seems to trigger a spew of data from the client's buffer (all heartbeats). Wireshark on the client also shows this massive amount of data all in one packet.
Unfortunately I don't really know what this means. It this a line mode on/off thing? Line endings (\r\n) are very clearly coming through.
**Update 2: running netcat instead of telnetd, the problem is not reproducible.
| The first thing I would do is get out Wireshark and try to find out if the server is truly sending the message. It would be instructive to run Wireshark at the server as well as third party PC. Is there anything different about the last heartbeat?
Edit. Well, that was an interesting find on your client.
It seems like there's some sort of terminal thing in the way. You may want to use the netcat program rather than telnetd. netcat is designed for sending arbitrary data over a TCP session in raw mode, without any special formatting, and it has the ability to hook up an arbitrary process to a socket. On a Windows machine you can use PuTTY in raw mode to accomplish the same thing.
It may still be worth examining traffic with a third party between your client and server. The kernel may be optimizing away writes to the network and internally buffering data. That's the only way to ensure that what see is what's really happening on the wire.
|
3,041,249 | 3,041,264 | When are temporaries created as part of a function call destroyed? | Is a temporary created as part of an argument to a function call guaranteed to stay around until the called function ends, even if the temporary isn't passed directly to the function?
There's virtually no chance that was coherent, so here's an example:
class A {
public:
A(int x) : x(x) {printf("Constructed A(%d)\n", x);}
~A() {printf("Destroyed A\n");}
int x;
int* y() {return &x;}
};
void foo(int* bar) {
printf("foo(): %d\n", *bar);
}
int main(int argc, char** argv) {
foo(A(4).y());
}
If A(4) were passed directly to foo it would definitely not be destroyed until after the foo call ended, but instead I'm calling a method on the temporary and losing any reference to it. I would instinctively think the temporary A would be destroyed before foo even starts, but testing with GCC 4.3.4 shows it isn't; the output is:
Constructed A(4)
foo(): 4
Destroyed A
The question is, is GCC's behavior guaranteed by the spec? Or is a compiler allowed to destroy the temporary A before the call to foo, invaliding the pointer to its member I'm using?
| Temporary objects exist up until the end of the full expression in which they are created.
In your example, the A object created by A(4) will exist at least until the expression ends just after the return from the call to foo().
This behavior is guaranteed by the language standard:
Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception (C++03 §12.2/3).
The lifetime of the temporary may be extended by binding a reference to it (in which case its lifetime is extended until the end of the lifetime of the reference), or by using it as an initializer in a constructor's initializer list (in which case its lifetime is extended until the object being constructed is fully constructed).
|
3,041,262 | 3,146,626 | Most efficient way to draw circles for polygon outlines | I'm using OpenGL and was told I should draw circles at each vertex of my outline to get smoothness. I tried this and it works great. The problem is speed. It crippled my application to draw a circle at each vertex. I'm not sure how else to fix the anomaly of my outlines other than circles, but using display lists and trying with vertex array both were brutally slow. Thanks
see: Edges on polygon outlines not always correct
| One (perhaps too fancy) alternative is to draw a single polygon that bounds the circle (say, a quad), and then use a fragment program to discard the fragments. This would not be entirely trivial to write, but I would bet it's the fastest way.
You would simply pass the circle parameters to the fragment program and discard the fragment if the distance from the fragment center to the center of the circle is bigger than the desired radius.
|
3,041,312 | 3,042,193 | fastest way to crawl recursive ntfs directories in C++ | I have written a small crawler to scan and resort directory structures.
It based on dirent(which is a small wrapper around FindNextFileA)
In my first benchmarks it is surprisingy slow:
around 123473ms for 4500 files(thinkpad t60p local samsung 320 GB 2.5" HD).
121481 files found in 123473 milliseconds
Is this speed normal?
This is my code:
int testPrintDir(std::string strDir, std::string strPattern="*", bool recurse=true){
struct dirent *ent;
DIR *dir;
dir = opendir (strDir.c_str());
int retVal = 0;
if (dir != NULL) {
while ((ent = readdir (dir)) != NULL) {
if (strcmp(ent->d_name, ".") !=0 && strcmp(ent->d_name, "..") !=0){
std::string strFullName = strDir +"\\"+std::string(ent->d_name);
std::string strType = "N/A";
bool isDir = (ent->data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) !=0;
strType = (isDir)?"DIR":"FILE";
if ((!isDir)){
//printf ("%s <%s>\n", strFullName.c_str(),strType.c_str());//ent->d_name);
retVal++;
}
if (isDir && recurse){
retVal += testPrintDir(strFullName, strPattern, recurse);
}
}
}
closedir (dir);
return retVal;
} else {
/* could not open directory */
perror ("DIR NOT FOUND!");
return -1;
}
}
| There are some circumstances where such a speed is normal yes. First, using FindFirstFileA instead of FindFirstFileW is going to incur overhead for the conversion from UTF-16 to ANSI. Second, if you are going through directories that have not yet been accessed by the operating system, you will incur at least one seek penalty (about 16ms for most consumer hard drives), limiting your enumeration to well under 100 directory checks per second. This will get worse if the Master File Table on the given drive is badly fragmented.
Regarding number of files, it's going to depend more upon the number of files per directory than the number of files themselves.
|
3,041,329 | 3,041,349 | C++: Keep track of times function is called | Keeping track of how many times a function is called is easy when passing the counter as an argument into the function. It's also easy when returning a one from the called function. But, I do not want to go that route. The reason behind this is because it seems like bad programming (letting the function know too much information). Is there a better way to keep track of how many times this function has been called?
I'm just looking for concepts that I could study. Providing code examples is not neccessary, but might be helpful.
Edit: I'm not actually looking for profiling tools. Let me add some code to get my point across. Because scope for funcCounter ends in main, I have no way of getting back a variable from myFunction that will increment funcCounter. I could possibly return 1 from myFunction and then increment funcCounter that way, but this doesn't seem like very good programming. Is there another way to do it?
int main()
{
int funcCounter = 0;
char *mystring = "This is a silly function.";
myFunction(mystring);
cout << "Times function is called: " << funcCounter << endl;
return 0;
}
void myFunction(char *mystring)
{
cout << mystring << endl;
}
| Have a static variable in your function and keep incrementing it each time the function in called.
void my_Function(void) {
static unsigned int call_count = 0;
call_count++;
}
If you want to do it for debugging reasons, then there are tools like gcov which do this for you. (I'm pretty sure Microsoft doesn't have an alternative bundled with Microsoft Visual C++)
|
3,041,408 | 3,041,414 | Printing escape character | When I am given "d""\"/""b", I need to print out the statement character for character. (d, b, a slash, a backslash, and 5 quotes) in C++. The only errors that show now are the lines if(i.at(j)="\\") and else if(i.at(j)="\""). Also, how should the outside double apostrophes be excluded?
#include <iostream>
#include <cstdlib>
using namespace std;
int main (int argc, const char* argv[] )
{
string i= argv[1];
for (int j=0; j>=sizeof(i)-1; j++)
{
if(i.at(j)=='\\')
{
cout << '\\';
}
else if(i.at(j)=='\"')
{
cout << '\"';
}
else
{
cout << i.at(j);
}
}
return 0;
}
*Revision - OK so I corrected the double apostrophes to single apostrophes but the code always aborts on me.
| You've goofed up your equality testing (==, not =).
Also, start at index 1, and go until 1 less (2 less, by index) than the length of the string.
|
3,041,493 | 3,041,512 | Can't convert from 'int' to 'int *' | So I have these lines of code:
int maxY, maxX;
getmaxyx(stdscr, &maxY, &maxX);
It gives me the following error:
error C2440: '=' : cannot convert from 'int' to 'int *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast
twice for each time I use it. I'm not even using the = operator! The curses.h file is included. What am I doing wrong?
| getmaxyx is a macro, which doesn't take int*, but int.
It resolves to something like
getmaxyx(S,Y,X) -> X=s->X, Y=s->Y
try
getmaxyx(stdscr, maxY, maxX); // without the & operator
see http://opengroup.org/onlinepubs/007908775/xcurses/getmaxyx.html
|
3,041,507 | 3,041,542 | Any way to display C++ on a webpage? | Is there a relatively easy way to display the output of a C++ program on a webpage? And I don't mean manually, in other words, you see it on a webpage as it runs not as in I make a code tag and write it in myself.
EDIT: Just so everybody can get this clear I am going to post this up here. I am NOT trying to make a webpage in C++. Please excuse me if this sounds spiteful or anything but I am getting a lot of answers relating to that.
| Step one, get yourself a server-side language. Be that PHP, ASP, Python, Ruby, whatever. Get it set up so you can serve it.
Step two, find your language's exec equivalent. Practically all of them have them. It'll let you run a command as if it were from the command line, usually with arguments and capture the output. Here's PHP's:
http://php.net/manual/en/function.exec.php
Of course, if you're passing user-input as arguments, sanitise!
I've just seen that you accepted Scott's answer. I usually wouldn't chase up a SO thread so persistently but I fear you're about to make a mistake that you'll come to regret down the line. Giving direct access to your program and its own built-in server is a terrible idea for two reasons:
You waste a day implementing this built-in server and then getting it to persist and testing it
More importantly, you've just opened up another attack vector into your server. When it comes to security, keep it simple.
You're far better having your C++ app running behind another (mature) server side language as all the work is done for you and it can filter the input to keep things safe.
|
3,041,672 | 3,041,685 | In this example where is the C++ assignment operator used rather than the copy constructor? | As part of an ongoing process of trying to upgrade my C++ skills, I am trying to break some old habits. My old school C programmer inclination is to write this;
void func( Widget &ref )
{
Widget w; // default constructor
int i;
for( i=0; i<10; i++ )
{
w = ref; // assignment operator
// do stuff that modifies w
}
}
This works well. But I think the following is closer to best practice;
void func( Widget &ref )
{
for( int i=0; i<10; i++ )
{
Widget w = ref; // ??
// do stuff that modifies w
}
}
With my Widget class at least, this works fine. But I don't fully understand why. I have two theories;
1) The copy constructor runs 10 times.
2) The copy constructor runs once then the assignment operator runs 9 times.
Both of these trouble me a little. 2) in particular seems artificial and wrong. Is there a third possibility that I am missing ?
| Of course the copy constructor runs 10 times! When you iterate the for(;;) cycle, at each iteration the variables declared inside the braces will go out of scope. If Widget has a destructor, it will be called 10 times (possible performance hit).
|
3,041,673 | 3,041,734 | no match for operator= using a std::vector | I've got a class declared like this:
class Level
{
private:
std::vector<mapObject::MapObject> features;
(...)
};
and in one of its member functions I try to iterate through that vector like this:
vector<mapObject::MapObject::iterator it;
for(it=features.begin(); it<features.end(); it++)
{
/* loop code */
}
This seems straightforward to me, but g++ gives me this error:
src/Level.cpp:402: error: no match for ‘operator=’ in ‘it = ((const yarl::level::Level*)this)->yarl::level::Level::features.std::vector<_Tp, _Alloc>::begin [with _Tp = yarl::mapObject::MapObject, _Alloc = std::allocator<yarl::mapObject::MapObject>]()’
/usr/include/c++/4.4/bits/stl_iterator.h:669: note: candidates are: __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*,std::vector > >& __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*,std::vector > >::operator=(const __gnu_cxx::__normal_iterator<yarl::mapObject::MapObject*, ``std::vector<yarl::mapObject::MapObject, std::allocator<yarl::mapObject::MapObject> > >&)
Anyone know why this is happening?
| I'd guess that this part of the error describes your problem:
(const yarl::level::Level*)this
Is the member function in which this code is found a const-qualified member function? If so, you'll need to use a const_iterator:
vector<mapObject::MapObject>::const_iterator it;
If the member function is const-qualified, then only the const-qualified overloads of begin() and end() on the member vector will be available, and both of those return const_iterators.
|
3,041,680 | 3,041,689 | How to avoid integer overflow? | In the following C++ code, 32767 + 1 = -32768.
#include <iostream>
int main(){
short var = 32767;
var++;
std::cout << var;
std::cin.get();
}
Is there any way to just leave "var" as 32767, without errors?
| Yes, there is:
if (var < 32767) var++;
By the way, you shouldn't hardcode the constant, use numeric_limits<short>::max() defined in <limits> header file instead.
You can encapsulate this functionality in a function template:
template <class T>
void increment_without_wraparound(T& value) {
if (value < numeric_limits<T>::max())
value++;
}
and use it like:
short var = 32767;
increment_without_wraparound(var); // pick a shorter name!
|
3,041,759 | 3,041,786 | Template problems: No matching function for call | I'm trying to create a template class, and when I define a non-member template function, I get the "No matching function for call to randvec()" error.
I have a template class defined as:
template <class T>
class Vector {
T x, y, z;
public:
//constructors
Vector();
Vector(const T& x, const T& y, const T& z);
Vector(const Vector& u);
//accessors
T getx() const;
T gety() const;
T getz() const;
//mutators
void setx(const T& x);
void sety(const T& y);
void setz(const T& z);
//operations
void operator-();
Vector plus(const Vector& v);
Vector minus(const Vector& v);
Vector cross(const Vector& v);
T dot(const Vector& v);
void times(const T& s);
T length() const;
//Vector<T>& randvec();
//operators
Vector& operator=(const Vector& rhs);
friend std::ostream& operator<< <T>(std::ostream&, const Vector<T>&);
};
and the function in question, which I've defined after all those functions above, is:
//random Vector
template <class T>
Vector<double>& randvec()
{
const int min=-10, max=10;
Vector<double>* r = new Vector<double>;
int randx, randy, randz, temp;
const int bucket_size = RAND_MAX/(max-min +1);
temp = rand(); //voodoo hackery
do randx = (rand()/bucket_size)+min;
while (randx < min || randx > max);
r->setx(randx);
do randy = (rand()/bucket_size)+min;
while (randy < min || randy > max);
r->sety(randy);
do randz = (rand()/bucket_size)+min;
while (randz < min || randz > max);
r->setz(randz);
return *r;
}
Yet, every time I call it in my main function using a line like:
Vector<double> a(randvec());
I get that error. However, if I remove the template and define it using 'double' instead of 'T', the call to randvec() works perfectly. Why doesn't it recognize randvec()?
P.S. Don't mind the bit labeled voodoo hackery - this is just a cheap hack so that I can get around another problem I encountered.
| You defined your randvec as a function template, yet no function parameters depend on template parameter T (in fact randvec has no function parameters at all). This immediately means that it is impossible for the compiler to deduce the template argument T from the call to randvec(). You have to specify the template argument T for each call to randvec explicitly, as in
randvec<some_type>()
or, in your context
Vector<double> a( randvec<some_type>() );
This actually rises the question of why you decided to define your randvec as a function template, when nothing in randvec actually depends on the template parameter T. Why?
P.S. Returning a dynamically allocated object by reference... It can be made to work correctly, but it is still a very questionable practice. I don't see your entire code, but I'd guess that your
Vector<double> a( randvec<some_type>() );
leaks Vector<double> object allocated and returned by randvec.
|
3,041,811 | 3,041,817 | Pointer to 2D array. Why does this example work? | I have this code example, but I don't understand why changing the values in the array inside
outputUsingArray() are changing the original array.
I would have expected changing the values of the array in outputUsingArray() would only be for a local copy of the array.
Why isn't that so?
However, this is the behaviour I would like, but I don't understand why it work.
#include <stdlib.h>
#include <stdio.h>
void outputUsingArray(int array[][4], int n_rows, int n_cols) {
int i, j;
printf("Output Using array\n");
for (i = 0; i < n_rows; i++) {
for (j = 0; j < n_cols; j++) {
// Either can be used.
//printf("%2d ", array[i][j] );
printf("%2d ", *(*(array+i)+j));
}
printf("\n");
}
printf("\n");
array[0][0] = 100;
array[2][3] = 200;
}
void outputUsingPointer(int (*array)[4], int n_rows, int n_cols) {
int i, j;
printf("Output Using Pointer to Array i.e. int (*array)[4]\n");
for (i = 0; i < n_rows; i++) {
for (j = 0; j < n_cols; j++) {
printf("%2d ", *(*(array+i) + j ));
}
printf("\n");
}
printf("\n");
}
int main() {
int array[3][4] = { { 0, 1, 2, 3 },
{ 4, 5, 6, 7 },
{ 8, 9, 10, 11 } };
outputUsingPointer((int (*)[4])array, 3, 4);
outputUsingArray(array, 3, 4);
printf("0,0: %i\n", array[0][0]);
printf("2,3: %i\n", array[2][3]);
return 0;
}
| passing int[] is really passing the pointer to the first element of the array.
passing int* is passing the pointer to the first element of the array as well.
They're identical.
Since they're both pointing towards the same part of memory, changing one will change the other one.
|
3,041,890 | 3,041,899 | C++: Unknown pointer size when forward declaring (error C2036) | In a header file, I have forward declared two members of a namespace:
namespace Foo {
struct Odp
typedef std::vector<Odp> ODPVEC;
};
class Bar
{
public:
Foo::ODPVEC baz; // C2036
};
The error generated by the compiler is:
error C2036: 'Foo::Odp *': unknown size
I'm guessing this is an issue with forward declaring Odp. How can I get around this?
| Don't forward declare Odp. The compiler does not know what the type of std::vector<Odp> is, because Odp isn't yet declared. Give the compiler a full declaration for that class.
|
3,041,897 | 3,041,941 | Sorting a 2 dimensional array on multiple columns | I need to sort a 2 dimensional array of doubles on multiple columns using either C or C++. Could someone point me to the algorithm that I should use or an existing library (perhaps boost?) that has this functionality?
I have a feeling that writing a recursive function may be the way to go but I am too lazy to write out the algorithm or implement it myself if it has been done elsewhere. :-)
Thanks
| You can use std::sort (C++) or qsort (C or C++) to perform the sorting operation. The tricky part is that you need to define a custom comparison function for comparing your rows. For example:
bool compareTwoRows(double* rowA, double* rowB){
return ( (rowA[0]<rowB[0]) || ((rowA[0]==rowB[0])&&(rowA[1]<rowB[1])) );
}
// ...
double** two_dimensional_array = // ...
int rows = // ... number of rows ...
std::sort(two_dimensional_array,two_dimensional_array+rows,&compareTwoRows);
// ...
|
3,041,925 | 3,041,967 | Is Objective-C++ a totally different language from Objective-C? | As the title says... are they considered different languages? For example if you've written an application using a combination of C++ and Objective-C++ would you consider it to have been written in C++ and Objective-C, C++ and Objective-C++ or all three?
Obviously C and C++ are different languages even though C++ and C are directly compatible, how is the situation with Objective-C++ and Objective-C?
| Objective-C++ simply allows Objective-C and C++ code to be mixed (with caveats). It's not really a language on its own so much as a mechanism for allowing the two languages to intermix.
|
3,041,946 | 3,041,989 | How to integer-divide round negative numbers *down*? | Seems like whenever I divide a negative int by a positive int, I need it to round down (toward -inf), not toward 0. But both C# and C++ round toward 0.
So I guess I need a DivideDownward() method. I can write it in a few lines with a test for negative and so on, but my ideas seem klugey. So I'm wondering if I'm missing something and if you have an "elegant" way to round negative division downward.
| Note: this post produces incorrect results for input with a=-1. Please see other answers.
[c++]
This is probably what you meant by 'kludgey', but it's what I came up with.
int divideDown(int a, int b){
int r=a/b;
if (r<0 && r*b!=a)
return r-1;
return r;
}
In the if statement, I put r<0 - however I'm not sure if that's what you want. You may wish to change the if statement to
if (a<0 && b>0)
which would be consistent with your description "Seems like whenever I divide a negative int by a positive int ".
|
3,041,959 | 3,041,980 | Life Scope of Temporary Variable | #include <cstdio>
#include <string>
void fun(const char* c)
{
printf("--> %s\n", c);
}
std::string get()
{
std::string str = "Hello World";
return str;
}
int main()
{
const char *cc = get().c_str();
// cc is not valid at this point. As it is pointing to
// temporary string internal buffer, and the temporary string
// has already been destroyed at this point.
fun(cc);
// But I am surprise this call will yield valid result.
// It seems that the returned temporary string is valid within
// scope (...)
// What my understanding is, scope means {...}
// Is this valid behavior guarantee by C++ standard? Or it depends
// on your compiler vendor implementations?
fun(get().c_str());
getchar();
}
The output is :
-->
--> Hello World
Hello, may I know the correct behavior is guarantee by C++ standard, or it depends on your compiler vendor implementations? I have tested this under VC2008 and VC6. Works fine for both.
| See this question. The standard guarantees that a temporary lives until the end of the expression of which it is a part. Since the entire function invocation is the expression, the temporary is guaranteed to persist until after the end of the function invocation expression in which it is a part.
|
3,041,960 | 3,048,930 | Filling in gaps for outlines | I'm using an algorithm to generate quads. These become outlines. The algorithm is:
void OGLENGINEFUNCTIONS::GenerateLinePoly(const std::vector<std::vector<GLdouble>> &input,
std::vector<GLfloat> &output, int width)
{
output.clear();
if(input.size() < 2)
{
return;
}
int temp;
float dirlen;
float perplen;
POINTFLOAT start;
POINTFLOAT end;
POINTFLOAT dir;
POINTFLOAT ndir;
POINTFLOAT perp;
POINTFLOAT nperp;
POINTFLOAT perpoffset;
POINTFLOAT diroffset;
POINTFLOAT p0, p1, p2, p3;
for(unsigned int i = 0; i < input.size() - 1; ++i)
{
start.x = static_cast<float>(input[i][0]);
start.y = static_cast<float>(input[i][1]);
end.x = static_cast<float>(input[i + 1][0]);
end.y = static_cast<float>(input[i + 1][1]);
dir.x = end.x - start.x;
dir.y = end.y - start.y;
dirlen = sqrt((dir.x * dir.x) + (dir.y * dir.y));
ndir.x = static_cast<float>(dir.x * 1.0 / dirlen);
ndir.y = static_cast<float>(dir.y * 1.0 / dirlen);
perp.x = dir.y;
perp.y = -dir.x;
perplen = sqrt((perp.x * perp.x) + (perp.y * perp.y));
nperp.x = static_cast<float>(perp.x * 1.0 / perplen);
nperp.y = static_cast<float>(perp.y * 1.0 / perplen);
perpoffset.x = static_cast<float>(nperp.x * width * 0.5);
perpoffset.y = static_cast<float>(nperp.y * width * 0.5);
diroffset.x = static_cast<float>(ndir.x * 0 * 0.5);
diroffset.y = static_cast<float>(ndir.y * 0 * 0.5);
// p0 = start + perpoffset - diroffset
//p1 = start - perpoffset - diroffset
//p2 = end + perpoffset + diroffset
// p3 = end - perpoffset + diroffset
p0.x = start.x + perpoffset.x - diroffset.x;
p0.y = start.y + perpoffset.y - diroffset.y;
p1.x = start.x - perpoffset.x - diroffset.x;
p1.y = start.y - perpoffset.y - diroffset.y;
p2.x = end.x + perpoffset.x + diroffset.x;
p2.y = end.y + perpoffset.y + diroffset.y;
p3.x = end.x - perpoffset.x + diroffset.x;
p3.y = end.y - perpoffset.y + diroffset.y;
output.push_back(p2.x);
output.push_back(p2.y);
output.push_back(p0.x);
output.push_back(p0.y);
output.push_back(p1.x);
output.push_back(p1.y);
output.push_back(p3.x);
output.push_back(p3.y);
}
}
The problem is that there are then gaps as seen here:
http://img816.imageshack.us/img816/2882/eeekkk.png
There must be a way to fix this. I see a pattern but I just cant figure it out. There must be a way to fill the missing inbetweens.
Thanks
| EDIT: See my other answer.
Add a triangle connecting the "outside" (check the sign of the 2D 'cross product') vertexes with the center joint vertex.
If you want to get fancier you can do a 2D slerp to get a more rounded outer join, though this does cost correspondingly more triangles.
Also, if you're going to use lines that wide and so finely subdivided you might try simplifying them first to reduce overdraw/polycount.
|
3,041,984 | 3,042,007 | Where to begin with multi-threaded programming with c++? | I'm trying to implement my own IRC client as a personal proejct and I realized I needed a way to read and write from the socket at the same time. I realized I could have a reading thread which reads from the socket in the background and puts data in a queue and I could have another thread which writes data from a queue to the socket. However I have no idea on how to start with multithreaded programing or how to do it with c++. Where do I go from here?
| For C++ threads, boost::thread (which is the basis for the upcoming std::thread) is the best way to go. That said, while threads might be the correct solution for your particular case, I just wanted to throw it out there that select and non-blocking sockets are a common approach to interleaving the reading/writing and writing of multiple sockets without the need for threads. The boost::asio library wraps the functionality of select and non-blocking sockets in a cross-platform, C++ manner.
|
3,042,146 | 3,042,546 | boost::bind breaks strict-aliasing rules? | Using Boost 1.43 and GCC 4.4.3, the following code
boost::bind(&SomeObject::memberFunc, this, _1));
Generates the following warning
boost/function/function_base.hpp:321:
warning: dereferencing type-punned
pointer will break strict-aliasing
rules
What's the correct way to eliminate these warnings without setting -fno-strict-aliasing?
| Are you sure that you've got the right object matched with the class that the member function foo is in? In other words, in the code you posted, is the type of *this the same as SomeObject? Aliasing occurs when the compiler has to track multiple pointers of different types to the same raw data, which is why I suspect that the type of *this and SomeObject are not the same.
|
3,042,160 | 3,042,223 | What's wrong with my code? (pdcurses/getmaxyx) | It gives me an access violation on the getmaxyx line (second line in the main function) and also gives me these two warnings:
LINK : warning LNK4049: locally defined symbol "_stdscr" imported
LINK : warning LNK4049: locally defined symbol "_SP" imported
Yes, it's the same code as in another question I asked, it's just that I'm making it more clear. And yes, I have written programs with pdcurses before with no problems.
#include <time.h>
#include <curses.h>
#include "Ball.h"
#include "Paddle.h"
#include "config.h"
int main(int argc, char *argv[])
{
int maxY, maxX;
getmaxyx(stdscr, maxY, maxX);
Paddle *paddleLeft = new Paddle(0, KEY_L_UP, KEY_L_DOWN);
Paddle *paddleRight = new Paddle(maxX, KEY_R_UP, KEY_R_DOWN);
Ball *ball = new Ball(paddleLeft, paddleRight);
int key = 0;
initscr();
cbreak();
noecho();
curs_set(0);
while (key != KEY_QUIT)
{
key = getch();
paddleLeft->OnKeyPress(key);
paddleRight->OnKeyPress(key);
}
endwin();
return 0;
}
| It has been a long time since I have used curses, but I would guess you need to call initscr() before any other curses call like getmaxyx.
Also, you probably are also missing some error checking on the return of initscr and need to use the return values properly (perhaps you have to pass it on to other curses method?).
|
3,042,191 | 3,042,224 | Having trouble storing a CRTP based class in a vector | Im not sure if this can be done, im just delving into templates so perhaps my understanding is a bit wrong.
I have a Platoon of soldiers, the platoon inherits from a formation to pick up the formations properties, but because i could have as many formations as i can think of I chose to use the CRTP to create the formations, hoping that i could make a vector or array of Platoon to store the platoons in. but, of course, when i make a Platoon, it wont store it in the vector, "types are unrelated"
Is there any way around this ? i read about "Veneers" which are similar and that they work with arrays but i cant get it to work, perhaps im missing something.
here's some code: (sorry about the formatting, the code is here in my post but its not showing up for some reason )
template < class TBase >
class IFormation
{
public :
~IFormation(){}
bool IsFull()
{
return m_uiMaxMembers == m_uiCurrentMemCount;
}
protected:
unsigned int m_uiCurrentMemCount;
unsigned int m_uiMaxMembers;
IFormation( unsigned int _uiMaxMembers ): m_uiMaxMembers( _uiMaxMembers ), m_uiCurrentMemCount( 0 ){} // only allow use as a base class.
void SetupFormation( std::vector<MySoldier*>& _soldierList ){}; // must be implemented in derived class
};
/////////////////////////////////////////////////////////////////////////////////
// PHALANX FORMATION
class Phalanx : public IFormation<Phalanx>
{
public:
Phalanx( ):
IFormation( 12 ),
m_fDistance( 4.0f )
{}
~Phalanx(){}
protected:
float m_fDistance; // the distance between soldiers
void SetupFormation( std::vector<MySoldier*>& _soldierList );
};
///////////////////////////////////////////////////////////////////////////////////
// COLUMN FORMATINO
class Column : public IFormation< Column >
{
public :
Column( int _numOfMembers ):
IFormation( _numOfMembers )
{}
~Column();
protected:
void SetupFormation( std::vector<MySoldier*>& _soldierList );
};
I then use these formations in the platoon class to derive, so that platoon gets the relevant SetupFormation() function:
template < class Formation >
class Platoon : public Formation
{
public:
**** platoon code here
};
everything works great and as expected up until this point.
now, as my general can have multiple platoons, I need to store the platoons.
typedef Platoon< IFormation<> > TPlatoon; // FAIL
typedef std::vector<TPlatoon*> TPlatoons;
TPlatoon m_pPlatoons
m_pPlatoons.push_back( new Platoon<Phalanx> ); // FAIL, types unrelated.
typedef Platoon< IFormation<> > TPlatoon; fails because i need to specify a template parameter, yet specifying this will only allow me to store platoons created with the same template parameter.
so i then created FormationBase
class FormationBase
{
public:
virtual bool IsFull() = 0;
virtual void SetupFormation( std::vector<MySoldier*>& _soldierList ) = 0;
};
and made IFormation publicly inherit from that, and then changed the typedef to
typedef Platoon< IFormation< FormationBase > > TPlatoon;
but still no love.
now in my searches i have not found info that says this is possible - or not possible.
| C++ does not allow simple use of compile time and run time polymorphism. You are correct in that your vector is only able to hold one type. You're going to have to have your vector store a pointer to a non template type, or change the design to not use a vector.
If you want to have the CRTP'd classes publicly inherit from FormationBase, then the vector would have to be a std::vector<FormationBase *>. It's impossible to go back from the runtime class FormationBase to the compile time template parameters it was instantiated with.
Considering your data looks relatively consistent and you merely want to change how your algorithm arranges the soldiers and units on the battlefield, I'd consider using the strategy pattern to specify the SetupFormation function, and have a separate, nonpolymorphic class using that which you store in the vector.
|
3,042,249 | 3,042,266 | Pure virtual destructor in interface | Here is my problem: I'm making a C++ DLL which relies extensively on instance object exports.
So I return my actual instances as a pointers to an interface through some exported factory method.
The interfaces I use are purely virtual, to avoid linking problems. So I need a pure virtual destructor too, and I implemented one (with empty body, as I googled it).
All compiles perfectly well, except... I can't see if the actual destructors are called or not - because when I added some std::cout << "hello destructor"; I never get to see it.
I have some explicit "delete obj" (EDIT: and it is called from the "FreeObject" method inside the DLL), that's not the problem.
Am I missing something? Is there another way to delete my object through an interface?
EDIT: Again, I don't have memory management inconsistency, it's all inside the DLL. But the right destructor just isn't called.
| You shouldn't mix and match calls to new and delete across DLL boundaries.
Instead, I'd recommend the tried-and-true method that COM uses: AddRef and Release. When the reference count hits zero, Release calls delete this; from inside the DLL, ensuring that new and delete are matched.
|
3,042,296 | 3,048,136 | Tool used to retrieve code metrics in xUnit Test Patterns? | I'm reading xUnit Test Patterns by Gerard Meszaros.
On one of the pages he refers to some software metrics:
While the need to wrap lines to keep
them at 65 characters makes this code
look even longer than it really is, it
is still unnecessarily long. It
contains 25 executable statements
including initialized declarations, 6
lines of control statements, 4 in-line comments, and 2 lines to declare the test method—giving a total of 37 lines of unwrapped source code.
Short of counting the statements to find these metrics, does anybody have any idea if he used a particular tool to calculate the metrics?
(If you have any suggestions for tools that will count similar metrics, I'm looking for one that works on Java, Javascript and C++)
Thanks!
| Sorry to disappoint you but I did count by hand (well, by eye). It's only 25 lines of code! I just went through and counted semi-colons and subtracted lines that weren't acutally executed (like uninitialized variable declarations.)
The point is not exactly how many lines of code there are but rather how much fewer lines of code you need to write (once) and read/understand/modify (many times).
Gerard
|
3,042,543 | 3,042,569 | Porting Windows socket program to Unix: Alternative for winsock32 APIs in unix | In Socket Programming, how will a Unix thread receive a Socket CLOSE event from a client if connection is closed?
Are there any API's which will notify the unix thread about the CLOSE event received?
As in Windows we have WSAEnumNetworkEvents API which gets the event notification for a specified socket descriptor. What will be the equivalent API used in the Unix socket programing?
Please provide the help for the query.
| You can track the closure event when performing reading. The socket is closed when read returns 0 (talking about "Berkeley sockets" of course).
//EDIT:
Use poll or select to wait for some event to occur (data arrival, socket closure ...).
|
3,042,873 | 3,042,878 | C++ pointers and constructors |
Possible Duplicate:
question about copy constructor
if I have this snippet of the code
A a1(i);
A a2 = a1;
A *pa1 = new A(a2);
can somebody please explain what exactly the last line does, it makes copy of the a2 and pointer for this new object is pa1 or it just creates pointer for a2, thanks in advance
| The last line creates a new object A, to which pa1 points, and its contents are the same as those of a2.
I believe this example demonstrates the use of a constructor with arguments (first line), a copy constructor (second line) and another copy constructor (last line). In the end all the three object will have the same contents.
|
3,042,925 | 3,043,425 | strange results with /fp:fast | We have some code that looks like this:
inline int calc_something(double x) {
if (x > 0.0) {
// do something
return 1;
} else {
// do something else
return 0;
}
}
Unfortunately, when using the flag /fp:fast, we get calc_something(0)==1 so we are clearly taking the wrong code path. This only happens when we use the method at multiple points in our code with different parameters, so I think there is some fishy optimization going on here from the compiler (Microsoft Visual Studio 2008, SP1).
Also, the above problem goes away when we change the interface to
inline int calc_something(const double& x) {
But I have no idea why this fixes the strange behaviour. Can anyone explane this behaviour? If I cannot understand what's going on we will have to remove the /fp:fastswitch, but this would make our application quite a bit slower.
| I'm not familiar enough with FPUs to comment with any certainty, but my guess would be that the compiler is letting an existing value that it thinks should be equal to x sit in on that comparison. Maybe you go y = x + 20.; y = y - 20; y is already on the FP stack, so rather than load x the compiler just compares against y. But due to rounding errors, y isn't quite 0.0 like it is supposed to be, and you get the odd results you see.
For a better explanation: Why is cos(x) != cos(y) even though x == y? from the C++FAQ lite. This is part of what I'm trying to get across, I just couldn't remember where exactly I had read it until just now.
Changing to a const reference fixes this because the compiler is worried about aliasing. It forces a load from x because it can't assume its value hasn't changed at some point after creating y, and since x is actually exactly 0.0 [which is representable in every floating point format I'm familiar with] the rounding errors vanish.
I'm pretty sure MS provides a pragma that allows you to set the FP flags on a per-function basis. Or you could move this routine to a separate file and give that file custom flags. Either way, it could prevent your whole program from suffering just to keep that one routine happy.
|
3,042,972 | 3,043,000 | transferring parameters in C++ | can I have this snippet of the code:
C *pa1 = new C(c2);
and I transfer it to another function:
foo(pa1);
what exactly do I transfer actual pointer or its copy, thanks in advance
and can somebody give some info about in which cases info is copied, and in which I transfer actual pointer
declaration of foo:
foo(A const *pa)
| Assuming foo is declared as:
void foo(C* p);
you are passing a copy of the pointer.
This means, if foo does this:
p = &some_other_object;
that change to the pointer won't be seen by the caller.
It also means we're copying the pointer, not the thing pointed to. If foo does this:
p->bar = "Smurf!"
pa1 in the caller will also see the change. For this reason, pointers are often used to implement a kind of pass-by-reference.
If foo were declared:
void foo(C*& p);
then p would be a reference to pa1, and changes to p would result in changes to pa1. Historically, this has also been implemented using pointers to pointers:
void foo(C** p);
in which case you call foo like this:
foo(&pa1);
and foo can do something like:
*p = &some_other_object;
to change what pa1 points to.
|
3,043,214 | 3,043,318 | How to define and use a friend function to a temlate class with the same template? | I have written the following code:
#include <iostream>
using namespace std;
template <class T>
class AA
{
T a;
public:
AA()
{
a = 7;
}
friend void print(const AA<T> & z);
};
template <class T>
void print(const AA<T> & z)
{
cout<<"Print: "<<z.a<<endl;
}
void main()
{
AA<int> a;
print<int>(a);
}
And getting the following error:
error C2248: 'AA<T>::a' : cannot access private member declared in class 'AA<T>'
1> with
1> [
1> T=int
1> ]
1> c:\users\narek\documents\visual studio 2008\projects\aaa\aaa\a.cpp(7) : see declaration of 'AA<T>::a'
1> with
1> [
1> T=int
1> ]
1> c:\users\narek\documents\visual studio 2008\projects\aaa\aaa\a.cpp(30) : see reference to function template instantiation 'void print<int>(const AA<T> &)' being compiled
1> with
1> [
1> T=int
1> ]
What's wrong?
P.S. I am using Visual Studio 2008.
| The problem is that when you do something like
template<class T>
class AA {friend void print(const AA<T>&);};
and you instantiate AA with like this
AA<int> a;
the friend declaration will be instantiated like
friend void print(const AA<int>&);
which is a non-template function! This means the compiler will not match the friend declaration with your print function.
The solution is basically to declare print before AA and explicitly tell the compiler that your friend declaration is talking about a template function. Like this:
#include <iostream>
using namespace std;
//forward declare AA because print needs it
template<class T>
class AA;
//declare print before AA to make the friend declaration
//match with this function
template<class T>
void print(const AA<T> & z);
template <class T>
class AA
{
//the <> is needed to make sure the compiler knows we're
//dealing with a template function here
friend void print<>(const AA<T> & z);
public:
AA() {a = 7;}
private:
T a;
};
//implement print
template<class T>
void print(const AA<T> & z)
{
cout<<"Print: "<<z.a<<endl;
}
int main()
{
AA<int> a;
print(a);
}
It is interesting to see what happens if you do not add the <> in the friend declaration. You will get a linker error. Why? Well, because the compiler cannot match the friend declaration with your template print function, it will implicitly assume a function with prototype
void print(const AA<int>&);
exists. Since I didn't explicitly provide a template parameter to the call to print (which isn't necessary because the compiler should be able to deduce this), the compiler will match this call with the function declared as friend. This function is nowhere implemented, hence the linker error.
|
3,043,219 | 3,043,239 | possible implementations of casting in c++ | I have this snippet of the code in my header:
class A {
private:
int player;
public:
A(int initPlayer = 0);
A(const A&);
A& operator=(const A&);
~A();
void foo() const;
friend int operator==(const A& i, const A& member) const;
};
implementation of the operator==
int operator==(const A& i, const A& member) const{
if(i.player == member.player){
return 1;
}
return 0;
}
and I need casting for this part of my code:
i - is some int, which my function receives
A *pa1 = new A(a2);
assert(i == *pa1);
I receive an error non-member function, How can I fix it? thanks in advance
| Your error is nothing to do with casting or user-defined conversions.
You can't have a const qualification on a function that isn't a member function so this:
int operator==(const A& i, const A& member) const;
should be this:
int operator==(const A& i, const A& member);
|
3,043,294 | 3,120,484 | How to build a VS2010 C++ Project on a BuildServer | I've a .NET Solution with a managed C++ assemlby Targeting .NET 3.5 created with VS2010. The command:
%windir%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln
compiles the solution on my dev machine.
On my BuildServer I get this error:
Build FAILED.
"F:\CruiseControl.NET\Projects\MyProject\MyProject.sln"
(default target) (1) ->
"F:\CruiseControl.NET\Projects\MyProject\MyProject\MyProject.csproj"
(default target) (2) ->
"F:\CruiseControl.NET\Projects\MyProject\MyProjectMAPIHelper\MyProjectMAPIHelper.vcxproj"
(default target) (3) ->
F:\CruiseControl.NET\Projects\MyProject\MyProjectMAPIHelper\MyProjectMAPIHelper.vcxproj(23,3):
error MSB4019: The imported project
"C:\Program
Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.Default.props"
was not found. Confirm that the path
in the <Import> declaration is
correct, and that the file exists on
disk.
0 Warning(s)
1 Error(s)
On my dev machine the claimed file
"C:\Program Files\MSBuild\Microsoft.Cpp\v4.0\Microsoft.Cpp.Default.props"
exists. On my build server not.
When I try to copy this files (and all others in the same directory) other errors occurred. So this is the wrong way.
EDIT: other errors means: When I copy the file "Microsoft.Cpp.Default.props" on the build server, MSBuild is claiming other files. That shows me, that just doing a copy of missing files is not what the build environment is expecting. I am looking for an MSI/whatever package that I could install on my build server and any C++ Project will build. Installing the SDK did not the trick. Or I did something wrong during SDK installation. Or it is not possible to compile Managed C++ VS2010 Solutions just with the SDK.
I believe that "other errors" has nothing to do with my problem. My Problem is: "How do I setup my build environment correctly". /EDIT
What I've done till now:
I have installed the latest Win7 SDK (Link)
I am targeting .net 3.5
I've tried playing with the Platform Toolset Property - but it was just playing
In my solution there is a managed C++ Assembly (my Problem)
I am using MSBuild 4.0 because the new VS2010 project files cannot be compiled with MSBuild 3.5
I am using CC.NET. compilation fails in CC.NET and on the command line. So it should not be a CC.NET issue.
Are there any tips and tricks how to configure my project properly to compile on my dev machine with VS2010 and on my build server? Is there anything more to install (except VS2010)?
Thanks, Arthur
| For now, installing VS 2010 is your only safe option. The Windows SDK will be updated to enable your scenario, but I don't have a specific release date. Until then, you'll need to install VS 2010 with the C++ tools in order to build your 2010 solution with C++ projects. Make sure you let the C++ team know about how dissatisfaction with this situation via their team blog and/or MSDN Forum.
Even after installing VS 2010, you may need to invoke the appropriate vcvars*.bat file to setup your environment variables correctly.
|
3,043,339 | 3,043,387 | Project Euler Problem #11 | Source: http://projecteuler.net/index.php?section=problems&id=11
Quick overview: Take a 20x20 grid of numbers and compute the largest product of 4 pairs of numbers in either horizontal, vertical, or diagonal.
My current approach is to divide the 20x20 grid up into single rows and single columns and go from there with a much more manageable grid. The code I'm using to divide the rows into rows is
void fillRows
( string::const_iterator& fieldIter,
list<int>& rowElements,
vector<list<int>>& rows )
{
// fieldIter is already initialized.
int count(0);
for( ; fieldIter < field.end(); ++fieldIter )
{
if(isdigit(field[*fieldIter]))
{
rowElements.push_back(toInt(field[*fieldIter]));
++count;
}
if(count == 40)
{
rows.push_back(rowElements);
count = 0;
rowElements.clear();
}
}
}
Short explanation:
I have the field set as static const std::string field and I am filling a vector with lists of rows. Why a list? Because the queue doesn't have a clear function. Also practice using STL container lists and not ones I write myself.
However, this thing isn't working. Oftentimes I see it omitting a character( function toInt parses the const char as int ) and I end up with 18 rows, two rows short of the 20x20 grid. The length of the rows seem good.
Rows: 18
RowElements[0]: 40 (instead of pairs I saved each number individually. Will fix that later)
What am I doing wrong?
| You know the grid is 20x20, so just paste it into a text file and read it like you would normally read a matrix:
for (int i = 0; i < 20; ++i)
for (int j = 0; j < 20; ++j)
inFile >> mat[i][j];
Then do the obvious: for each element [i][j], go 4 elements down, 4 to the right, 4 diagonally to the right and 4 diagonally to the left and find the product. If you can't get 4 elements because of boundaries, ignore those you can get.
There's no need to complicate this like you seem to be doing. Keep it simple, because this is a simple problem, and if you overthink it you will only make your life harder.
|
3,043,487 | 3,043,590 | Compile C++ code via C# class in Visual Studio | I use this method to compile C++ file in VS. But even i provide the correct file it returns false. Can any one help me...
This is class called CL
class CL
{
private const string clexe = @"cl.exe";
private const string exe = "Test.exe", file = "test.cpp";
private string args;
public CL(String[] args)
{
this.args = String.Join(" ", args);
this.args += (args.Length > 0 ? " " : "") + "/Fe" + exe + " " + file;
}
public Boolean Compile(String content, ref string errors)
{
if (File.Exists(exe))
File.Delete(exe);
if (File.Exists(file))
File.Delete(file);
File.WriteAllText(file, content);
Process proc = new Process();
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.FileName = clexe;
proc.StartInfo.Arguments = this.args;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
//errors += proc.StandardError.ReadToEnd();
errors += proc.StandardOutput.ReadToEnd();
proc.WaitForExit();
bool success = File.Exists(exe);
return success;
}
}
This is my button click event
private void button1_Click(object sender, EventArgs e)
{
string content = "#include <stdio.h>\nmain(){\nprintf(\"Hello world\");\n}\n";
string errors = "";
CL k = new CL(new string[] { });
if (k.Compile(content, ref errors))
Console.WriteLine("Success!");
else
MessageBox.Show("Errors are : ", errors);
}
| In your Visual Studio installation folder there should be the following path:
VC\bin\x86_amd64\1033\1033
There should be a clui.dll in this path. Copy it to the parent folder (VC\bin\x86_amd64\1033). This should solve your problem.
I took the solution from http://connect.microsoft.com/VisualStudio/feedback/details/108528/command-line-issue-when-building-for-64bit-in-32bit-with-cl-exe:
|
3,043,519 | 3,043,551 | How to const declare the this pointer sent as parameter | I want to const declare the this pointer received as an argument.
static void Class::func(const OtherClass *otherClass)
{
// use otherClass pointer to read, but not write to it.
}
It is being called like this:
void OtherClass::func()
{
Class::func(this);
}
This does not compile nad if i dont const declare the OtherClass pointer, I can change it.
Thanks.
| You cannot define static class memberv functions like this:
static void Class::func(const OtherClass *otherClass)
{
// use otherClass pointer to read, but not write to it.
}
The function must be declared static in the class declaration, and then the function definition looks like:
void Class::func(const OtherClass *otherClass)
{
// use otherClass pointer to read, but not write to it.
}
|
3,043,625 | 3,043,637 | C++ Arrays of Structure access | I'm studying C++ from Schildt's book and don't quite understand what does he mean under third structure; Can somebody explain this ->
To access a specific structure within
an array of structures, you must index
the structure name. For example, to
display the on_hand member of the
third structure, you would write
cout << invtry[2].on_hand;
Some code:
struct type{
char item[40];
double cost;
double retail;
int on_hand;
int lead_time;
}invtry[SIZE];
| The third structure in an array of structures is the one placed in the third position in the array, i.e., the one with index 2.
In your (ugly) code, invtry is declared as an array (of size SIZE) of structures of type type. Hence invtry[0] is the first element, invtry[1] the second, and invtry[2] the third - assuming, of course, SIZE >= 3.
Normally, you would write:
struct type{
char item[40];
double cost;
double retail;
int on_hand;
int lead_time;
};
const int SIZE = 500;
type invtry[SIZE];
This is synonymous to what you wrote, except for the definition of SIZE of course. But it leads to less confusion - in one part you say what a type (terrible name for the struct!) is - in other words, you define the type type. Later, you create an array of structs of type type, called invtry.
Doing this in the same line, as the author did, is simply awful - to my eyes.
Now you have an array of 500 structs. If "type" was "Product", you would have an array representing 500 products. Each one with its item, cost, retail, etc.
To access the third struct in the array, write invtry[2]. to access its particular on_hand field, write invtry[2].on_hand. This has nothing to do with the specific position of on_hand in the layout of the defined type.
If you want the lead_time of the third structure, first access the third structure and then its lead_time member: invtry[2].lead_time.
Of course since type does not have a default (parameterless) constructor, the 500 products are uninitialized - you have garbage in them. But that is your problem.
|
3,043,971 | 3,044,450 | Refactoring a leaf class to a base class, and keeping it also a interface implementation | I am trying to refactor a working code. The code basically derives an interface class into a working implementation, and I want to use this implementation outside the original project as a standalone class.
However, I do not want to create a fork, and I want the original project to be able to take out their implementation, and use mine. The problem is that the hierarchy structure is very different and I am not sure if this would work. I also cannot use the original base class in my project, since in reality it's quite entangled in the project (too many classes, includes) and I need to take care of only a subdomain of the problems the original project is.
I wrote this code to test an idea how to implement this, and while it's working, I am not sure I like it:
#include <iostream>
// Original code is:
// IBase -> Derived1
// I need to refactor Derive2 to be both indipendet class
// and programmers should also be able to use the interface class
// Derived2 -> MyClass + IBase
// MyClass
class IBase {
public:
virtual void printMsg() = 0;
};
///////////////////////////////////////////////////
class Derived1 : public IBase {
public:
virtual void printMsg(){ std::cout << "Hello from Derived 1" << std::endl; }
};
//////////////////////////////////////////////////
class MyClass {
public:
virtual void printMsg(){ std::cout << "Hello from MyClass" << std::endl; }
};
class Derived2: public IBase, public MyClass{
virtual void printMsg(){ MyClass::printMsg(); }
};
class Derived3: public MyClass, public IBase{
virtual void printMsg(){ MyClass::printMsg(); }
};
int main()
{
IBase *o1 = new Derived1();
IBase *o2 = new Derived2();
IBase *o3 = new Derived3();
MyClass *o4 = new MyClass();
o1->printMsg();
o2->printMsg();
o3->printMsg();
o4->printMsg();
return 0;
}
The output is working as expected (tested using gcc and clang, 2 different C++ implementations so I think I am safe here):
[elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1
Hello from Derived 1
Hello from MyClass
Hello from MyClass
Hello from MyClass
[elcuco@pinky ~/src/googlecode/qtedit4/tools/qtsourceview/qate/tests] ./test1.clang
Hello from Derived 1
Hello from MyClass
Hello from MyClass
Hello from MyClass
The question is
My original code was:
class Derived3: public MyClass, public IBase{
virtual void IBase::printMsg(){ MyClass::printMsg(); }
};
Which is what I want to express, but this does not compile. I must admit I do not fully understand why this code work, as I expect that the new method Derived3::printMsg() will be an implementation of MyClass::printMsg() and not IBase::printMsg() (even tough this is what I do want).
How does the compiler chooses which method to re-implement, when two "sister classes" have the same virtual function name?
If anyone has a better way of implementing this, I would like to know as well :)
| The answer is, compiler overrides both functions, as can be shown by this sample:
#include <cstdio>
using std::printf;
class A {
public:
virtual void a() {
printf("A::a\n");
}
};
class B {
public:
virtual void a() {
printf("B::a\n");
}
};
class C : public A, public B {
public:
virtual void a() {
printf("C::a\n");
A::a();
B::a();
}
};
int main() {
C c;
A &a = c;
B &b = c;
printf("Calling C::a via A\n");
a.a();
printf("Calling C::a via B\n");
b.a();
}
The output is:
Calling C::a via A
C::a
A::a
B::a
Calling C::a via B
C::a
A::a
B::a
If you want to override one and not the other, you need to rename it. Not only it will do what you want, but it will be clearer as well.
|
3,044,036 | 3,044,132 | is this possible with activex controls? | I'm developing an Activex controller for IE7.
I want to check version of flash+svg and install it if missing or old, and also change some settings in IE like setting up the printer to use landscape format..
I'm completly new to activex, so i'm trying to figure out how to do it, can you please post some pointers ? is what i'm trying to do possible with activex controls ?
Thanks
| Starting with Windows Vista, IE7 will run in Protected Mode (unless User Account Control is disabled) so the browser will run in a sandbox with very low rights. It prevents exactly what you're trying to do. You can override it only if you have full control of the target systems (i.e. using policies) but in this case you don't have to use this "trojan horse" method to deploy Flash...
|
3,044,177 | 3,044,187 | push_back private vectors with 2 methods, one isn't working | I have a class with a private vector of doubles.
To access or modify these values, at first I used methods such as
void classA::pushVector(double i)
{
this->vector.push_back(i);
}
double classA::getVector(int i)
{
return vector[i];
}
This worked for a while until I found I would have to overload a lot of operators for what I needed, so I tried to change it to get and set the vector directly instead of the values, i.e.
void classA::setVector(vector<double> vector)
{
this->vector = vector;
}
vector<double> classA::getVector()
{
return vector;
}
Now, say there is a classB, which has a private classA element, which also has get and set methods to read and write. The problem was when I tried to push back a value to the end vector in classA.
void classB::setFirstValue(double first)
{
this->getClassA().getVector().push_back(first);
}
This does absolutely nothing to the vector. It remains unchanged and I can't figure out why... Any ideas?
| You are returning the vector by value in your getVector(). This means that in your call "this->getClassA().getVector().push_back(first);", you copy the vector, then you push the element on the copy. The copy is then immediately discarded.
In order to get it work the way you want, you need to return the vector by reference. Your method will look like:
"vector & classA::getVector()"
|
3,044,386 | 3,044,495 | Segmentation fault on writing char to char* address | I've got problem with my little C program. Maybe you could help me.
char* shiftujVzorku(char* text, char* pattern, int offset){
char* pom = text;
int size = 0;
int index = 0;
while(*(text + size) != '\0'){
size++;
}
while(*(pom + index) != '\0'){
if(overVzorku(pom + index, pattern)){
while(*pattern != '\0'){
//vyment *pom s *pom + offset
if(pom + index + offset < text + size){
char x = *(pom + index + offset);
char y = *(pom + index);
int adresa = *(pom + index + offset);
*(pom + index + offset) = y; // SEGMENTATION FAULT
*(pom + index) = x;
//*pom = *pom - *(pom + offset);
//*(pom + offset) = *(pom + offset) + *pom;
//*pom = *(pom + offset) - *pom;
}
else{
*pom = *pom - *(pom + offset - size);
*(pom + offset - size) = *(pom + offset - size) + *pom;
*pom = *(pom + offset - size) - *pom;
}
pattern++;
}
break;
}
index++;
}
return text;
}
Isn't important what's the programm doing. Maybe there's lot of bugs. But, why do I get SEGMENTATION FAULT (for destination see code) at this line? I'm, trying to write some char value to memory space, with help of address "pom + offset + index". Thanks for everything helpful. :)
| Are you by any chance calling the code like this:
shiftujVzorku( "foobar", "xx", 0 );
If so, your code attempts to write to a character literal, which is illegal in C. You should rather do:
char buf[] = "foobar";
shiftujVzorku( buf, "xx", 0 );
|
3,044,484 | 3,044,539 | Same socket getting created | I have this piece of code where a server socket is created and is set to listen on a particular port number say 5005. Now once the accept socket function returns the socket that gets created is copied into the m_Socket variable and finally i shutdown the server socket named SocServer which was created locally.
Now my question
Is it possible that the SocServer(created initially) and m_Socket(copied when accept returns) get the same number say 1500.
struct sockaddr_in ServerSock; // Socket address structure to bind the Port Number to listen to
char *localIP ;
SOCKET SocServer;
//To Set up the sockaddr structure
ServerSock.sin_family = AF_INET;
ServerSock.sin_addr.s_addr = INADDR_ANY
ServerSock.sin_port = htons(PortNumber);//port number of 5005
// To Create a socket for listening on PortNumber
if(( SocServer = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET )
{
return FALSE;
}
//To bind the socket with wPortNumber
if(bind(SocServer,(sockaddr*)&ServerSock,sizeof(ServerSock))!=0)
{
return FALSE;
}
// To Listen for the connection on wPortNumber
if(listen(SocServer,SOMAXCONN)!=0)
{
return FALSE;
}
// Structure to get the IP Address of the connecting Entity
sockaddr_in insock;
int insocklen=sizeof(insock);
//To accept the Incoming connection on the wPortNumber
m_Socket=accept(SocServer,(struct sockaddr*)&insock,&insocklen);
//delete the server socket
if(SocServer != INVALID_SOCKET)
{
//To close and shutdown the Socserver
shutdown(SocServer, 2 );
closesocket(SocServer);
}
is it possible that Socserver and m_socket are the same because
as per my code the socket connection is established and for some other reason it gets closed and in TCPView it shows established for a while and then no connection at all.
Note: This happens only in some machines and is not reproducible always. Can any other network related issue be the cause.
| Are you certain that the client who is connecting to your server did not close the connection? Also, you did not provide any function which uses the m_Socket so i cannot tell you if there is any problem while handling the incoming connection. I do not think that m_socket and SocServer may end up the same.
|
3,044,603 | 3,061,030 | PDCurses TUI C++ Win32 console app - Access violation reading location | I have downloaded pdcurses source and was able to successfully include curses.h in my project, linked the pre-compiled library and all good.
After few hours of trying out the library, I saw the tuidemo.c in the demos folder, compiled it into an executable and brilliant! exactly what I needed for my project.
Now the problem is that it's a C code, and I am working on a C++ project in VS c++ 2008.
The files I need are tui.c and tui.h
How can I include that C file in my C++ code? I saw few suggestions here
but the compiler was not too happy with 100's of warnings and errors.
How can I go on including/using that TUI pdcurses includes!?
Thanks
EDIT:
I added extern "C" statement, so my test looks like this now, but I'm getting some other type of error
#include <stdio.h>
#include <stdlib.h>
using namespace std;
extern "C" {
#include <tui.h>
}
void sub0()
{
//do nothing
}
void sub1()
{
//do nothing
}
int main (int argc, char * const argv[]) {
menu MainMenu[] =
{
{ "Asub", sub0, "Go inside first submenu" },
{ "Bsub", sub1, "Go inside second submenu" },
{ "", (FUNC)0, "" } /* always add this as the last item! */
};
startmenu(MainMenu, "TUI - 'textual user interface' demonstration program");
return 0;
}
Although it is compiling successfully, it is throwing an Error at runtime, which suggests a bad pointer:
0xC0000005: Access violation reading location 0x021c52f9
at line
startmenu(MainMenu, "TUI - 'textual user interface' demonstration program");
Not sure where to go from here.
thanks again.
| Finally got it working. The solution was in the steps below:
First I renamed tui.c to tui.cpp
For the header tui.h, I followed the exact same step of wrapping the code as described here.
then in my project i just included the header without any extern "C" block
#include "tui.h"
Compiled and it worked!
|
3,044,674 | 3,044,809 | What is this (C/C++) program doing? | It's calling these API functions (advapi32.dll) with these parameters:
CryptCreateHash ( 3275488, 32771, 0, 0, 1243424 );
CryptHashData ( 3203040, 'UY30930037661', 13, 0 );
CryptCreateHash ( 3276304, 32771, 0, 0, 46463812 );
CryptHashData ( 3203296, '-585164138661', 10, 0 );
CryptCreateHash ( 3276304, 32771, 0, 0, 46463808 );
CryptHashData ( 3203424, '1db17bd8ef8bcbd734424a9eae818907LOGIN OK³·óéB', 40, 0 );
CryptCreateHash ( 3276304, 32771, 0, 0, 46463808 );
CryptHashData ( 3203296, '1db17bd8ef8bcbd734424a9eae818907HWHASH OK', 41, 0 );
Not sure how it would come to
1db17bd8ef8bcbd734424a9eae818907
Anyone have any ideas?
| (see here:)
The call to CryptCreateHash initiates hashing with MD5 (32771 = 0x8003): CALG_MD5 0x00008003 MD5 hashing algorithm.. And the call to CryptHashData hashes the second parameter (the one in quotes) using that hash object. I guess these long strings could be keys that are to be hashed before transmission over a network or something.
|
3,045,141 | 3,045,567 | Okay to compare pointers returned by RUNTIME_CLASS() macro? | I've got a function that takes a list of CRuntimeClass pointers in order to setup a view. I'd like to return without doing anything if the function is called with a list of the same classes that are already setup. Saving the pointer values and comparing them on the next call is currently working, but I want to verify that that's a legal thing to do, and not something that just happens to work. Maybe my doc-search-fu is lacking, but I can't find anywhere that guarantees the pointer value returned from the RUNTIME_CLASS() macro for a given class will be the same for the life of the program. The closest I could find is in the docs for CObject::GetRuntimeClass():
There is one CRuntimeClass structure for each CObject-derived class.
That implies that the pointer value shouldn't change, but doesn't exactly state it. Does anyone have something a bit more concrete on that? Or is there a better way to compare the CRuntimeClasses?
| Taking a peek at afx.h plus a little of debugging shows that RUNTIME_CLASS() returns a pointer to a static member: static CRuntimeClass class##class_name (as it can be seen in the definition of DECLARE_DYNAMIC(class_name) macro).
As the member is static, the pointer to it does not change during runtime. In other words static is your guarantee.
|
3,045,188 | 3,049,374 | Serialize boost array | I would like to serialize a boost::array, containing something that is already serializable.
If get this error:
error C2039: 'serialize' : is not a member of 'boost::array<T,N>'
I have tried to include the serialization/array.hpp header but it did not help.
Is there another header to include ?
Thanks
EDIT:
Removed a wrong link
| You need to show the code for the class contained in the boost::array. Since boost::array is STL-compliant, there should be no reason that this would not work. You should be doing something like the bus_route and bus_stop classes in this example.
The class contained in the boost::array must declare boost::serialization::access as a friend class and implement the serialize method as below:
class bus_stop
{
friend class boost::serialization::access;
friend std::ostream & operator<<(std::ostream &os, const bus_stop &gp);
virtual std::string description() const = 0;
gps_position latitude;
gps_position longitude;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
ar & latitude;
ar & longitude;
}
protected:
bus_stop(const gps_position & _lat, const gps_position & _long) :
latitude(_lat), longitude(_long)
{}
public:
bus_stop(){}
virtual ~bus_stop(){}
};
Once that is done, a std container should be able to serialize the bus_stop:
class bus_route
{
friend class boost::serialization::access;
friend std::ostream & operator<<(std::ostream &os, const bus_route &br);
typedef bus_stop * bus_stop_pointer;
std::list<bus_stop_pointer> stops;
template<class Archive>
void serialize(Archive &ar, const unsigned int version)
{
// in this program, these classes are never serialized directly but rather
// through a pointer to the base class bus_stop. So we need a way to be
// sure that the archive contains information about these derived classes.
//ar.template register_type<bus_stop_corner>();
ar.register_type(static_cast<bus_stop_corner *>(NULL));
//ar.template register_type<bus_stop_destination>();
ar.register_type(static_cast<bus_stop_destination *>(NULL));
// serialization of stl collections is already defined
// in the header
ar & stops;
}
public:
bus_route(){}
void append(bus_stop *_bs)
{
stops.insert(stops.end(), _bs);
}
};
Note the important line:
ar & stops;
Which will automatically iterate through the std container, in this case a std::list of bus_stop pointers.
The error:
error C2039: 'serialize' : is not a member of 'boost::array<T,N>'
Indicates that the class contained in the boost::array either has not declared boost::serialization::access as a friend class or has not implemented the template method serialize.
|
3,045,418 | 3,045,435 | Why is std::tr1::shared_ptr<>.reset() so expensive? | Profiling some code that heavily uses shared_ptrs, I discovered that reset() was surprisingly expensive.
For example:
struct Test {
int i;
Test() {
this->i = 0;
}
Test(int i) {
this->i = i;
}
} ;
...
auto t = make_shared<Test>(1);
...
t.reset(somePointerToATestObject);
Tracing the reset() in the last line (under VC++ 2010), I discovered that it creates a new reference-counting object.
Is there a cheaper way, that reuses the existing ref-count and does not bother the heap?
| In the general case, you can't reuse the existing ref count because there may be other shared_ptrs or weak_ptrs using it.
If you can create somePointerToATestObject using make_shared(), then the implementation may use a single heap allocation for both the ref counts and the object. That will save you one of the heap allocations.
|
3,045,483 | 3,045,529 | Resolving a Forward Declaration Issue Involving a State Machine in C++ | I've recently returned to C++ development after a hiatus, and have a question regarding
implementation of the State Design Pattern. I'm using the vanilla pattern, exactly as
per the GoF book.
My problem is that the state machine itself is based on some hardware used as part of
an embedded system - so the design is fixed and can't be changed. This results in a
circular dependency between two of the states (in particular), and I'm trying to
resolve this. Here's the simplified code (note that I tried to resolve this by using
headers as usual but still had problems - I've omitted them in this code snippet):
#include <iostream>
#include <memory>
using namespace std;
class Context
{
public:
friend class State;
Context() { }
private:
State* m_state;
};
class State
{
public:
State() { }
virtual void Trigger1() = 0;
virtual void Trigger2() = 0;
};
class LLT : public State
{
public:
LLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class ALL : public State
{
public:
ALL() { }
void Trigger1() { new LLT(); }
void Trigger2() { new DH(); }
};
// DL needs to 'know' about DH.
class DL : public State
{
public:
DL() { }
void Trigger1() { new ALL(); }
void Trigger2() { new DH(); }
};
class HLT : public State
{
public:
HLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class AHL : public State
{
public:
AHL() { }
void Trigger1() { new DH(); }
void Trigger2() { new HLT(); }
};
// DH needs to 'know' about DL.
class DH : public State
{
public:
DH () { }
void Trigger1() { new AHL(); }
void Trigger2() { new DL(); }
};
int main()
{
auto_ptr<LLT> llt (new LLT);
auto_ptr<ALL> all (new ALL);
auto_ptr<DL> dl (new DL);
auto_ptr<HLT> hlt (new HLT);
auto_ptr<AHL> ahl (new AHL);
auto_ptr<DH> dh (new DH);
return 0;
}
The problem is basically that in the State Pattern, state transitions are made by
invoking the the ChangeState method in the Context class, which invokes the
constructor of the next state.
Because of the circular dependency, I can't invoke the constructor because it's
not possible to pre-define both of the constructors of the 'problem' states.
I had a look at this article, and the template method which seemed to be the ideal solution - but it doesn't compile and my knowledge of templates is a rather limited...
The other idea I had is to try and introduce a Helper class to the subclassed states,
via multiple inheritance, to see if it's possible to specify the base class's constructor
and have a reference to the state subclasse's constructor. But I think that was rather
ambitious...
Finally, would a direct implmentation of the Factory Method Design Pattern be the best way
to resolve the entire problem?
| You can define the member functions outside of the class definitions, e.g.,
class DL : public State
{
public:
void Trigger2();
};
inline void DL::Trigger2() { new DH(); }
Define the member functions that rely on later class definitions after those classes are defined. The inline keyword is only necessary if you define the member function outside of the class in the header file.
As an aside, why are you just using new DH() in your functions; you're leaking memory everywhere!
|
3,045,522 | 3,046,393 | Best of both worlds: browser and desktop game? | When considering a platform for a game, I've decided on multi-platform (Win/Lin/Mac) but can't make up my mind as far as browser vs. desktop. As I'm not all too far in development, and now having second thoughts, I'd like your opinion!
Browser-based games using Java applets:
market penetration is reasonably high (for version 6, it's somewhere around 60% I believe?)
using JOGL, 3D performance/quality is decent; certainly good enough to render the crappy 3D graphics that I make
there's the (small?) possibility of porting something to Android
great for an audience of gamers who switch computers often; can sit down at any computer, load a webpage and play it
also great for casual gamers or less knowledgeable gamers who are quite happy with playing games in a browser but don't want to install more things to their computer
written in a high-level language which I am more familiar with than C++ - but at the same time, I would like to improve my skills with C++ as it is probably where I am headed in the game industry once I get out of school...
easier update process: reload the page.
Desktop games using good ol' C++ and OpenGL
100% market penetration, assuming complete cross-platform; however, that number reduces when you consider how many people will go through downloading and installing an executable compared to just browsing to a webpage and hitting "yes" to a security warning.
more trouble to maintain the cross-platform; but again, for learning purposes I would embrace the challenge and the knowledge I would gain
better performance all around
true full screen, whereas browser games often struggle with smooth full screen graphics (especially on Linux, in my experience)
can take advantage of distribution platforms such as Steam
more likely to be considered a "real" game, whereas browser and Java games are often dismissed as not being real games and therefore not played by "hardcore gamers"
installer can be large; don't have to worry so much about download times
Is there a way to have the best of both worlds? I love Java applets, but I also really like the reasons to write a desktop game. I don't want to constantly port everything between a Java applet project and a C++ project; that would be twice the work!
Unity chose to write their own web player plugin. I don't like this, because I am one of the people that will not install their web player for anything, and I don't see myself being able to convince my audience to install a browser plugin.
What are my options? Are there other examples out there besides Unity, of games that have browser and desktop versions? Did I leave out anything in the pro/con lists above?
| Yes you can have the best of both worlds.
It's perfectly possible to write a Java application that will run in both an applet (for your online users) while also running as a standalone application in downloaded form.
The key technologies are:
JNLP
JOGL for the graphics, which also has some good demos
I'm not so familiar with it but I think jMonkeyEngine looks very promising if you want more of a full-featured game engine
If it's any use, an old game I wrote called Tyrant supported running both as an applet and as a standalone downloaded .jar file, all the source is open if you want to look at it. This used simple AWT rather than 3D graphics.
And finally here's another example of converting an applet into an application with a pretty minimal amount of code.
|
3,045,602 | 3,045,653 | Is C++ explicit conversion really that bad? | My knowledge of C++ at this point is more academic than anything else. In all my reading thus far, the use of explicit conversion with named casts (const_cast, static_cast, reinterpret_cast, dynamic_cast) has come with a big warning label (and it's easy to see why) that implies that explicit conversion is symptomatic of bad design and should only be used as a last resort in desperate circumstances. So, I have to ask:
Is explicit conversion with named casts really just jury rigging code or is there a more graceful and positive application to this feature? Is there a good example of the latter?
| There're cases when you just can't go without it. Like this one. The problem there is that you have multiple inheritance and need to convert this pointer to void* while ensuring that the pointer that goes into void* will still point to the right subobject of the current object. Using an explicit cast is the only way to achieve that.
There's an opinion that if you can't go without a cast you have bad design. I can't agree with this completely - different situations are possible, including one mentioned above, but perhaps if you need to use explicit casts too often you really have bad design.
|
3,045,603 | 3,045,652 | What does an object file contain? | During the various stages of compilation in C or C++, I know that an object file gets generated (i.e., any_name.o file). What does this .o file contain? I can't open it since it's a binary file.
Could anybody please help me? Are the contents of the object file mainly dependent on the compiler which we use on Unix?
| Object files can contain a bunch of stuff: Basically it's some or all of the list below:
Symbol Names
Compiled code
Constant data, eg. strings
Imports - which symbols the compiled code references (gets fixed up by linker)
Exports - which symbols the object file makes available to OTHER object files.
The linker turns a bunch of object files into an executable, by matching up all the imports and exports, and modifying the compiled code so the correct functions get called.
|
3,045,645 | 3,045,967 | Precompiled headers question | I am right now reorganizing my project and what recently was a simple application now became a pair of C++ projects - static library and real application.
I would like to share one precompiled header between two projects, but face some troubles with setting up the .pdb file paths.
Assume my first project is called Library and builds it's .lib file with a corresponding Library.pdb file. Now, the second project is called Application and builds everything into the same folder (.exe and another Application.pdb file).
Right now my both projects create their own precompiled headers file (Library.pch and Application.pch) based on one actual header file. It works, but I think it's a waste of time and I also think there should be a way to share one precompiled header between two projects.
If in my Application project I try to set the Use Precompiled Header (/Yu) option and set it to Library.pch, it wouldn't work, because of the following error:
error C2858: command-line option 'program database name "Application.pdb" inconsistent with precompiled header, which used "Library.pdb".
So, does anyone know some trick or way to share one precompiled header between two projects preserving proper debug information?
| The question is, why do you want to share the precompiled header (PCH) files. Generally I woul d say, that does not make sense. PCH are used to speed up compiling not to share any information between different projects.
Since you also write about the PDB file, you probably want to debug the library code with your applications. This can be achieved by setting the /Fd parameter when compiling the library. When you link the library in your application and the linker finds the corresponding PDB file, you get full debug support.
|
3,045,831 | 3,045,985 | Sort List based on dynamically generated numbers in C++ | I have a list of objects ("Move"'s in this case) that I want to sort based on their calculated evaluation. So, I have the List, and a bunch of numbers that are "associated" with an element in the list. I now want to sort the List elements with the first element having the lowest associated number, and the last having the highest. Once the items are order I can discard the associated number. How do I do this?
This is what my code looks like (kind've):
list<Move> moves = board.getLegalMoves(board.turn);
for(i = moves.begin(); i != moves.end(); ++i)
{
//...
a = max; // <-- number associated with current Move
}
| I would suggest a Schwartzian transform sort. Make a new vector (I recommend vector for more efficient sorting) of pairs of the associated value, and a pointer to its item. Sort the vector of pairs and then regenerate the list from the sorted vector. Since operator< is defined on a std::pair to be comparison by the first item of the pair and then the second, you will get a proper ordering.
Example:
#include <algorithm> // gives you std::sort
#include <utility> // gives you std::pair
typedef double CostType;
typedef std::pair<CostType, Move*> Pair;
// Create the vector of pairs
std::vector<Pair> tempVec;
tempVec.reserve(moves.size());
for (std::list<Move>::iterator i = moves.begin(); i != moves.end(); ++i)
{
CostType cost = calcCost(*i);
Move* ptrToI = &(*i);
tempVec.push_back(Pair(cost, ptrToI));
}
// Now sort 'em
std::sort(tempVec.begin(), tempVec.end());
// Regenerate your original list in sorted order by copying the original
// elements from their pointers in the Pair.
std::list<Move> sortedMoves;
for (std::vector<Pair>::iterator i = tempVec.begin(); i != tempVec.end(); ++i)
{
sortedMoves.push_back(*(i->second));
}
Note that you will need a calcCost function that I have assumed here. This approach has an advantage over creating a comparison function if your comparison value calculation is time consuming. This way, you only pay the cost for calculating the comparison N times instead of 2 * N * log(N).
|
3,046,050 | 3,046,087 | STL iterators - purpose | What is the purpose of STL iterators? Why have programmers created this concept at all?
| Iterators allow you to separate algorithms from the container. As long as you have a start and end iterator, and know the capabilities of the iterator (random access etc) you can do operations on the range specified by the iterators. For example, see std::for_each, std::transform. This way you can implement just one version of an algorithm rather than needing to write a new one for each container on which you wish it to operate.
|
3,046,359 | 3,046,479 | Validity of a Socket | I have created a socket using the following lines of code and i get a valid socket and connection is established between the client and server machines. Is there a possibility that the socket becomes invalid due to network disturbances or any other reason.
If so how do we check whether the socket is valid or not.
SOCKET SocServer;
//To Set up the sockaddr structure
ServerSock.sin_family = AF_INET;
ServerSock.sin_addr.s_addr = INADDR_ANY
ServerSock.sin_port = htons(PortNumber);//port number of 5005
// To Create a socket for listening on PortNumber
if(( SocServer = socket( AF_INET, SOCK_STREAM, 0 )) == INVALID_SOCKET )
{
return FALSE;
}
//To bind the socket with wPortNumber
if(bind(SocServer,(sockaddr*)&ServerSock,sizeof(ServerSock))!=0)
{
return FALSE;
}
// To Listen for the connection on wPortNumber
if(listen(SocServer,SOMAXCONN)!=0)
{
return FALSE;
}
I know i can check for INVALID_SOCKET which in other words means the socket is 0. Is there any other way out because my SocServer will have a value say 2500, i want to check if this socket is valid.
| Pass your socket to any one of the windows socket functions (eg. getsockopt()), if the socket is invalid, it will return SOCKET_ERROR while WSAGetLastError() will return WSAENOTSOCK.
It is important to note that INVALID_SOCKET does not equal 0(the actual value, which you should not use specifically is ((SOCKET)(~0))
|
3,046,598 | 3,047,879 | buffer overflow with boost::program_options | I have a problem using boost:program_options
this simple program, copy-pasted from boosts' documentation :
#include <boost/program_options.hpp>
int main( int argc, char** argv )
{
namespace po = boost::program_options;
po::options_description desc("Allowed options");
desc.add_options()
("help", "produce help message")
("compression", po::value<int>(), "set compression level")
;
return 0;
}
fails with a buffer overflow.
I have activated the "buffer security switch", and when I run it I get an "unknown exception (0xc0000409)" when I step over the line desc.add_options()...
I use Visual Studio 2005 and boost 1.43.0.
By the way it does run if I deactivate the switch but I don't feel comfortable doing so... unless it's possible to deactivate it locally.
So do you have a solution to this problem?
EDIT
I found the problem
I was linking against libboost_program_options-vc80-mt.lib which wasn't the good library.
| I found the problem I was linking against libboost_program_options-vc80-mt.lib which wasn't the good library since I changed the runtime library to Multithread DLL.
|
3,046,624 | 3,046,740 | How will the Windows C/Sleep() function operate during clock drift? | If I run something like Sleep(10000), and the system clock changes during that, will the thread still sleep for 10 seconds of wall-clock time, or less or more? I.e. does the Sleep() function convert milliseconds into hardware ticks?
| Sleep() is independent of the wall-clock time. It is based on the same timer that is used for thread scheduling.
You will mostly not sleep exactly 10 seconds though, due to the frequency of the system clock and when you actually get scheduled to run after the timeout elapses.
|
3,046,668 | 3,046,715 | How to mute microphone in Windows 7 with C/C++? | I made a program to mute microphone using WinAPI and it seems to work perfectly in Windows XP but doesn't do a thing in Windows 7. Is it possible to control microphone volume or mute with WinAPI in Windows 7?
void setVolume(DWORD volume) {
HMIXER mixer;
if (mixerOpen(&mixer, 0, 0, 0, 0) != MMSYSERR_NOERROR) {
MessageBoxW(NULL, L"Error: mixerOpen()", NULL, MB_ICONHAND);
return;
}
// Get the line info
MIXERCAPS mixcaps;
MIXERLINE mixerLine;
mixerGetDevCaps(0, &mixcaps, sizeof(MIXERCAPS));
mixerLine.cbStruct = sizeof(MIXERLINE);
mixerLine.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_WAVEIN;
mixerLine.dwSource = 0;
mixerLine.dwDestination = 0;
if (mixerGetLineInfo(reinterpret_cast<HMIXEROBJ>(mixer), &mixerLine, MIXER_GETLINEINFOF_SOURCE)
!= MMSYSERR_NOERROR) {
MessageBoxW(NULL, L"Error: mixerGetLineInfo()", NULL, MB_ICONHAND);
return;
}
// Get control for mixerline
MIXERCONTROL mixerCtrl;
MIXERLINECONTROLS mixerLineCtrl;
mixerLineCtrl.cbStruct = sizeof(MIXERLINECONTROLS);
mixerLineCtrl.dwLineID = mixerLine.dwLineID;
mixerLineCtrl.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
mixerLineCtrl.cControls = 1;
mixerLineCtrl.pamxctrl = &mixerCtrl;
mixerLineCtrl.cbmxctrl = sizeof(MIXERCONTROL);
mixerLineCtrl.cControls = 5;
if (mixerGetLineControls(reinterpret_cast<HMIXEROBJ>(mixer), &mixerLineCtrl, MIXER_GETLINECONTROLSF_ONEBYTYPE)
!= MMSYSERR_NOERROR) {
MessageBoxW(NULL, L"Error: mixerGetLineControls()", NULL, MB_ICONHAND);
return;
}
// Volume..
MIXERCONTROLDETAILS mixerCtrlDetails;
MIXERCONTROLDETAILS_UNSIGNED mixerCtrlDetailsUnsigned;
mixerCtrlDetailsUnsigned.dwValue = volume;
mixerCtrlDetails.dwControlID = mixerCtrl.dwControlID;
mixerCtrlDetails.cbStruct = sizeof(MIXERCONTROLDETAILS);
mixerCtrlDetails.cMultipleItems = 0;
mixerCtrlDetails.paDetails = &mixerCtrlDetailsUnsigned;
mixerCtrlDetails.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
mixerCtrlDetails.cChannels = 1;
if (mixerSetControlDetails(reinterpret_cast<HMIXEROBJ>(mixer), &mixerCtrlDetails, MIXER_OBJECTF_HMIXER | MIXER_GETCONTROLDETAILSF_VALUE)
!= MMSYSERR_NOERROR) {
MessageBoxW(NULL, L"Error: mixerSetControlDetails()", NULL, MB_ICONHAND);
return;
}
mixerClose(mixer);
}
| You need to use the new audio APIs introduced by Windows Vista.
Here is an example.
*EDIT: Visual Studio 2015 (C++):
Usange:
// To 100%
ConsoleApplication3.exe -f 1
// To 0%
ConsoleApplication3.exe -f 0
// To 50%
ConsoleApplication3.exe -f 0.50
Code:
#include "stdafx.h"
#include <stdio.h>
#include <windows.h>
#include <mmdeviceapi.h>
#include <endpointvolume.h>
void Usage()
{
printf("Usage: \n");
printf(" SetVolume [Reports the current volume]\n");
printf(" SetVolume -d <new volume in decibels> [Sets the current default render device volume to the new volume]\n");
printf(" SetVolume -f <new volume as an amplitude scalar> [Sets the current default render device volume to the new volume]\n");
}
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr;
bool decibels = false;
bool scalar = false;
double newVolume;
if (argc != 3 && argc != 1)
{
Usage();
return -1;
}
if (argc == 3)
{
if (argv[1][0] == '-')
{
if (argv[1][1] == 'f')
{
scalar = true;
}
else if (argv[1][1] == 'd')
{
decibels = true;
}
}
else
{
Usage();
return -1;
}
newVolume = _tstof(argv[2]);
}
// -------------------------
CoInitialize(NULL);
IMMDeviceEnumerator *deviceEnumerator = NULL;
hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID *)&deviceEnumerator);
IMMDevice *defaultDevice = NULL;
hr = deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &defaultDevice);
deviceEnumerator->Release();
deviceEnumerator = NULL;
IAudioEndpointVolume *endpointVolume = NULL;
hr = defaultDevice->Activate(__uuidof(IAudioEndpointVolume), CLSCTX_INPROC_SERVER, NULL, (LPVOID *)&endpointVolume);
defaultDevice->Release();
defaultDevice = NULL;
// -------------------------
float currentVolume = 0;
endpointVolume->GetMasterVolumeLevel(¤tVolume);
printf("Current volume in dB is: %f\n", currentVolume);
hr = endpointVolume->GetMasterVolumeLevelScalar(¤tVolume);
printf("Current volume as a scalar is: %f\n", currentVolume);
if (decibels)
{
hr = endpointVolume->SetMasterVolumeLevel((float)newVolume, NULL);
}
else if (scalar)
{
hr = endpointVolume->SetMasterVolumeLevelScalar((float)newVolume, NULL);
}
endpointVolume->Release();
CoUninitialize();
return 0;
}
|
3,046,889 | 3,048,361 | Optional Parameters with C++ Macros | Is there some way of getting optional parameters with C++ Macros? Some sort of overloading would be nice too.
| Here's one way to do it. It uses the list of arguments twice, first to form the name of the helper macro, and then to pass the arguments to that helper macro. It uses a standard trick to count the number of arguments to a macro.
enum
{
plain = 0,
bold = 1,
italic = 2
};
void PrintString(const char* message, int size, int style)
{
}
#define PRINT_STRING_1_ARGS(message) PrintString(message, 0, 0)
#define PRINT_STRING_2_ARGS(message, size) PrintString(message, size, 0)
#define PRINT_STRING_3_ARGS(message, size, style) PrintString(message, size, style)
#define GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4
#define PRINT_STRING_MACRO_CHOOSER(...) \
GET_4TH_ARG(__VA_ARGS__, PRINT_STRING_3_ARGS, \
PRINT_STRING_2_ARGS, PRINT_STRING_1_ARGS, )
#define PRINT_STRING(...) PRINT_STRING_MACRO_CHOOSER(__VA_ARGS__)(__VA_ARGS__)
int main(int argc, char * const argv[])
{
PRINT_STRING("Hello, World!");
PRINT_STRING("Hello, World!", 18);
PRINT_STRING("Hello, World!", 18, bold);
return 0;
}
This makes it easier for the caller of the macro, but not the writer.
|
3,046,964 | 3,047,278 | #define far, #define near Windef.h |
Possible Duplicate:
Is there a clean way to prevent windows.h from creating a near & far macro?
What's the point of these two defines in Windef.h?
#define far /* nothing */
#define near /* nothing */
I know it has to do with near and far pointers and the fact they're no longer used, but, is it safe to #undef them, so I can use near and far as function and variable names in my code?
Or, should I simply avoid it and never use near and far as identifiers?
| Don't reuse them. The last thing you need is to have to repeatedly explain to people that they aren't the old-school ornaments.
If it is critical to your app, you might consider using capitalized versions (since identifiers are case sensitive) - the compiler will catch typos when you mess up.
Just accept that this is cruft from the good old days when computers were still made from metal.
|
3,047,002 | 3,047,118 | Two separate tm structs mirroring each other | Here is my current situation:
I have two tm structs, both set to the current time
I make a change to the hour in one of the structs
The change is occurring in the other struct magically....
How do I prevent this from occurring? I need to be able to compare and know the number of seconds between two different times -- the current time and a time in the future. I've been using difftime and mktime to determine this. I recognize that I don't technically need two tm structs (the other struct could just be a time_t loaded with raw time) but I'm still interested in understanding why this occurs.
void Tracker::monitor(char* buffer){
// time handling
time_t systemtime, scheduletime, currenttime;
struct tm * dispatchtime;
struct tm * uiuctime;
double remainingtime;
// let's get two structs operating with current time
dispatchtime = dispatchtime_tm();
uiuctime = uiuctime_tm();
// set the scheduled parameters
dispatchtime->tm_hour = 5;
dispatchtime->tm_min = 05;
dispatchtime->tm_sec = 14;
uiuctime->tm_hour = 0;
// both of these will now print the same time! (0:05:14)
// what's linking them??
// print the scheduled time
printf ("Current Time : %2d:%02d:%02d\n", uiuctime->tm_hour, uiuctime->tm_min, uiuctime->tm_sec);
printf ("Scheduled Time : %2d:%02d:%02d\n", dispatchtime->tm_hour, dispatchtime->tm_min, dispatchtime->tm_sec);
}
struct tm* Tracker::uiuctime_tm(){
time_t uiucTime;
struct tm *ts_uiuc;
// give currentTime the current time
time(&uiucTime);
// change the time zone to UIUC
putenv("TZ=CST6CDT");
tzset();
// get the localtime for the tz selected
ts_uiuc = localtime(&uiucTime);
// set back the current timezone
unsetenv("TZ");
tzset();
// set back our results
return ts_uiuc;
}
struct tm* Tracker::dispatchtime_tm(){
time_t currentTime;
struct tm *ts_dispatch;
// give currentTime the current time
time(¤tTime);
// get the localtime for the tz selected
ts_dispatch = localtime(¤tTime);
// set back our results
return ts_dispatch;
}
| You have to do this:
struct tm* temp_tm;
struct tm dispatchtime; // No longer a pointer
struct tm uiuctime; // No longer a pointer
temp_tm = dispatchtime_tm();
dispatchtime = *temp_tm; // Member to member copy
temp_tm = uiuctime_tm();
uiuctime = *temp_tm; // Member to member copy
This way you will keep a local copy of the tm struct. This struct is allocated internally in the standard library, each call to localtime will point to the same memory address!
|
3,047,095 | 3,048,590 | I'm having a problem identifying a floating point exception | I'm using c++ in visual studio express to generate random expression trees for use in a genetic algorithm type of program.
Because they are random, the trees often generate (I'll call them exceptions, I'm not sure what they are)
Thanks to a suggestion by George, I turned the mask _MCW_EM on so that hardware interrupts are turned off. (the default)
So, the program runs uninterrupted, but some of the values returned are: -1.#INF, -1.#NAN, -1.#INV.
I don't know how to identify these so that I can throw an exeption:
if ( variable == -1.#INF) ??
DigitalRoss in this post seemed to have the solution, but as I understood it I couldn't make it work.
I've been looking all over the place for this simple bit of code, that I assumed would be used all
the time, but have had no luck.
thanks
| Thanks to KennyTM for spotting the duplicate. A link in the link answered my query.
I used:
#include "limits.h"
#include "math.h"
bool isIndeterminate(const double pV)
{
return (pV != pV);
};
bool isInfinite(const double pV)
{
return (pV >= DBL_MAX || pV <= -DBL_MAX);
};
As KennyTM's response was as a comment, I'm (perhaps a little presumtiously) answering my own question.
|
3,047,276 | 3,052,606 | Profiling help required | I have a profiling issue - imagine I have the following code...
void main()
{
well_written_function();
badly_written_function();
}
void well_written_function()
{
for (a small number)
{
highly_optimised_subroutine();
}
}
void badly_written_function()
{
for (a wastefully and unnecessarily large number)
{
highly_optimised_subroutine();
}
}
void highly_optimised_subroutine()
{
// lots of code
}
If I run this under vtune (or other profilers) it is very hard to spot that anything is wrong. All the hotspots will appear in the section marked "// lots of code" which is already optimised. The badly_written_function() will not be highlighted in any way even though it is the cause of all the trouble.
Is there some feature of vtune that will help me find the problem?
Is there some sort of mode whereby I can find the time taken by badly_written_function() and all of its sub-functions?
| That's usually known as a "callgraph profile", and I'm fairly sure Visual Studio will do that.
|
3,047,381 | 3,048,698 | Boost signals and passing class method | I've defined some signal:
typedef boost::signals2::signal<void (int temp)> SomeSig;
typedef SomeSig::slot_type SomeSigType;
I have some class:
class SomeClass
{
SomeClass()
{
SomeSig.connect(&SomeClass::doMethod);
}
void doMethod(const SomeSig &slot);
};
And got a lot of errors:
error: ‘BOOST_PP_ENUM_SHIFTED_PARAMS_M’ was not declared in this scope
error: ‘T’ was not declared in this scope
error: a function call cannot appear in a constant-expression
error: a function call cannot appear in a constant-expression
error: template argument 1 is invalid
error: ‘BOOST_SIGNALS2_MISC_STATEMENT’ has not been declared
error: expected identifier before ‘~’ token
error: expected ‘)’ before ‘~’ token
error: expected ‘;’ before ‘~’ token
UPD:
New code (the same error):
typedef boost::signals2::signal<void (int keyCode)> SigKeyPressed;
typedef SigKeyPressed::slot_type SigKeyPressedType;
class SomeClass
{
SigKeyPressed mSigKeyPressed;
public:
SomeClass() { mSigKeyPressed.connect(&SomeClass::keyPressed); }
void keyPressed(const SigKeyPressedType &slot);
};
| Both Pavel and Keith are correct (+1 for both). SomeSig is a type, you cannot call on a type. You must instantiate SomeSig. You also must provide a pointer to the object when using method function pointers. The _1 is a place holder required during a bind indicating that the method function pointer being bound requires a single argument.
typedef boost::signals2::signal<void (int keyCode)> SigKeyPressed;
typedef SigKeyPressed::slot_type SigKeyPressedType;
class SomeClass
{
SigKeyPressed mSigKeyPressed;
public:
SomeClass() { mSigKeyPressed.connect(boost::bind(&SomeClass::keyPressed, this, _1); }
void keyPressed(const SigKeyPressedType &slot);
};
|
3,047,410 | 3,047,440 | How do I benefit from argc and argv in C++, the standard way? | What is the standard way to retrive and check for the argc and argv and what is the best usage and how to do that in linux?
Please provide examples.
"I want to have a complex command-line options and I want to use them in my application"
That what I mean.
Thanks
| Please use boost program options http://www.boost.org/doc/html/program_options.html for access to the command arguments.
|
3,047,438 | 3,047,528 | I want to make a wrapped acces type for certain internals of one of classes and I have some performance questions | I am writing an abstract matrix class (and some concrete subclasses) for use on very differing hardwares/architectures, etc. and I want to write a row and column type that provides a transparent reference to the rows and columns of the matrix.
However, I want to tune for performance, so I'd like this class to be essentially a compiler construct. In other words, I'm willing to sacrifice some dev time to making the overhead of these classes as small as possible.
I assume all (small) methods would want to be inline? Keep the structure small? Any other suggestions?
| Design for efficiency golden rule number 1 is to really properly fully completely totally understand and appreciate all of the nuances of the environment in which you are working.
Including, but not limited to:
Understanding the costs of each compiler construct you are using
Understand how the compiler uses memory
Do a proper design on the back of an envelope or napkin. If it doesn't fit you're in trouble.
Build small examples and test / disassemble
Revisit the design.
Then write some realistic test cases and test on the disparate hardware to identify if there are performance issues; I've done this a few times and unless you're writing in assembler the performance hit can be in the strangest places.
If it's too slow add hardware. If you can't add hardware optimise.
|
3,047,511 | 3,047,780 | C++ private inheritance and static members/types | I am trying to stop a class from being able to convert its 'this' pointer into a pointer of one of its interfaces. I do this by using private inheritance via a middle proxy class. The problem is that I find private inheritance makes all public static members and types of the base class inaccessible to all classes under the inheriting class in the hierarchy.
class Base
{
public:
enum Enum
{
value
};
};
class Middle : private Base
{
};
class Child : public Middle
{
public:
void Method()
{
Base::Enum e = Base::value; // doesn't compile BAD!
Base* base = this; // doesn't compile GOOD!
}
};
I've tried this in both VS2008 (the required version) and VS2010, neither work.
Can anyone think of a workaround? Or a different approach to stopping the conversion?
Also I am curios of the behavior, is it just a side effect of the compiler implementation, or is it by design? If by design, then why? I always thought of private inheritance to mean that nobody knows Middle inherits from Base. However, the exhibited behavior implies private inheritance means a lot more than that, in-fact Child has less access to Base than any namespace not in the class hierarchy!
| You should be able to access Base::Enum by fully qualifying it:
class Child : public Middle
{
public:
void Method()
{
::Base::Enum e = ::Base::value;
}
};
This is the behavior specified by the language (C++03 §11.2/3):
Note: A member of a private base class might be inaccessible as an inherited member name, but accessible directly.
This is followed by an extended example that is effectively similar to your example code.
However, it appears that neither Visual C++ 2008 nor Visual C++ 2010 correctly implements this, so while you can use the type ::Base::Enum, you still can't access ::Base::value. (Actually, Visual C++ seems to have gotten a lot of this wrong, as it incorrectly allows you to use the not-fully-qualified Base::Enum).
To "get around" the problem, you can add using declarations to the Middle class:
class Middle : private Base
{
protected:
using Base::Enum;
using Base::value;
};
This won't let you use Base::Enum or Base::value in your Child class, but it will allow you to use an Enum and value or Middle::Enum and Middle::value.
|
3,047,567 | 3,047,593 | Object allocation in C++ | char *myfunc() {
char *temp = "string";
return temp;
}
In this piece of code, where does the allocation of the object pointed to by temp happen and what would be its scope?
Is this function a valid way to return a char* pointer?
| Is the code correct?
Yes your code is (almost) fine, because "string" is a string literal and located in static storage.
Note: A pointer is just a variable which stores a memory address. This line simply stores the address of the string literal "string" inside a variable called temp.
char *temp = "string";
The C++ standard guarantees that the string literal will stay in memory for the duration of the program as defined below. Which means you are free to use that memory address in any scope anywhere during the whole life of your program.
Why?
The C++03 standard (current) has this to say:
An ordinary string literal has type
“array of n const char” and static
storage duration (3.7),
And section 3.7.1 - 1:
All objects which neither have dynamic
storage duration nor are local have
static storage duration. The storage
for these objects shall last for the
duration of the program.
Warning:
In your code you are returning a char*, you should really be returning a const char *. It is undefined behavior if you try to modify a string literal, and your function return value shouldn't pretend to allow it.
On a related side note to the warning. If you have in your code in 2 different places a string called "string" then whether or not they are distinct strings is implementation defined.
|
3,047,646 | 3,047,662 | How to use a "vector of vector"? | I already searched on the web for it but I didn't get satisfying results.
I want to create something like
vector< vector<int*> > test_vector;
How do i fill this vector of vector? How to access it's members? Maybe someone knows some nice tutorials on the web?
kind regards
mikey
| Just remember that each element of test_vector is of type vector<int*>. You would fill test_vector by filling each element vector.
You can access this just like any multi-dimensional array. See:
int *p = test_vector[0][0];
Or:
int *p = test_vector.at(0).at(0);
|
3,047,753 | 3,051,260 | How to convert a C++ program that uses CUDA into MEX | For work, I am converting the Image Denoising program that comes with the CUDA SDK into a MATLAB program. As far as I know, I have made all the necessary changes required by MATLAB, but when I try to call mex on it, MATLAB returns a bunch of linkage errors that I have no idea how to fix. If anyone has any suggestions on what I might be doing wrong, I would greatly appreciate it.
The command I am giving MATLAB is:
mex imageDenoisingGL.cpp -I..\..\common\inc -IC:\CUDA\include -L..\..\common\lib -lglut32
And the output from MATLAB is a bunch of these:
imageDenoisingGL.obj : error LNK2019: unresolved external symbol __imp__cutCheckCmdLineFlag@12 referenced in function "void __cdecl __cutilExit(int,char * *)" (?__cutilExit@@YAXHPAPAD@Z)
I am running:
Windows XP x32
Visual Studio 2005
MATLAB 2007a
| You need to link the CUDA libraries to your MEX file. It looks like you're also using some of the "cutil.h" stuff from the CUDA SDK (such as cutCheckCmdLineFlag), so you'll need to link against not only the cudart library, but also cutil. I.e. you probably need to add something like
-Lc:\CUDA\lib -lcudart -lcuda -L<path-to-cutil.lib> -lcutil
to your MEX command-line.
|
3,048,200 | 3,048,578 | Maximum Width of a Printed Double in C++ | I was wondering, how long in number of characters would the longest a double printed using fprintf be? My guess is wrong.
Thanks in advance.
| Who knows. The Standard doesn't say how many digits of precision a double provides other than saying it (3.9.1.8) "provides at least as much precision as float," so you don't really know how many characters you'll need to sprintf an arbitrary value. Even if you did know how many digits your implementation provided, there's still the question of exponential formatting, etc.
But there's a MUCH bigger question here. Why the heck would you care? I'm guessing it's because you're trying to write something like this:
double d = ...;
int MAGIC_NUMBER = ...;
char buffer[MAGIC_NUMBER];
sprintf(buffer, "%f", d);
This is a bad way to do this, precisely because you don't know how big MAGIC_NUMBER should be. You can pick something that should be big enough, like 14 or 128k, but then the number you picked is arbitrary, not based on anything but a guess that it will be big enough. Numbers like MAGIC_NUMBER are, not suprisingly, called Magic Numbers. Stay away from them. They will make you cry one day.
Instead, there's a lot of ways to do this string formatting without having to care about buffer sizes, digits of precision, etc, that let you just get on with the buisness of programming. Streams is one:
#include <sstream>
double d = ...;
stringstream ss;
ss << d;
string s = ss.str();
cout << s;
...Boost.Format is another:
#include <boost\format\format.hpp>
double d = ... ;
string s = (boost::format("%1%") % d).str();
cout << s;
|
3,048,377 | 3,048,384 | How to free memory in try-catch blocks? | I have a simple question hopefully - how does one free memory which was allocated in the try block when the exception occurs? Consider the following code:
try
{
char *heap = new char [50];
//let exception occur here
delete[] heap;
}
catch (...)
{
cout << "Error, leaving function now";
//delete[] heap; doesn't work of course, heap is unknown to compiler
return 1;
}
How can I free memory after the heap was allocated and exception occurred before calling delete[] heap? Is there a rule not to allocate memory on heap in these try .. catch blocks?
| Study the RAII idiom (Resource Acquisition Is Initialization)! See e.g. the Wikipedia article on RAII.
RAII is just the general idea. It is employed e.g. in the C++ standard library's std::unique_ptr or std::shared_ptr template classes.
Very brief explanation of the RAII idiom:
Basically, it is the C++ version of try..finally blocks found in some other languages. The RAII idiom is arguably more flexible.
It works like this:
You write a wrapper class around your resource (e.g. memory). The destructor is responsible for freeing the resource.
You create, as a local (automatic) variable, an instance of your wrapper class in a scope. Once program execution leaves that scope, the object's destructor will be called, thereby releasing the resource (e.g. memory).
The important point is that it doesn't matter how the scope is exited. Even if an exception is thrown, the scope is still exited and the wrapper object's destructor is still called.
Very crude example:
// BEWARE: this is NOT a good implementation at all, but is supposed to
// give you a general idea of how RAII is supposed to work:
template <typename T>
class wrapper_around
{
public:
wrapper_around(T value)
: _value(value)
{ }
T operator *()
{
return _value;
}
virtual ~wrapper_around()
{
delete _value; // <-- NOTE: this is incorrect in this particular case;
// if T is an array type, delete[] ought to be used
}
private:
T _value;
};
// ...
{
wrapper_around<char*> heap( new char[50] );
// ... do something ...
// no matter how the { } scope in which heap is defined is exited,
// if heap has a destructor, it will get called when the scope is left.
// Therefore, delegate the responsibility of managing your allocated
// memory to the `wrapper_around` template class.
// there are already existing implementations that are much better
// than the above, e.g. `std::unique_ptr` and `std::shared_ptr`!
}
|
3,048,548 | 3,048,575 | Why an auto_ptr can "seal" a container | auto_ptr on wikipedia said that "an auto_ptr containing an STL container may be used to prevent further modification of the container.". It used the following example:
auto_ptr<vector<ContainedType> > open_vec(new vector<ContainedType>);
open_vec->push_back(5);
open_vec->push_back(3);
// Transfers control, but now the vector cannot be changed:
auto_ptr<const vector<ContainedType> > closed_vec(open_vec);
// closed_vec->push_back(8); // Can no longer modify
If I uncomment the last line, g++ will report an error as
t05.cpp:24: error: passing ‘const std::vector<int, std::allocator<int> >’
as ‘this’ argument of ‘void std::vector<_Tp, _Alloc>::push_back(const _Tp&)
[with _Tp = int, _Alloc = std::allocator<int>]’ discards qualifiers
I am curious why after transferring the ownership of this vector, it can no longer be modified?
Thanks a lot!
| The closed_vec pointer holds the type const vector<ContainedType>. Because the type is const, you can't call any methods on it that aren't also defined as const (which means they don't change internal data). Naturally push_back is non-const, as it changes the vector, so you can't call it on a const pointer. It doesn't really have anything to do with auto_ptr, you could accomplish the same with regular pointers:
vector<ContainedType>* open_vec = new vector<ContainedType>();
open_vec->push_back(5);
open_vec->push_back(3);
const vector<ContainedType>* closed_vec = open_vec;
closed_vec->push_back(8); // Fails
|
3,048,577 | 6,832,617 | Dependency issue with MSBuild 4.0 when doing DllImport from C# into unmanaged C++ library | Explicitly setting dependency in VS2010 between unmanaged C++ project and C# project is honored in VS2010, but dependency is ignored in MSBuild 4.0.
It is impossible to add a reference to unmanaged C++ project from C# project, afaik.
How do i ensure correct build order if a solution contains unmanaged and managed projects?
| MSBuild has a bug in it and doesn't correctly honor project dependencies added at the solution level. Take a look at http://social.msdn.microsoft.com/Forums/en-US/msbuild/thread/80cc6447-b720-4806-8395-7c257b207613/ and https://connect.microsoft.com/VisualStudio/feedback/details/613284/msbuild-4-does-not-respect-build-order-when-building-a-solution
A posting by Microsoft on the connect page indicates that its a bug in the 64-bit version of MSBuild. Try switching to the 32-bit version to see if that solves the problem.
If you can't do that, or it doesn't work, there are two other options. Neither of them are ideal.
The first option would be to manually edit the SLN file and change the order the projects appear in the file to match the build order you want. I imagine Victor's solution would be a much better idea, since additional changes to the solution file could end up overwriting the changes again.
The second option would be to manually export the MSBuild "metaproject" for the solution and edit the build order directly and add any other customizations you need. From what I've read, even at Microsoft they don't "dogfood" solution compilation - instead, they avoid them completely during builds and use custom MSBuild files instead.
To generate the metaproj, set the environment variable MSBuildEmitSolution to 1. After running MSBuild on the solution and you should see a ".metaproj" file in the same directory - it contains the script that MSBuild generates in-memory to compile the solution. You should be able to make the necessary edits, check it in, then set the build server to compile it.
The issue will disappear in the next release of Visual Studio. The Microsoft Connect page has a posting from Microsoft that it will be fixed in the next release, and rumor has it they're getting rid of .sln files and replacing them with proper MSBuild projects.
|
3,048,629 | 3,051,858 | How to turn stream from Named Pipe into Socket Stream? (in C++ on Windows) | How to turn stream from Named Pipe into Socket Stream? (in on Windows) (Share all new data in pipe stream on socket)?
| The nice thing of named pipes in Windows is that they already work in a network just specifying the server name in the:
CreateFile("\\ServerName\pipe\PipeName", ...
However, if this not fits your needs, you just have to build a read loop (I suggest OVERLAPPED I/O) that, at every read from the pipe, writes the received data to the socket.
|
3,048,677 | 3,048,964 | Access Violation reading elements of an array | I've written my own code to parse an .obj model file - essentially just ASCII text. The file gets parsed and stored in the class correctly according to my tests. I can read back the values (from data members) just fine in the loading function.
The problem occurs when I try to read back the values in my main rendering loop. There is an access violation error on the line beginning "int v":
for(int i = 0; i<data.numFaces; i++){
for(int j = 0; j<3; j++){ //Assuming triangles for now.
int v = data.faceList[i].vertex[j]; // Access violation here.
double vX = data.vertexList[v].x;
double vY = data.vertexList[v].y;
double vZ = data.vertexList[v].z;
glVertex3d(vX, vY, vZ);
}
}
I'm not exactly sure why this happens, and I've checked everything I could possibly think of. I'm not very experienced in C++. Most of my programming experience is in Java, Python and PHP although I have previously written a medium sized project in C++.
I'm sure the problem is something basic related to memory allocation or pointers used for the dynamic arrays.
Here are the relevant parts of code in the obj loading class:
ObjData ObjLoader::LoadObj(std::string filename){
//... Initalization ...
// 1st pass: find number of elements so array sizes can be defined.
while(!file.eof()){
//...
}
//...close file...
_data.faceList = new ObjFace[_data.numFaces];
_data.vertexList = new ObjVert[_data.numVertices];
_data.uvList = new ObjUV[_data.numUVcoords];
_data.normalList = new ObjNormal[_data.numNormals];
//TODO: Make size dynamic according to each face. Just use the first 3 points for now.
for (int i = 0; i < _data.numFaces; i++){
_data.faceList[i].vertex = new int[3];
_data.faceList[i].normal = new int[3];
_data.faceList[i].uv = new int[3];
}
//... file stuff ...
// 2nd pass: read values into arrays.
while(!file.eof()){
//...
if(type=="v"){
_data.vertexList[currentVertex].x = atof(param1.c_str());
_data.vertexList[currentVertex].y = atof(param2.c_str());
_data.vertexList[currentVertex].z = atof(param3.c_str());
currentVertex++;
}else if(type=="vt"){
_data.uvList[currentUV].u = atof(param1.c_str());
_data.uvList[currentUV].v = atof(param2.c_str());
currentUV++;
}else if(type=="vn"){
_data.normalList[currentNormal].x = atof(param1.c_str());
_data.normalList[currentNormal].y = atof(param2.c_str());
_data.normalList[currentNormal].z = atof(param3.c_str());
currentNormal++;
}else if(type=="f"){
//...Within loop over each vertex in a single face ...
if(endPos != string::npos){
// Value before 1st "/" (Vertex index).
// ...find value in string...
_data.faceList[currentFace].vertex[i] = atoi(token.c_str()) -1; // File format begins indices from 1.
// Value between slashes (UV index).
// ...find value in string...
_data.faceList[currentFace].uv[i] = atoi(token.c_str()) -1;
// Value after 2nd "/" (Normal index).
// ...find value in string...
_data.faceList[currentFace].normal[i] = atoi(token.c_str()) -1;
}
//...End of loop over every vertex in a single face...
currentFace++;
}
}
return _data;
}
And the structs ObjFace, ObjVert, ObjUV and ObjNormal are defined as:
struct ObjVert{
float x, y, z;
};
struct ObjUV{
float u, v;
};
struct ObjNormal{
float x, y, z;
};
// Contains indexes.
struct ObjFace{
int* vertex;
int* uv;
int* normal;
};
Thanks for any help. Also, any good sources on avoiding these types of errors in future would be appreciated.
| I had typed up some silly response which I realized wasn't right...but I had to keep thinking on it, and I came up with another idea.
Where is this object being assigned?
Your code isn't clear if data and _data are the same object or not, but I noticed that your method there seems to return _data as an object. I'm led to believe that perhaps you are using an assignment like ObjData data = LoadObj("myfilename"); somewhere?
If this is the case, I believe your problem may come from a lack of a copy constructor or overloaded assignment operator for your ObjData class. (I'm not a C++ guru, so I don't recall exactly which one this would fall under. Hopefully someone else can confirm if we're on the right track).
If your pointers are not being copied correctly during the copy and assignment (returning from LoadObj calls a copy constructor iirc, and then the obvious assignment to data), then even though you intended to already have an array of int at that location, you may in fact be accessing uninitialized memory, thus causing your Access Violation.
I'm not an expert with either copy constructors or overloaded assignment operators, but a quick way around this would be to return a pointer to an ObjData rather than to return an object itself.
|
3,048,689 | 3,048,749 | Self referential type | What type T makes the following code compilable?
T f(){ return &f; }
I'd prefer a C answer, but I marked the question as C and C++ in case there is only an answer using templates.
| I hope this isn't cheating (C++ only):
class T {
private:
T (*_func)();
public:
T(T (*func)()) : _func(func) {}
T operator()() {
return *this;
}
};
T f() { return &f; }
int main() {
f()()()()()()()();
}
|
3,048,761 | 3,048,799 | Howto mix TDD and RAII | I'm trying to make extensive tests for my new project but I have a problem.
Basically I want to test MyClass. MyClass makes use of several other class which I don't need/want to do their job for the purpose of the test. So I created mocks (I use gtest and gmock for testing)
But MyClass instantiate everything it needs in it's constructor and release it in the destructor. That's RAII I think.
So I thought, I should create some kind of factory, which creates everything and gives it to MyClass's constructor. That factory could have it's fake for testing purposes. But's thats no longer RAII right?
Then what's the good solution here?
| You mock it the same way you'd mock any other class. Have the RAII class' constructor take care of it.
class MyInterface
{
virtual void MyApiFunction(int myArg)
{
::MyApiFunction(myArg);
}
};
class MyRAII : boost::noncopyable //Shouldn't be copying RAII classes, right?
{
MyInterface *api;
public:
MyRAII(MyInterface *method = new MyInterface)
: api(method)
{
//Aquire resource
}
~MyRAII()
{
//Release resource
delete api;
}
};
class MockInterface : public MyInterface
{
MOCK_METHOD1(MyApiFunction, void(int));
};
TEST(Hello, Hello)
{
std::auto_ptr<MockInterface> mock(new MockInterface);
EXPECT_CALL(*mock, ....)...;
MyRAII unitUnderTest(mock.release());
}
|
3,048,809 | 3,048,938 | error in C++, within context | I received homework to make program without casting using constructors so this is my code, I have two classes:
class Base {
protected:
int var;
public:
Base(int var = 0);
Base(const Base&);
Base& operator=(const Base&);
virtual ~Base(){};
virtual void foo();
void foo() const;
operator int();
};
class Derived: public Base {
public:
Derived(int var): Base(var){};
Derived(const Base&);
Derived& Derived::operator=(const Base& base);
~Derived(){};
virtual void foo();
};
here two of my functions of Derived:
Derived::Derived(const Base& base){
if (this != &base){
var=base.var;
}
}
Derived& Derived::operator=(const Base& base){
if (this != &base){
var=base.var;
}
return *this;
}
but I have an error within context when I call these rows
Base base(5);
Base *pderived = new Derived(base); //this row works perfectly
Derived derived = *pderived; // I think the problem is here
thanks for any help
| You can only access protected members from another object if that object is of the same type as the object that is trying to access it. In your example the constructor and assignment operator both take in a const Base& so there is no guarantee that the actual object will be of type Derived.
|
3,048,946 | 3,232,123 | Recommendations for a C++ polymorphic, seekable, binary I/O interface | I've been using std::istream and ostream as a polymorphic interface for random-access binary I/O in C++, but it seems suboptimal in numerous ways:
64-bit seeks are non-portable and error-prone due to streampos/streamoff limitations; currently using boost/iostreams/positioning.hpp as a workaround, but it requires vigilance
Missing operations such as truncating or extending a file (ala POSIX ftruncate)
Inconsistency between concrete implementations; e.g. stringstream has independent get/put positions whereas filestream does not
Inconsistency between platform implementations; e.g. behavior of seeking pass the end of a file or usage of failbit/badbit on errors
Don't need all the formatting facilities of stream or possibly even the buffering of streambuf
streambuf error reporting (i.e. exceptions vs. returning an error indicator) is supposedly implementation-dependent in practice
I like the simplified interface provided by the Boost.Iostreams Device concept, but it's provided as function templates rather than a polymorphic class. (There is a device class, but it's not polymorphic and is just an implementation helper class not necessarily used by the supplied device implementations.) I'm primarily using large disk files, but I really want polymorphism so I can easily substitute alternate implementations (e.g. use stringstream instead of fstream for unit tests) without all the complexity and compile-time coupling of deep template instantiation.
Does anyone have any recommendations of a standard approach to this? It seems like a common situation, so I don't want to invent my own interfaces unnecessarily. As an example, something like java.nio.FileChannel seems ideal.
My best solution so far is to put a thin polymorphic layer on top of Boost.Iostreams devices. For example:
class my_istream
{
public:
virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way) = 0;
virtual std::streamsize read(char* s, std::streamsize n) = 0;
virtual void close() = 0;
};
template <class T>
class boost_istream : public my_istream
{
public:
boost_istream(const T& device) : m_device(device)
{
}
virtual std::streampos seek(stream_offset off, std::ios_base::seekdir way)
{
return boost::iostreams::seek(m_device, off, way);
}
virtual std::streamsize read(char* s, std::streamsize n)
{
return boost::iostreams::read(m_device, s, n);
}
virtual void close()
{
boost::iostreams::close(m_device);
}
private:
T m_device;
};
| I just ended up going with a set of abstract interfaces similar to what I outlined in the question. There don't seem to be any lightweight, polymorphic standards for this...
|
3,049,123 | 3,050,142 | strcmp() but with 0-9 AFTER A-Z? (C/C++) | For reasons I completely disagree with but "The Powers (of Anti-Usability) That Be" continue to decree despite my objections, I have a sorting routine which does basic strcmp() compares to sort by its name. It works great; it's hard to get that one wrong. However, at the 11th hour, it's been decided that entries which begin with a number should come AFTER entries which begin with a letter, contrary to the ASCII ordering. They cite the EBCDIC standard has numbers following letters so the prior assumption isn't a universal truth, and I have no power to win this argument... but I digress.
Therein lies my problem. I've replaced all appropriate references to strcmp with a new function call nonstd_strcmp, and now need to implement the modifications to accomplish the sort change. I've used a FreeBSD source as my base: http://freebsd.active-venture.com/FreeBSD-srctree/newsrc/libkern/strncmp.c.html
if (n == 0)
return (0);
do {
if (*s1 != *s2++)
return (*(const unsigned char *)s1 -
*(const unsigned char *)(s2 - 1));
if (*s1++ == 0)
break;
} while (--n != 0);
return (0);
I guess I might need to take some time away to really think about how it should be done, but I'm sure I'm not the only one who's experienced the brain-deadness of just-before-release spec changes.
| In this special case with only uppercase letters (as mentioned by the OP in comments) and digits 0-9, you could also omit the order table and instead multiply both differing characters by 4 and compare the results modulo 256. The range of ASCII digits (48 to 57) will not overflow 8 bits (57 × 4 = 228), but the range of uppercase letters (65 to 90) will (65 × 4 = 260). When we compare the multiplied values modulo 256, the value for each letter will be less than that of any digit: 90×4 % 256 = 104 < 192 = 48×4
The code might look something like:
int my_strcmp (const char *s1, const char *s2) {
for (; *s1 == *s2 && *s1; ++s1, ++s2);
return (((*(const unsigned char *)s1) * 4) & 0xFF) - \
(((*(const unsigned char *)s2) * 4) & 0xFF);
}
Of course, the order table solution is far more versatile in general as it allows one to define a sort order for every character—this solution is sensible only for this special case with uppercase letters vs digits. (But e.g. on microcontroller platforms, saving even the small amount of memory used by the table can be a real benefit.)
|
3,049,404 | 3,049,483 | Apples, oranges, and pointers to the most derived c++ class | Suppose I have a bunch of fruit:
class Fruit { ... };
class Apple : public Fruit { ... };
class Orange: public Fruit { ... };
And some polymorphic functions that operate on said fruit:
void Eat(Fruit* f, Pesticide* p) { ... }
void Eat(Apple* f, Pesticide* p) { ingest(f,p); }
void Eat(Orange* f, Pesticide* p) { peel(f,p); ingest(f,p); }
OK, wait. Stop right there. Note at this point that any sane person would make Eat() a virtual member function of the Fruit classes. But that's not an option, because I am not a sane person. Also, I don't want that Pesticide* in the header file for my fruit class.
Sadly, what I want to be able to do next is exactly what member functions and dynamic binding allow:
typedef list<Fruit*> Fruits;
Fruits fs;
...
for(Fruits::iterator i=fs.begin(), e=fs.end(); i!=e; ++i)
Eat(*i);
And obviously, the problem here is that the pointer we pass to Eat() will be a Fruit*, not an Apple* or an Orange*, therefore nothing will get eaten and we will all be very hungry.
So what I really want to be able to do instead of this:
Eat(*i);
is this:
Eat(MAGIC_CAST_TO_MOST_DERIVED_CLASS(*i));
But to my limited knowledge, such magic does not exist, except possibly in the form of a big nasty if-statement full of calls to dynamic_cast.
So is there some run-time magic of which I am not aware? Or should I implement and maintain a big nasty if-statement full of dynamic_casts? Or should I suck it up, quit thinking about how I would implement this in Ruby, and allow a little Pesticide to make its way into my fruit header?
Update: Instead of the contrived bit with the bare Eat functions and Pesticide, suppose instead that I just don't want to put Eat in the fruit because it makes no sense. A fruit that knows how to eat itself? Pshaw. Instead I need an Eater class with an Eat function, with different code for eating each kind of fruit, and some default code in case it's a fruit that the eater doesn't recognize:
class Eater
{
public:
void Eat(Apple* f) { wash(); nom(); }
void Eat(Orange* f) { peel(); nom(); }
void Eat(Fruit* f) { nibble(); }
};
...
Eater me;
for(Fruits::iterator i=fs.begin(), e=fs.end(); i!=e; ++i)
me.Eat(*i); //me tarzan! me eat!
But again, this doesn't work, and the straightforward solution in C++ seems to be a bunch of calls to dynamic_cast.
However, as one of the answers suggests, there may be another clever solution. What if Fruits exposed the qualities that mattered to eaters, with functions like MustPeel() and MustWash()? Then you could get by with a single Eat() function ...
Update: Daniel Newby points out that using Visitor also solves the problem as presented ... but this requires a bit of a semantic headstand (Fruit::use or Fruit::beEaten?).
While I'd like to accept several answers, I think psmears's answer is actually the best one for future readers. Thanks, everyone.
| When a question like this comes up, it's good to look at exactly why you want to make particular decisions - for instance, why do you not want the Fruit classes to know about Pesticide?
I'm sure there is a good reason for this - but expressing that reason will help clarify in your mind exactly what your aims are - and this often sheds a new light on a possible angle for structuring the program.
For instance, you might end up adding new virtual methods "IsEdible" and "PrepareForEating". Then you can implement these for each fruit, and implement one generic Eat method that works for all fruits - and ingests the pesky pesticide too - all without the Fruit classes knowing anything about it.
Of course, depending on your precise aims, that may be totally inappropriate - which is why you'll have to clarify the example in your own head :-)
|
3,049,445 | 3,049,468 | _dl_runtime_resolve -- When do the shared objects get loaded in to memory? | We have a message processing system with high performance demands. Recently we have noticed that the first message takes many times longer then subsequent messages. A bunch of transformation and message augmentation happens as this goes through our system, much of it done by way of external lib.
I just profiled this issue (using callgrind), comparing a "run" of just one message with a "run" of many messages (providing a baseline of comparison).
The main difference I see is the function "do_lookup_x" taking up a huge amount of time. Looking at the various calls to this function, they all seem to be called by the common function: _dl_runtime_resolve. Not sure what this function does, but to me this looks like the first time the various shared libraries are being used, and are then being loaded in to memory by the ld.
Is this a correct assumption? That the binary will not load the shared libraries in to memory until they are being prepped for use, therefore we will see a massive slowdown on the first message, but on none of the subsequent?
How do we go about avoiding this?
Note: We operate on the microsecond scale.
| From the ld.so(8) man page, ENVIRONMENT section:
LD_BIND_NOW
(libc5; glibc since 2.1.1) If set to a non-empty string, causes
the dynamic linker to resolve all symbols at program startup
instead of deferring function call resolution to the point when
they are first referenced. This is useful when using a debug-
ger.
So, LD_BIND_NOW=y ./timesensitiveapp.
|
3,049,597 | 3,049,633 | STL ostream_iterator writes to screen even though I overwrote it? | In my code, I have the following:
ostream_iterator<double> doubleWriter(cout, " ~ ");
// ...
*doubleWriter = 1.1;
doubleWriter++;
*doubleWriter = 2.2;
*doubleWriter = 3.3; // shouldn't 2.2 be overwritten?
doubleWriter++;
*doubleWriter = 44.2;
cout << endl << endl;
I expected it to output this:
1.1 ~ 3.3 ~ 44.2 ~
Instead, the output was this:
1.1 ~ 2.2 ~ 3.3 ~ 44.2 ~
Why does this happen? It would seem to me that I overwrite 2.2 and stick 3.3 in its spot, since I didn't increment. Is incrementation an optional step?
| For standard ostream_iterator, operator ++ (both prefix and postfix) is a no-op. It does nothing and makes no difference.
There's no need to do the ++ manually, since the iterator always "advances" when you output something through it.
P.S. According to library Defect Report 485, the intent was to require that assignment and increments alternate. This requirement apparently haven't made it into the current version of the standard. But in the future revisions, it will be included. In other words, as others already noted, the proper way to use output iterator is to alternate assignments and increments.
|
3,049,736 | 3,610,312 | Compiling a DLL which includes Ogre3D gives an assertion error when used | I have a framework that I am building and is being compiled into a static library to be used by other projects. The library works perfectly without issues. The problem is that the link time is very long for the projects that use the library so I thought I will make a DLL project of the same framework. I started with baby steps and created an MFC DLL project through visual studio. The project has the following header:
/// --------------------------------------------
#ifndef OGRECORE_H
#define OGRECORE_H
#ifdef OGREFW_EXPORT
#define OGREFW_DLL __declspec(dllexport)
#else
#define OGREFW_DLL __declspec(dllimport)
#endif
class OgreRoot;
namespace OgreFW
{
class OGREFW_DLL OgreCore// : public OIS::KeyListener, public OIS::MouseListener
{
public:
OgreCore();
~OgreCore();
};
};
#endif // OGRECORE_H
and this is the source
#include "stdafx.h"
#include "OgreCore.h"
//#include "Ogre.h"
//#include "OgreRoot.h"
//#include "OgreRenderWindow.h"
//#include "OgreLog.h"
//#include "OgreLogManager.h"
//#include "OgreOverlay.h"
//#include "OgreViewport.h"
//#include "OgreRenderWindow.h"
//#include "OgreFrameListener.h"
//#include "OgreWindowEventUtilities.h"
//#include "OgreSceneNode.h"
//#include "OgreEntity.h"
//#include "OgreManualObject.h"
//#include "OgreMeshManager.h"
//#include "OgreConfigFile.h"
//#include "OgreOverlayContainer.h"
//#include "OgreOverlayManager.h"
namespace OgreFW
{
OGREFW_DLL
OgreCore::OgreCore()
{
}
// ------------------------
OGREFW_DLL
OgreCore::~OgreCore()
{
}
}
As you can see I have commented out Ogre includes. When a project uses the compiled DLL and constructs this (OgreCore) class, it works perfectly fine. As soon as uncomment one of the Ogre includes and compile the DLL again, the project that uses the DLL now gives an assertion error. The full details can be found here in the Ogre forum post. I posted the question there first but since its not really an Ogre specific question I thought I will try here as well. The link to the Ogre post is:
http://www.ogre3d.org/forums/viewtopic.php?f=2&t=58403
Thank you in advance
| Finally found the solution HERE
Short explanation is that the DLL I was creating should be a non-MFC DLL without a DLL main, but Visual Studio gives me an MFC DLL template.
|
3,049,806 | 3,049,820 | C++ destructor problem with boost::scoped_ptr | I have a question about the following code:
#include <iostream>
#include <boost/scoped_ptr.hpp>
class Interface
{
};
class A : public Interface
{
public:
A() { std::cout << "A()" << std::endl; }
virtual ~A() { std::cout << "~A()" << std::endl; }
};
Interface* get_a()
{
A* a = new A;
return a;
}
int main()
{
{
std::cout << "1" << std::endl;
boost::scoped_ptr<Interface> x(get_a());
std::cout << "2" << std::endl;
}
std::cout << "3" << std::endl;
}
It creates the following output:
1
A()
2
3
As you can see, it doesn't call the destructor of A.
The only way I see to get the destructor of A being called, is to add a destructor for the Interface class like this:
virtual ~Interface() { }
But I really want to avoid any Implementation in my Interface class and virtual ~Interface() = 0; doesn't work (produces some linker errors complaining about a non existing implementation of ~Interface().
So my question is: What do I have to change in order to make the destructor being called, but (if possible) leave the Interface as an Interface (only abstract methods).
| You must define a virtual destructor in the base class, otherwise you'll get no polymorphic behavior.
And more importantly, you get undefined behavior otherwise; §5.3.5/3:
If the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined.
Emphasis mine.
I'd argue the best is this one:
class Interface
{
public:
virtual ~Interface(void) = 0;
};
inline Interface::~Interface(void) {}
The compiler can easily inline this, unlike a solution where the implementation resides in a source file. (Speaking of which, this solution doesn't even mandate you have one.) It also leaves the class pure virtual.
|
3,049,824 | 3,049,841 | C++: Return NULL instead of struct | I have a struct Foo. In pseudocode:
def FindFoo:
foo = results of search
foundFoo = true if a valid foo has been found
return foo if foundFoo else someErrorCode
How can I accomplish this in C++?
Edited to remove numerous inaccuracies.
| C++ objects can never be null or empty. Pointers can hold a null pointer value indicating they point at nothing.
The typical solution would be to throw an exception. Otherwise, use a pointer; just make sure you aren't returning the address of a temporary.
I wouldn't recommend trying to teach yourself C++ with knowledge from other languages, you'll hurt yourself. Grab a good beginner-level book, it's the best way to learn.
|
3,049,866 | 3,049,871 | C++: Trouble with tr1::bind (C2065) | I'm getting a compiler error with bind:
using namespace std;
bool odp(int arg1, int arg2);
// ...
find_if(vec.begin(), vec.end(), tr1::bind(odp, iValue, _1)); // C2065
My goal is to curry odp(), so its first argument is iValue, and apply that function in find_if.
The error:
C2065: '_1' : undeclared identifier.
What am I doing wrong?
| You need using namespace std::tr1::placeholders or using std::tr1::placeholders::_1.
|
3,049,936 | 3,049,957 | Trying to instantiate a class member in C++ with a variable name | I am writing a program for class that is asking us to create a class of "book". We are then supposed to create new instantiations of that class upon demand from the user. I am new to C++ so I am attempting to code this out but am running into a problem.
The main problem is how do I instantiate a class with a variable if I don't know how many I will have to do ahead of time. The user could ask to add 1 book or 1000. I am looking at this basic code:
This is the simple code I started with. I wanted to have an index int keep a number and have the book class I create be called by that int (0, 1, 2, etc...) So I attempted to convert the incoming index int into a string, but I'm kind of stuck from here.
void addBook(int index){
string bookName;
std::stringstream ss;
ss << index;
book bookName;
cout << "Enter the Books Title: ";
cin >> bookName.title;
}
But obviously this doesn't work as "bookName" is a string to the computer and not the class member I tried to create.
All of the tutorials I have seen online and in my text show the classes being instantiated with names in the code, but I just don't know how to make it variable so I can create any amount of "books" that the user might want. Any insight on this would be appreciated. Thank you for your time.
| Given your type book, if you want to create a list of books, try using a container like std::vector, std::list or std::deque.
typedef std::vector<book> library_type;
library_type library;
book catch22("Catch 22")
library.push_back(catch22);
book haltingState("Halting State");
library.push_back(haltingState);
You can create books and add to the library from a loop, which sounds like what you want.
Your choice of container type will depend on the access pattern you want. For example, a std::vector is good if you want to add books like this and you rarely want to remove them in an arbitrary order. It's fairly straightforward to change the type later if you change your mind about this.
|
3,049,952 | 3,049,976 | Getting functions of inherited functions to be called | Let's say I have a base class Animal from which a class Cow inherits, and a Barn class containing an Animal vector, and let's say the Animal class has a virtual function scream(), which Cow overrides.
With the following code:
Animal.h
#ifndef _ANIMAL_H
#define _ANIMAL_H
#include <iostream>
using namespace std;
class Animal {
public:
Animal() {};
virtual void scream() {cout << "aaaAAAAAAAAAAGHHHHHHHHHH!!! ahhh..." << endl;}
};
#endif /* _ANIMAL_H */
Cow.h
#ifndef _COW_H
#define _COW_H
#include "Animal.h"
class Cow: public Animal {
public:
Cow() {}
void scream() {cout << "MOOooooOOOOOOOO!!!" << endl;}
};
#endif /* _COW_H */
Barn.h
#ifndef _BARN_H
#define _BARN_H
#include "Animal.h"
#include <vector>
class Barn {
std::vector<Animal> animals;
public:
Barn() {}
void insertAnimal(Animal animal) {animals.push_back(animal);}
void tortureAnimals() {
for(int a = 0; a < animals.size(); a++)
animals[a].scream();
}
};
#endif /* _BARN_H */
and finally main.cpp
#include <stdlib.h>
#include "Barn.h"
#include "Cow.h"
#include "Chicken.h"
/*
*
*/
int main(int argc, char** argv) {
Barn barn;
barn.insertAnimal(Cow());
barn.tortureAnimals();
return (EXIT_SUCCESS);
}
I get this output:
aaaAAAAAAAAAAGHHHHHHHHHH!!! ahhh...
How should I code this to get MOOooooOOOOOOOO!!! (and whatever other classes inheriting Animal wants scream() to be) instead?
| A slight modification that stores pointers to animals should help:
#ifndef _BARN_H
#define _BARN_H
#include "Animal.h"
#include <vector>
class Barn {
std::vector<Animal *> animals;
public:
Barn() {}
void insertAnimal(Animal *animal) {animals.push_back(animal);}
void tortureAnimals() {
for(int a = 0; a < animals.size(); a++)
animals[a]->scream();
}
};
int main(int argc, char** argv) {
Barn barn;
barn.insertAnimal(new Cow());
barn.tortureAnimals();
// should clean up barn contents here...
return (EXIT_SUCCESS);
}
|
3,050,129 | 3,050,138 | Will the compiler optimize escaping an inner loop? | The code I have looks like this (all uses of done shown):
bool done = false;
for(int i = 0; i < big; i++)
{
...
for(int j = 0; j < wow; j++)
{
...
if(foo(i,j))
{
done = true;
break;
}
...
}
if(done) break;
...
}
will any compilers convert it to this:
for(int i = 0; i < big; i++)
{
...
for(int j = 0; j < wow; j++)
{
...
if(foo(i,j))
goto __done; // same as a labeled break if we had it
...
}
...
}
__done:;
Note: While I'm mostly interested in if the if(done)break; gets bypassed and removed as dead code, I'm also interested in if it and done gets removed altogether.
| Obviously this depends on the compiler. The best thing to do when you're unsure is to view the compiler's assembly output (all popular compilers have a switch for this). Even if you aren't familiar with assembly, you can at least compare the debug version with the optimized version.
That being said, this is one of the few situations where goto is NOT a bad idea. Feel free to use it to break out of inner loops.
Edit
Just tried the following in VS2010 and it does indeed optimize the outer conditional:
bool done = false;
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
if(i == 7 && j == 3)
{
done = true;
break;
}
}
if(done) break;
}
return 0;
|
3,050,400 | 3,050,404 | How do I create a duplicate instance of object contained in a shared pointer in c++? | I have an object which has both a copy constructor and assignment operator defined. It is enclosed inside a shared pointer.
I want to make another shared pointer that contains a copy of the original shared pointer (i.e. new shared pointer to a new memory location, which however, has the same data as the original object).
Thanks for any assistance.
| You invoke the copy constructor when creating the new object:
std::shared_ptr<C> ptr1(new C()); // invokes the default constructor
std::shared_ptr<C> ptr2(new C(*ptr1)); // invokes the copy constructor
In this case, it's really no different than if you have regular, dumb pointers.
|
3,050,409 | 3,050,833 | error LNK2001: unresolved external symbol | I am receiving this error
>GXRenderManager.obj : error LNK2001: unresolved external symbol "private: static class GXRenderer * GXRenderManager::renderDevice" (?renderDevice@GXRenderManager@@0PAVGXRenderer@@A)
The following is my code...
GXDX.h
class GXDX: public GXRenderer {
public:
void Render();
void StartUp();
};
GXGL.h
class GXGL: public GXRenderer {
public:
void Render();
void StartUp();
};
GXRenderer
class GXRenderer {
public:
virtual void Render() = 0;
virtual void StartUp() = 0;
};
GXRenderManager.h
#ifndef GXRM
#define GXRM
#include <windows.h>
#include "GXRenderer.h"
#include "GXDX.h"
#include "GXGL.h"
enum GXDEVICE {
DIRECTX,
OPENGL
};
class GXRenderManager {
public:
static int Ignite(GXDEVICE);
private:
static GXRenderer *renderDevice;
};
#endif
GXRenderManager.cpp
#include "GXRenderManager.h"
int GXRenderManager::Ignite(GXDEVICE DeviceType)
{
switch(DeviceType)
{
case DIRECTX:
GXRenderManager::renderDevice = new GXDX;
return 1;
break;
case OPENGL:
GXRenderManager::renderDevice = new GXGL;
return 1;
break;
default:
return 0;
}
}
main.cpp
#include "GXRenderManager.h"
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
LPSTR lpCmdLine, int nCmdShow)
{
return 0;
}
I am not trying to get it to do anything. I am just trying to compile with no errors. I am new with all this so if anyone can give me a hand. that will be great. thanks
| You need an actual definition (or instance) for the static member GXRenderer::renderDevice. The class declares it, but there needs to be a definition of it in exactly one place.
In your GXRenderManager.cpp file have a line like so:
GXRenderer * GXRenderer::renderDevice = NULL;
or whatever initialization might be appropriate.
|
3,050,621 | 3,050,764 | File writing with overlapped IO vs file writing in a separate thread | Is there any advantage in using file writing with overlapped IO in Windows, vs just doing the file writing in a separate thread that I create?
[Edit - please note that I'm doing the file writes without system caching, ie I use the FILE_FLAG_NO_BUFFERING flag in CreateFile)
| Since all writes are cached in the system cache by default, there is little advantage to doing overlapped I/O or creating a separate thread for writes at all. Most WriteFile calls are just memcpys at their core, which are lazily written to disk by the OS in an optimal fashion with other writes.
You can, of course, turn off buffered I/O via flags to CreateFile and then there are advantages to doing some sort of async I/O - but you probably didn't/shouldn't do that.
Edit
The OP has clarified they are in fact using unbuffered I/O. In that case the two suggested solutions are nearly identical; internally Windows uses a thread pool to service async I/O requests. But hypothetically Windows can be more efficient because their half is implemented in the kernel, has less context switches, etc.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.