question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,615,916 | 1,615,930 | Most natural blinking visualization? | What is the ideal method for blinking information on a display to draw attention to an error condition in some data in a natural fashion.
Should the blink be all on / all off, or should there be an aspect of fast ramp up and down of brightness instead of instant on / off transitions?
Should the blink be equally on and off, or should it be something like 60% time on alternating with 40% time off?
What is the most natural frequency? How many blinks per second?
The goal is to draw attention to the error in some data, but to look natural and ascetically pleasing.
Hopefully, the solution is not to hard to implement using Qt and C++.
| I've always found the highlight effect present in various javascript libraries pleasing. It basically flashes the background of the object a bright-ish yellow immediately, then fades back to the original background color.
|
1,616,086 | 1,616,621 | Shifting elements in an array C++ | I've developed a method called "rotate" to my stack object class. What I did was that if the stack contains elements: {0,2,3,4,5,6,7} I would needed to rotate the elements forwards and backwards.
Where if i need to rotate forwards by 2 elements, then we would have, {3,4,5,6,7,0,2} in the array. And if I need to rotate backwards, or -3 elements, then, looking at the original array it would be, {5,6,7,0,2,3,4}
So the method that I have developed works fine. Its just terribly ineffecient IMO. I was wondering if I could wrap the array around by using the mod operator? Or if their is useless code hangin' around that I havent realized yet, and so on.
I guess my question is, How can i simplify this method? e.g. using less code. :-)
void stack::rotate(int r)
{
int i = 0;
while ( r > 0 ) // rotate postively.
{
front.n = items[top+1].n;
for ( int j = 0; j < bottom; j++ )
{
items[j] = items[j+1];
}
items[count-1].n = front.n;
r--;
}
while ( r < 0 ) // rotate negatively.
{
if ( i == top+1 )
{
front.n = items[top+1].n;
items[top+1].n = items[count-1].n; // switch last with first
}
back.n = items[++i].n; // second element is the new back
items[i].n = front.n;
if ( i == bottom )
{
items[count-1].n = front.n; // last is first
i = 0;
r++;
continue;
}
else
{
front.n = items[++i].n;
items[i].n = back.n;
if ( i == bottom )
{
i = 0;
r++;
continue;
}
}
}
}
| The function rotate below is based on reminders (do you mean this under the 'mod' operation?)
It is also quite efficient.
// Helper function.
// Finds GCD.
// See http://en.wikipedia.org/wiki/Euclidean_algorithm#Implementations
int gcd(int a, int b) {return b == 0 ? a : gcd(b, a % b);}
// Number of assignments of elements in algo is
// equal to (items.size() + gcd(items.size(),r)).
void rotate(std::vector<int>& items, int r) {
int size = (int)items.size();
if (size <= 1) return; // nothing to do
r = (r % size + size) % size; // fits r into [0..size)
int num_cycles = gcd(size, r);
for (int first_index = 0; first_index < num_cycles; ++first_index) {
int mem = items[first_index]; // assignment of items elements
int index = (first_index + r) % size, index_prev = first_index;
while (index != first_index) {
items[index_prev] = items[index]; // assignment of items elements
index_prev = index;
index = (index + r) % size;
};
items[index_prev] = mem; // assignment of items elements
}
}
Of course if it is appropriate for you to change data structure as described in other answers, you can obtain more efficient solution.
|
1,616,093 | 1,682,309 | does presence of mutex help getting rid of volatile key word ? | I have a multi-R/W lock class that keeps the read, write and pending read , pending write counters. A mutex guards them from multiple threads.
My question is Do we still need the counters to be declared as volatile so that the compiler won't screw it up while doing the optimization.
Or does the compiler takes into account that the counters are guarded by the mutex.
I understand that the mutex is a run time mechanism to for synchronization and "volatile" keyword is a compile time indication to the compiler to do the right thing while doing the optimizations.
Regards,
-Jay.
| There are 2 basically unrelated items here, that are always confused.
volatile
threads, locks, memory barriers, etc.
volatile is used to tell the compiler to produce code to read the variable from memory, not from a register. And to not reorder the code around. In general, not to optimize or take 'short-cuts'.
memory barriers (supplied by mutexes, locks, etc), as quoted from Herb Sutter in another answer, are for preventing the CPU from reordering read/write memory requests, regardless of how the compiler said to do it. ie don't optimize, don't take short cuts - at the CPU level.
Similar, but in fact very different things.
In your case, and in most cases of locking, the reason that volatile is NOT necessary, is because of function calls being made for the sake of locking. ie:
Normal function calls affecting optimizations:
external void library_func(); // from some external library
global int x;
int f()
{
x = 2;
library_func();
return x; // x is reloaded because it may have changed
}
unless the compiler can examine library_func() and determine that it doesn't touch x, it will re-read x on the return. This is even WITHOUT volatile.
Threading:
int f(SomeObject & obj)
{
int temp1;
int temp2;
int temp3;
int temp1 = obj.x;
lock(obj.mutex); // really should use RAII
temp2 = obj.x;
temp3 = obj.x;
unlock(obj.mutex);
return temp;
}
After reading obj.x for temp1, the compiler is going to re-read obj.x for temp2 - NOT because of the magic of locks - but because it is unsure whether lock() modified obj. You could probably set compiler flags to aggressively optimize (no-alias, etc) and thus not re-read x, but then a bunch of your code would probably start failing.
For temp3, the compiler (hopefully) won't re-read obj.x.
If for some reason obj.x could change between temp2 and temp3, then you would use volatile (and your locking would be broken/useless).
Lastly, if your lock()/unlock() functions were somehow inlined, maybe the compiler could evaluate the code and see that obj.x doesn't get changed. But I guarantee one of two things here:
- the inline code eventually calls some OS level lock function (thus preventing evaluation) or
- you call some asm memory barrier instructions (ie that are wrapped in inline functions like __InterlockedCompareExchange) that your compiler will recognize and thus avoid reordering.
EDIT: P.S. I forgot to mention - for pthreads stuff, some compilers are marked as "POSIX compliant" which means, among other things, that they will recognize the pthread_ functions and not do bad optimizations around them. ie even though the C++ standard doesn't mention threads yet, those compilers do (at least minimally).
So, short answer
you don't need volatile.
|
1,616,571 | 1,616,642 | c++ send data to multiple UDP sockets | I got a c++ non-blocking server socket, with all the clients stored in a std::map structure.
I can call the send() method for each clientObject to send something to the connected client and that works pretty good already.
But for sending a message to all (broadcast?) i wanna know:
there is something better than do a for/loop with all the clients and call to ClientObject->send("foo") each iteration?
Or should i just try having a peek on multicast sockets?
Thanks in advance.
Rag.
| Multicast is only an option if you're communicating over a LAN. It won't work over the Internet.
What you may want to do here is to demultiplex the sockets using asynchronous I/O. This allows you to send data to multiple sockets at the same time, and use asynchronous event handlers to deal with each transmission.
I would recommend looking into Boost ASIO for a portable way to do this. You can also use OS specific system calls, (such as poll/select on UNIX or epoll on Linux) to do this, but it is a lot more complicated.
|
1,616,827 | 1,616,960 | Problem with Pointers in C++ | char *str = NULL;
str = Operation(argv[1]);
cout << Cal(str);
Operation function return a pointer, but I really don't know why str in Cal is null.
in line 2, it still has content. What am I missing?
char* Operation(char* name)
{
fstream file(name,ios::in);
char c;
char stack[256]; int count_stack = -1;
char result[256]; int count_result = -1;
while ( !file.eof() )
{
c = file.get();
if ( c=='(')
{
count_stack++;
stack[count_stack] = c ;
}
else if ( isOperand(c) )
{
count_result++;
result[count_result] = c;
}
else if ( isOperator(c) )
if ( isOperator( (stack[count_stack]) )>0 )
if ( isOperator(c) > isOperator( stack[count_stack] ) )// dua ra so sanh khi trong stack co n>=1 ptu
{
count_result++;
result[count_result] = c;
}
else
{
count_result++;
result[count_result] = (stack[count_stack]);
stack[count_stack]= c;
}
else
{
count_stack++;
stack[count_stack] = c ;
}
else if ( c==')') // Neu gap dau ngoac dong se lay het phan tu ra den khi gap ngoac mo
{
while( stack[count_stack] != '(')
{
count_result++;
result[count_result] = stack[count_stack];
count_stack--;
}
count_stack--;
}
}
while ( count_stack >=0 )
{
count_result++;
result[count_result] = stack[count_stack];
count_stack--;
}
return &result[0];
}
This is the Operation Function . I'm really bad in pointer :P
| Well, firstly, in your Operation function you're returning a pointer to a temporary stack array. In Operation you declare char result[256] as a temporary stack variable. The 256 bytes you allocate here are ONLY valid for the duration of the Operation function. So using the pointer to result after Operation returns will cause undefined behavior.
To fix this, you have a few options:
1) You can allocate result on the heap, (using the new operator)
2) Even better, instead of returning a char* pointer, simply return an std::string object so you don't need to worry about allocating/deallocating memory.
3) Finally, if your program is single-threaded, you can also simply make char result[256] a static variable by declaring static char result[256]. This way, the pointer will be valid even after you return from Operation.
I would recommend option 2.
|
1,616,855 | 1,618,134 | Boost::Xpressive compile puzzle under MinGW | Switching to GCC for the first time, and I'm getting a bit confused by what the compiler is telling me here. Essentially, it's behaving like boost::xpressive::wsregex is not defined (I believe).
Here is the relevant code:
#include "criterion.h"
#include <string>
#include <boost/xpressive/xpressive.hpp>
//More lines of code omitted here
class perlRegex : public regexClass
{
private:
std::wstring regexString;
boost::xpressive::wsregex regex; // This is the line complained about
public:
unsigned __int32 getPriorityClass() const;
BOOL include(fileData &file) const;
unsigned int directoryCheck(const std::wstring& /*directory*/) const;
std::wstring debugTree() const;
perlRegex(const std::wstring& inRegex);
};
And here is the error:
regex.h:46: error: using-declaration for non-member at class scope
regex.h:46: error: expected `;' before "regex"
What I'm confused about here is that I'm declaring a member, yet it complains that I'm using a member somewhere else.
Have I forgotten to #include something?
Thanks in advance,
Billy3
| cygwin and mingw do not support wide characters, so xpressive can't either. See the following from xpressive_fwd.hpp:
#if defined(BOOST_NO_CWCHAR) | \
defined(BOOST_NO_CWCTYPE) | \
defined(BOOST_NO_STD_WSTRING)
# ifndef BOOST_XPRESSIVE_NO_WREGEX
# define BOOST_XPRESSIVE_NO_WREGEX
# endif
#endif
The macros BOOST_NO_CWCHAR, BOOST_NO_CWCTYPE and BOOST_NO_STD_WSTRING are defined automatically by boost's config.hpp header for your platcorm/compiler/std-library. Sorry.
In the future, you'll get better results posting boost questions to the boost users' list.
--
Eric Niebler
BoostPro Computing
www.boostpro.com
|
1,616,886 | 1,616,891 | How to make class not derivable at all. is there any way? | Hi any one let me know How to make class not derivable at all. is there any way?
please let me know.
regards
Hara
| See this explanation on how do to it, and why it might not be a good idea, by Bjarne Stroustrup (creator of C++ himself).
|
1,617,055 | 1,617,073 | function implementation in : file.h vs in file.cxx | My question is very simple:
I am working on a old legacy code where most of function are implemented in header file only.
As per my knowledge, Compiler convert function implemented in header into inline functions.
I wanted to know if i move these implementation into .cxx file , What will be benefits?
| To the compiler there is no difference between input that come from a .cxx file or a .h file, this text gets compiled into the same unit of translation.
The main reason why we typically do not put code inside header files, is to avoid duplicate objects, which then conflict at the level of the linker, when a given header is be used by multiple .cxx files.
Maybe you are confusing inline functions with macros, for in the case of macros, which are essentially a pre-processing directive, there is no risk of linker-time conflicts, even when/if the same headers where included multiple times for different units of translation.
It is of course possible to define functions in the headers (or elsewhere), in a way which instructs the compiler to systematically inline the calls to the function, and in such cases there is also no conflict at link time. However this require special syntax, and is merely implied by the fact that code comes from an include file or a cpp file (as the question suggests).
Now, to answer the question, per se, moving all this code out of header files and into cpp files, should not have much of an impact on either the binary size nor on performance.
Apparently, if the function definitions in the header files were not inlined explicitly, there must have only one user of the header file per different exe/dll produced (otherwise there'd be duplicates at link time), and therefore the file would not change in either direction.
With regards to performance, with the general performance gains in the hardware, even if functions formerly inlined were to be now called normally, this should go generally unnoticed, performance-wise, with possible exception of particular tight loops, where the logic iterates very many times.
|
1,617,204 | 1,617,214 | undecorate function names with visual studio sdk | To undecorate mangled C++ names that Visual Studio generates, you can use undname.exe.
But what if you want to avoid the overhead of creating a full-blown process every time you need undecoration?
Is there any equivalent functionality in the Visual Studio SDK (should be supported in VS2005)?
| You're looking for UnDecorateSymbolName function provided by dbghelp.
|
1,617,286 | 1,671,205 | Easy check for unresolved symbols in shared libraries? | I am writing a fairly large C++ shared-object library, and have run into a small issue that makes debugging a pain:
If I define a function/method in a header file, and forget to create a stub for it (during development), since I am building as a shared object library rather than an executable, no errors appear at compile-time telling me I have forgotten to implement that function. The only way I find out something is wrong is at runtime, when eventually an application linking against this library falls over with an 'undefined symbol' error.
I am looking for an easy way to check if I have all the symbols I need at compile time, perhaps something I can add to my Makefile.
One solution I did come up with is to run the compiled library through nm -C -U to get a demangled list of all undefined references. The problem is this also comes up with the list of all references that are in other libraries, such as GLibC, which of course will be linked against along with this library when the final application is put together. It would be possible to use the output of nm to grep through all my header files and see if any of the names corresponding.. but this seems insane. Surely this is not an uncommon issue and there is a better way of solving it?
| Check out the linker option -z defs / --no-undefined. When creating a shared object, it will cause the link to fail if there are unresolved symbols.
If you are using gcc to invoke the linker, you'll use the compiler -Wl option to pass the option to the linker:
gcc -shared ... -Wl,-z,defs
As an example, consider the following file:
#include <stdio.h>
void forgot_to_define(FILE *fp);
void doit(const char *filename)
{
FILE *fp = fopen(filename, "r");
if (fp != NULL)
{
forgot_to_define(fp);
fclose(fp);
}
}
Now, if you build that into a shared object, it will succeed:
> gcc -shared -fPIC -o libsilly.so silly.c && echo succeeded || echo failed
succeeded
But if you add -z defs, the link will fail and tell you about your missing symbol:
> gcc -shared -fPIC -o libsilly.so silly.c -Wl,-z,defs && echo succeeded || echo failed
/tmp/cccIwwbn.o: In function `doit':
silly.c:(.text+0x2c): undefined reference to `forgot_to_define'
collect2: ld returned 1 exit status
failed
|
1,617,370 | 1,617,395 | How to use alpha transparency in OpenGL? | Here's my code:
void display(void);
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE|GLUT_RGBA);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable( GL_BLEND );
glutInitWindowSize(600,600);
glutInitWindowPosition(200,50);
glutCreateWindow("glut test");
glutDisplayFunc(display);
glutMainLoop();
return 0;
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT);
glPointSize(8);
glBegin(GL_POINTS);
glColor4f(.23,.78,.32,1.0);
glVertex2f(0,0);
glColor4f(.23,.78,.32,0.1);
glVertex2f(0.1,0);
glEnd();
glFlush();
}
The problem is that these two points appear identical (even when I set the alpha to 0). Is there something I missed to enable alpha transparency?
| Just a guess, but could it be that you dont have a background color ? So, when your rendering the second vertex which has alpha 0.1, there is no background to compute the proper color ? Just a guess, been years since i used opengl.
|
1,617,375 | 1,617,407 | Member function overriding accross class hierarchy | I have defined a class A and derived a new class B from A .
I have overloaded SetData() function in class B.
When I tried to access SetData function of class B using object of B, compiler doesn't permit it. Why is it so ?
class A{
public :
void SetData();
};
class B : public A {
public:
void SetData(int);
};
B b;
b.SetData() ; // error
| OMG, no error message. -1 for you.
But let us use telepathy and guess your error message. You're getting something like "symbol not found" because you try to call a function B::SetData() which doesn't have a body. And it must have a body even if it does nothing and even if it's declared in parent class! Try adding it into the body of your class
class B : public A {
public:
void SetData(int)
{ /* add body here */ };
};
or outside of it
class B : public A {
public:
void SetData(int);
};
void B::SetData(int)
{
//write it here
}
|
1,617,699 | 1,618,041 | How to obtain all subsequence combinations of a String (in Java, or C++ etc) | Let's say I've a string "12345" I should obtain all subsequence combinations of this string such as:
--> 1 2 3 4 5
--> 12 13 14 15 23 24 25 34 35 45
--> 123 124 125 234 235 345
--> 1234 1235 1245 1345 2345
--> 12345
Please note that I grouped them in different number of chars but not changed their order. I need a method/function does that.
| You want a powerset. Here are all the questions on StackOverflow that mention powersets or power sets.
Here is a basic implementation in python:
def powerset(s):
n = len(s)
masks = [1<<j for j in xrange(n)]
for i in xrange(2**n):
yield [s[j] for j in range(n) if (masks[j] & i)]
if __name__ == '__main__':
for elem in powerset([1,2,3,4,5]):
print elem
And here is its output:
[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]
[4]
[1, 4]
[2, 4]
[1, 2, 4]
[3, 4]
[1, 3, 4]
[2, 3, 4]
[1, 2, 3, 4]
[5]
[1, 5]
[2, 5]
[1, 2, 5]
[3, 5]
[1, 3, 5]
[2, 3, 5]
[1, 2, 3, 5]
[4, 5]
[1, 4, 5]
[2, 4, 5]
[1, 2, 4, 5]
[3, 4, 5]
[1, 3, 4, 5]
[2, 3, 4, 5]
[1, 2, 3, 4, 5]
Notice that its first result is the empty set. Change the iteration from this for i in xrange(2**n): to this for i in xrange(1, 2**n): if you want to skip an empty set.
Here is the code adapted to produce string output:
def powerset(s):
n = len(s)
masks = [1<<j for j in xrange(n)]
for i in xrange(2**n):
yield "".join([str(s[j]) for j in range(n) if (masks[j] & i)])
Edit 2009-10-24
Okay, I see you are partial to an implementation in Java. I don't know Java, so I'll meet you halfway and give you code in C#:
static public IEnumerable<IList<T>> powerset<T>(IList<T> s)
{
int n = s.Count;
int[] masks = new int[n];
for (int i = 0; i < n; i++)
masks[i] = (1 << i);
for (int i = 0; i < (1 << n); i++)
{
List<T> newList = new List<T>(n);
for (int j = 0; j < n; j++)
if ((masks[j] & i) != 0)
newList.Add(s[j]);
yield return newList;
}
}
|
1,617,746 | 1,617,828 | QDesktopServices::openUrl with Ressource | How do I open a ressource file (qressource) using the command QDesktopServices::openUrl ?
I tried several ways, but none seemed to work (for instance QDesktopServices::openUrl(QUrl(tr(":ressource.pdf")));)
Thank you.
| Unfortunately you can't do it directly, save it to a file first.
I check the Qt source. This is because the url is passed to the browser or other application (depending on the protocol) directly. These applications will not see your resource because thay are in a different process.
Here is the related source:
qdesktopservices.cpp:
bool QDesktopServices::openUrl(const QUrl &url)
{
...
}
qdesktopservices_x11.cpp:
static bool openDocument(const QUrl &url)
{
...
}
static bool launchWebBrowser(const QUrl &url)
{
...
}
inline static bool launch(const QUrl &url, const QString &client)
{
return (QProcess::startDetached(client + QLatin1Char(' ') + QString::fromLatin1(url.toEncoded().constData())));
}
|
1,617,856 | 1,657,397 | Choosing between WPF, wxWidgets, Win32 API and MFC | Imagine you are on Windows 7 and you have to write a GUI for a GRAPHIC application, (like a terrain editor, mesh viewer ..) which involves a great use of DirectX and OpenGL (so written in native C++).
If your goal is a multi-platform software then you should go for wxWidgets, but imagine you're doing a Windows' only app...what would your choice be? and why?
I'm supposing that the application would work on both XP and Vista/7 and obviously in the WPF case the UI will be managed, but it will call native functions by a C++/CLI proxy-like class
( will "bouncing" from managed-native and native-managed cause performance issues? ).
| RAD Studio can also make the job
Enhanced in 2010! VCL (Visual
Component Library) for rapidly
building Microsoft Windows
applications now includes seamless
Windows 7 support, and graceful
fallback compatibility with Windows
Vista, XP, and 2000
Enhanced in 2010! Windows Vista and
Windows 7 API headers to fully
exploit the latest Windows
capabilities
New in 2010! Support for Windows 7
Direct2D API
you can also make WPF with Delphi Prism and wxWidgets with twinforms
|
1,617,896 | 1,617,904 | Case insensitive search in Unicode in C++ on Windows | I asked a similar question yesterday, but recognize that i need to rephase it in a different way.
In short:
In C++ on Windows, how do I do a case-insensitive search for a string (inside another string) when the strings are in unicode format (wide char, wchar_t), and I don't know the language of the strings. I just want to know whether the needle exists in the haystack. Location of the needle isn't relevant to me.
Background:
I have a repository containing a lot of email bodies. The messages are in different languages (japanese, german, russian, finnish; you name it). All the data is in Unicode format, and I load it to wide strings (wchar_t) in my C++ application (the bodies have been MIME decoded, so in my debugger I can see the actual japanese, german characters). I don't know the language of the messages since email messages doensn't contain that detail, also a single email body may contain characters from several languages.
I'm looking for something like wcsstr, but with the ability to do the search in a case insensitve manner. I know that it's not possible to do a 100% proper conversion from upper case to lower case, without knowing the language of the text. I want a solution which works in the 99% cases where it's possible.
I'm using Visual Studio 2008 with C++, STL and Boost.
| Boost String Algorithms has an icontains() function template which may do what you need.
|
1,617,984 | 1,618,520 | Error: Compiling simple PjSIP program under ubuntu | I am trying to compile simple PjSIP program under ubuntu. I am getting error as
/usr/bin/ld: cannot find -lpjsua-i686-pc-linux-gnu
What does it mean?
Here is the ouput:-
root@mypc-desktop:/home/mypc/pjsip# make
gcc -o myapp myapp.cpp -DPJ_AUTOCONF=1 -O2 -I/home/mypc/pjproject-1.4.5/pjlib/include -I/home/mypc/pjproject-1.4.5/pjlib-util/include -I/home/mypc/pjproject-1.4.5/pjnath/include -I/home/mypc/pjproject-1.4.5/pjmedia/include -I/home/mypc/pjproject-1.4.5/pjsip/include -L/home/mypc/pjproject-1.4.5/pjlib/lib -L/home/mypc/pjproject-1.4.5/pjlib-util/lib -L/home/mypc/pjproject-1.4.5/pjnath/lib -L/home/mypc/pjproject-1.4.5/pjmedia/lib -L/home/mypc/pjproject-1.4.5/pjsip/lib -L/home/mypc/pjproject-1.4.5/third_party/lib -lpjsua-i686-pc-linux-gnu -lpjsip-ua-i686-pc-linux-gnu -lpjsip-simple-i686-pc-linux-gnu -lpjsip-i686-pc-linux-gnu -lpjmedia-codec-i686-pc-linux-gnu -lpjmedia-i686-pc-linux-gnu -lpjmedia-audiodev-i686-pc-linux-gnu -lpjnath-i686-pc-linux-gnu -lpjlib-util-i686-pc-linux-gnu -lresample-i686-pc-linux-gnu -lmilenage-i686-pc-linux-gnu -lsrtp-i686-pc-linux-gnu -lgsmcodec-i686-pc-linux-gnu -lspeex-i686-pc-linux-gnu -lilbccodec-i686-pc-linux-gnu -lg7221codec-i686-pc-linux-gnu -lportaudio-i686-pc-linux-gnu -lpj-i686-pc-linux-gnu -lm -lnsl -lrt -lpthread
/usr/bin/ld: cannot find -lpjsua-i686-pc-linux-gnu
collect2: ld returned 1 exit status
make: *** [myapp] Error 1
Here is code
#include <pjlib.h>
#include <pjlib-util.h>
#include <pjmedia.h>
#include <pjmedia-codec.h>
#include <pjsip.h>
#include <pjsip_simple.h>
#include <pjsip_ua.h>
#include <pjsua-lib/pjsua.h>
int main()
{
return 0;
}
Here is a Makefile
#Modify this to point to the PJSIP location.
PJBASE=/home/mypc/pjproject-1.4.5
include $(PJBASE)/build.mak
CC = $(APP_CC)
LDFLAGS = $(APP_LDFLAGS)
LDLIBS = $(APP_LDLIBS)
CFLAGS = $(APP_CFLAGS)
CPPFLAGS= ${CFLAGS}
# If your application is in a file named myapp.cpp or myapp.c
# this is the line you will need to build the binary.
all: myapp
myapp: myapp.cpp
$(CC) -o $@ $< $(CPPFLAGS) $(LDFLAGS) $(LDLIBS)
clean:
rm -f myapp.o myapp
Thanks
EDIT:
I just noticed that there is a error building PjSIP
make[2]: Entering directory
/home/mypc/pjproject-1.4.5/pjnath/build'
gcc -c -Wall -DPJ_AUTOCONF=1 -O2
-Wno-unused-label -Werror -I../include -I../../pjlib/include -I../../pjlib-util/include \ -o output/pjnath-i686-pc-linux-gnu/stun_session.o
\ ../src/pjnath/stun_session.c cc1:
warnings being treated as errors
../src/pjnath/stun_session.c: In
function ‘apply_msg_options’:
../src/pjnath/stun_session.c:230:
error: suggest parentheses around &&
within || make[2]: ***
[output/pjnath-i686-pc-linux-gnu/stun_session.o]
Error 1 make[2]: Leaving directory
/home/mypc/pjproject-1.4.5/pjnath/build'
make[1]: * [pjnath] Error 2 make[1]:
Leaving directory
`/home/mypc/pjproject-1.4.5/pjnath/build'
make: * [all] Error 1
When I tried to find -Werror in make files present at /home/mypc/pjproject-1.4.5/pjnath/build, $(PJDIR)/build.mak and $(PJDIR)/build/common.mak its not present there anybody know where it could be ?
| It seems that the pj* can't build the neccessary libaries - for a simple fix try to locate the line in /home/mypc/pjproject-1.4.5/build.mak where -Werror is added to $(APP_CFLAGS) and remove it (the -Werror, not the whole line if other flags are added :).
Alternatively apply the fix suggested by gcc on line 230 in src/pjnath/stun_session.c.
edit:
Just read that you found no -Werror. Could you either paste line 230 of stun_session.c or the make-files somewhere?
The source line would be preferred.
|
1,618,050 | 1,618,067 | C++ as first language for Windows game programming? | I'm a hobbyist programmer with a fair grasp of Python and I'm currently learning C. Recently I was talking to a colleague who also wants to learn to program. In his case, he wants to learn C++ as a path to Windows game programming using DirectX. Personally, I feel diving straight into C++ as your first language is a bit much - it's hard enough keeping motivated in an easier language, and I think it's better to learn another language to get your head round most of the basic concepts, then go into something like C++.
I found Python worked well as my first language as I'm more interested in network and web programming on Linux/Unix platforms, but for someone mainly interested in Windows game programming I was thinking C# might be a better choice as he could learn using Visual C# Express Edition and XNA, then switch over to Visual C++ when he's ready to start learning C++ and therefore already be in a familiar environment. I think memory management is a lot to take in, and C# at least handles that so he can put that off till he starts learning C++.
What do others think of C++ as a first programming language for this kind of application? Should I recommend he go for C# instead?
| C++ should be fine. I think he is best off learning about memory management, pointers, etc. BEFORE jumping up to C# as he will understand how the program is working better. Otherwise, he will just see memory as being magic and the garbage collector will have no real meaning. It's always good to have a solid understanding of underlying languages (C, C++, Assembly, etc.) to produce the best code.
|
1,618,196 | 1,618,290 | where should I put my test code for my class? | So I've written a class and I have the code to test it, but where should I put that code? I could make a static method Test() for the class, but that doesn't need to be there during production and clutters up the class declaration. A bit of searching told me to put the test code in a separate project, but what exactly would the format of that project be? One static class with a method for each of the classes, so if my class was called Randomizer, the method would be called testRandomizer?
What are some best practices regarding organizing test code?
EDIT: I originally tagged the question with a variety of languages to which I thought it was relevant, but it seems like the overall answer to the question may be "use a testing framework", which is language specific. :D
| Whether you are using a test framework (I highly recommend doing so) or not, the best place for the unit tests is in a separate assembly (C/C++/C#) or package (Java).
You will only have access to public and protected classes and methods, however unit testing usually only tests public APIs.
I recommend you add a separate test project/assembly/package for each existing project/assembly/package.
The format of the project depends on the test framework - for a .NET test project, use VSs built in test project template or NUnit in your version of VS doesn't support unit testing, for Java use JUnit, for C/C++ perhaps CppUnit (I haven't tried this one).
Test projects usually contain one static class init methods, one static class tear down method, one non-static init method for all tests, one non-static tear down method for all tests and one non-static method per test + any other methods you add.
The static methods let you copy dlls, set up the test environment and clear up the test enviroment, the non-static shared methods are for reducing duplicate code and the actual test methods for preparing the test-specific input, expected output and comparing them.
|
1,618,240 | 1,618,259 | How to support both IPv4 and IPv6 connections | I'm currently working on a UDP socket application and I need to build in support so that IPV4 and IPV6 connections can send packets to a server.
I was hoping that someone could help me out and point me in the right direction; the majority of the documentation that I found was not complete. It'd also be helpful if you could point out any differences between Winsock and BSD sockets.
Thanks in advance!
| The best approach is to create an IPv6 server socket that can also accept IPv4 connections. To do so, create a regular IPv6 socket, turn off the socket option IPV6_V6ONLY, bind it to the "any" address, and start receiving. IPv4 addresses will be presented as IPv6 addresses, in the IPv4-mapped format.
The major difference across systems is whether IPV6_V6ONLY is a) available, and b) turned on or off by default. It is turned off by default on Linux (i.e. allowing dual-stack sockets without setsockopt), and is turned on on most other systems.
In addition, the IPv6 stack on Windows XP doesn't support that option. In these cases, you will need to create two separate server sockets, and place them into select or into multiple threads.
|
1,618,280 | 1,618,297 | Where can I set path to make.exe on Windows? | When I try run make from cmd-console on Windows, it runs Turbo Delphi's make.exe but I need MSYS's make.exe. There is no mention about Turbo Delphi in %path% variable, maybe I can change it to MSYS in registry?
| The path is in the registry but usually you edit through this interface:
Go to Control Panel -> System -> System settings -> Environment Variables.
Scroll down in system variables until you find PATH.
Click edit and change accordingly.
BE SURE to include a semicolon at the end of the previous as that is the delimiter, i.e. c:\path;c:\path2
Launch a new console for the settings to take effect.
|
1,618,524 | 1,618,595 | Overload bracket access and assignment C++ | I'm writing a hash table for my data structs class, and I'd like to add a little syntactic sugar to my implementation.
template <typename HashedObj, typename Object>
Object & Dictionary<HashedObj, Object>::operator[](HashedObj & key)
{
return items.lookup(key);
}
That works fine when I do something like cout << dict["mykey"]. But how can I do assignment with the brackets? Something like:
dict["mykey"] = "something";
And no, this isn't part of my homework assignment (no pun intended), I just want to learn C++ a little better.
| It is not clear what exactly you are asking here. The code that you presented already supports assignment. Just do it and at will work (or at least it should compile). It makes absolutely no difference which side of the assignment operator your overloaded [] is used on. It will work in exactly the same way on left-hand side (LHS) as it does on the right-hand side (RHS) of the assignment (or as an operand of <<, as in your original post). Your [] returns a reference to an Object, and then the actual assignment is handled by the assignment operator of your Object type, meaning that the [] itself is not really involved in the actual assignment.
The real question here is how you want your [] to act in certain special cases. What is going to happen if your key is not present in the table? Reference to what Object is your lookup going to return in this case?
It is impossibe to figure out from what you posted. I see it returns a reference, so returning NULL is out of question. Does it insert a new, empty Object for the given key? If so, then you don't have to do anything. Your [] is already perfectly ready to be used on the LHS of the assigment. (This is how [] in std::map works, BTW)
In case your lookup returns a reference to a special "guard" Object, you have to take special steps. You probably don't want to assign anything to a "guard" object, so you have to "disable" its assignment operator somehow and you are done. The rest should work as is.
If your lookup throws an exception in case of a non-existent key, then you have to decide whether this is what you want when the [] is used on the LHS of an assignment. If so, then you don't need to do anything. If not, then it will take some extra work...
So, again, what happens if you pass a non-existent key to lookup?
P.S. Additionally, it would normally make more sense to declare the [] (and lookup) with either const HashedObj& parameter or just HashedObj parameter. Non-const reference, as in your example, looks strange and might lead to problems in some (actually, in most) cases. I'm surprized it works for you now...
|
1,618,551 | 1,618,555 | Compiler error when using nested operator overloading in C++ | I have a URL class that overloads the ==, <, >, and != operators for simple comparison. The URL class has a string data member and some functions to act on the string. The operators work fine when tested with the URL class.
I also have a Page class that has a URL data member. I am trying to overload the same operators in the Page class. Equality in the Page class is based on equality of their respective URLs, so I use the URL class boolean operators in comparing pages. This creates some compiler errors that I cannot figure out. Code for URL operators:
bool URL::operator ==(URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
Code for Page operators:
bool Page::operator ==(Page & p) const {
//url is the URL instance variable of the Page class
return url == p.GetURL();
}
This produces errors like so:
src/Page.cpp: In member function ‘bool Page::operator==(Page&) const’:
src/Page.cpp:21: error: no match for ‘operator==’ in ‘((const Page*)this)->Page::url == Page::GetURL()()’
inc/URL.h:118: note: candidates are: bool URL::operator==(URL&) const
I predict that it is something dumb that I am forgetting. Will you prove me right?
edit: Const correctness has bitten me in the bum. Thanks for the help.
| It should have been:
bool URL::operator ==(const URL & u) const {
//url is the string instance variable
return url == u.GetURL();
}
And analogously for the other operators.
If you still get compiler errors, perhaps you haven't made GetURL() const as well:
std:string URL::GetURL() const {
// whatever...
}
|
1,618,591 | 1,618,621 | How to delta encode a C/C++ struct for transmission via sockets | I need to send a C struct over the wire (using UDP sockets, and possibly XDR at some point) at a fairly high update rate, which potentially causes lots of redundant and unnecessary traffic at several khz.
This is because, some of the data in the struct may not have changed at times, so I thought that delta-encoding the current C struct against the previous C struct would seem like a good idea, pretty much like a "diff".
But I am wondering, what's the best approach of doing something like this, ideally in a portable manner that also ensures that data integrity is maintained? Would it be possible to simply XOR the data and proceed like this?
Similarly, it would be important that the approach remains extensible enough, so that new fields can be added to the struct or reordered if necessary (padding), which sounds as if it'd require versioning information, as well.
Any ideas or pointers (are there existing libraries?) would be highly appreciated!
Thanks
EDIT: Thanks to everyone one who provided an answer, the level of detail is really appreciated, I realize that I probably should not have mentioned UDP though, because that is in fact not the main problem, because there is already a corresponding protocol implemented on top of UDP that accounts for the mentioned difficulties, so the question was really meant to be specific to feasible means of delta encoding a struct, and not so much about using UDP in particular as a transport mechanism.
| UDP does not guarantee that a given packet was actually received, so encoding whatever you transmit as a "difference from last time" is problematic -- you can't know that your counterpart has the same idea as you about what the "last time" was. Essentially you'd have to build some overhead on top of UDP to check what packets have been received (tagging each packet with a unique ID) -- everybody who's tried to go this route will agree that more often than not you find yourself more or less duplicating the TCP streaming infrastructure on top of UDP... only, most likely, not as solid and well-developed (although admittedly sometimes you can take advantage of very special characteristics of your payloads in order to gain some modest advantage over plain good old TCP).
Does your transmission need to be one-way, sender to receiver? If that's the case (i.e., it's not acceptable for the receiver to send acknowledgments or retransmits) then there's really not much you can do along these lines. The one thing that comes to mind: if it's OK for the receiver to be out of sync for a while, then the sender could send two kinds of packets -- one with a complete picture of the current value of the struct, and an identifying unique tag, to be sent at least every (say) 5 minutes (so realistically the receiver may be out of sync for up to 15 minutes if it misses two of these "big packets"); one with just an update (diff) from the last "big packet", including the big packet's identifying unique tag and (e.g.) a run-length-encoded version of the XOR you mention.
Of course once having prepared the run-length-encoded version, the server will compare its size vs the size of the whole struct, and only send the delta-kind of packet if the savings are substantial, otherwise it might as well send the big-packet a bit earlier than needed (gains in reliability). The received will keep track of the last big-packet unique tag it has received and only apply deltas which pertain to it (helps against missing packets and packets delivered out of order, depending how sophisticated you want to make your client).
The need for versioning &c, depending on what exactly you mean (will senders and receivers with different ideas about how the struct's C layout should look need to communicate regularly? how do they handshake about what versions are know to both? etc), will add a whole further universe of complications, but that is really another question, and your core question as summarized in the title is already plenty big enough;-).
If you can afford occasional meta-messages from the receiver back to the sender (acks or requests to resend) then depending on the various numerical parameters in play you may design different strategies. I suspect acks would have to be pretty frequent to do much good, so a request to resend a big-packet (either a specifically identified one or "whatever you have that's freshest") may be the best meta-strategy to cull the options space (which otherwise threatens to explode;-). If so then the sender may be blissfully ignorant of whatever strategy the receiver is using to request big-packet-resends, and you can experiment on the receiver side with various such strategies without needing to redeploy the sender as well.
It's hard to offer much more help without some specifics, i.e., at least ballpark numbers for all the numerical parameters -- packet sizes, frequencies of sending, how long is it tolerable for the sender to be out of sync with the receiver, a bundle of network parameters, etc etc. But I hope this somewhat generic analysis and suggestions still help.
|
1,618,798 | 1,618,815 | Why is there a different string class in every C++ platform out there? | While I like programming in C++, I hate the idea of:
std::basic_string vs QString vs wxString vs .............
Doesn't the standard string class satisfy the needs for these frameworks? I mean what is wrong with the standard string class?!
Just to emphasize, that below is the important question:
Do you learn "the" string class of the framework in every framework you are going to work with? would you instead stick to the standard string class by trying to adapt it everywhere?
Thanks...
| The reason for multiple string classes is that the C++ standard was finalized fairly late (in 1998); it then took some time until all systems actually provided a correct C++ library. By that time, all these competing string classes where already written.
In addition, in some cases, people want to inherit from a single base class, which std::string wouldn't do.
|
1,618,811 | 1,619,215 | Do all Standard C++ features work in C++/CLI? | If I just include existing Standard C++ class in C++/CLI program, will it work?
In my tests everything worked pretty good, but is it true for every program?
| That is what Microsoft promises, yes. (I watched this video yesterday, in which they explicitly mentioned this -- specifically because the addition of nullptr in C++0x would compromise it)
So yeah, if you take a native C++ program and compile it as C++/CLI, with no code changes, then yes, it will still work.
And of course, if you change your code (gcnew instead of new and other "managed" changes, then of course, all bets are off, and you might or might not break the code)
|
1,618,828 | 1,622,693 | WCF (WCF-Binding) in/with C/C++ | Is thare any like WCF libs (OpenSourse) written in C\C++?
Or at least some kined of special WCF C++ services (NOT ON Basic HTTP Binding)?
| Sounds like what you're looking for is a C++-based library for exposing and consuming web-services supporting the WS-* protocols (i.e. like WS-Security). In that case, you could probably give Axis2/C a try. It's the C version of the normal Java-based Axis2 from Apache.
(There's also Axis/CPP, but not sure how up-to-date that is).
|
1,618,917 | 1,618,990 | Receiving packets in UDP | Let's say my program sends a 1000 bytes over the network (UDP). Does it guaranteed that the receiver will receive the 1000 bytes in one "batch"? Or perhaps he will need to perform sevral "reads" until he'll receive the entire message? if the later is true, how can i ensure that the order of the packets for the same message don't get "mixed up" (in order), or perhaps the protocol guarantees it?
Edit: that is, does it possible that my message will be split to sevral packets? (what if i try to send a 10000mb message, what happens then?)
| You will get it all or nothing.
But there is no particular guarantee that you will receive packets exactly once in the order they were transmitted; packet loss, reordering and (less often) duplication are all possible.
There is a maximum frame size (of 65,507 bytes), send()ing packets of larger sizes will return an error.
You must provide enough buffer to receive the entire frame in one call.
UDP packets CAN be fragmented into multiple IP fragments, but the OS will drop an incomplete packet. This is therefore transparent to the application.
|
1,619,263 | 1,619,264 | Networking in C/C++? | I am a begginer C++ programmer. In C#, I used the System.Net.Sockets.Socket class, which represents a networking socket, to create/connect a server. How can I do the same thing in C/C++? Are there any classes like this?
| In windows theres a library called winsock.dll.
In Unix, you can use unix sockets
Then, theres boost sockets
beej guide to internet sockets
windows sockets
boost networking
|
1,619,392 | 1,619,473 | Game programming structure | I've been programming in c++ for a bit now and Im very familiar with the syntax. I'm trying to use Allegro to make a card game. I understand everything I need to do for the game logic and what not. What puzzles me is how to drive the game. I'm sort of new to loop based applications. I got used to event based programming in VB .Net. I'm just not sure the proper way of for example switching players and raising "events" without having lots of ifs and bools. Also right now I have an array of bool to check which card is in play. And my game iterates through the whole bool array every time and it seems messy to me. Also, if I want to go from my menu loop to my settings loop, how is that done without a big bool?
Thanks
| Most gaming frameworks provide two methods you need to implement (both of them are called in a loop):
Update
Draw
The Update is where you should put all that stuff, which should check for User input, state changes, intervalled actions etc. Examples would be Physics, ButtonPressed, etc. Nothing prevents you from working with events here (have a look at BoostLibrary Signals).
void Game::update() {
if(pushedButton) {
this->cardsOnTable->add(this->hand->remove(0));
this->activePlayer = nextPlayer();
}
}
The Draw should just render the current, underlying state to the screen. So you have to make sure your underlying state/model is easy to access.
void Game::render() {
this->table->render();
this->cardsOnTable->render();
this->hand->render();
// ...
flipBuffers();
}
You can solve your Menu/SettingsMenu issue with Scenes and a SceneManager (which can be a Stack). So instead of putting the logic into the Game directly, you put it into Scenes. And you can push/pop scenes to/from the Manager.
void Game::update() {
this->sceneManager->activeScene->update();
}
void MenuScene::update() {
if(settingsMenuItemSelected) {
game->sceneManager->push(new SettingsMenuScene));
// now the next time Game::update() is called
// the active scene of the SceneManager will be
// the settings menu. And once it is closed/cancelled
// it will pop itself from the manager and we are back
// in the regular menu
}
}
If you want to start with more advanced stuff, you could try to store "events" into a huge list and fire all events when you enter the Game::update method - this is how VB makes sure that you can't modify controls from another thread than the UI thread - but I don't think that this is something you would do using C++.
|
1,619,522 | 1,619,738 | How to get text indent (tabs) from some text input? | For example, suppose I'm editing following text (\t is for tabs, it's not text)
'\t\t\tSome text...'
and my input keyboard position is right before 'S' (there is no selected text)
and I want to get number of tabs before 'S' (in this case it's 3)
So how to get that number of tabs using Win32 API?
p.s.
Maybe some function to get whole current line (and then parse that text)?
edit:
So I want my program (that is running in background and does not have a GUI) to determine number of tabs from current active line in any text editor that is currently active (that I'm editing in).
| For some applications such as the standard Windows Notepad, it may be possible to do this from another application. Notepad itself is little more than big Win32 "Edit" control inside a resizeable window, so all the regular Win32 Edit control messages can be used to get the actual text and the caret position and so on.
However, in the general case of any Windows text editor, there is no requirement for applications to use a Win32 Edit control for their text editing needs (and in fact, to do so would be just reinventing Notepad). There is no standard Win32 API method to find out where the caret is pointing, because the application is free to draw text on the screen in any way it sees fit (and will store that text internally inside the application with no corresponding API for you to call).
|
1,619,604 | 1,619,620 | Reading through file using ifstream | I am trying to read from file:
The file is multiline and basically i need to go over each "word". Word being anything non space.
Sample input file would be:
Sample file:
test 2d
word 3.5
input
{
test 13.5 12.3
another {
testing 145.4
}
}
So I tried something like this:
ifstream inFile(fajl.c_str(), ifstream::in);
if(!inFile)
{
cout << "Cannot open " << fajl << endl;
exit(0);
}
string curr_str;
char curr_ch;
int curr_int;
float curr_float;
cout << "HERE\n";
inFile >> curr_str;
cout << "Read " << curr_str << endl;
The problem is when it reads new line it just hangs. I read everything before test 13.5
but once it reaches that line it doesnt do anything.
Anyone can tell me what I am doing wrong?
Any better suggestion on how to do this???
I essentially need to go through file and go one "word" (non white char) at the time.
I
Thanks
| You open a file 'inFile' but are reading from the 'std::cin' any particular reason?
/*
* Open the file.
*/
std::ifstream inFile(fajl.c_str()); // use input file stream don't.
// Then you don't need explicitly specify
// that input flag in second parameter
if (!inFile) // Test for error.
{
std::cerr << "Error opening file:\n";
exit(1);
}
std::string word;
while(inFile >> word) // while reading a word succeeds. Note >> operator with string
{ // Will read 1 space separated word.
std::cout << "Word(" << word << ")\n";
}
|
1,619,631 | 1,619,685 | c++ hex number format | I'm trying to output the hex value of a char and format it in a nice way.
Required: 0x01 : value 0x1
All I can get is: 00x1 : value 0x1 // or 0x1 if i don't use iomanip
Here's the code i have, 'ch' was declared to be a unsigned char. Is there any other way to do it other than checking the value and manually add an '0'??
cout << showbase;
cout << hex << setw(2) << setfill('0') << (int) ch;
Edit:
I found one solution online:
cout << internal << setw(4) << setfill('0') << hex << (int) ch
| std::cout << "0x" << std::noshowbase << std::hex << std::setw(2) << std::setfill('0') << (int)ch;
Since setw pads out to the left of the overall printed number (after showbase is applied), showbase isn't usable in your case. Instead, manually print out the base as shown above.
|
1,619,643 | 1,619,646 | XCode will not take input from a file | For some reason, Xcode will not take input from a file, while Visual C++ will.
When I run this program in xcode, the variables numberRows and numberCols stay 0 (they are initialized to 0 in the main function).
When I run it in Visual C++ they become 30 and 30 (the top line of maze.txt is "30 30" without the quotes).
Any ideas why this is happening?
void readIn(int &numberRows, int &numberCols, char maze[][100]){
ifstream inData;
inData.open("maze.txt");
if (!inData.is_open()) {
cout << "Could not open file. Aborting...";
return;
}
inData >> numberRows >> numberCols;
cout << numberRows << numberCols;
inData.close();
return;
}
| There is something else wrong.
Unfortunately it is hard to tell.
Try flushing the output to make sure you get the error message:
void readIn(int &numberRows, int &numberCols, char maze[][100])
{
ifstream inData("maze.txt");
if (!inData) // Check for all errors.
{
cerr << "Could not open file. Aborting..." << std::endl;
}
else
{
// Check that you got here.
cerr << "File open correctly:" << std::endl;
// inData >> numberRows >> numberCols;
// cout << numberRows << numberCols;
std::string word;
while(inData >> word)
{
std::cout << "GOT:(" << word << ")\n";
}
if (!inData) // Check for all errors.
{
cerr << "Something went wrong" << std::endl;
}
}
}
|
1,619,653 | 1,619,660 | Can I mix C++ and C in a single project in Visual Studio? | I have a a Win32 DLL project in VS2008, it is written in a handful of C modules.
Because I also want to be able to build outside VS2008, with no dependency on VS2008, I have produced a custom makefile, that does all the build and link steps. All this is set up just fine.
Now I'd like to add a couple C++ modules to this DLL.
I have modified the custom makefile to compile the .cpp modules as C++, and the .c modules as regular C (/Tc) . This all works. It links everything together, no problem .
Can I configure the VS2008 project to do the same?
Can I mix C++ and C in the same VS2008 project?
Or do I need a custom build step for this?
Thanks.
ANSWER
I had the VS2008 project set to compile as C. I needed to change it to Compile As "Default". Right click the project, select Properties, and then... :
Thanks, Pavel.
| First of all, you shouldn't even need /Tc if you're building it yourself - cl.exe uses file extension to determine the type, so .c files will be compiled as C by default, and .cpp and .cxx files as C++.
For VS projects, it works in exact same way, except that you can't override this behavior (or at least I do not know how).
|
1,619,732 | 1,629,341 | How to assign a value to an enum based on input from a file in C++? | I have a file with values like: START and STOP. I also have the following enum declared:
enum Type {
START,
STOP
};
I'm trying to set the enum equal to the first value in the file with something like this:
enum Type foo;
ifstream ifile;
ifile.open("input.txt");
ifile >> foo;
I'm getting the error: no match for ‘operator>>’ in ‘ifile >> foo’.
How do I go about doing this correctly?
| I've found for my particular situation that the following code is the best solution:
template <class T> T a2e(string c, const string a[], const int size) {
for (int i=0; i < size; i++) {
if (c == a[i]) {
return static_cast<T>(i);
}
}
}
And would be used as follows:
enum StateType {START, STOP};
const int MAXVALUES = STOP+1;
const string stateNames[MAXVALUES] = {"START", "STOP"};
enum StateType state;
ifstream ifile;
ifile.open("input.txt");
ifile >> foo;
state = a2e <enum StateType> (foo, stateNames, MAXVALUES);
Hope this helps someone in the future. Thanks to everyone who made suggestions about how to tackle this problem.
|
1,619,748 | 1,619,820 | Enumerate the VCL controls in a external application | is possible via the Windows API's to enumerate and iterate the VCL controls on a form (TForm) belonging to a external Win32 application written in C ++ Builder or Delphi.
Bye.
| No. First of all, consider that the Windows API has no idea what the "VCL" is. It doesn't know "TButton" or "TStringGrid," and it certainly doesn't know "TImage" or "TLabel," which don't even have window handles.
You could use EnumChildWindows to get handles to the windowed controls. You could look at their class names to determine that they came from "TButton" or "TStringGrid," but even then, you would not have access to any object-related facilities. You wouldn't have an object reference, and so you could not read any properties or call any methods.
TestComplete, from Automated QA, offers access to a program's forms and classes from an external program, which sounds like what you might be trying to do. It works by having a unit that you include in the Delphi program, and that unit essentially provides a back door for the TestComplete program to use to query the program's internals. That requires cooperation from the application developer; you can't sic TestComplete on an arbitrary program.
|
1,619,754 | 1,619,761 | Is DbgHelp.dll built-in to Windows? Can I rely on it being there? | I use Jochen Kalmbach's StackWalker class from CodeProject, to produce a stacktrace when an exception occurs in my DLL.
It relies on DbgHelp.dll
Is DbgHelp.dll built-in to Windows Vista, WS2008, Windows 7?
I know about The Debugging Tools for Windows from Microsoft, and I'm aware that DbgHelp.dll ships in that package. But I also found DbgHelp.dll in %windir%\system32 on my machine.
If it is not installed by default, is there a way for me to redistribute it with debug builds of my DLL ?
| Microsoft says:
"The DbgHelp library is implemented by DbgHelp.dll. This DLL is included in the operating system."
Note that the version currently included with Debugging Tools for Windows may not be the same version that is included with the operating system.
|
1,619,769 | 1,619,779 | Is there a way to call an object's base class method that's overriden? (C++) | I know some languages allow this. Is it possible in C++?
| Yes:
#include <iostream>
class X
{
public:
void T()
{
std::cout << "1\n";
}
};
class Y: public X
{
public:
void T()
{
std::cout << "2\n";
X::T(); // Call base class.
}
};
int main()
{
Y y;
y.T();
}
|
1,619,797 | 1,619,808 | C++ HashTable Question | If I use an array of linked list to implement a hash table, the "remove" function might require traversing through a "chain."
Is this also true for "deleting"?
| Sure, it applies to anything you try to do with the hash table. Remove, delete (which sound like the same thing to me), insert, search, you name it.
|
1,619,831 | 1,619,837 | Can you chain methods by returning a pointer to their object? | My goal is to allow chaining of methods such as:
class Foo;
Foo f;
f.setX(12).setY(90);
Is it possible for Foo's methods to return a pointer to their instance, allowing such chaining?
| For that specific syntax you'd have to return a reference
class Foo {
public:
Foo& SetX(int x) {
/* whatever */
return *this;
}
Foo& SetY(int y) {
/* whatever */
return *this;
}
};
P.S. Or you can return a copy (Foo instead of Foo&). There's no way to say what you need without more details, but judging by the function name (Set...) you used in your example you probably need a reference return type.
|
1,619,989 | 1,716,923 | Visual Studio 2008 c++ conditional template inheritance bug? | I'm in the process of porting a C++/WTL project from Visual Studio 2005 to VS 2008. One of the project configurations is a unit-testing build, which defines the preprocessor symbol UNIT_TEST.
In order to get my WTL classes into my test harness, I made a CFakeWindow class that stubs all the CWindow methods. Then in my stdafx.h file, I do this right below the import of atlwin.h (which defines the CWindow class):
#ifdef UNIT_TEST
#include "fakewindow.h"
#define CWindow CFakeWindow
#endif
My window classes then look like this:
class CAboutDialog :
public CDialogImpl< CAboutDialog, CWindow >
, public CDialogResize< CAboutDialog >
{
// class definition omitted...
};
This works great in VS 2005. The problem is that in VS 2008, the methods from the original CWindow class are getting called, instead of the CFakeWindow class. This of course causes the tests to fail, because CWindow is sprinkled with ATLASSERT(::IsWindow(m_hWnd)).
When I step through the code in the debugger, I see that the CAboutDialog class is inheriting from CDialogImpl<CAboutDialog, CFakeWindow>. Yet when I call a method on CAboutDialog (e.g. EndDialog(code)), the CWindow method is getting called.
Is this a bug in VS 2008, or was my conditional template inheritance technique an abomination that VS 2005 allowed but VS 2008 "fixed"? Is there a work-around, or do I need to consider a different technique to unit-test WTL classes? I really like this technique, because it lets me get WTL classes into a test harness without mucking about with the WTL library.
Edit: As noted in the response to Conal, below, the preprocessor output shows that my class is inheriting from CFakeWindow:
class CAboutDialog :
public CDialogImpl<CAboutDialog, CFakeWindow >
, public CDialogResize< CAboutDialog >
...
And as stated above, when I step through the code in the debugger, CAboutDialog is shown in the locals window as inheriting from CFakeWindow.
Edit 2: As per Conal's advice, I stepped through the disassembly, and the code is supposedly calling the CFakeWindow method, but the CWindow method is what is actually called.
if ( wID == IDCANCEL )
00434898 movzx edx,word ptr [ebp+8]
0043489C cmp edx,2
0043489F jne CAboutDialog::OnCloseCmd+90h (4348B0h)
{
EndDialog( wID ) ;
004348A1 movzx eax,word ptr [ebp+8]
004348A5 push eax
004348A6 mov ecx,dword ptr [ebp-10h]
004348A9 call ATL::CDialogImpl<CAboutDialog,ATL::CFakeWindow>::EndDialog (40D102h)
}
else
004348AE jmp CAboutDialog::OnCloseCmd+9Ah (4348BAh)
{
EndDialog(IDOK);
004348B0 push 1
004348B2 mov ecx,dword ptr [ebp-10h]
004348B5 call ATL::CDialogImpl<CAboutDialog,ATL::CFakeWindow>::EndDialog (40D102h)
I'm starting to lean more toward a bug in the VC++ 2008 debugger.
| This might be a clearer way of handling it:
#ifdef UNIT_TEST
#include "fakewindow.h"
#define TWindow CFakeWindow
#else
#define TWindow CWindow
#endif
Perhaps there's a case where the redefine is not getting through the precompiled headers. If so, this will catch any such problem.
|
1,619,993 | 1,620,012 | Template specialization for enum | Is it possible to specialize a templatized method for enums?
Something like (the invalid code below):
template <typename T>
void f(T value);
template <>
void f<enum T>(T value);
In the case it's not possible, then supposing I have specializations for a number of types, like int, unsigned int, long long, unsigned long long, etc, then which of the specializations an enum value will use?
| You can use std::enable_if with std::is_enum from <type_traits> to accomplish this.
In an answer to one of my questions, litb posted a very detailed and well-written explanation of how this can be done with the Boost equivalents.
|
1,620,079 | 1,620,381 | Passing around a nested functor (C++) | Is there a way to pass foo_ around outside of main? I saw something about Boost in another question regarding functors. That looks like it may work. Here's the answer mentioning Boost in that question. If I can, I would like to avoid Boost.
#include <iostream>
int main()
{
class foo {
public:
void operator()() {
std::cout << "Hello" << std::endl;
}
};
foo foo_;
foo_();
return 0;
}
| No, currently local types aren't allowed to go into templates (otherwise you could've used boost or std::tr1::function). However, you could maybe do it OOP, where Foo inherits something (that has a virtual opeator() func that your foo implemen ts) and you pass a ptr to Foo around instead.
|
1,620,218 | 1,620,449 | Free tools that automatically reformat whole C/C++ source files in VS2008 on save? | I'm looking for a tool (macro, extension) for Visual Studio 2008 that would reformat the source code (C/C++) when you save the file.
| AStyle was my first hit on Google. Looks reasonable. You can tie that to a keyboard event under 'External Tools' in Visual Studio. (I suspect writing/recording a small macro that formats and saves the file is easy, as is rebinding that to Ctrl-S)
See also https://stackoverflow.com/questions/841075/best-c-code-formatter-beautifier, which also recommends AStyle.
|
1,620,854 | 1,620,871 | C++ library for making GUIs | I am looking for a simple C++ library for making GUIs. I tried wxWidgets and GTK, but I think both are complex.
I want your opinion on what to use. Should I learn wxWidgets or you know a better one?
Thanks.
| Try Nokia's QT. It's free, awesome and cross platform.
If you only need to support Windows, then you can check MFC or even better IMHO Windows Forms (with Managed C++).
|
1,621,077 | 1,686,247 | Strange behaviour of edit control background color when using WinXp common controls | I am having a strange problem ( well, at least i find it strange =) ). I am writing my own GUI library, which is a wrapper around windows api (and yes, i am aware of WTL and frameworks like MFC =) ). At the current stage i have incapsulated common controls in such manner: for example, Edit class consists of a simple window and an standard edit window above it ( MainWindow -> GhostWindow -> EditBox ). That is how i can for example change a background colour of an edit inside an edit class itself:
myedit->SetBkColor ( RGB ( 0, 0, 0 ) );
And it worked fine, until i called InitCommonControlsEx and attached manifest file to my program. After doing this, my edits become capable of changing colours only when they have focus. To be honest, i don't have a comprehensive thoughts about why do the behave like this and what am i doing wrong, so i will appreciate any help.
Thank you, #535.
| Well, everything is much easier, than i thought. I was just too inattentive =( When one don't use styling, one cane use ::SetBkColor(...) to change background colour, and return a brush from WM_CTLCOLOR* to change a border colour. Things become different after enabling styling. Now ::SetBkColor(...) correspond to focus colour and returning brush changes background colour. Shame on me =(
|
1,621,301 | 1,820,946 | Javascript receives ActiveX event only once | I've written an ActiveX control using ATL. I used the wizard to add support for connection points which added public IConnectionPointContainerImpl<CActiveX> and CProxy_IActiveXEvents<CActiveX>, where the CProxy_... is the wizard generated code to fire events.
I've defined a dispinterface as follows:
[
uuid(43ECB3DF-F004-4FAD-9BFB-79211A693C3A),
helpstring("ActiveX Events")
]
dispinterface _IActiveXEvents
{
properties:
methods:
[id(1)] void receiveCertificate([in] VARIANT_BOOL isPermissionGranted, [in] BSTR certificateXml);
};
and included it in the coclass with [default,source] dispinterface _IActiveXEvents. To fire the event I call Fire_receiveCertificate(isGranted, _bstr_t(certXml.c_str()).copy()), which is defined in the wizard-code.
The following Javascript will receive the event
function ActiveXObject::receiveCertificate(permission, certificate) {
alert("alert!");
}
The problem is it only receives the event once, and I have to close and reopen IE to get it to receive the event again. Am I missing something?
| If anyone is interested, I found the solution to this problem. I had registered the object in the ROT (running object table), but was not revoking any previously existing registrations. Thus, multiple registrations were appearing. Once I ensured I revoked previous registrations, events fired reliably.
|
1,621,446 | 1,621,721 | Automate pimpl'ing of C++ classes -- is there an easy way? | Pimpl's are a source of boilerplate in a lot of C++ code. They seem like the kind of thing that a combination of macros, templates, and maybe a little external tool help could solve, but I'm not sure what the easiest way would be. I've seen templates that help do some of the lifting but not much -- you still end up needing to write forwarding functions for every method of the class that you're trying to wrap. Is there an easier way?
I'm imagining a tool used as part of the make process. You want your public headers to be pimpl'd classes, so you provide some input file, say pimpl.in, that lists the classes (implemented un-pimpl'd) that you'd like to wrap, then that file is examined, the pimpl classes are generated and only their headers (not the original class's headers) are installed during a 'make install'. The problem is I don't see any way to do this without a full blown C++ parser, something even compiler vendors can't get right. Maybe the classes could be written in someway that makes the job of an external tool easier, but I'm sure I'd end up missing all sorts of corner cases (e.g. templated classes and/or templated member functions).
Any ideas? Has anyone else come with a solution for this problem already?
| No, there isn't an easy answer. :-( I would think with nearly every OO expert saying "prefer composition over inheritance", there would be language support for making composition a whole lot easier than inheritance.
|
1,621,574 | 1,621,664 | Can the arguments of main's signature in C++ have the unsigned and const qualifiers? | The standard explicitly states that main has two valid (i.e., guaranteed to work) signatures; namely:
int main();
int main(int, char*[]);
My question is simple, would something like the following be legal?
int main(const unsigned int, const char* const* argv);
My tests say 'yes', but I'm unsure of the answer because am I not overloading main by changing int to unsigned int as well as the non top-level const-ness of argv? If I am, then that's clearly prohibited.
So, are these modifications guaranteed to work on a standards conforming compiler?
| The C++98 standard says in section 3.6.1 paragraph 2
An implementation shall not predefine the main function. This function shall not be overloaded. It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both the following definitions of main: int main() and int main(int argc, char* argv[])
So it's not mandated by the standard that the env accepting main is acceptable but it is permissible.
Because this is referred to often, here is the previous paragraph exempting freestanding environments from anything but documenting their behavior:
A program shall contain a global function called main, which is the designated start of the program. It is
implementation defined
whether a program in a freestanding environment is required to define a main
function. [Note: in a freestanding environment, startup
and termination is implementation defined;
startup
contains the execution of constructors for objects of namespace scope with static storage duration; termination
contains the execution of destructors for objects with static storage duration. ]
|
1,621,612 | 1,621,666 | What is the proper way to compare an element of an std::string with a character? | I am not a very experienced C++ programmer, i get a warning when i do the following:
if (myString[i] != 'x')
{
}
what is the appropriate way to compare these?
thanks for your help!
| possibility 1:
the int that identifies the element in the array should not be larger than a regular int.
possibility 2:
If myString is of type std::wstring the appropriate comparison is myString[i] != L'x'
(ty popester!)
|
1,621,621 | 1,621,644 | Learning C++ on Linux or Windows? | Since you 'should' learn C/C++ and as part of 'learn as much languages as possible', i decided to learn C++ in depth.
My OS is Windows and my question is should i re-install Linux as a dual boot to learn C++ on Linux?
Do i miss something if I develop in C++ only on the Windows platform?
(possible duplicate: https://stackoverflow.com/questions/1128050/best-operating-system-for-c-development-and-learning)
| Doesn't really matter what platform you write your code on.
If you want to verify that your code is portable, you could install cygwin and gcc as well as visual studio.
Then you could compile with both compilers without having to dualboot
|
1,621,629 | 1,621,645 | Threading with .NET and OpenCV? | I am having trouble getting a thread to work with OpenCV. The problem is with the ThreadStart() part of my code.
public ref class circles
{
public:
static void circleFind(bool isPhoto, const char * windowName1, const char * windowName2, const char * photoName)
{(stuff)}
};
int main(int argc, char* argv[])
{
const char *windowName1;
const char *windowName2;
const char *photoName;
windowName1 = "Find Circles";
windowName2 = "Gray";
photoName = "Colonies 3.jpg";
bool isPhoto = false;
//circles(isPhoto, windowName1, windowName2, photoName);
Thread^ circleThread = gcnew Thread(
gcnew ThreadStart (&circles::circleFind(isPhoto, windowName1, windowName2, photoName) ));
circleThread->Start();
area(isPhoto, photoName);
return 0;
}
This is not all of the code but the important part. The errors I get are:
1>..\..\..\..\..\..\..\Program Files (x86)\OpenCV\samples\c\circle dection.cpp(130) : error C2102: '&' requires l-value
1>..\..\..\..\..\..\..\Program Files (x86)\OpenCV\samples\c\circle dection.cpp(130) : error C3350: 'System::Threading::ThreadStart' : a delegate constructor expects 2 argument(s)
| The problem here is that you are trying to use a function for a ThreadStart delegate which has an incompatible signature. ThreadStart is a delegate which has no arguments and returns no value. You are trying to use a method though which takes 4 arguments. This won't work.
You'll need to instead pass in a method which takes no arguments.
To pass parameters in C++, your best bet is to create a new class which has all of the parameters as fields. Then give it a method which has no parameters and returns no value and use that as the ThreadStart target.
ThreadHelper^ h = gcnew ThreadHelper();
h->Param1 = someValue;
ThreadStart^ threadDelegate = gcnew ThreadStart( h, &ThreadHelper::DoMoreWork );
There is a full example of this on the ThreadStart documentation page
http://msdn.microsoft.com/en-us/library/system.threading.threadstart.aspx
|
1,622,044 | 1,622,074 | Unfixable circular dependency | This code gives error C2504: 'IKeyEvent': base class undefined on line 3.
class IKeyEvent;
class EventDispatcher : private IKeyEvent {
public:
enum EEActions {
A_FEW_ACTIONS
};
private:
void OnKey(EventDispatcher::EEActions action, char multiplier);
}
class IKeyEvent {
public:
virtual void OnKey(EventDispatcher::EEActions action, char multiplier) = 0;
};
You cannot inherit from a class until it is defined, understandably. But I cannot define IKeyEvent until after EventDispatcher is defined.
I know I can move that enum out of the Event Dispatcher definition to make it global but this would require refactoring a large portion of the program. Is there any way to have EventDispatcher inherit from a class dependent on EventDispatcher?
| My recommendation: move EEActions into the base class - it is part of the interface, after all:
class IKeyEvent {
public:
enum EEActions {
A_FEW_ACTIONS
};
virtual void OnKey(EEActions action, char multiplier) = 0;
};
class EventDispatcher : public IKeyEvent {
private:
void OnKey(EventDispatcher::EEActions action, char multiplier);
};
If you then also make the inheritance from IKeyEvent public, you can continue to refer to the enum as EventDispatcher::EEActions (despite the enum being defined in the base type).
|
1,622,054 | 1,622,061 | C++ - Pointer to a class method | I have to set up a pointer to a library function (IHTMLDocument2::write) which is a method of the class IHTMLDocument2. (for the curious: i have to hook that function with Detours)
I can't do this directly, because of type mismatch, neither can I use a cast (reinterpret_cast<> which is the "right one" afaik doesn't work)
Here's what I am doing:
HRESULT (WINAPI *Real_IHTMLDocument2_write)(SAFEARRAY *) = &IHTMLDocument2::write
Thanks for your help!
| The pointer to function has the following type:
HRESULT (WINAPI IHTMLDocument2::*)(SAFEARRAY*)
As you can see, it's qualified with it's class name. It requires an instance of a class to call on (because it is not a static function):
typedef HRESULT (WINAPI IHTMLDocument2::*DocumentWriter)(SAFEARRAY*);
DocumentWriter writeFunction = &IHTMLDocument2::write;
IHTMLDocument2 someDocument = /* Get an instance */;
IHTMLDocument2 *someDocumentPointer = /* Get an instance */;
(someDocument.*writefunction)(/* blah */);
(someDocumentPointer->*writefunction)(/* blah */);
|
1,622,117 | 1,622,140 | Move a bitmap around a window quickly in C++ | I'm looking for some C++ code to let me quickly move a bitmap around a window, restoring the background as it moves. At present I capture the Window contents to a bitmap during the app initialization and in the OnPaint() I draw the this bitmap and then I draw my overlayed bitmap. I am double buffering the paint. The overlayed bitmap position moves with the mouse which invalidates the Window.
This works fine except it is too slow when the background window is large (think Windows Desktop) and the PC is slow. My guess is that redrawing the large background bitmap on every mouse move is the bottleneck. There has to be a much better and faster way to do this, but my searching hasn't found the answer I need.
| Probably your fastest way would be to store your movable image in one bitmap and then maintain a second temporary bitmap of the same size in memory as well. To draw your movable bitmap over your main image, you would first use the BitBlt API function to copy the region you're about to draw the movable bitmap onto into your temporary bitmap, then BitBlt your movable bitmap onto your main image. As you move the movable bitmap then, you would 1) BitBlt the temp bitmap onto its original location, then 2) BitBlt the new location into the temp bitmap, and then 3) BitBlt the movable image onto the new location in the main bitmap.
|
1,622,298 | 1,622,413 | How to generate automatic properties (get, set) for Visual Studio 2008 C++ | Having read this question on generating getters and setters in Visual Studio and tried (somewhat) the techniques described, I have failed miserably to graduate beyond the longhand way of writing Getters and Setters.
While I recognize the conceptual advantage of encapsulation (private members of a class in this case), writing 25 getters and setters is a waste of space and my time.
Why 25? Well apart form the exageration factor (approx 2.5) I just don't know at what point I will need access to that one variable in the future. I guess I could write a function that returns all of them and fish out the one I need, but if I add more members (often do) then the function must be changed throughout the code.
I like the form suggested here for VS 2008:
string sName { get; set; }
But it won't compile in C++. Is this just for .NET and C#?
Is there some tidy way to simulate this in C++?
| Thanks @Dan for pointing out this trick in Microsoft Compiler (non-portable)
Here is the way:
struct person
{
std::string m_name;
void setName(const std::string& p_name)
{
m_name = p_name;
}
const std::string& getName() const
{
return m_name;
}
// Here is the name of the property and the get, set(put) functions
__declspec(property(get = getName, put = setName)) std::string name;
};
int main()
{
person p;
p.name = "Hello World!"; // setName(...)
std::cout << p.name; // getName(...)
}
After creating your member variables plus the getters and setters of these member variables, you create a property for each getter/setter pair. You can call it whatever you want, because you have to specify the getter and setter for this property.
Just for fun :)
#define property(Type, Variable) private: Type Variable; \
public: const Type##& get##Variable() const { return Variable; }; \
void set##Variable(const Type& Variable##_) { Variable = Variable##_;}
struct Test
{
property(int, x); property(int, y);
property(std::string, text);
};
int main()
{
Test t;
t.setx(10);
t.sety(10);
t.settext("Hello World at: ");
std::cout << t.gettext() << " " << t.getx() << ", " << t.gety();
}
|
1,622,546 | 1,622,551 | Constructor abort constructing | I would like to have the constructor abort object construction whenever it encounters certain error code (e.g. if the following is encountered):
CudaObj::CudaObj(InsertionSim *theSim)
{
// Setup
if(cublasInit() == CUBLAS_STATUS_NOT_INITIALIZED) {
printf("CUBLAS init error.\n");
return -1; // abort here rather than return a value
}
...
}
What would be the easiest way for this to be accomplished? Would it be exception handling?
| I think the idiomatic way is to throw an exception from the constructor to emphasize that the object is not in a valid state.
|
1,622,592 | 1,622,623 | Atomic delete for large amounts of files | I am trying to delete 10000+ files at once, atomically e.g. either all need to be deleted at once, or all need to stay in place.
Of course, the obvious answer is to move all the files into a temporary directory, and delete it recursively on success, but that doubles the amount of I/O required.
Compression doesn't work, because 1) I don't know which files will need to be deleted, and 2) the files need to be edited frequently.
Is there anything out there that can help reduce the I/O cost? Any platform will do.
EDIT: let's assume a power outage can happen anytime.
| Kibbee is correct: you're looking for a transaction. However, you needn't depend on either databases or special file system features if you don't want to. The essence of a transaction is this:
Write out a record to a special file (often called the "log") that lists the files you are going to remove.
Once this record is safely written, make sure your application acts just as if the files have actually been removed.
Later on, start removing the files named in the transaction record.
After all files are removed, delete the transaction record.
Note that, any time after step (1), you can restart your application and it will continue removing the logically deleted files until they're finally all gone.
Please note that you shouldn't pursue this path very far: otherwise you're starting to reimplement a real transaction system. However, if you only need a very few simple transactions, the roll-your-own approach might be acceptable.
|
1,622,694 | 1,625,024 | Is it possible to have a non-template class subclass a template class? | I have a template class defined like so:
template <class T>
class Command {
public:
virtual T HandleSuccess(std::string response) = 0;
virtual std::string FullCommand() const = 0;
// ... other methods here ...
};
Will C++ allow me to create a non-template subclass of a template class? What I mean is can I do something like this:
class NoopCommand : public Command<NoopResult> {
public:
NoopResult HandleSuccess(std::string response);
std::string FullCommand() const;
// ... other methods here ...
};
As is that is not working for me because it says the following virtual functions are undefined:
T admix::Command<T>::HandleSuccess(std::string) [with T = admix::NoopResult]
std::string admix::Command<T>::FullCommand() const [with T = admix::NoopResult]
How can I specifically define them for the given T?
| litb found the solution on ##c++ last night.
The issue was I was passing a NoopCommand to a function like this:
void SendCommand(Command<T> command);
When I should have made the signature this:
void SendCommand(Command<T>& command);
Making that change allows everything to compile.
|
1,622,817 | 1,623,697 | Using the mod operator C++ | Without using any stls, boosts, and the like I have been trying to rotate the elements in my array. I've been trying to use the mod operator, to be efficient:
void stack::rotate(int r)
{
r = ( r % maxSize + maxSize ) % maxSize;
for ( int first_index = 0; first_index < r; ++first_index )
{
int mem = items[first_index].n;
int index = ( first_index + r ) % maxSize, index_prev = first_index;
while ( index != first_index )
{
items[index_prev] = items[index];
index_prev = index;
index = ( index + r ) % maxSize;
}
items[index_prev].n = mem;
}
Where items is an allocated array to an item struct. Although it is a little weird the item struct has an integer 'n' member so that i may use it with integer type varaibles.
But its still not comming out right =( . Im losing the contents of my second element. I think its break time ;)
| Tips:
Add assertions (r is positive, nonzero?, less than maxsize, maxsize is nonzero, etc.)
Write tests for this function, starting from an easy array and going up. Do not throw them away - keep them written and run all of them in a row.
Give clear names to variables.
Do not reuse r.
Your code looks a bit too obscure for me. At first sight it is crying "Off by one errors here! Come see!". Assert each and every possible boundary error.
For any more detailed answers, you should expand a bit on "its still not comming out right".
|
1,622,936 | 1,664,866 | How to export Visual Studio project to Qt? | I wonder how can I export a Visual Studio C++ project to Qt?
I am using openCV and OpenMP so I would like to know about setting these libraries in Qt.
| Answer to myself.
Visual Studio is capable to export the current project to a make file so.
File>Export to make file should work.
(I got this info form microsoft msdn site. So, it should work)
|
1,623,010 | 1,623,084 | Cleaner pointer arithmetic syntax for manipulation with byte offsets | In the following lines of code, I need to adjust the pointer pm by an offset in bytes in one of its fields. Is there an better/easier way to do this, than incessantly casting back and forth from char * and PartitionMap * such that the pointer arithmetic still works out?
PartitionMap *pm(reinterpret_cast<PartitionMap *>(partitionMaps));
for ( ; index > 0 ; --index)
{
pm = (PartitionMap *)(((char *)pm) + pm->partitionMapLength);
}
return pm;
For those that can't grok from the code, it's looping through variable length descriptors in a buffer that inherit from PartitionMap.
Also for those concerned, partitionMapLength always returns lengths that are supported by the system this runs on. The data I'm traversing conforms to the UDF specification.
| I often use these templates for this:
template<typename T>
T *add_pointer(T *p, unsigned int n) {
return reinterpret_cast<T *>(reinterpret_cast<char *>(p) + n);
}
template<typename T>
const T *add_pointer(const T *p, unsigned int n) {
return reinterpret_cast<const T *>(reinterpret_cast<const char *>(p) + n);
}
They maintain the type, but add single bytes to them, for example:
T *x = add_pointer(x, 1); // increments x by one byte, regardless of the type of x
|
1,623,103 | 1,623,112 | Questions about C++ memory allocation and delete | I'm getting a bad error. When I call delete on an object at the top of an object hierarchy (hoping to the cause the deletion of its child objects), my progam quits and I get this:
*** glibc detected *** /home/mossen/workspace/abbot/Debug/abbot: double free or corruption (out): 0xb7ec2158 ***
followed by what looks like a memory dump of some kind. I've searched for this error and from what I gather it seems to occur when you attempt to delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete. Here's the wacky part: it does not occur in debug mode. The code in question:
Terrain::~Terrain()
{
if (heightmap != NULL) // 'heightmap' is a Heightmap*
{
cout << "heightmap& == " << heightmap << endl;
delete heightmap;
}
}
I have commented out everything in the heightmap destructor, and still this error. When the error occurs,
heightmap& == 0xb7ec2158
is printed. In debug mode I can step through the code slowly and
heightmap& == 0x00000000
is printed, and there is no error. If I comment out the 'delete heightmap;' line, error never occurs. The destructor above is called from another destructor (separate classes, no virtual destructors or anything like that). The heightmap pointer is new'd in a method like this:
Heightmap* HeightmapLoader::load() // a static method
{
// ....
Heightmap* heightmap = new Heightmap();
// ....other code
return heightmap;
}
Could it be something to do with returning a pointer that was initialized in the stack space of a static method? Am I doing the delete correctly? Any other tips on what I could check for or do better?
| What happens if load() is never called? Does your class constructor initialise heightmap, or is it uninitialised when it gets to the destructor?
Also, you say:
... delete memory that has already been deleted. Impossible as there's only one place in my code that attempts this delete.
However, you haven't taken into consideration that your destructor might be called more than once during the execution of your program.
|
1,623,197 | 1,623,208 | Receiving data in TCP | If i send 1000 bytes in TCP, does it guarantee that the receiver will get the entire 1000 bytes "togther"? or perhaps he will first only get 500 bytes, and later he'll receive the other bytes?
EDIT: the question comes from the application's point of view. If the 1000 bytes are reassembles into a single buffer before they reach the application .. then i don't care if it was fragmented in the way..
| See Transmission Control Protocol:
TCP provides reliable, ordered delivery of a stream of bytes from a program on one computer to another program on another computer.
A "stream" means that there is no message boundary from the receiver's point of view. You could get one 1000 byte message or one thousand 1 byte messages depending on what's underneath and how often you call read/select.
Edit: Let me clarify from the application's point of view. No, TCP will not guarantee that the single read would give you all of the 1000 bytes (or 1MB or 1GB) packet the sender may have sent. Thus, a protocol above the TCP usually contains fixed length header with the total content length in it. For example you could always send 1 byte that indicates the total length of the content in bytes, which would support up to 255 bytes.
|
1,623,250 | 1,623,296 | std::regex -- is there some lib that needs to be linked? | I get a linker error with the following code:
#include <regex>
int main()
{
std::regex rgx("ello");
return 0;
}
test.o: In function `basic_regex':
/usr/lib/gcc/i586-redhat-linux/4.4.1/../../../../include/c++/4.4.1/tr1_impl/regex:769: undefined reference to `std::basic_regex<char, std::regex_traits<char> >::_M_compile()'
collect2: ld returned 1 exit status
| From gcc-4.4.1/include/c++/4.4.1/tr1_impl/regex
template <...>
class basic_regexp {
...
private:
/**
* @brief Compiles a regular expression pattern into a NFA.
* @todo Implement this function.
*/
void _M_compile();
I guess it's not ready yet.
UPDATE: current bleeding edge GCC (SVN @153546) doesn't appear to have the implementation yet.
|
1,623,378 | 1,623,418 | Trying to create a Math Input Panel in C# | How do I create a Math Input Panel in C#?
I have tried to put it into a dll and call it but it just closes right away.
#include <stdafx.h>
#include <atlbase.h>
#include "micaut.h"
#include "micaut_i.c"
extern "C" __declspec(dllexport) int run()
{
CComPtr<IMathInputControl> g_spMIC; // Math Input Control
HRESULT hr = CoInitialize(NULL);
hr = g_spMIC.CoCreateInstance(CLSID_MathInputControl);
hr = g_spMIC->EnableExtendedButtons(VARIANT_TRUE);
hr = g_spMIC->Show();
return hr;
}
I call the dll function in C# and the panel pops up but disappears right away. Any suggestions?
| In your C# project, add a reference to the COM library micautLib. Then you can use the following code (in C#):
MathInputControl ctrl = new MathInputControlClass();
ctrl.EnableExtendedButtons(true);
ctrl.Show();
I'm not sure if this is exactly how you're supposed to do it, but this seems to work cleanly (complete program).
using System;
using System.Windows.Forms;
using micautLib;
namespace MathInputPanel
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
MathInputControl ctrl = new MathInputControlClass();
ctrl.EnableExtendedButtons(true);
ctrl.Show();
ctrl.Close += () => Application.ExitThread();
Application.Run();
}
}
}
|
1,623,427 | 1,623,484 | How to find whether system has the font I needed in MFC? | I want to write the following function
bool IsFontExistInSystem(const CString& fontStyle) const
{
}
Is there any API in windows to do this?
Many Thanks!
| Here's some old code I dug out that will check if a font is installed. It could do with being tidied up but you get the idea:
static int CALLBACK CFontHelper::EnumFontFamExProc(ENUMLOGFONTEX* /*lpelfe*/, NEWTEXTMETRICEX* /*lpntme*/, int /*FontType*/, LPARAM lParam)
{
LPARAM* l = (LPARAM*)lParam;
*l = TRUE;
return TRUE;
}
bool Font::IsInstalled(LPCTSTR lpszFont)
{
// Get the screen DC
CDC dc;
if (!dc.CreateCompatibleDC(NULL))
{
return false;
}
LOGFONT lf = { 0 };
// Any character set will do
lf.lfCharSet = DEFAULT_CHARSET;
// Set the facename to check for
_tcscpy(lf.lfFaceName, lpszFont);
LPARAM lParam = 0;
// Enumerate fonts
::EnumFontFamiliesEx(dc.GetSafeHdc(), &lf, (FONTENUMPROC)EnumFontFamExProc, (LPARAM)&lParam, 0);
return lParam ? true : false;
}
|
1,623,455 | 1,623,627 | sendto fails with a non administrator user with errorcode 10013 | I found more source codes which are working like ping. My only problem with them is, that if i run the program with a non administrative user, then i get back errorcode 10013 which means : "An attempt was made to access a socket in a way forbidden by its access permissions." If i run the program with a user which is member of the administrator goup then it's working fine.
nResult = sendto (sock, pSendBuffer, sizeof (ICMPheader) + nMessageSize, 0, (SOCKADDR *)&dest, sizeof (SOCKADDR_IN));
::GetSystemTime (&timeSend);
++nPacketsSent;
if (nResult == SOCKET_ERROR)
{
cerr << endl << "An error occured in sendto operation: " << "WSAGetLastError () = " << WSAGetLastError () << endl;
}
Can anyone help me to solve this problem, or tell me why can't a non administrator user use this code? If not, then i would appriciate some code, which i can use with a user which isn't member of the administrator group.
Thanks in advance!
kampi
| If you want to implement ping functionality in your application on Windows, then you should have a look at the IcmpSendEcho2 function instead of trying to use raw sockets.
|
1,623,575 | 1,623,614 | operator= (T *r) in nested templates | I have a problem concerning nested templates and the overriding of the assignment operator.
Say i want to have a refcounting class template _reference. This _reference for now simply
holds a pointer to the ref-counted object. The problem now is that this all works fine,
as long as im doing this with simple classes or structs. eg. _reference ...,
But now i want to make a class template that is a reference to a std-vector forwarding the class it holds.
Nah, i just post the code: (it doesnt do refcounting and that stuff right now, its just the extraction of the problem i have)
template <typename T>
class _reference
{
private:
T* p_;
public:
// !!! this assignment seems only to work, when T is no class template already...
void operator= (T* r)
{
p_ = r;
}
// WHILE this ALWAYS works as well...
void simplySetIt (T* r)
{
p_ = r;
}
};
template <typename T>
class _ref_vector : public _reference<vector<T> >
{
};
void test2 ()
{
_reference<vector<long> > ref_ptr2;
_ref_vector<long> ref_ptr3;
ref_ptr2 = new vector<long>; // works fine.
ref_ptr3 = new vector<long>; // BUT: THIS doesnt work
ref_ptr3.simplySetIt (new vector<long>); // WHILE: this works fine...
}
MSVC-Error:
error C2679: binary '=' : no operator found which takes a right-hand operand of type
'std::vector<_Ty> *' (or there is no acceptable conversion)
GCC-Error:
error: no match for 'operator=' in 'ptr3 = (((const stlp_std::allocator<long int>&)
((const stlp_std::allocator<long int>*)(& stlp_std::allocator<long int>()))),
(((stlp_std::vector<long int, stlp_std::allocator<long int> >*)operator new(12u)),
((<anonymous> != 0u) ? (<anonymous>->stlp_std::vector<_Tp, _Alloc>::vector [with
_Tp = long int, _Alloc = stlp_std::allocator<long int>]
(<anonymous>), <anonymous>) : <anonymous>)))'
So please can anybody explain me why the assignment operator doesnt work here, while the simplySetIt - function does ?
| The base operator= gets hidden by implicit assignment operators, so that it doesn't take part in the overloading anymore. You need to write _ref_vector as
template <typename T>
class _ref_vector : public _reference<vector<T> >
{
using _reference<vector<T> >::operator=;
};
As there is no compiler-added version of simplySetIt, lookup will find it in the base class.
|
1,623,687 | 1,623,739 | OS API allocates members in struct. Free just the struct or every member first? | Let's say we have an array of PRINTER_INFO_2 like this:
PRINTER_INFO_2* printers = (PRINTER_INFO_2*)malloc(sizeof(PRINTER_INFO_2) * 64); // room for 64 items
Then we call EnumPrinters() to get a list of locally installed printers:
EnumPrinters(
PRINTER_ENUM_LOCAL,
NULL,
2,
(LPBYTE)printers,
...);
Here's the structure info for PRINTER_INFO_2.
Now, the string members are of type LPTSTR, so they are not stored inside of the struct itself.
What I am wondering about now, is if I can simply call free(printers) when I'm done with it, or will that result in a memory leak (all those strings not being freed)?
Will I have to call free() on every string member, like below?
free(printers[i].pServerName);
free(printers[i].pPrinterName);
free(printers[i].pShareName);
...
free(printers);
Seems awfully complicated to me this way. Especially if the struct has many, many members that needs to be freed.
Is there a better way to do this?
Thanks for helping me out with this!
| IIUC, you need to overallocate the buffer beyond the size of the structure, to accommodate for any output strings as well. EnumPrinters will tell you if the memory block was too small. As you can't know upfront how much memory you will need, you typically call it twice: once to learn the amount of memory needed, and the second time with an appropriately-sized buffer. You then deallocate the buffer with the same API that you used for allocation (e.g. malloc/free).
|
1,623,735 | 1,623,823 | Calculate the first day of a calendar week | I need to calculate the date of the first day in a calendar week, e.g.
Week 1 in 2009 -> Mon, 29.12.2008 (!)
Week 44 in 2009 -> Mon, 26.10.2009
I have some ugly code for this, but I would prefer a nice C++ lib.
Any suggestions?
| what about boost::gregorian::date with its algorithms ?
|
1,623,759 | 1,623,893 | C-DLL from C++ source | I have a C-Wrapper for my C++ Framework. Since this should run on mac and windows I am using scons:
env = Environment()
env.Append(CPPPATH = ['./'])
env.Append(LIBS = 'kernel32.lib')
env.Append(LIBPATH = 'C:/Program Files/Microsoft SDKs/Windows/v6.0A/Lib')
env.SharedLibrary(target='warpLib', source='warplib.cpp')
Simple Versions of warplib.cpp and warplib.h look like this:
warplib.cpp
#define DllExport __declspec( dllexport )
#include "warplib.h"
extern "C" {
DllExport int foo(int a) {
return a;
}
}
warplib.h
#define DllExport __declspec( dllexport )
extern "C" {
DllExport int foo(int a);
}
Can anybody tell me what is wrong with that? I tried almost all the combinations possible of 'extern "C"' but it always throws me something like "error C2732: linkage specification contradicts earlier specification for '...'".
If I skip 'extern "C"' it works but I see no .lib file and I am pretty sure I need that to really use the library.
| You should only need extern "C" on the declaration. Anyone then including that header will expect to link against it using the C linking standard, rather than the C++ decorated form. The warplib.cpp source file, and subsequent object file will expose the function foo correctly if warplib.h is included.
When using MSVC, there are a plethora of semi-useful scripts, and "build environment" console shortcuts provided, with a lot of dev-related environment variables and paths provided. I recommend locating a suitable script to execute to insert these variables into your environment, or running the dev console.
|
1,623,769 | 1,623,787 | Is there any safe strcmp? | I made a function like this:
bool IsSameString(char* p1, char* p2)
{
return 0 == strcmp(p1, p2);
}
The problem is that sometimes, by mistake, arguments are passed which are not strings (meaning that p1 or p2 is not terminated with a null character).
Then, strcmp continues comparing until it reaches non-accessible memory and crashes.
Is there a safe version of strcmp? Or can I tell whether p1 (and p2) is a string or not in a safe manner?
| No, there's no (standard) way to tell whether a char * actually points to valid memory.
In your situation, it is better to use std::string rather than char *s for all your strings, along with the overloaded == operator. If you do this, the compiler would enforce type safety.
EDIT: As per the comments below if you find yourself in a situation where you sometimes pass char *s that may or may not be valid strings to functions that expect null-terminated strings then something is fundamentally wrong with your approach, so basically
@janm's answer below.
|
1,623,975 | 1,624,013 | AMD multi-core programming | I want to start to write applications(C++) that will utilize the additional cores to execute portions of the code that have a need to perform lots of calculations and whose computations are independent of each other. I have the following processor : x64 Family 15 Model 104 Stepping 2 Authentic AMD ~1900 Mhz running on Windows Vista Home premium 32 bit and Opensuse 11.0 64 bit.
On the Intel platforms , I've used the following APIs Intel TBB, OpenMP. Do they work on AMD and does AMD have similar APIs.what has been your experience?
| OpenMP and TBB are both available also for AMD - it is also a compiler question.
E.g. see linux TBB on AMD.
I think the latest development on this end is to use the graphic card via CUDA or similar APIs- but this depends on the nature of your calculations. If it fits, it is faster than the CPU anyway.
|
1,624,109 | 1,624,133 | Is type specifier required for const? | Is a type specifier required here?
const c = 7;
Bjarne Stroustrup's 'The C++ Programming Language' on page 80 says that this is illegal. However, I've been practicing some brainbench tests, and one of the questions states that the type defaults to int. Brainbench is usually correct, so I'm unsure of which reference is right, and I've been unable to find anything in the standard. Does anyone have a definitive answer and a reference?
| The default type of int is valid for C, but not for C++. Even in C this style of coding should be avoided. Also note that Bjarne Stroustrup's book is one of the most authoritative reference for standard C++.
|
1,624,564 | 1,624,676 | Access protected member of a class in a derived class | i have an old codebase here, where they used protected member variables. Whether or not this is a good idea can be discussed. However, the code must have compiled fine with gcc3.
I have a derived template class Bar that uses protected member x from class template Foo like so
template <class Something> class Foo {
public:
// stuff...
protected:
some::type x;
}
template <class Something> Bar : Foo<Something> {
public:
void cleanup();
}
And in the method declaration of cleanup() there is something done with x
template <class Something> void Bar<Something>::cleanup() {
doSomeThingCleanUpLike (x);
}
This does not work with gcc4, although it should have worked with gcc3. It works when I change it to
doSomeThingCleanUpLike (this->x);
Why is that the case?
| The expression x used in the derived class is, by the rules in the standard, not dependent on any template parameter of the derived class. Because of this, lookup happens in the context of the template definition and not at the point of use/instantiation. Even though the template base class of the template appears to be visible, because it is a template class the particular instantiation that might be used might involve specialized templates so the base class template definition cannot be used for name lookup.
By changing the expression to this->x you are making it a dependent expression (this in a class template always depends on the template parameters). This means that lookup will occur in the instantiation context at which point the base class is fully known and its members are visible.
|
1,624,648 | 1,624,826 | Can I use a C style library built with VC6 directly in VC9 project? | We use an internal library(developed by some other team) built with VC6 compiler. This library mainly contains C Style APIs. We have a plan to migrate to Visual Studio 9 compiler. Should I request for the library to be built with VC9 compiler?
A more generic question, On which points ( may be name mangling, optimization etc) a DLL built with two different version of Visual Studio compiler differs?
| Conflict usually occurs in C Runtime library. The main idea is that memory should be deallocated in module where it was allocated. Then it will be safe to use library that was built with different version of compiler. Another problem is packing of structs, but it has no difference if you use only Visual C++ compiler.
Name mangling is differs from version to version in Visual C++, but it applies only to C++ libraries. If you use C style exporting (for instance, if you have DEF file) then there's nothing to worry about.
This question is not a full duplicate of your, but could be helpful.
|
1,624,762 | 1,625,184 | C++ Win32 -- COM Method: equivalent C declaration | I've been told that every COM method callable from C++ code (take for instance IHTMLDocument2::write) has an equivalent C declaration, usable from C code...
How do I find it?
Thanks in advance!
| This particular interface is documented as being provided by <mshtml.h>. Now, as it happens the second and third line of that file are:
// Include the full header file that works for C
#include "mshtmlc.h"
Looking into that file, we find the declaration
/* [id][vararg] */ HRESULT ( STDMETHODCALLTYPE *write )(
IHTMLDocument2 * This,
/* [in] */ __RPC__in SAFEARRAY * psarray);
Note that this is actually a pointer to the IHTMLDocument2::write method.
Sometimes the C declaration is the same header; sometimes the declaration isn't publicly available. But the COM standard is an ABI (a binary interface) designed such that you can always write a C declaration. Could be painful though.
|
1,624,803 | 1,624,815 | Does resizing a vector invalidate iterators? | I found that this C++ code:
vector<int> a;
a.push_back(1);
a.push_back(2);
vector<int>::iterator it = a.begin();
a.push_back(4);
cout << *it;
print some big random number; but if you add a.push_back(3) between 3rd and 4th lines, it will print 1. Can you explain it to me?
| Edited with more careful wording
yes, resizing a vector might invalidate all iterators pointing into the vector.
The vector is implemented by internally allocating an array where the data is stored. When the vector grows, that array might run out of space, and when it does, the vector allocates a new, bigger, array, copies the data over to that, and then deletes the old array.
So your old iterators, which point into the old memory, are no longer valid.
If the vector is resized downwards (for example by pop_back()), however, the same array is used. The array is never downsized automatically.
One way to avoid this reallocation (and pointer invalidation) is to call vector::reserve() first, to set aside enough space that this copying isn't necessary. In your case, if you called a.reserve(3) before the first push_back() operation, then the internal array would be big enough that the push_back's can be performed without having to reallocate the array, and so your iterators will stay valid.
|
1,624,905 | 1,656,972 | Using Boost Python with Weak Ptrs? | Trying to set up a dependency in C++ with a parent-child relationship. The parent contains the child and the child has a weak pointer to the parent.
I would also like to be able to derive from the parent in Python. However, when I do this, I get a weak pointer error connecting up this parent-child relationship.
C++ code:
#include <boost/python.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
using namespace boost;
using namespace boost::python;
struct Child;
struct Parent : public enable_shared_from_this<Parent>
{
void initialize();
shared_ptr<Child> m_child;
};
struct Child: public enable_shared_from_this<Child>
{
void setParent(shared_ptr<Parent> ptr);
weak_ptr<Parent> m_parent;
};
void Parent::initialize()
{
shared_ptr<Child> ptr(new Child);
m_child = ptr;
m_child->setParent(shared_from_this());
}
void Child::setParent(shared_ptr<Parent> ptr)
{
m_parent = ptr;
}
static PyObject* create(PyObject* object)
{
PyObject* instance = PyObject_CallObject(object, NULL);
Parent* parent = extract<Parent*>(instance);
parent->initialize();
return instance;
}
Python binding:
BOOST_PYTHON_MODULE(test_module)
{
class_<Parent>("Parent");
def("create", &create);
}
Python code:
from test_module import *
class Test(Parent):
def __init__(self):
Parent.__init__(self)
n = create(Test)
Error:
Traceback (most recent call last):
File "main.py", line 8, in <module>
n = create(Test)
RuntimeError: tr1::bad_weak_ptr
If I try and convert the extracted pointer to Parent into a shared_ptr, I get a free() invalid pointer error in Python.
Is there a way of getting round this problem or should I give up using weak pointers with Boost Python?
| I played with the code without the python stuff.
This reproduced the problem:
Parent* p(new Parent);
p->initialize();
The problem is nothing is holding on to the shared_ptr object.
This fixes it:
boost::shared_ptr<Parent> p(new Parent);
p->initialize();
Boost.Python FAQ : "When a shared_ptr is converted from Python, the shared_ptr actually manages a reference to the containing Python object. When a shared_ptr is converted back to Python, the library checks to see if it's one of those "Python object managers" and if so just returns the original Python object"
The Parent* needs to be stored in a shared_ptr somehow. I haven't figured out how yet.
Parent* parent = boost::python::extract<Parent*>(instance);
|
1,625,105 | 1,956,217 | How to write `is_complete` template? | After answering this question I was trying to find is_complete template in Boost library and I realized that there is no such template in Boost.TypeTraits. Why there is no such template in Boost library? How it should look like?
//! Check whether type complete
template<typename T>
struct is_complete
{
static const bool value = ( sizeof(T) > 0 );
};
...
// so I could use it in such a way
BOOST_STATIC_ASSERT( boost::is_complete<T>::value );
The code above is not correct, because it is illegal to apply sizeof to an incomplete type. What will be a good solution? Is it possible to apply SFINAE in this case somehow?
Well, this problem couldn't be solved in general without violating the ODR rule, but there is there a platform specific solution which works for me.
| The answer given by Alexey Malistov can be used on MSVC with a minor modification:
namespace
{
template<class T, int discriminator>
struct is_complete {
static T & getT();
static char (& pass(T))[2];
static char pass(...);
static const bool value = sizeof(pass(getT()))==2;
};
}
#define IS_COMPLETE(X) is_complete<X,__COUNTER__>::value
Unfortunately, the __COUNTER__ predefined macro is not part of the standard, so it would not work on every compiler.
|
1,625,299 | 1,625,387 | Processing huge text files | Problem:
I've a huge raw text file (assume of 3gig), I need to go through each word in the file
and find out that a word appears how many times in the file.
My Proposed Solution:
Split the huge file into multiple files and each splitted file will have words in a sorted manner. For example,
all the words starting with "a" will be stored in a "_a.dic" file. So, at any time we will not execeed more than 26 files.
The problem in this approach is,
I can use streams to read the file, but wanted to use threads to read certain parts of the file. For example, read 0-1024 bytes with a separate thread (atleast have 4-8 threads based on the no. of processors exist in the box). Is this is possible or am I dreaming?
Any better approach?
Note: It should be a pure c++ or c based solution. No databases etc., are allowed.
| You need to look at 'The Practice of Programming' by Kernighan and Pike, and specifically chapter 3.
In C++, use a map based on the strings and a count (std::map<string,size_t>, IIRC). Read the file (once - it's too big to read more than once), splitting it into words as you go (for some definition of 'word'), and incrementing the count in the map entry for each word you find.
In C, you'll have to create the map yourself. (Or find David Hanson's "C Interfaces and Implementations".)
Or you can use Perl, or Python, or Awk (all of which have associative arrays, equivalent to a map).
|
1,625,362 | 1,629,183 | Will IntelliTrace(tm) (historical debugging) be available for unmanaged c++ in future versions of Visual Studio? | I love the idea of historical debugging in VS 2010.
However, I am really disappointed that unmanaged C++ is left out.
IntelliTrace supports debugging Visual
Basic and C# applications that use
.NET version 2.0, 3.0, 3.5, or 4. You
can debug most applications, including
applications that were created by
using ASP.NET, Windows Forms, WPF,
Windows Workflow, and WCF.
IntelliTrace does not support
debugging C++, script, or other
languages. Debugging of F#
applications is supported on an
experimental basis.
(editorial) [This is really poor support in my opinion. .NET is less in need of this assistance than unmanaged c++. I an getting a little tired of the status of plain old C++ and its second-class status in the MS tools world. Yes, I realize it is probably WAAY easier to implement this with .NET and MS are pushing .NET as the future, and yes, I know that C++ is an "old" language, but that does not diminish the fact that there are lots of C++ apps out there and there will continue to be more apps built with C++. I sincerely hope MS has not dropped C++ as a supported developer tool/language- that would be a shame.]
Does anyone know if there are plans for it to support C++?
| According to this MSDN blog post they "hope to fix this limitation in the future."
|
1,625,422 | 1,683,286 | Where I can find the appWizard that can generate C++ application | I have an project to modify. This project was create with AppWizard many years ago. This generated weird code when I open it with visual studio 8. I would like to modify the interface. Can I find a free AppWizard.
Thanks,
| After using Visual Studio 6.0 it worked.
|
1,625,531 | 1,625,579 | C++, WCHAR[] to std::cout and comparision | I need to put WCHAR[] to std::cout ... It is a part of PWLAN_CONNECTION_NOTIFICATION_DATA passed from Native Wifi API callback.
I tried simply std::cout << var; but it prints out the numeric address of first char. the comparision (var == L"some text") doesn't work either. The debugger returns the expected value, however the comparision returns 0. How can I convert this array to a standard string(std::string)?
Thanks in advance
| Assuming var is a wchar_t *, var == L"some text" does a pointer comparison. In order to compare the string pointed to by var, use a function such as wcscmp.
|
1,626,036 | 1,626,053 | How do I collapse selected chunks of code in Visual Studio 2008? | In Visual Studio 2008: Is there a way for me to customly collapse bits of code similar to like how I can automatically collapse chunks of comments?
| Your piece of code needs to be a block surrounded by, as desired:
braces
#region and #endregion in C#
#pragma region and #pragma endregion in C/C++
If you can't collapse statement blocks, you need to enable this feature :
Tools -> Options -> Text Editor -> C/C++ -> Formatting -> check everything in "outlining"
(In Visual Studio 2013 it's Tools -> Options -> Text Editor -> C/C++ -> View)
Then, reopen the source file to reload outlining.
|
1,626,038 | 1,626,188 | Should an implementor of IShellBrowser::QueryActiveShellView Method call AddRef for the caller? | I am attempting to implement an IShellBrowser. One method of such is:
HRESULT STDMETHODCALLTYPE IShellBrowser::QueryActiveShellView(/* [out] */ __RPC__deref_out_opt IShellView **ppshv)
This gets the active shell view pointer for the caller (in my case, there is only one shell view at any given time).
But it is very unclear whether I should call AddRef on behalf of the caller, or whether it is in fact the caller's responsibility to do their own AddRef/Release?
I'm not at all a fan of programming-by-side-effect - and that's exactly what AddRef would be - a hidden expectation on the caller, that the caller wouldn't necessarily know about.
And looking at the docs for IShellBrowser::QueryActiveShellView, they make no mention of it at all. But looking at IUnknown::AddRef, we see that any method that makes a copy of an interface pointer should call AddRef - http://msdn.microsoft.com/en-us/library/ms691379%28VS.85%29.aspx
Call this method for every new copy of an interface pointer that you make. For example, if you are passing a copy of a pointer back from a method, you must call AddRef on that pointer.
| Yes, COM has a very detailed contract on this behavior: all [out] parameters must be copied (in the case of value types) or AddRef:ed (in the case of interface pointers).
So, you should definitely AddRef.
|
1,626,116 | 1,626,174 | How to write a class capable of foreach | It's been a while since Visual Studio added support for a foreach extension that works like
vector<int> v(3)
for each (int i in v) {
printf("%d\n",i);
}
I want to know how to make any class able to use foreach. Do I need to implement some interface?
| for each statement in VC++, when used on a non-managed class:
for each (T x in xs)
{
...
}
is just syntactic sugar for this:
for (auto iter = xs.begin(), end = xs.end(); iter != end; ++iter)
{
T x = *iter;
}
Where auto means that type of variable is deduced automatically from type of initializer.
In other words, you need to provide begin() and end() methods on your class that would return begin and end input iterators for it.
Here is an example of class that wraps an istream and allows you to iterate over all lines in it:
#include <istream>
#include <iostream>
#include <fstream>
#include <string>
class lines
{
public:
class line_iterator
{
public:
line_iterator() : in(0)
{
}
line_iterator(std::istream& in) : in(&in)
{
++*this;
}
line_iterator& operator++ ()
{
getline(*in, line);
return *this;
}
line_iterator operator++ (int)
{
line_iterator result = *this;
++*this;
return result;
}
const std::string& operator* () const
{
return line;
}
const std::string& operator-> () const
{
return line;
}
friend bool operator== (const line_iterator& lhs, const line_iterator& rhs)
{
return (lhs.in == rhs.in) ||
(lhs.in == 0 && rhs.in->eof()) ||
(rhs.in == 0 && lhs.in->eof());
}
friend bool operator!= (const line_iterator& lhs, const line_iterator& rhs)
{
return !(lhs == rhs);
}
private:
std::istream* const in;
std::string line;
};
lines(std::istream& in) : in(in)
{
}
line_iterator begin() const
{
return line_iterator(in);
}
line_iterator end() const
{
return line_iterator();
}
private:
std::istream& in;
};
int main()
{
std::ifstream f(__FILE__);
for each (std::string line in lines(f))
{
std::cout << line << std::endl;
}
}
Note that implementation of line_iterator is actually somewhat bigger than the minimum needed by for each; however, it is the minimum implementation that conforms to input iterator requirements, and thus this class is also usable with all STL algorithms that work on input iterators, such as std::for_each, std::find etc.
|
1,626,248 | 1,626,269 | Does GCC inline C++ functions without the 'inline' keyword? | Does GCC, when compiling C++ code, ever try to optimize for speed by choosing to inline functions that are not marked with the inline keyword?
| Yes. Any compiler is free to inline any function whenever it thinks it is a good idea. GCC does that as well.
At -O2 optimization level the inlining is done when the compiler thinks it is worth doing (a heuristic is used) and if it will not increase the size of the code. At -O3 it is done whenever the compiler thinks it is worth doing, regardless of whether it will increase the size of the code. Additionally, at all levels of optimization (enabled optimization that is), static functions that are called only once are inlined.
As noted in the comments below, these -Ox are actually compound settings that envelop multiple more specific settings, including inlining-related ones (like -finline-functions and such), so one can also describe the behavior (and control it) in terms of those more specific settings.
|
1,626,673 | 1,626,723 | C++ multiplayer UDP socket API | Can anyone recommend an easy to use, fast and reliable C++ API for sending and receiving data over a UDP socket? Maybe something that is specifcally intended for multiplayer games?
| Raknet is amazingly good. So good that is the basis for networking in commercial engines like unity3d. http://www.jenkinssoftware.com
|
1,626,846 | 1,626,967 | How do I allocate variably-sized structures contiguously in memory? | I'm using C++, and I have the following structures:
struct ArrayOfThese {
int a;
int b;
};
struct DataPoint {
int a;
int b;
int c;
};
In memory, I want to have 1 or more ArrayOfThese elements at the end of each DataPoint. There are not always the same number of ArrayOfThese elements per DataPoint.
Because I have a ridiculous number of DataPoints to assemble and then stream across a network, I want all my DataPoints and their ArrayOfThese elements to be contiguous. Wasting space for a fixed number of the ArrayOfThese elements is unacceptable.
In C, I would have made an element at the end of DataPoint that was declared as ArrayOfThese d[0];, allocated a DataPoint plus enough extra bytes for however many ArrayOfThese elements I had, and used the dummy array to index into them. (Of course, the number of ArrayOfThese elements would have to be in a field of DataPoint.)
In C++, is using placement new and the same 0-length array hack the correct approach? If so, does placement new guarantee that subsequent calls to new from the same memory pool will allocate contiguously?
| Since your structs are PODs you might as well do it just as you would in C. The only thing you'll need is a cast. Assuming n is the number of things to allocate:
DataPoint *p=static_cast<DataPoint *>(malloc(sizeof(DataPoint)+n*sizeof(ArrayOfThese)));
Placement new does come into this sort of thing, if your objects have a a non-trivial constructor. It guarantees nothing about any allocations though, for it does no allocating itself and requires the memory to have been already allocated somehow. Instead, it treats the block of memory passed in as space for the as-yet-unconstructed object, then calls the right constructor to construct it. If you were to use it, the code might go like this. Assume DataPoint has the ArrayOfThese arr[0] member you suggest:
void *p=malloc(sizeof(DataPoint)+n*sizeof(ArrayOfThese));
DataPoint *dp=new(p) DataPoint;
for(size_t i=0;i<n;++i)
new(&dp->arr[i]) ArrayOfThese;
What gets constructed must get destructed so if you do this you should sort out the call of the destructor too.
(Personally I recommend using PODs in this sort of situation, because it removes any need to call constructors and destructors, but this sort of thing can be done reasonably safely if you are careful.)
|
1,627,152 | 1,627,845 | Can I mix JNI headers implementation with normal C++ classes? | If I try to implement my class on this file I get an error UnsatisfiedLinkError, however if I remove the implementation of the Broker.h Class it goes ok. Why?
Broker.h
#include "XletTable.h"
#ifndef BROKER_H_
#define BROKER_H_
class Broker {
private:
static Broker* brokerSingleton;
static XletTable *table;
// Private constructor for singleton
Broker(JNIEnv *, XletTable *);
// Get XletTable (Hash Table) that contains the...
static XletTable* getTable();
public:
virtual ~Broker();
static Broker* getInstance(JNIEnv *);
jobject callMethod(JNIEnv *, jclass, jstring, jobject, jbyteArray);
};
#endif /* BROKER_H_ */
BrokerJNI.h
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class Broker */
#ifndef _Included_Broker
#define _Included_Broker
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: Broker
* Method: callMethod
* Signature: (Ljava/lang/String;Ljava/lang/reflect/Method;[B)Ljava/lang/Object;
*/
JNIEXPORT jobject JNICALL Java_Broker_callMethod
(JNIEnv *, jclass, jstring, jobject, jbyteArray);
#ifdef __cplusplus
}
#endif
#endif
| Probably your library miss reference to some symbol, or another library. Try make some main.cpp with empty main() function, and link it with your library - g++ main.cpp -o main -lInterAppCC. If you miss something, the linker will give you a detailed error message.
PS. Since your header file already wraps function prototype with extern "C", you don't required to do the same when writing implementation.
|
1,627,348 | 1,627,606 | Programmatically move registry keys | Does anyone know how I can programmaically move a registry from HKEY_LOCAL_MCAHINE to HKEY_CURRENT_USER?
I wrote a recursive function that uses RegEnumKeyEx and RegEnumValue, but it appears that RegEnumValue returns all of the values under the top level key.
For example, if the key is HKEY_LOCAL_MACHINE\SOFTWARE\MyApp\KeyName1 and has 3 values under it and I have HKEY_LOCAL_MACHINE\SOFTWARE\MyApp\KeyName2 and that has 2 values. It looks like RegEnumKeyEx is returning the proper keys, but when I call RegEnumValue for the first Key (ie. KeyName1) i get all 5 values returned and not just the 3 under that key.
Hope that all makes sense... am I doing something wrong?
Thanks for any help
Here is a snippet, if it helps:
void CArgusApp::RecurseSubKeys(CString csStartKey)
{
CQERegistry reg;
HRESULT hr = reg.Open(HKEY_LOCAL_MACHINE, "SOFTWARE\\" + csStartKey, KEY_QUERY_VALUE );
CStringArray csaDataNames;
reg.GetAllDataNames(csaDataNames);
for (int j = 0; j < csaDataNames.GetSize(); j++)
{
CString csValueName = csaDataNames.ElementAt(j);
TRACE(csStartKey + " - " + csValueName);
}
CStringArray csaKeys;
reg.GetAllSubKeys(csaKeys);
for (int i = 0; i < csaKeys.GetSize(); i++)
{
CString csKey = csaKeys.ElementAt(i);
this->RecurseSubKeys(csStartKey + "\\" + csKey);
}
reg.Close();
}
i.e. GetAllDataNames above simply calls RegEnumValue and GetAllSubKeys call RegEnumKeyEx.
| Looking through all the registry functions, I found this: SHCopyKey or I can use this: RegCopyTree for Vista and later.
Thanks for the help.
|
1,627,479 | 1,627,527 | Is the use of previously defined members as part of later members in an enum definition legal? | namespace ValueType {
enum Enum {
Boolean = 0,
Float = 1,
Double,
SInt = 8,
SLong,
UInt = SInt + (1 <<4),
ULong = SLong + (1 << 4)
};
}
| Yes -- the requirement is that it's an integral constant expression. The C++ standard includes the following example:
enum { d, e, f=e+2 };
|
1,627,866 | 1,627,870 | Instantiating at global level (C++) | I get the following error with the code below.
expected constructor, destructor, or type conversion before '=' token
--
#include <string>
#include <map>
class Foo {
};
std::map<std::string, Foo> map;
map["bar"] = Foo();
int main()
{
return 0;
}
| map["bar"] = Foo(); // This line is a statement not a declaration.
// You have to put it in main, or any execution context
Untill C++0x becomes mainstream, I would suggest using boost. Filling the map becomes piece of cake. Here is an example:
std::map<std::string, Foo> mymap;
...
int main()
{
insert(mymap)
("First", Foo(...))
("Second", Foo(...))
("Third", Foo(...));
...
}
|
1,628,001 | 1,628,022 | Python, Perl And C/C++ With GUI | I'm now thinking, is it possible to integrate Python, Perl and C/C++ and also doing a GUI application with this very nice mix of languages?
| Well, there is Wx, Inline::Python and Inline::C, but the question is why?
|
1,628,034 | 1,628,060 | GetDlgItemInt( ) problem | Ok, i have 2 edit controls and a button in my main window; in one edit control the user can write a number and when he push the button i read that number and i print it in the other edit control (which is read only).
My problem is that when i put a number and i press the button, for some reason that i dont understand i can get that number. And GetDlgItemInt() always return zero and his third parameter always return me false.
This is the code where i use GetDlgItemInt () to read the number:
case CM_BUTTON:
number = GetDlgItemInt(hwndEdit2, CM_EDIT2, &flag, FALSE);
if(flag)
{
if(number > 0 && number < 20)
{
sprintf(message, "This is the number %d", number);
SetWindowText(hwndEdit, message);
}
else
MessageBox(hwnd, "Number to high or to low", "Error", MB_OK | MB_ICONWARNING);
}
else
MessageBox(hwnd, "Error getting the number", "Error", MB_ICONEXCLAMATION | MB_OK);
break;
Any suggest?
| The first parameter to GetDlgItemInt should be the handle to the dialog box. Unless the name hwndEdit2 is extremely deceiving, you're currently passing the handle to the edit control itself instead.
|
1,628,189 | 1,628,207 | Static inline methods? | Okay,
Here is what I'm trying to do... Right now it is compiling but failing at linking... LNK2001
I want the methods static because there are no member variables, however I also want them inline for the speedups they provide.
What is the best way to do this? Here is what I have in a nutshell:
/* foo.h */
class foo
{
static void bar(float* in);
};
/* foo.cpp */
inline void foo::bar(float* in)
{
// some dark magic here
}
I'm trying to do this because I want to be able to go:
foo::bar(myFloatPtr);
foo doesn't have any member variables... it doesn't make sense to.
| If you are calling bar from another cpp file, other than foo.cpp, it needs to be in a header file.
|
1,628,321 | 1,628,399 | Boost multi-index container with index based on nested values | If I have an object like this:
struct Bar {
std::string const& property();
};
I can create a multi-index container for it like this:
struct tag_prop {};
typedef boost::multi_index_container<
Bar,
boost::multi_index::indexed_by<
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<tag_prop>,
boost::multi_index::const_mem_fun<
Bar, const std::string&, &Bar::property
>
>
>
, ... other indexes
> BarContainer;
But if I have a class like this:
struct Foo {
Bar const& bar();
};
How can I construct an index on .bar().property() for a container of Foo objects?
Normally I would nest calls to boost::bind, but I can't figure out how to make it work in the context of a multi-index container.
| I believe you need to create a predicate object that takes two instances of Foo and its operator() can call Foo::bar() on both instances.
Something like
struct MyPredicate
{
bool operator() (const Foo& obj1, const Foo& obj2) const
{
// fill in here
}
};
and then use
...
boost::multi_index::ordered_unique<boost::multi_index::tag<tag_prop>,
boost::multi_index::identity<Foo>, MyPredicate>,
...
Check out MultiIndex Ordered indices reference
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.