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,110,824 | 1,110,890 | Eclipse-CDT: How do I handle permission denied errors opening sockets? | My program opens a socket on port 80, but if I don't run it as root (with sudo) then it fails to open the socket with a permission error.
This means my application doesn't work when I launch it in the debugger.
So:
Can I tell Eclipse-CDT somehow to launch the app using sudo?
Or, can I somehow enable my program to have permission to open port 80?
thx
Alex
| For debugging purposes, I'd pass --port 8080 as an argument, or use some other configuration method, and open on 8080. No need for root permissions then.
|
1,110,954 | 1,110,974 | What is the easiest way to call a Java method from C++? | I'm writing a C++ program which needs to be able to read a complex and esoteric file type. I already have a Java program for handling these files which includes functionality to convert them into simpler file formats. My idea is, whenever my program needs to read info from a complex file, to have it call the Java method to convert it to the simpler file type, then write it out to a temp file which my program can easily read. The files are small enough that performance will be acceptable. I'm writing my program in Qt and running it on a Windows Vista machine.
I've looked into using Java Native Interface, but the more I look into it the more it seems I should avoid it at all costs. Is there a better way to accomplish this, or should I continue with the JNI approach?
| How often do you need to do this? If it's not that often you can shell out and do it there. Just generate the command line to do it. JNI works, but it's a bit of a pain to get set up. Once you have it set up it should work just fine.
|
1,110,985 | 1,111,005 | Class doesn't support operators | I created a vector out of a struct to store multiple types of values. However, I can't get input to work.
#include "std_lib_facilities.h"
struct People{
string name;
int age;
};
int main()
{
vector<People>nameage;
cout << "Enter name then age until done. Press enter, 0, enter to continue.:\n";
People name;
People age;
while(name != "0"){
cin >> name;
nameage.push_back(name);
cin >> age;
nameage.push_back(age);}
vector<People>::iterator i = (nameage.end()-1);
nameage.erase(i);
}
I've also tried having the name and age variables in the main function be string/int types, and while that fixes the operator issue, it leads to an issue with function calling in the push_back line.
P.S. Is it possible to push_back multiple inputs such as...
cin >> name >> age;
nameage.push_back(name,age);
?
| Why not do:
People p;
cin >> p.name;
cin >> p.age;
nameage.push_back( p );
You can't just cin >> p, as istream doesn't understand how to input a "People" object. So you can either define operator>> for People, or you can just read in the individual fields into a People object.
Also, note, you need to push_back an object of type People, as that is what your vector is -- it is a People container.
|
1,111,078 | 1,111,099 | reduce the capacity of an stl vector | Is there a way to reduce the capacity of a vector ?
My code inserts values into a vector (not knowing their number beforehand), and
when this finishes, the vectors are used only for read operations.
I guess I could create a new vector, do a .reseve() with the size and copy
the items, but I don't really like the extra copy operation.
PS: I don't care for a portable solution, as long as it works for gcc.
| std::vector<T>(v).swap(v);
Swapping the contents with another vector swaps the capacity.
std::vector<T>(v).swap(v); ==> is equivalent to
std::vector<T> tmp(v); // copy elements into a temporary vector
v.swap(tmp); // swap internal vector data
Swap() would only change the internal data structure.
|
1,111,376 | 1,111,628 | How-to do unit-testing of methods involving file input output? | I'm using C++Test from Parasoft for unit testing C++ code.
I came across the following problem. I have a function similar to the next one (pseudocode):
bool LoadFileToMem(const std::string& rStrFileName)
{
if( openfile(rStrFileName) == successfull )
{
if( get_file_size() == successfull )
{
if( read_entire_file_to_buffer() == successfull )
{
return true;
}
return false;
}
return false;
}
return false;
}
My questions in this case are:
Should I use stubs for file system functions? Or should I include specific sample test files for running the unit tests?
In my case std::fstream class is used for file input.
Has anyone better suggestions? (Best if done in C++Test but not mandatory).
| For unit-testing THIS function, you should use stubs for each of the called functions.
Each called function then has its own unit test suite, which exercises that function.
For read_entire_file_to_buffer(), you want at least one test file that overflows the buffer, massively, to verify that you do not crash and burn when they feed you the New York Stock Exchange histories instead of the 40-character config file you were expecting.
|
1,111,415 | 1,111,683 | Make GDC front end emit intermediate C/C++ code? | While investigating the D language, I came across GDC, a D Compiler for GCC. I downloaded the version for MinGW from here:
http://sourceforge.net/projects/dgcc/files/
Documentation was almost nonexistent, but it did say that most of the command line switches were the same as for the GCC compiler. However, that doesn't help me much, since I don't usually build with GCC.
GDC is described as a "GCC front end". That makes me think that at some point it has to generate intermediate C++ or C that the GCC compiler can actually swallow. I believe that this is how GCC compiles Objective-C programs.
What I want to know is this: Is there a way to get GDC to emit the intermediate C/C++ code as files that I can then inspect and compile by hand with GCC/MinGW?
| No.
Front-ends to GCC generate a language-independent representation that is then compiled directly to assembly. This is the case for the C, C++, Obj-C, D, Fortran, Java, Ada, and other front-ends. There is no intermediate C or C++ representation, nor can one be generated.
|
1,111,440 | 1,111,470 | Undefined reference error for template method | This has been driving me mad for the past hour and a half. I know it's a small thing but cannot find what's wrong (the fact that it's a rainy Friday afternoon, of course, does not help).
I have defined the following class that will hold configuration parameters read from a file and will let me access them from my program:
class VAConfig {
friend std::ostream& operator<<( std::ostream& lhs, const VAConfig& rhs);
private:
VAConfig();
static std::string configFilename;
static VAConfig* pConfigInstance;
static TiXmlDocument* pXmlDoc;
std::map<std::string, std::string> valueHash;
public:
static VAConfig* getInstance();
static void setConfigFileName( std::string& filename ) { configFilename = filename; }
virtual ~VAConfig();
void readParameterSet( std::string parameterGroupName );
template<typename T> T readParameter( const std::string parameterName );
template<typename T> T convert( const std::string& value );
};
where the method convert() is defined in VAConfig.cpp as
template <typename T>
T VAConfig::convert( const std::string& value )
{
T t;
std::istringstream iss( value, std::istringstream::in );
iss >> t;
return t;
}
All quite simple. But when I test from my main program using
int y = parameters->convert<int>("5");
I get an undefined reference to 'int VAConfig::convert<int>...' compilation error. Ditto for readParameter().
Looked at a lot of template tutorials but coul not figure this out. Any ideas?
| Templated code implementation should never be in a .cpp file: your compiler has to see them at the same time as it sees the code that calls them (unless you use explicit instantiation to generate the templated object code, but even then .cpp is the wrong file type to use).
What you need to do is move the implementation to either the header file, or to a file such as VAConfig.t.hpp, and then #include "VAConfig.t.hpp" whenever you use any templated member functions.
|
1,111,479 | 1,111,977 | Keep a stream from fstream open through member functions | I am trying to keep a stream to a file /dev/fb0 (linux framebuffer) open throughout several Qt member functions. The goal is to use a myscreen::connect function to open up the framebuffer
bool myscreen::connect()
{
std::fstream myscreen_Fb;
myscreen_Fb.open("/dev/fb0")
QImage* image;
image = new QImage(w, h, QImage::Format_RGB888);
QScreen::data = image->bits();
}
This would ideally open the frame buffer and create a new QImage to act as a memory buffer for the data being written to the screen. Then my "image" would point to the first visible pixel (memory) on the screen through the bits() function. I have to implement this because my hardware does not support the default memory mapping.
I would then like to blit it to the screen with:
void myscreen::blit(const QImage &img, const QPoint &topLeft, const QRegion ®ion)
{
QScreen::blit(img, topLeft, region);
write(myscreen_Fb, image.bits(), image.size());
}
I cant seem to get the pointer to the first visible pixel open to use and get complaints from GCC about myscreen_Fb not being declared in the scope. Any ideas?
update
I made the changes suggested and declared the function in the class but get this error which is driving me crazy.
error: expected constructor, destructor, or type conversion before '.' token
It refers to the line which contains:
vopuscreenFd.open("/dev/fb0", fstream::out);
Bryce
| That is because myscreen_Fb is, in fact, not declared in the scope of the blit function. Here you declared it in the connect() function.
Declare myscreen_Fb as a member variable of the myscreen class. It will be accessible to all functions in that instance of the class.
class myscreen
{
public:
myscreen( void );
~myscreen( void );
bool
connect ( void );
void
blit ( const QImage &img,
const QPoint &topLeft,
const QRegion ®ion)
private:
std::fstream myscreen_Fb;
};
In relation to this question: "I cant seem to get the pointer to the first visible pixel open to use", what exactly do you mean here? All I can presume is that you mean to use blit using the image ptr you created within connect, which is also not yet a member variable, so perhaps you want to do this:
bool myscreen::connect()
{
std::fstream myscreen_Fb;
myscreen_Fb.open("/dev/fb0")
QImage* image;
image = new QImage(w, h, QImage::Format_RGB888);
//QScreen::data = image->bits(); //don't need this?
blit( image, "topleft ref", "region ref"); //add this, replacing
// "topleft ref" and
// "region ref" with correct
// values you've pulled
}
and the write function within myscreen::blit get's the ptr to the first pixel. I am making a lot of presumptions here because the question is a bit unclear.
|
1,112,005 | 1,112,079 | Does the anonymous namespace enclose all namespaces? | In C++ you specify internal linkage by wrapping your class and function definitions inside an anonymous namespace. You can also explicitly instantiate templates, but to be standards conforming any explicit instantiations of the templates must occur in the same namespace. AFAICT this should compile, but GCC fails on it:
namespace foo {
template<class T>
class bar {};
}
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
With the error:
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace 'foo')
Which is interesting because the anonymous namespace should just be specifying linkage, not really functioning as a namespace, and the global namespace definitely encloses foo, since it encloses every namespace. But even this doesn't work!:
template<class T>
class bar {};
using namespace foo;
namespace {
template class bar<int>;
}
int main()
{
return 0;
}
Which fails with the same error, just listing the global namespace instead:
namespace_test.cpp:11: error: explicit instantiation of 'class bar<int>' in namespace '<unnamed>' (which does not enclose namespace '::')
:/
| An anonymous namespace is logically equivalent to
namespace _TU_specific_unique_generated_name
{
// ...
}
using namespace _TU_specific_unique_generated_name;
A namespace, anonymous or otherwise, has no effect on the linkage of its members. In particular members of an anonymous namespace do not magically get internal linkage.
|
1,112,126 | 1,112,131 | VS 2005 rebuilds project without changing any files | This is a really strange issue. One day my project started to do a rebuild every time I launched it in the debugger, even if I hadn't changed the code. ie. I would go Build->Build Solution, then Debug->Start Debugging, it would rebuild when I tried to start debugging. The specific file that it recompiles is shown (left out source code, just function definitions):
The Header:
#ifdef IPC_USE_DLL
#ifdef IPC_EXPORTS
#define IPC_API __declspec(dllexport)
#else
#define IPC_API __declspec(dllimport)
#endif
#else
#define IPC_API
#endif
#include <windows.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <stdio.h>
#include <string>
namespace Ipc {
/** Class provides basic network functionality, connecting, etc.
*/
class IPC_API NetworkUtilities
{
public:
//! Attempts to connect to the specified port/address.
static int connectToServer( const std::string& port, const std::string& address, SOCKET& serverConnection );
//! Attempts to initiate a server on the specified port.
static int initiateServer( const std::string& port, SOCKET& serverSocket );
//! Assuming the passed socket is a valid socket, the function waits the specified amount of time for a connection.
/** Returns: NTWK_SUCCESS, NTWK_WSA_ERROR, NTWK_TIMEOUT, NTWK_INVALID_PEER_ADDRESS, NTWK_INVALID_SOCKET.
*/
static int waitForClient( SOCKET& serverSocket, SOCKET& clientSocket, const std::string address, unsigned timeOut = 0 );
};
//! Various error codes
IPC_API enum {
};
}
The CPP:
#include "StdAfx.h"
#include "NetworkUtilities.h"
namespace Ipc {
// Implementation of functions from header
// ...
}
This is a DLL. Can anyone tell me why this constantly needs to rebuild? It is quite irritating while debugging.
Thanks
| One possibility is a time stamp issue. Can you check the time on the files and see if their modified date is at some point in the future?
|
1,112,254 | 1,112,286 | (Obj) C++: Instantiate (reference to) class from template, access its members? | I'm trying to fix something in some Objective C++ (?!) code. I don't know either of those languages, or any of the relevant APIs or the codebase, so I'm getting stymied left and right.
Say I have:
Vector<char, sizeof 'a'>& sourceData();
sourceData->append('f');
When i try to compile that, I get:
error: request for member 'append' in 'WebCore::sourceData', which is of non-class type 'WTF::Vector<char, 1ul >& ()();
In this case, Vector is WTF::Vector (from WebKit or KDE or something), not STD::Vector. append() very much is supposed to be a member of class generated from this template, as seen in this documentation. It's a Vector. It takes the type the template is templated on.
Now, because I never write programs in Real Man's programming languages, I'm hella confused about the notations for references and pointers and dereferences and where we need them.
I ultimately want a Vector reference, because I want to pass it to another function with the signature:
void foobar(const Vector<char>& in, Vector<char>& out)
I'm guessing the const in the foobar() sig is something I can ignore, meaning 'dont worry, this won't be mangled if you pass it in here'.
I've also tried using .append rather than -> because isn't one of the things of C++ references that you can treat them more like they aren't pointers? Either way, its the same error.
I can't quite follow the error message: it makes it sound like sourceData is of type WTF:Vector<char, 1ul>&, which is what I want. It also looks from the those docs of WTF::Vector that when you make a Vector of something, you get an .append(). But I'm not familiar with templates, either, so I can't really tell i I'm reading that right.
EDIT:
(This is a long followup to Pavel Minaev)
WOW THANKS PROBLEM SOLVED!
I was actually just writing an edit to this post that I semi-figured out your first point after coming across a reference on the web that that line tells the compiler your forward declaring a func called sourceData() that takes no params and returns a Vector of chars. so a "non-class type" in this case means a type that is not an instance of a class. I interpreted that as meaning that the type was not a 'klass', i.e. the type of thing you would expect you could call like .addMethod(functionPointer).
Thanks though! Doing what you suggest makes this work I think. Somehow, I'd gotten it into my head (idk from where) that because the func sig was vector&, I needed to declare those as &'s. Like a stack vs. heap pass issue.
Anyway, that was my REAL problem, because I tried what you'd suggested about but that doesn't initialize the reference. You need to explicitly call the constructor, but then when I put anything in the constructor's args to disambiguate from being a forward decl, it failed with some other error about 'temporary's.
So in a sense, I still don't understand what is going on here fully, but I thank you heartily for fixing my problem. if anyone wants to supply some additional elucidation for the benefit of me and future google people, that would be great.
| This:
Vector<char, sizeof 'a'>& sourceData();
has declared a global function which takes no arguments and returns a reference to Vector. The name sourceData is therefore of function type. When you try to access a member of that, it rightfully complains that it's not a class/struct/union, and operator-> is simply inapplicable.
To create an object instead, you should omit the parentheses (they are only required when you have any arguments to pass to the constructor, and must be omitted if there are none):
Vector<char, sizeof 'a'> sourceData;
Then you can call append:
sourceData.append('f');
Note that dot is used rather than -> because you have an object, not a pointer to object.
You do not need to do anything special to pass sourceData to a function that wants a Vector&. Just pass the variable - it will be passed by reference automatically:
foobar(sourceData, targetData);
|
1,112,456 | 1,112,493 | Cross-platform way of hiding cryptographic keys in C++? | My application needs to use a couple of hard-coded symmetric cryptographic keys (while I know that storing a public key would be the only perfect solution, this is non-negotiable). We want the keys to be stored obfuscated, so that they won't be recognizable by analyzing the executable, and be "live" in memory for as little time as possible - as to increase the difficulty of a memory dump retrieving them in clear-text. I'm interested in using C++ features (using some sort of scoped_key comes to mind). The solution must be portable - Windows, Linux, MacOS -, so it cannot take advantage of the operating system crypto API.
How would you go about designing such a system? Thanks a lot.
| your scoped_key can be simply a KeyHolder object on the stack. Its constructor takes the obfuscated buffer and makes a real key out of it and its destructor zeros out the memory and deallocates the memory.
As for how to actually obfuscate the key in the binary, One silly choice you might try is put inside a much larger random binary block and remember its offset and size and probably XOR it with some short random sequence.
If you do the XORing thing you can actually avoid ever having the real key in memory. simply modify the decryption to read a byte from the key and before using it, to XOR it with the appropriate value.
*Add here disclaimer on how foolish security through obscurity is*
|
1,112,531 | 1,112,543 | What is the best way to use two keys with a std::map? | I have a std::map that I'm using to store values for x and y coordinates. My data is very sparse, so I don't want to use arrays or vectors, which would result in a massive waste of memory. My data ranges from -250000 to 250000, but I'll only have a few thousand points at the most.
Currently I'm creating a std::string with the two coordinates (i.e. "12x45") and using it as a key. This doesn't seem like the best way to do it.
My other thoughts were to use an int64 and shove the two int32s into it and use it as a key.
Or to use a class with the two coordinates. What are the requirements on a class that is to be used as the key?
What is the best way to do this? I'd rather not use a map of maps.
| Use std::pair<int32,int32> for the key:
std::map<std::pair<int,int>, int> myMap;
myMap[std::make_pair(10,20)] = 25;
std::cout << myMap[std::make_pair(10,20)] << std::endl;
|
1,112,584 | 1,112,589 | std::vector of functions | I want a std::vector to contain some functions, and that more functions can be added to it in realtime. All the functions will have a prototype like this:
void name(SDL_Event *event);
I know how to make an array of functions, but how do I make a std::vector of functions? I've tried this:
std::vector<( *)( SDL_Event *)> functions;
std::vector<( *f)( SDL_Event *)> functions;
std::vector<void> functions;
std::vector<void*> functions;
But none of them worked. Please help
| Try using a typedef:
typedef void (*SDLEventFunction)(SDL_Event *);
std::vector<SDLEventFunction> functions;
|
1,112,716 | 1,112,728 | Why can't you use a Template when iterating | When compiling :
#include <vector>
template<class T> class foo {
void bar() {
std::vector<T> x;
std::vector<T>::iterator i = x.begin();
}
};
int main() {
return 0;
}
I get :
# g++ ~test.cpp
test.cpp: In member function `void foo<T>::bar()':
test.cpp:7: error: expected `;' before "i"
Shouldn't this work?
g++ version 3.4.3 on RHEL.
| You can, but you need to tell it that iterator there is a type (it doesn't know, because in general it can depend on T - as vector is a template type, and could in theory have specializations for some T where iterator is a function or something else). So, you have to use typename to indicate that it is always a type:
typename std::vector<T>::iterator i = x.begin();
|
1,112,724 | 1,112,739 | Why isn't there an operator[] for a std::list? | Can anyone explain why isn't the operator[] implemented for a std::list? I've searched around a bit but haven't found an answer. It wouldn't be too hard to implement or am I missing something?
| Retrieving an element by index is an O(n) operation for linked list, which is what std::list is. So it was decided that providing operator[] would be deceptive, since people would be tempted to actively use it, and then you'd see code like:
std::list<int> xs;
for (int i = 0; i < xs.size(); ++i) {
int x = xs[i];
...
}
which is O(n^2) - very nasty. So ISO C++ standard specifically mentions that all STL sequences that support operator[] should do it in amortized constant time (23.1.1[lib.sequence.reqmts]/12), which is achievable for vector and deque, but not list.
For cases where you actually need that sort of thing, you can use std::advance algorithm:
int iter = xs.begin();
std::advance(iter, i);
int x = *iter;
|
1,112,827 | 1,112,885 | Loading Native DLL as Debug Module in Managed C# Code for Windows CE | I am writing a Windows CE application in C# that references a native C++ DLL (that I am also coding) using the following method:
[DllImport("CImg_IP_CE.dll")]
public static unsafe extern void doBlur(byte* imgData, int sigma);
This actually works fine but I am unable to debug the DLL. When I check the debug modules that are loaded after running the EXE, CImg_IP_CE.dll is not one of them. Even after calling functions successfully from the DLL it still does not show up in the modules list.
Upon looking around, it seems that the LoadLibrary() function might work, but I cannot find any examples of using this in a C# Windows CE application. How would I do this or is there a better way to make sure the DLL loads up for debugging?
| I found the answer through this post:
http://www.eggheadcafe.com/conversation.aspx?messageid=31762078&threadid=31762074
In summary, the same question was asked and the response was:
No, you can't step from managed code through a P/Invoke call into native
code in the Smart Device debugger. You might be able to use Attach to
Process to do the native debugging (with the native DLL project loaded into
that instance of VS2005), or simply write debug information from the native
DLL to a serial port or something. This really doesn't come up very often,
though, where you actually need to step from one to the other.
Further along in the thread, someone figured out how to accomplish this:
A quick test shows that the easiest way to handle this is to 'run' your DLL.
That is, set the debugging options to start the managed code EXE that will
use your DLL and set your breakpoints in the DLL (all from the DLL project,
of course). Naturally, when the EXE starts, your DLL won't be loaded, so
you'll see the breakpoints as hollow circles with ! on them, but, when you
call any of the native functions in your DLL, the DLL will be loaded (it's
not loaded on startup), and the breakpoints will be set.
So strangely, when you run the C# program and make a call to the native DLL code, it still does not show as loaded in the debug modules window. However, if you set the DLL project as the startup project, and then set the Remote Executable as the EXE file in the Debugging options, now when you first call the DLL, it will load up in the debugger. Okay... whatever works!
|
1,112,840 | 1,113,209 | Trouble restarting exe | I need to restart the program that im working on after an update has been downloaded except im running into some issues.
If i use CreateProcess nothing happens, if i use ShellExecute i get an 0xC0150002 error and if i use ShellExecute with the command "runas" it works fine. I can start the command prompt fine using CreateProcess and ShellExecute just not the same exe again and dont want to use runas as this will elevate the exe.
Any Ideas?
Windows 7, visual studio 2008 c++
alt text http://lodle.net/shell_error.jpg
CreateProcess:
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
PROCESS_INFORMATION ProcInfo = {0};
STARTUPINFO StartupInfo = {0};
BOOL res = CreateProcess(name, "-wait", NULL, NULL, false, 0, NULL, exePath, &StartupInfo, &ProcInfo );
ShellExecute:
char exePath[255];
GetModuleFileName(NULL, exePath, 255);
size_t exePathLen = strlen(exePath);
for (size_t x=exePathLen; x>0; x--)
{
if (exePath[x] == '\\')
break;
else
exePath[x] = '\0';
}
char name[255];
GetModuleFileName(NULL, name, 255);
INT_PTR r = (INT_PTR)ShellExecute(NULL, "runas", name, "-wait", exePath, SW_SHOW);
| Ok worked it all out in the end.
The first time my exe ran it used the default paths and as such loaded vld (a leak detector dll) from the default path. However in the exe i modified the dll path to be the bin folder ([app]\bin) when i restarted the exe using CreateProcess it picked up on a different vld dll (this was my mistake) that had incorrect side by side linkage and it was only after looking at event viewer that i worked it out.
Thanks for all your help.
|
1,113,082 | 1,113,161 | Beginner's Guide to Setting Up Qt for C++ | I'm interested in playing around with GUIs and I've been trying to set up Qt for Visual Studio 2008 and MinGW but have failed miserably—in that at times I'd compile the library and it still wouldn't work and others the compile would fail. Can anyone recommend a good guide to set up Qt (or another GUI toolkit if setting up Qt just doesn't work well for beginners). No preference for IDE really, just want to start coding already :)
Edit I tried both answers and they were both great, the QtCreator is a fast way to get started with Qt. And 20th Century Boy's blogpost was a thorough guide to setting up Qt with VS08 that I could even follow (answering the original question). Thanks and happy coding :)
| I have covered Qt and VS 2008 integration in my blog. Have a look at it here...
http://cplusplus-mortals.blogspot.com/2009/04/qt-part-3-configuration-for-visual.html
|
1,113,095 | 1,113,189 | From C++ Tools to.... ? Trying to be exposed to modern tools | I'm a long-time C++ programmer developing on Windows, and have been using Visual Studio for developing unmanaged C++.
In the past 2-3 months, for the first time, I have been exposed to the world of C# and Java. Man, I'm astounded by the productivity gain!
In particular:
C# and Java have so many cool
tools (TestDriven.NET, NetBeans
IDE). Personally, the tools feel much more
modern than the C++ tools that I've
been using.
All the libraries are
there for me to use right away,
without me having to download extras
(Boost, Qt, etc)
Blazingly-fast
compile time. C# compilation is
super fast. Each time I make changes
to Java code on my Netbeans IDE, I
never have to wait for the usual
compile/link. It's just done right
there. No waiting! (People who have used Boost probably agree with me on the slow compile time such as Asio library)
Simple deployment scheme. I really like the fact that I can just write the code once and it can be run on different machines (OS) without me having to recompile it.
Having said all that, here's my real question: are C# and Java good technology to learn the most modern tools and libraries? Are these the two technologies that have the best tools available? I want to be exposed to new tools to broaden my perspective. This way I can learn from it, and try to find equivalent tools in C++.
Disclaimer: My intention is not to dis C++ as a language at all. After I have used the tools available for Java and C#, I just feel like the tools that I have available for C++ are quite limited (especially refactoring).
I use the following for my C++ dev:
VS.NET 08
Visual Assist X
Intel Parallel Studio (profiler)
TeamCity
I plan to use Bullseye and PC-Lint + Visual Lint for code checking
Clarification
When I asked for tools, I meant tools as in IDE, Unit testing tools, refactoring tools, and the likes. TestDriven.NET is probably the most perfect example. I just love the fact I can start coding my unit tests, and right click to run those tests inside my IDE! It's so sad that I cant have the same convenience in unmanaged C++!
| I agree, too. No matter if it is C# or Java. Both are very modern languages and have a huge community contributing new Technologie implementation and Frameworks. Depending on the field you worked in with C++ moving to e.g. C# can be a big productivity boost. The choice of the language also depends on your field. Java is huge among Enterprise Webapplications and for a beginner the amount of different Frameworks, Shortcuts and Technologies seems to be bone crushing (and some indeed tend to overspecify and therefore oftentimes overcomplicate things). For Java Eclipse is probably the best IDE (I used Visual Studio for a while and maybe it is my lack of experience there, but I really missed some features there that Eclipse has especially when it comes to Code Generation).
C# on the other hand is very .NET Framework and - of course - Microsoft oriented. If you used to program in C++ for windows trying C# is probably really easy (because switching from C++ to C# is exactly what Microsoft wants C++ developers to do) and definitely the better choice for Desktop Applications (the Linux Ports of the .NET runtime environment are constantly getting better, too).
I had to work on a C++ compatibility project and I tried to adapt some of the technologies I was used to working with from Java e.g. the versatile Logging Frameworks or Test Driven development to C++ but it turned out to be way more complex and time consuming than I expected it to be. My personal conclusion was, that some Technologies are not adaptable to C++ (or just with disproportional effort) the way they fit in the languages mentioned above.
|
1,113,214 | 1,113,227 | C++ development for Linux on Windows | I am trying to setup a development environment for Linux C++ application. Because I'm limited to my laptop (vista) which provides essential office applications, I want to program and access email, word at the same time.
I'd prefer a local Windows IDE. SSH to a company linux server and using VI doesn't seem productive to me. Even using some IDE installed on the linux server doesn't seem good to me, because I can't do the work at home.
So does Eclipse CDT + MinGW work for me, or is there any other choice?
Thanks.
ZXH
| Why not install a Linux virtual machine on your laptop, in VMware or similar? That way you can test while you're developing too.
|
1,113,578 | 1,114,704 | Threading Building Blocks (TBB) for Qt-based CD ripper? | I am building a CD ripper application in C++ and Qt. I would like to parallelize the application such that multiple tracks can be encoded concurrently. Therefore, I have structured the application in such a way that encoding a track is a "Task", and I'm working on a mechanism to run some number of these Tasks concurrently. I could, of course, accomplish this using threads and write my own Task queue or work manager, but I thought Intel's Threading Building Blocks (TBB) might be a better tool for the job. I have a couple of questions, however.
Is encoding a WAV file into a FLAC, Ogg Vorbis, or Mp3 file something that would work well as a tbb::task? The tutorial document states that "if threads block frequently, there is a performance loss when using the task scheduler". I don't think my encoding tasks would block for mutexes frequently, but the will need to access disk relatively frequently, since they must read the WAV data from disk in order to encode. Is this level of disk activity problematic in the sense described by the tutorial?
Does TBB work well with Qt? When using Qt threads, you can use Qt's signals/slots mechanism transparently across threads. Would the same be true if I were using tbb::tasks instead of Qt threads? Would there be any other "gotchas"?
Thanks for any insights you can provide.
| TBB is suppose to work well, even transparently, with other threading mechanisms so theoretically there should be nothing preventing you from using QT's thread classes in the same program. If there is something that works more naturally with QT threads, like the GUI, use them and keep the TBB stuff segregated as best you can or want.
I don't see that you are making the best use of TBB as you currently outlined your design. You parallelize at the grossest level, the file. As you suspect, since the CD is a pretty slow device, you may spend more time seeking back and forth for data from multiple files than you actually save.
The real bang for the buck with TBB should involve exploiting whatever data and/or task parallelism there is in the transformation process. Can you, for instance, pull any block of bytes out of the stream and apply whatever transform to it independently of any part of the stream before or after? Are there multiple steps to the transform that can be parallelized?
|
1,113,694 | 1,113,814 | How to set up a local test/build machine? | I am about to start a new personal project. It aims to be a pretty big one so I thought it would be a good idea to keep some sort of CVS. I have also read lot of interesting stuff about unit testing and I would like to include some system that automatically builds the project and runs a series of test after each check in.
The characteristics are:
Only one developer and one machine (just me and my computer!).
Include a CVS.
Include automated testing.
The software should be free (as in no-cost) and run under Linux.
It is going to be C++ and ANTLR based.
So far, I have set up SVN and Eclipse+CDT+ANTLR for development but I am pretty lost about the automated build+test setting. To write the tests I have been thinking in Boost.Test or UnitTest++.
So that's the source of my question. How should I set up my local test/build machine?
Links to valuable tutorials are more than welcome.
Thanks.
| It seems that most open source continuous integration servers are built on java and does not support C++ "out-of-the-box". However there are some links you can start with (note that for running most open source continuous integration servers you need a java environment):
What continuous integration tool is best for a C++ project - some alternatives for continuous integration software
Continuous integration for C++ - some ideas for Hudson configuration
Using CruiseControl with C++ - some ideas and configurations for CruiseControl
Compiling C/C++ code with Ant - if you do use the "Makefile project" in CDT and do not want to use make as a build tool
I personally prefer Hudson because of its simply install (no need for application server just start with java -jar hudson.war) and easy to use and quite "clever" gui. Hudson can checkout your code from SVN (or CVS) and can run a shell script or Ant file as a build script. Maybe you have to spend a few days to set up a configuration with a proper build script but I think it worth the time.
|
1,113,704 | 1,130,203 | Cache design: flyweight of mutable entity objects based on an immutable key | A lot of different screens in my app refer to the same entity/business objects over and over again.
Currently, each screen refers to their own copy of each object.
Also, entity objects may themselves expose access to other entity objects, again new copies of objects are created.
I'm trying to find a caching solution.
I'm looking for something similar to boost::flyweight.
However, based on immutable key/mutable value and reference counted.
boost::flyweight<key_value<long, SomeObject>, tag<SomeObject> > object;
The above is almost perfect.
I'm looking for a similar container that will give mutable access to SomeObject
Edit:
I like the flyweight's syntax and semantics. However, flyweight only allows const SomeObject& access, no chance to modify the object.
Edit2: Code has to compile on MSVC++6
Any ideas?
| As long as you are happy affecting intrinsic state, then from the internals in boost/flyweight/key_value.hpp it looks like you can get away with a const_cast. If you have your own key extractor you should ensure it doesn't vary with the operations that making x mutable will expose it to.
flyweight<key_value<long, SomeObject> > kvfw(2);
SomeObject &x = const_cast<SomeObject &>(static_cast<const SomeObject&>(kvfw));
|
1,113,981 | 1,114,002 | Visual C++ argv question | I'm having some trouble with Visual Studio 2008. Very simple program: printing strings that are sent in as arguments.
Why does this:
#include <iostream>
using namespace std;
int _tmain(int argc, char* argv[])
{
for (int c = 0; c < argc; c++)
{
cout << argv[c] << " ";
}
}
For these arguments:
program.exe testing one two three
Output:
p t o t t
?
I tried doing this with gcc instead and then I got the whole strings.
| By default, _tmain takes Unicode strings as arguments, but cout is expecting ANSI strings. That's why it's only printing the first character of each string.
If you want use the Unicode _tmain, you have to use it with TCHAR and wcout like this:
int _tmain(int argc, TCHAR* argv[])
{
for (int c = 0; c < argc; c++)
{
wcout << argv[c] << " ";
}
return 0;
}
Or if you're happy to use ANSI strings, use the normal main with char and cout like this:
int main(int argc, char* argv[])
{
for (int c = 0; c < argc; c++)
{
cout << argv[c] << " ";
}
return 0;
}
A bit more detail: TCHAR and _tmain can be Unicode or ANSI, depending on the compiler settings. If UNICODE is defined, which is the default for new projects, they speak Unicode. It UNICODE isn't defined, they speak ANSI. So in theory you can write code that doesn't need to change between Unicode and ANSI builds - you can choose at compile time which you want.
Where this falls down is with cout (ANSI) and wcout (Unicode). There's no _tcout or equivalent. But you can trivially create your own and use that:
#if defined(UNICODE)
#define _tcout wcout
#else
#define _tcout cout
#endif
int _tmain(int argc, TCHAR* argv[])
{
for (int c = 0; c < argc; c++)
{
_tcout << argv[c] << " ";
}
return 0;
}
|
1,114,017 | 1,114,031 | Is it good practice to use size_t in C++? | I've seen people use size_t whenever they mean an unsigned integer. For example:
class Company {
size_t num_employees_;
// ...
};
Is that good practice? One thing is you have to include <cstddef>. Should it be unsigned int instead? Or even just int?
Just using int sounds attractive to me since it avoids stupid bugs like these (because people do often use int):
for(int i = num_employees_ - 1; i >= 0; --i) {
// do something with employee_[i]
}
| size_t may have different size to int.
For things like number of employees, etc., this difference usually is inconsequential; how often does one have more than 2^32 employees? However, if you a field to represent a file size, you will want to use size_t instead of int, if your filesystem supports 64-bit files.
Do realise that object sizes (as obtained by sizeof) are of type size_t, not int or unsigned int; also, correspondingly, there is a ptrdiff_t for the difference between two pointers (e.g., &a[5] - &a[0] == ptrdiff_t(5)).
|
1,114,115 | 1,114,131 | Undefined symbol error for base class in C++ shared library | I compiled the following code as a shared library using g++ -shared ...:
class Foo {
public:
Foo() {}
virtual ~Foo() = 0;
virtual int Bar() = 0;
};
class TestFoo : public Foo {
public:
int Bar() { return 0; }
};
extern "C" {
Foo* foo;
void init() {
// Runtime error: undefined symbol: _ZN3FooD2Ev
foo = new TestFoo(); // causes error
}
void cleanup() { delete(foo); }
void bar() { foo->Bar(); }
}
The point is to expose the functionality of my classes (here just minimal toy classes as an example) as a simple C API with the three functions init, cleanup, and bar.
When I try to load the shared library (using dyn.load in R) I get an error:
unable to load shared library 'test.so':
test.so: undefined symbol: _ZN3FooD2Ev
So, it seems it cannot find the Foo constructor. What am I doing wrong and how can this be fixed?
UPDATE: Thanks, jbar! So it was the Foo destructor. Could I have known this from the cryptic symbol in the error message: _ZN3FooD2Ev? Does the D in FooD stand for destructor?
| We can't declare pure virtual destructor. Even if a virtual destructor is declared as pure, it will have to implement an empty body (at least) for the destructor.
|
1,114,219 | 1,114,271 | Visual C++ 2008 Forms Incredibly Slow | In Visual C++ 2008 Express Edition when adding forms all of the default handlers for buttons, check boxes, etc go into FormName.h by default. So when I do this most of my handler code now goes in the header, then I switch back to the "Design View" to see the form designer. Once I have any reasonable size interface going back to "Design View" from the code view (of the header FormName.h) takes on the order of 1-3 minutes for (what I assume to be) the form designer to re-parse the header file to roundtrip any changes I may have made in the actual code.
Is there a way to change this behavior? I've done some basic Googling but haven't really found anyone complaining about this issue, so I assume I'm missing something obvious. Any help would be much appreciated.
| It's a known problem with using Windows Forms designer with C++ in Visual Studio. You have to move your definitions of member functions manually from a header file to corresponding source file. You might want to take a look at this thread where I raised this issue on msdn c++ group.
Welcome to Visual C++.
ps.
Developers, developers, developers, developers; Yada, yada...
|
1,114,237 | 1,114,263 | Unhandled exception when dereferencing char pointer in Visual C++ 2008 | I'm trying to do some classic C development in Visual C++ 2008 that will modify the characters of a string like so:
void ModifyString(char *input)
{
// Change first character to 'a'
*input = 'a';
}
I'm getting a unhandled exception when I try to change a character. It seems like I could do this in Visual Studio 6 or using gcc, but maybe I'm just forgetting something. Does Visual Studio somehow pass char* by value (managing memory). If so, how do I turn this off?
| You're probably passing a string literal somewhere:
ModifyString("oops"); // ERROR!
C and C++ allow you to implicitly cast from string literals (which have type const char[]) to char*, but such usage is deprecated. String constants are allowed to be allocated in read-only memory (and they usually are), so if you attempt to modify them, you'll get an access violation (aka segmentation fault or bus error). If the compiler doesn't put string constants in read-only memory, the program will still work, but it is undefined behavior.
The correct way to do this is to copy the string into a writeable buffer:
// one way:
char mystring[] = "test";
ModifyString(mystring); // ok
// another way:
char mystring[64]; // make sure this is big enough!!
strcpy(mystring, "test");
ModifyString(mystring); // ok
|
1,114,447 | 1,185,085 | How to use C#-like attributes in C++ | I'm considering the use of C++ for a personal project. I would like to make it platform independent (no Mono please, since some platforms don't yet support it), and that's why I considered C++.
I have one doubt, however. I've grown quite fond of C#'s attributes, and I would like to know if I can use something similar in C++.
Also, is it possible to use the decorator pattern for this?
EDIT: I would now consider other possibilities or approximations for this matter, ie. some way to attach additional behavior to a class in runtime.
EDIT 2: Java is not an option, because some devices I'd like to port it to don't support java.
| To "attach additional behavior to a class in runtime" in most any OO language I recommend the Strategy design pattern -- have the class (and/or its instances) hold (through a pointer in C++, a [reseatable] reference in other languages) an instance of a suitable interface / abstract class known as the "strategy interface" (with one method [virtual in C++ of course, non-final in languages that have final, etc -- IOW, an overridable method!-)] per point of extensibility), and generally supply getter and setter methods (or properties or whatever's appropriate to the specific language) to access and change that instance.
Lastly, the class or instance must delegate all appropriate functionality through the methods of the strategy interface instance it's holding.
I often recommend this "high-ceremony" approach (for this specific purpose) even in dynamic languages such as Python or Ruby which would also allow more informal approaches via duck typing and the ability of an object of class to directly reach into the internals of another -- such dynamic abilities are generally speaking quite useful, but for this specific purpose (as I think of "changing a class behavior at runtime") a more highly architected and controlled approach, in my experience, leads to better-maintainable and clearer code (this bit is controversial: many developers in dynamic-language communities like "monkey patching" approaches even in such situations, but a dozen years of successful development practice in dynamic languages, mostly Python, have made me otherwise inclined).
In appropriate case you can modify the fundamental Strategy DP approach in various ways; for example, when the modifiable functionality falls neatly into a few cohesive groups, it's best to "fragment" the Strategy object into several simple and cohesive ones (DrawingStrategy, PersistenceStrategy, BusinessRulesStrategy, and so forth).
This whole approach does not take the place of performing proper analysis and consequently proper design, as it won't allow extension of a class functionality along an axis that was not originally taken into consideration; rather, the approach is intended as a proper way to architect a well-thought-out design, providing "hooks" for extensibility in a well-controlled manner. If new considerations come into play it may still well be necessary to iterate and perfect the classes' design to cover such new ideas. But then, iterative development (including tweaks and extensions to the original design) is inevitable in any rich, complex real-world project -- the Strategy DP is just one arrow in your quiver to help make the process more orderly and effective.
|
1,114,594 | 1,114,631 | MSXML DOM: Add namespace declaration to an existing node in a tree | Problem description: Read an xml file, traverse to a particular node (element), if it does not have a particular namespace declaration, add the required namespace declaration, and write out the file.
I need to do this in C++ using Microsoft's MSXML DOM APIs. The namespaceURI property on IXMLDOMNode COM object is read-only according to this msdn reference. Appreciate any workarounds.
Edit: I spent quite some time on a workaround: Create a new sibling node in the same document with the namespace I need, then move all the child elements of the original node to this new node, then delete the original node. Well, this does not work, because the child nodes are going to keep whatever default namespace they had before.
And then this simple idea hit me and it works but I am not sure if it will bite me in the future: just create an "xmlns" attribute on the element, giving it the desired namespace value! Any comments?
| Guessing that you mean to add a default namespace to an element its first important to understand that this is not strictly possible. The namespace that an element's name belongs to forms it fully qualified name hence "adding" a default namespace is tantamount to renaming the element. There is no mechanism built into the DOM to rename elements.
The strictest approach would be to process the XML as an input to a transform (either in code or via XSLT) that generates the corrected XML output.
However a pragmatic solution would be to use some string processing like RegEx to find the element and inject the xmlns attribute. Personally I prefer the former.
|
1,114,608 | 1,114,949 | Helgrind for Windows? |
Helgrind is a Valgrind tool for
detecting synchronisation errors in C,
C++ and Fortran programs that use the
POSIX pthreads threading primitives.
Anyone knows an equivalent tool for windows? After googling a bit I haven't found anything...
| For the people that eventually should land there: I've found that: Intel thread checker: should be pretty similar to Hellgrind.
|
1,114,792 | 1,115,340 | How to initialize a static char* with gettetxt() using local operating system environment? | Is there a standard or common way in C++ to handle static strings that need to be set by gettext()?
Here is an example using the answer to Complete C++ i18n gettext() “hello world” example as a base just changing the literal hello world to a static char* hws and char* hw.
It looks like hws is getting initialized to the default English text before the locale is set from the
local operating system environment. While hw is getting set after the locale is changed thus producing the Spanish text.
cat >hellostaticgt.cxx <<EOF
// hellostaticgt.cxx
#include <libintl.h>
#include <locale.h>
#include <iostream>
char* hws = gettext("hello, world static!");
int main (){
setlocale(LC_ALL, "");
bindtextdomain("hellostaticgt", ".");
textdomain( "hellostaticgt");
char* hw = gettext("hello, world!");
std::cout << hws << std::endl;
std::cout << hw << std::endl;
}
EOF
g++ -o hellostaticgt hellostaticgt.cxx
xgettext --package-name hellostaticgt --package-version 1.0 --default-domain hellostaticgt --output hellostaticgt.pot hellostaticgt.cxx
msginit --no-translator --locale es_MX --output-file hellostaticgt_spanish.po --input hellostaticgt.pot
sed --in-place hellostaticgt_spanish.po --expression='/#: /,$ s/""/"hola mundo"/'
mkdir --parents ./es_MX.utf8/LC_MESSAGES
msgfmt --check --verbose --output-file ./es_MX.utf8/LC_MESSAGES/hellostaticgt.mo hellostaticgt_spanish.po
LANGUAGE=es_MX.utf8 ./hellostaticgt
| You need to split gettext usage into two parts. First, you just mark the string with a macro, such as gettext_noop, so that xgettext will extract it. Then, when you refer to the the global variable, you wrap the access with the true gettext call.
See Special Cases in the gettext manual.
N.B. Your variable hws is not a static variable (no "static keyword"); it is a global variable.
|
1,114,860 | 1,114,897 | Which is the best C++ compiler? | Can a C++ compiler produce a not so good binary? You can think here of the output's robustness and performance. Is there such a thing as the "best" C++ compiler to use? If not, what are the strong points, and of course, the not-so-strong (known Bugs and Issues) points, of the well-known compilers (g++, Intel C++ Compiler, Visual C++, etc.).
Are there documented cases when a compiler produced incorrect output which resulted in a failure of mission-critical software?
| G++ seems to be the most popular. It's free, portable and quite good. The Windows port (MinGW) was really dated the last time I used it (maybe one year ago).
The Intel C++ compiler is considered as the one which generates the fastest code (however it's known that it generates bad SIMD code for AMD processors).
You can use it freely on GNU/Linux under quite restrictive conditions.
I've used it for some time and I liked the fact that it emits clever warnings which others don't.
VC++ is often regarded as the best C++ IDE, and from what I hear the compiler is quite good too. It's free (as in free beer), and only available on Windows of course.
If you are interested in Windows programming I would suggest this compiler, because it's always up-to-date and provides more advanced features for this purpose.
I would suggest VC++ on Windows, G++ for other OSes. Try the free version of I++ yourself, to see if it's worth the money.
Are there documented cases when a compiler produced incorrect output which resulted in a failure of mission-critical software?
Yes, probably, but I'd say that most of the time it's probably the programmer's fault. For example, if someone doesn't know how floating-point arithmetic works, it's easy to write unreliable code. A good programmer must also know what is guaranteed to work by the C++ standard and what isn't. The programmer should also know what are the limits of the compiler, e.g. how well it implements the standard and how aggressively it optimizes.
|
1,114,914 | 1,114,922 | Add Library to Visual Studio 2008 C++ Project | I'm completely new to Visual Studio and I'm having some trouble getting a project started with Visual Studio 2008. I'm experimenting with MAPI, and I'm getting error messages like this when I go to build the project:
"unresolved external symbol _MAPIUninitialize@0 referenced in function _main"
I know I need to link to MAPI32.lib, but the guides I have found thus far have indicated going to the "Visual Studio settings link tab" and adding it there (which was - apparently - from an older version of Visual Studio). I can't find anything like that in the project properties linker or C/C++ sections of VS 2008.
Where do I need to tell Visual Studio to use that library?
Thanks
| It's under Project Properties / Configuration Properties / Linker / Input / Additional Dependencies.
The help tip at the bottom of the screen says "Specifies additional items add to the line line (ex: kernel32.lib)".
|
1,114,969 | 1,114,982 | Boost::regex issue, Matching an HTML span element | I don't get it. I created this regular expression:
<span class="copy[Green|Red].*>[\s]*(.*)[\s]*<\/span>
to match certain parts of HTML code (a part between spans). For instance the following:
<span class="copyGreen">0.12</span>
<span class="copyRed"> 0.12 </span>
Now, this works beautifully with RegexBuddy and others, but with Boost::regex
I have an issue. It doesn't match up.
EDIT: To be more precise, I want to capture the number between the spans. Before and after
the number, there can be white spaces as well (\n, \r, etc.).
Here's the code I've been done:
try {
const boost::regex e("<span class=\"copy[Green|Red].*>[\\s]*(.*)[\\s]*<\\/span>");
boost::smatch matches;
std::string html("<span class=\"copyGreen\"> 0.12 </span>");
if (boost::regex_match(html, matches, e)) {
// Works... (not).
} else {
throw std::runtime_error("Couldn't match the regex against HTML-source!");
}
} catch (boost::regex_error& e) {
std::cout << e.what() << std::endl;
}
What am I doing wrong here? Thanks in advance!
EDIT:
It seems, that the correct expression would be
boost::regex("<span class=\"copy(?:Green|Red)[^>]*>\\s*(.*?)\\s*<\\/span>"); // Thanks chaos!.
This actually matches up with Boost. However, I needed to enable boost::match_extra
in order to get all the captures I needed. This was done by defining
BOOST_REGEX_MATCH_EXTRA
in boost\regex\user.hpp
Thank you once again.
| For one thing, this:
[Green|Red]
doesn't do what you think it does. You want:
(?:Green|Red)
[Green|Red] is a character class made up of the letters GRred|, not a way of alternating between matches. The way you've written it, it will match exactly one of those characters followed by any number of other characters.
This:
[\s]
is redundant and maybe hazardous (depending on interpretation it could be what's actually making your match not work). It can be just
\s
In order for your second \s to work, the capturing expression probably needs to be
(.*?)
I also recommend making your first .* into [^>]*, to avoid the problem you'll get if you ever apply this to actual HTML documents, where it will suck in arbitrary amounts of HTML.
|
1,114,991 | 1,115,199 | Lua bindings to C++ and garbage collection | Ok, here's a problem I'm having.
I have Lua bindings to a rendering engine that has an internal render manager that keeps its own track of pointers for the render scene and manages them. The problem is that when I'm using it from Lua, if i don't keep a Lua reference to every single object i add to the C++ render manager, it starts to garbage collect the pointers and of course cause things to crash. I don't particularly want to have to save every single reference to every single thing i create. Is there a way to force Lua to not garbage collect certain things? Are there any other ways I can get around this problem?
I'm generating the Lua bindings with SWIG.
| A simple way to prevent Lua from garbage collecting an object is to put that object into a table (call it uncollectable) and then to put that table into the Lua registry.
Your other option is to use an extra level of indirection with every Lua object, i.e., use "light userdata". The light userdata points to a pointer to the C++ object, and even if the light userdata is collected, the underlying object remains unscathed.
These explanations are pretty terse, but I hope with the help of Programming in Lua, you can turn one into working code.
|
1,115,356 | 1,115,415 | Efficiency of c++ built ins | I am fairly new to C++, having much more C experience.
I am writing a program that will use the string class, and began to wonder about the efficiency of the "length()" method.
I realized though that I didn't have a good answer to this question, and so was wondering if the answer to this and similar questions exist somewhere. While I am more than capable of determining the runtime of my own code, I'm at a bit of a loss when it comes to provided code, and so I find I can't accurately judge the efficiency of my programs.
Is there c++ documentation (online, or in "man" format) that includes information on the runtime of provided code?
Edit: I'm interested in this in general, not just string::length.
| At present, time complexity of size() for all STL containers is underspecified. There's an open C++ defect report for that.
The present ISO C++ standard says that STL containers should have size() of constant complexity:
21.3[lib.basic.string]/2
The class template basic_string conforms to the requirements of a Sequence, as specified in (23.1.1). Additionally, because the iterators supported by basic_string are random access iterators (24.1.5), basic_string conforms to the the requirements of a Reversible Container, as specified in (23.1).
23.1[lib.container.requirements]/5
Expression: a.size()
Complexity: (Note A)
Those entries marked ‘‘(Note A)’’ should have constant complexity
However, "should" is not a binding requirement in the Standard parlance; indeed, the above applies to std::list as well, but in practice some implementations (notably g++) have O(N) std::list::size().
The only thing that can be guaranteed is that (end() - begin()) for a string is (possibly amortized) O(1). This is because string iterators are guaranteed to be random-access, and random-access iterators are guaranteed to have constant time operator-.
As a more practical issue, for all existing C++ implementations out there, the following holds:
std::string::size() is O(1)
std::vector::size() is O(1)
They are fairly obvious, as both strings and vectors are most efficiently implemented as contiguous arrays with separately stored size: contiguous because it gives fastest element access while satisfying all other complexity requirements, and storing size is because Container requirements demand that end() be constant-time.
|
1,115,428 | 1,116,078 | Run an Application in GDB Until an Exception Occurs | I'm working on a multithreaded application, and I want to debug it using GDB.
Problem is, one of my threads keeps dying with the message:
pure virtual method called
terminate called without an active exception
Abort
I know the cause of that message, but I have no idea where in my thread it occurs. A backtrace would really be helpful.
When I run my app in GDB, it pauses every time a thread is suspended or resumed. I want my app to continue running normally until one of the threads dies with that exception, at which point everything should halt so that I can get a backtrace.
| You can try using a "catchpoint" (catch throw) to stop the debugger at the point where the exception is generated.
The following excerpt From the gdb manual describes the catchpoint feature.
5.1.3 Setting catchpoints
You can use catchpoints to cause the debugger to stop for certain kinds of program events, such as C++ exceptions or the loading of a shared library. Use the catch command to set a catchpoint.
catch event
Stop when event occurs. event can be any of the following:
throw
The throwing of a C++ exception.
catch
The catching of a C++ exception.
exec
A call to exec. This is currently only available for HP-UX.
fork
A call to fork. This is currently only available for HP-UX.
vfork
A call to vfork. This is currently only available for HP-UX.
load or load libname
The dynamic loading of any shared library, or the loading of the library libname. This is currently only available for HP-UX.
unload or unload libname
The unloading of any dynamically loaded shared library, or the unloading of the library libname. This is currently only available for HP-UX.
tcatch event
Set a catchpoint that is enabled only for one stop. The catchpoint is automatically deleted after the first time the event is caught.
Use the info break command to list the current catchpoints.
There are currently some limitations to C++ exception handling (catch throw and catch catch) in GDB:
If you call a function interactively, GDB normally returns control to you when the function has finished executing. If the call raises an exception, however, the call may bypass the mechanism that returns control to you and cause your program either to abort or to simply continue running until it hits a breakpoint, catches a signal that GDB is listening for, or exits. This is the case even if you set a catchpoint for the exception; catchpoints on exceptions are disabled within interactive calls.
You cannot raise an exception interactively.
You cannot install an exception handler interactively.
Sometimes catch is not the best way to debug exception handling: if you need to know exactly where an exception is raised, it is better to stop before the exception handler is called, since that way you can see the stack before any unwinding takes place. If you set a breakpoint in an exception handler instead, it may not be easy to find out where the exception was raised.
To stop just before an exception handler is called, you need some knowledge of the implementation. In the case of GNU C++, exceptions are raised by calling a library function named __raise_exception which has the following ANSI C interface:
/* addr is where the exception identifier is stored.
id is the exception identifier. */
void __raise_exception (void **addr, void *id);
To make the debugger catch all exceptions before any stack unwinding takes place, set a breakpoint on __raise_exception (see section Breakpoints; watchpoints; and exceptions).
With a conditional breakpoint (see section Break conditions) that depends on the value of id, you can stop your program when a specific exception is raised. You can use multiple conditional breakpoints to stop your program when any of a number of exceptions are raised.
|
1,115,464 | 1,115,484 | MSVC: union vs. class/struct with inline friend operators | This piece of code compiles and runs as expected on GCC 3.x and 4.x:
#include <stdio.h>
typedef union buggedUnion
{
public:
// 4 var init constructor
inline buggedUnion(int _i) {
i = _i;
}
friend inline const buggedUnion operator - (int A, const buggedUnion &B) {
return buggedUnion(A - B.i);
}
friend inline const buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) {
return buggedUnion(A.i - B.i);
}
int i;
} buggedUnion;
int main()
{
buggedUnion first(10);
buggedUnion second(5);
buggedUnion result = 10 - (first - second);
printf("%d\n", result.i); // 0
return 0;
}
MSVC, however, will not compile that code, complaining:
main.cpp(60) : error C3767: '-': candidate function(s) not accessible
could be the friend function at 'main.cpp(41)' : '-' [may be found via argument-dependent lookup]
or the friend function at 'main.cpp(45)' : '-' [may be found via argument-dependent lookup]
main.cpp(60) : error C2676: binary '-' : 'buggedUnion' does not define this operator or a conversion to a type acceptable to the predefined operator
Which of the compilers is correct? How can this be resolved? I'm trying to achieve clean code (no outside friend methods) while maintaining portability, flexibility and self-documenting code.
Some notes:
This is a test-case to show the problem, the original data-type is much more sophisticated and carefully designed, albeit not working in MSVC (main compiler is GCC, though MSVC compatibility is also desired).
Adding 'public:' at the start of the union declaration does not resolve it.
Adding 'public:' before each operator does not resolve it
Converting the test case to a struct/class does fix it, but this is not desired (Please no flames, I got reasons. Most of them are limitations of the C++ language)
Operator method is to be left at global scope (not a member function)
Optimal solution would not rely on moving the declaration outside of the union definition for aestetic reasons (over 24 different combinations of operators and operands), but will be done if there is no other solution.
| It is difficult to say which one is right, since unnamed structs are not allowed by the standard (although they are a common extension), and as such the program is ill-formed.
Edit: It does seem to be a bug in msvc, since the following code, which is perfectly valid, fails to compile.
union buggedUnion
{
friend buggedUnion operator - (int A, const buggedUnion &B) {
return B;
}
friend buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) {
return A;
}
int i;
};
int main()
{
buggedUnion first = { 1 };
buggedUnion second = { 1 };
buggedUnion result = 3 - (first - second);
}
You can work around this by defining the functions outside the class.
union buggedUnion
{
int i;
};
buggedUnion operator - (int A, const buggedUnion &B) {
return B;
}
buggedUnion operator - (const buggedUnion &A, const buggedUnion &B) {
return A;
}
You can even retain the friend status by declaring the functions inside the class (but still defining them outside), but I doubt you'd ever need that in a union.
Note that I removed the unnecessary typedef and inlines.
|
1,115,474 | 1,115,927 | C++: TR1 vs GSL vs Boost for statistical distributions? | in my previous post I was asking how to generate numbers following a normal distribution.
Since I have also other distributions to generate and I saw 3 libraries might provide them (GSL, TechnicalReport1(doc link?), Boost), I was wondering which one you would choose.
As a side note: the reference platform for my application is a GNU/Linux system and performance is a matter.
| Here are some notes on getting started with random number generation using C++ TR1.
|
1,115,511 | 1,115,533 | Set IP_HDRINCL to setsockopt function in win32 | I'm fighting with raw sockets in Win32 and now I'm stuck, the soetsockopt function give me the 10022 error (invalid argument), but I think I pass the correct arguments... of course I'm wrong u_u'
sock = socket(AF_INET,SOCK_RAW,IPPROTO_UDP);
if (sock == SOCKET_ERROR)
{
printf("Error socket(): %d", WSAGetLastError());
return;
}
char on = 1;
error = setsockopt(sock,IPPROTO_IP,IP_HDRINCL,&on,sizeof(on));
if (sock == SOCKET_ERROR)
{
printf("Error setsockopt(): %d", WSAGetLastError());
return;
}
Anybody knows what happen to my code?
| As far as I remember you need to use int on = 1 instead of char...
|
1,115,633 | 1,115,649 | Should I use std:: and boost:: prefixes everywhere? | In my C++ code I don't use the declarations using namespace std; or using namespace boost;. This makes my code longer and means more typing. I was thinking about starting to use the "using" declarations, but I remember some people arguing against that. What is the recommended practice? std and boost are so common there should be no much harm in that?
| I use using namespace only in C++ files, not in headers. Besides, using hole namespace not needed in most of times. For instance, you could write using boost::shared_ptr or using std::tr1::shared_ptr to easily switch between shared_ptr implementations.
Sample:
#include <iostream>
using std::cout;
int main()
{
cout << "test" << std::endl;
return 0;
}
|
1,115,876 | 14,764,809 | Autocompletion in Vim | In a nutshell, I'm searching for a working autocompletion feature for the Vim editor. I've argued before that Vim completely replaces an IDE under Linux and while that's certainly true, it lacks one important feature: autocompletion.
I know about Ctrl+N, Exuberant Ctags integration, Taglist, cppcomplete and OmniCppComplete. Alas, none of these fits my description of “working autocompletion:”
Ctrl+N works nicely (only) if you've forgotton how to spell class, or while. Oh well.
Ctags gives you the rudiments but has a lot of drawbacks.
Taglist is just a Ctags wrapper and as such, inherits most of its drawbacks (although it works well for listing declarations).
cppcomplete simply doesn't work as promised, and I can't figure out what I did wrong, or if it's “working” correctly and the limitations are by design.
OmniCppComplete seems to have the same problems as cppcomplete, i.e. auto-completion doesn't work properly. Additionally, the tags file once again needs to be updated manually.
I'm aware of the fact that not even modern, full-blown IDEs offer good C++ code completion. That's why I've accepted Vim's lack in this area until now. But I think a fundamental level of code completion isn't too much to ask, and is in fact required for productive usage. So I'm searching for something that can accomplish at least the following things.
Syntax awareness. cppcomplete promises (but doesn't deliver for me), correct, scope-aware auto-completion of the following:
variableName.abc
variableName->abc
typeName::abc
And really, anything else is completely useless.
Configurability. I need to specify (easily) where the source files are, and hence where the script gets its auto-completion information from. In fact, I've got a Makefile in my directory which specifies the required include paths. Eclipse can interpret the information found therein, why not a Vim script as well?
Up-to-dateness. As soon as I change something in my file, I want the auto-completion to reflect this. I do not want to manually trigger ctags (or something comparable). Also, changes should be incremental, i.e. when I've changed just one file it's completely unacceptable for ctags to re-parse the whole directory tree (which may be huge).
Did I forget anything? Feel free to update.
I'm comfortable with quite a lot of configuration and/or tinkering but I don't want to program a solution from scratch, and I'm not good at debugging Vim scripts.
A final note, I'd really like something similar for Java and C# but I guess that's too much to hope for: ctags only parses code files and both Java and C# have huge, precompiled frameworks that would need to be indexed. Unfortunately, developing .NET without an IDE is even more of a PITA than C++.
| Try YouCompleteMe. It uses Clang through the libclang interface, offering semantic C/C++/Objective-C completion. It's much like clang_complete, but substantially faster and with fuzzy-matching.
In addition to the above, YCM also provides semantic completion for C#, Python, Go, TypeScript etc. It also provides non-semantic, identifier-based completion for languages for which it doesn't have semantic support.
|
1,115,891 | 1,115,895 | Covariant virtual functions and smart pointers | In C++, a subclass can specify a different return type when overriding a virtual function, as long as the return type is a subclass of the original return type (And both are returned as pointers/references).
Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template class)
To illustrate:
class retBase {...};
class retSub : public retBase {...};
class Base
{
virtual retBase *f();
};
class Sub : public Base
{
virtual retSub *f(); // This is ok.
};
class smartBase
{
virtual smartPtr<retBase> f();
};
class smartSub : public smartBase
{
virtual smartPtr<retSub> f(); // Can this be somehow acheived?
};
EDIT: As Konrad Rudolph suggested, this is not directly possible. However, I ran accross this method:
class smartBase
{
protected:
virtual retBase *f_impl();
public:
smartPtr<refBase> f()
{
return f_impl();
}
};
class smartSub : public smartBase
{
protected:
virtual retSub *f_impl();
public:
smartPtr<refSub> f()
{
return f_impl();
}
};
Would you suggest going this way?
|
Is it possible to expand this feature to smart pointers as well? (Assuming a smart pointer is some template class)
No: C++ doesn't know/allow covariant or contravariant templates. There's no relation between types Ptr<A> and Ptr<B>, even if A inherits from B.
|
1,116,018 | 1,116,035 | Is assert and unit-testing incompatible? | I have some concerns related to the fact of testing some functions containing the assert macro from assert.h.
If the assert fails the test fails also.
This leaves me with some test cases that will never work.
For example a function instead of indicating failure (return false or something similar) asserts.
Is there a solution for this (unit-testing functions containing assert)?
| No, unit testing is what you do during development. Asserts are a run-time construct.
In my experience, most of the time asserts are turned off in production. But you should always be testing.
CppUnit is a fine test framework. It's part of the nUnit family for C++.
|
1,116,040 | 1,116,055 | Memory-efficient C++ strings (interning, ropes, copy-on-write, etc) | My application is having memory problems, including copying lots of strings about, using the same strings as keys in lots of hashtables, etc. I'm looking for a base class for my strings that makes this very efficient.
I'm hoping for:
String interning (multiple strings of the same value use the same memory),
copy-on-write (I think this comes for free in nearly all std::string implementations),
something with ropes would be a bonus (for O(1)-ish concatenation).
My platform is g++ on Linux (but that is unlikely to matter).
Do you know of such a library?
| If most of your strings are immutable, the Boost Flyweight library might suit your needs.
It will do the string interning, but I don't believe it does copy-on-write.
|
1,116,187 | 1,116,427 | Just adding some documentation triggers recompilation: Is there a solution? | Sometimes, when I look through my header files I'd like to add something little to the (doxygen) documentation. That might be a quick note about the use of some function parameter, or just fixing a little typo.
But then I think: Oh no, that'll trigger a recompile on the next make call! And for certain basic headers the whole project would recompile, which can take a long time. So, nevermind!
Is there a solution to this dilemma? Are there approaches where the functions/classes are documented not directly in the headers? Or are there (plans for) a smart make that would notice that only some comment has changed, but no recompilation is necessary?
| How about checking out (you do version control, don't you?) another copy of the codebase in a different directory, just for these kinds of edits?
It can be a separate branch, or not. Then, when these kinds of small changes occur to you, you just make them here. You can commit them directly: now they are in a safe place, and won't disturb your actual development. Every once in a while, like once a week if your build times really are that long, you can merge these changes to what you are working on. Merge conflicts should rarely occur, as long as you document in one directory and write code in the other.
|
1,116,213 | 1,116,259 | Profiling instructions | I want to count several cpu instructions in my code. e.g. I would like to know how many additions, how many multiplications, how many float operations, how many branches my code executes. I currently use gprof under Linux for profiling my c++ code but it only gives the number of calls to my functions, and I manually estimate the number of instructions. Are there any tools that might do the trick for me? Maybe some virtual machine?
| You may be able to use Valgrind's Callgrind with the --dump-instr=yes flag to achieve this
|
1,116,225 | 1,117,132 | Refusing connection from a host | I'm writing a simple tcp server application using sockets. As far as I know I can obtain the client's ip address and port after calling accept().
Now lets assume I have a banlist and I want to ban some ip addresses from my server. Is there a better way than accepting the connection and then dropping it?
Is there a way to get the client's ip and port before accepting the connection? If we have accept() why don't we have something like refuse()? Is there a way to refuse the connection or simply ignore connection attempt from a host?
| The TCP implementation normally completes the TCP 3-way handshake before the user process even has access to the connection, and the accept() function merely gets the next connection off the queue. So it is too late to pretend that the server is down. This works the same way for regular TCP data; the TCP implementation does not wait for the application to actually recv() the data before a TCP ACK is sent. This keeps the other side from needlessly retransmitting packets that were received correctly, and allows the throughput to remain high, even when the application is bogged down with other things. In the case of new connections (SYN packets), this also allows the kernel to protect itself (and the application) from SYN flood attacks.
Although not portable, many platforms provide some sort of firewall capability that will allow filtering incoming connections based on IP address/port. However that is usually configured system-wide and not by an individual application.
|
1,116,503 | 1,116,583 | High-quality libraries for C++ | We all know about Boost.
What other free C++ libraries are worth using? Why? Are they easily usable with common compilers?
| See: What modern C++ libraries should be in my toolbox?
|
1,116,569 | 1,213,720 | desktopdock or stardock in Qt | Is there any opensource/sample application in qt/c++, just like desktopdock or objectdock..?
| XQDE is an OSX-style dock written in Qt.
|
1,116,602 | 1,116,646 | Where can I see the list of functions that interact with errno? | In the book "The C Programming Language" it says:
"Many of the functions in the library set status indicators when error or end of file occur. These
indicators may be set and tested explicitly. In addition, the integer expression errno (declared
in <errno.h>) may contain an error number that gives further information about the most
recent error."
Where can I see a list of these functions?
| The standard says this about errno:
The value of errno is zero at program startup, but is never set to zero by any library
function. The value of errno may be set to nonzero by a library function call whether or not there is an error, provided the use of errno is not documented in the description of the function in this International Standard.
Which says to me that any library function can screw around with errno in any way it likes except:
it can't set errno to 0
it can't do what it likes if the standard explicitly says otherwise
Note that the standard suggests the following in a footnote:
Thus, a program that uses errno for error checking should set it to zero before a library function call, then inspect it before a subsequent library function call. Of course, a library function can save the value of errno on entry and then set it to zero, as long as the original value is restored if errno's value is still zero just before the return.
As noted in other answers, it's common for functions that are not in the standard to set errno as well.
|
1,116,641 | 1,116,763 | Is returning by rvalue reference more efficient? | for example:
Beta_ab&&
Beta::toAB() const {
return move(Beta_ab(1, 1));
}
| Beta_ab&&
Beta::toAB() const {
return move(Beta_ab(1, 1));
}
This returns a dangling reference, just like with the lvalue reference case. After the function returns, the temporary object will get destructed. You should return Beta_ab by value, like the following
Beta_ab
Beta::toAB() const {
return Beta_ab(1, 1);
}
Now, it's properly moving a temporary Beta_ab object into the return value of the function. If the compiler can, it will avoid the move altogether, by using RVO (return value optimization). Now, you can do the following
Beta_ab ab = others.toAB();
And it will move construct the temporary into ab, or do RVO to omit doing a move or copy altogether. I recommend you to read BoostCon09 Rvalue References 101 which explains the matter, and how (N)RVO happens to interact with this.
Your case of returning an rvalue reference would be a good idea in other occasions. Imagine you have a getAB() function which you often invoke on a temporary. It's not optimal to make it return a const lvalue reference for rvalue temporaries. You may implement it like this
struct Beta {
Beta_ab ab;
Beta_ab const& getAB() const& { return ab; }
Beta_ab && getAB() && { return move(ab); }
};
Note that move in this case is not optional, because ab is neither a local automatic nor a temporary rvalue. Now, the ref-qualifier && says that the second function is invoked on rvalue temporaries, making the following move, instead of copy
Beta_ab ab = Beta().getAB();
|
1,116,654 | 1,116,656 | Function template with an operator | In C++, can you have a templated operator on a class? Like so:
class MyClass {
public:
template<class T>
T operator()() { /* return some T */ };
}
This actually seems to compile just fine, but the confusion comes in how one would use it:
MyClass c;
int i = c<int>(); // This doesn't work
int i = (int)c(); // Neither does this*
The fact that it compiles at all suggests to me that it's doable, I'm just at a loss for how to use it! Any suggestions, or is this method of use a non-starter?
| You need to specify T.
int i = c.operator()<int>();
Unfortunately, you can't use the function call syntax directly in this case.
Edit: Oh, and you're missing public: at the beginning of the class definition.
|
1,116,721 | 1,116,816 | COM: how to get more details about COM errors? | Greets,
When working with DirectX, you get this nice header to #include called DxErr9.h which has really helpful functions like:
DXGetErrorString9
and
DXGetErrorDescription9
They tell you everything you need to know about the error given the HR.
But now working with COM and OLE, I find I'm kind of on my own with the HRESULTS that come back from COM functions. Is it really just me and MSDN at this point, or are there similar helper functions in OLE DB that I just haven't come across yet?
| Additionally, you should look at the error info. Part of the COM system is the concept of the error information, which is a per-thread global which can be set and cleared at various times. You query for it in response to an error, and if it is set, it will have more useful information than just looking at the HRESULT.
HRESULT hr=something();
if (FAILED(hr))
{
CComPtr<IErrorInfo> err;
::GetErrorInfo(0, &err);
if (err)
{
CComBSTR description;
err->GetDescription(&description);
// description will be a more descriptive error message than just formatting the
// HRESULT because it is set by the COM server code at the point of the error
}
}
|
1,116,735 | 1,116,843 | i++ less efficient than ++i, how to show this? | I am trying to show by example that the prefix increment is more efficient than the postfix increment.
In theory this makes sense: i++ needs to be able to return the unincremented original value and therefore store it, whereas ++i can return the incremented value without storing the previous value.
But is there a good example to show this in practice?
I tried the following code:
int array[100];
int main()
{
for(int i = 0; i < sizeof(array)/sizeof(*array); i++)
array[i] = 1;
}
I compiled it using gcc 4.4.0 like this:
gcc -Wa,-adhls -O0 myfile.cpp
I did this again, with the postfix increment changed to a prefix increment:
for(int i = 0; i < sizeof(array)/sizeof(*array); ++i)
The result is identical assembly code in both cases.
This was somewhat unexpected. It seemed like that by turning off optimizations (with -O0) I should see a difference to show the concept. What am I missing? Is there a better example to show this?
| In the general case, the post increment will result in a copy where a pre-increment will not. Of course this will be optimized away in a large number of cases and in the cases where it isn't the copy operation will be negligible (ie., for built in types).
Here's a small example that show the potential inefficiency of post-increment.
#include <stdio.h>
class foo
{
public:
int x;
foo() : x(0) {
printf( "construct foo()\n");
};
foo( foo const& other) {
printf( "copy foo()\n");
x = other.x;
};
foo& operator=( foo const& rhs) {
printf( "assign foo()\n");
x = rhs.x;
return *this;
};
foo& operator++() {
printf( "preincrement foo\n");
++x;
return *this;
};
foo operator++( int) {
printf( "postincrement foo\n");
foo temp( *this);
++x;
return temp;
};
};
int main()
{
foo bar;
printf( "\n" "preinc example: \n");
++bar;
printf( "\n" "postinc example: \n");
bar++;
}
The results from an optimized build (which actually removes a second copy operation in the post-increment case due to RVO):
construct foo()
preinc example:
preincrement foo
postinc example:
postincrement foo
copy foo()
In general, if you don't need the semantics of the post-increment, why take the chance that an unnecessary copy will occur?
Of course, it's good to keep in mind that a custom operator++() - either the pre or post variant - is free to return whatever it wants (or even do whatever it wants), and I'd imagine that there are quite a few that don't follow the usual rules. Occasionally I've come across implementations that return "void", which makes the usual semantic difference go away.
|
1,116,779 | 1,116,792 | using header files from another project (directory) | I am using Visual Studio 2008, and I need to use certain header files from another project. I have tried to add the path in "Additional Include Directories" in C/C++ General properties pane, but my project still puts out the same errors
(fatal error C1083: Cannot open include file: 'tools/rcobject.h'.
All the other cpp and header files I am using I added as existing files from another directory, and for some headers it puts out an error and for others it doesn't. There was no change in errors after adding additional include directories.
Can someone help me, I am stuck as I need to Debug...
| In the "Additional Include "Directories", did you put the path to the "tools" directory, or the path to the directory that includes the "tools" directory? It needs to be the latter.
How the preprocessor works to resolve #include directives, is to take the path specified in the #include and then append it to each of the paths specified in the "Additional Include Directories" (and some other places specific for the project). So, you need to make sure that the path specified in the "Additional Include Directories" plus the path you gave to the #include exactly matches the path to the file you are trying to include.
For example, suppose you have the following file you want to include:
c:\blah\bletch\foo\bar.txt
Then you did this:
#include "bar.txt"
Then you would need to make sure that "c:\blah\bletch\foo" was in the "Additional Include Directories".
Or if you had done this:
#include "foo\bar.txt"
Then you would need to make sure that "c:\blah\bletch" was in the "Additional Include Directories".
|
1,117,101 | 1,208,159 | <list> throws unhandled exception when calling push_front() | I'm working on a GUI in SDL. I've created a slave/master class that contains a std::list of pointers to it's own slaves to create a heirarchy in the GUI (window containing buttons. Button a label and so on). It worked fine for a good while, until I edited a completely different class that doesn't effect the slave/master class directly. The call to the list.push_front() in the old slave/master class now throws the following error when debugging in VS C++ 2008 express and I can't find what's causing it.
"Unhandled exception at 0x00b6decd in
workbench.exe: 0xC0000005: Access
violation reading location
0x00000004."
*workbench.exe is my project.
The exception is raised in the _Insert method in the list code on row 718:
_Nodeptr _Newnode = _Buynode(_Pnode, _Prevnode(_Pnode), _Val);
The list is created in the master/slave class' definition and the slave/master class is created on the heap to be inserted in another master's slave list. The list that crashes is empty when push_front() is called but it is second in line in the heirarchy, so it worked once. As I said, it worked fine before and the slave/master class hasn't been altered to cause the error.
The new class does use lists aswell. Can the use of several lists cause clashes? May I have accidentally screwed up the heap?
Any help and tips to what I could look for is appreciated.
P.S The code is rather large now so I would guess it's better to not include it. Especially since I'm not exactly sure just what causes the error. Sorry if it's a bit scarce
Update: I've replaced the push_front() with creating an iterator and using insert(). The result was an iterator pointing to "baadf00d" after assigning the list.begin(). baadf00d is some error/NULL pointer that VS uses to objects that haven't been assigned anything, as far as I can tell. I guess it's another sign that the list is corrupt?
| Finally after looking through every nook and cranny I've found the bug! It was completely unexpected and I feel a bit embarrassed about it.
I had recently re-arranged the files. Prior to that I had generic classes in one folder and my user interface files in a subfolder. I copied the GUI files to the main folder and I thought I linked everything up correctly, but obviously I missed one line and it never occurred to me when it started acting up. My library compiled since that was linked fine, but my testing program wasn't... it simply looked at the old header files! Worked fine to begin with ofcourse since the headers were the same, but then I edited one and the class declared in it started acting funny as mentioned, obviously, since it couldn't recognize the damn thing anymore. It looked like corrupted memory, so that's what I looked for.
Lesson learned: Don't keep two versions close to each other or at all.
|
1,117,230 | 1,117,476 | Best aproach to java like adapters event-handling in C++ | I'm doing some research in how to implement a event-handling scheme in C++ that can be easyest as its to implements an adpter to a class in java. The problem is that with the approach shown below, I will need to have all adapters already implemented with its function overriding in the devived class (because the linker needs it). On the other side, using a delegate strategy where I can use the adapter just in the derived class should imply in less performance considering the way it need to be implemented.
wich one, or what on else should be the best approach to it?
class KeyboardAdapter
{
public:
virtual void onKeyDown(int key) = 0;
}
class Controller : public KeyApadter
{
private:
void onKeyDown(int key);
}
void Controller::onKeyDown(int key) {}
class UserController : public Controller {
private:
void onKeyDown(int key);
}
void UserController::onKeyDown(int key) {
// do stuff
}
int main() {
UserController * uc = new UserController();
Controller * c = uc;
c->_onKeyDown(27);
}
| Take a look at Boost.Signals library for an example of how you can implement event handling without classes with virtual functions (http://www.boost.org/doc/libs/1_39_0/doc/html/signals.html).
|
1,117,284 | 1,117,297 | C++ file parse number of arguments | I got a pack of c++ files with static source code (already developped, not needed to do anything to them).
There is an program/lib/way to get a list of the number of params each function withing one of those files?
I mean, getting a result like:
#File a.cpp
##a() -> 3 paramss
##foo() -> 0 params (void)
#File b.cpp
##test() -> 1 param
....
And a better question.
There is any way to also process the number of returns it has?
#File a.cpp
##a() -> 3 params, 1 return
##foo() -> 0 params (void), 2 returns
For example if "foo" has a return if condition is true and another if false
Thanks in advance.
| You could try running Doxygen over the source files.
Since the content is (presumably) undocumented, you need to configure doxygen to extract content from undocumented files.
If you just want to browse a list of the available functions, you could use the HTML output.
You could also configure Doxygen output to be XML, and then write a parser to pull statistics that you are looking for on each function.
|
1,117,292 | 1,117,299 | What's the Right Way to use the rand() Function in C++? | I'm doing a book exercise that says to write a program that generates psuedorandom numbers. I started off simple with.
#include "std_lib_facilities.h"
int randint()
{
int random = 0;
random = rand();
return random;
}
int main()
{
char input = 0;
cout << "Press any character and enter to generate a random number." << endl;
while (cin >> input)
cout << randint() << endl;
keep_window_open();
}
I noticed that each time the program was run, there would be the same "random" output. So I looked into random number generators and decided to try seeding by including this first in randint().
srand(5355);
Which just generated the same number over and over (I feel stupid now for implementing it.)
So I thought I'd be clever and implement the seed like this.
srand(rand());
This basically just did the same as the program did in the first place but outputted a different set of numbers (which makes sense since the first number generated by rand() is always 41.)
The only thing I could think of to make this more random is to:
Have the user input a number and set that as the seed (which would be easy to implement, but this is a last resort)
OR
Somehow have the seed be set to the computer clock or some other constantly changing number.
Am I in over my head and should I stop now? Is option 2 difficult to implement? Any other ideas?
Thanks in advance.
| Option 2 isn't difficult, here you go:
srand(time(NULL));
you'll need to include stdlib.h for srand() and time.h for time().
|
1,117,424 | 1,117,435 | Data structure similar to a 2-argument map | Is there a data structure (readily available in STL or boost), that accepts two arguments and maps it to a certain value?
Examples would be for returning certain information in a coordinate grid or getting the weight of an edge in a graph:
coordinate_quadrant(-1,-1) = 3
weight_of(u,v) = 10
The quadrant example could be done in a simple function with four if statements. I'm mainly looking for an example that would suit the weight example. I'm trying to avoid having to create an edge class and pass that into the weight_of(Edge edge) function.
| You could use std::map< std::pair<Type1,Type2>, Type3 >.
|
1,117,481 | 1,117,484 | Can the default destructor be generated as a virtual destructor automatically? | Can the default destructor be generated as a virtual destructor automatically?
If I define a base class but no default destructor, is there a default virtual destructor
generated automatically?
| No. There is a cost associated with making a method virtual, and C++ has a philosophy of not making you pay for things that you don't explicitly state that you want to use. If a virtual destructor would have been generated automatically, you would have been paying the price automatically.
Why not just define an empty virtual destructor?
|
1,117,486 | 1,121,418 | WinForm not receiving messages except right after creation | I've got some unmanaged code sitting in a DLL. It publishes some methods that my calling (managed) code uses to hook into some COM notifications. Rather than deal with unmanaged code calling back into managed code, I've created a hidden Control derived object and am passing its handle property which the unmanaged code then uses as a parameter to SendMessage.
My Control derived class:
class InteropWindow : Control
{
//delegate
private Handler m_callback;
//window message
private uint m_message;
public InteropWindow(Handler callback, uint message)
: base()
{
m_callback = callback;
m_message = message;
}
protected override void WndProc(ref Message m)
{
if (m.Msg == m_message)
{
m_callback(new IntPtr((int)m.WParam));
}
base.WndProc(ref m);
}
}
Relevant line in unmanaged code:
SendMessage(m_notify, m_window_message, (WPARAM)pData, 0);
m_window_message & m_message are the same (both from RegisterWindowMessage), and m_notify == InteropWindow.Handle (pData varies, but is used as an opaque handle in the managed code). The unmanaged code is being invoked. These facts have been confirmed via debugging.
Shortly after I create the InteropWindow, the calls to SendMessage succeed. Afterwards (seconds later) the messages stop getting to WndProc, though there is no indication of any error.
The question is, what am I doing wrong here?
I've ruled out lifecycle issues (to the best of knowledge anyway), and played with HandleRef to no avail.
Edit the second.
I've re-written this to use function calls instead, which while fraught with its own perils, works a bit more like I'd expect. I've come to suspect this is a COM threading issue, but that's just a gut feeling.
| Did you try passing your managed window's handle as a HandleRef? C# can marshal a HandleRef as an IntPtr and vice versa, I've seen Microsoft use that trick quite a bit when decompiling some of their stuff.
You can also load up a .Net profiler and watch the GC. It would be nice to know if your app is breaking right after a collect.
|
1,117,693 | 1,118,444 | Initializing template base-class member types in derived-class initializer lists | Here is some code outlining a problem I've been wrestling with. The final problem (as far as g++ is concerned at the moment) is that: "error: 'Foo-T' was not declared in this scope" when performing the Bar::Bar(...) constructor routine. Otherwise, the problem I'm attempting to learn my way through is one of setting base-class member types based on arguments passed to a derived-class constructor using templates. If there were a way to set the base-class member type (T Foo-T) simply by passing arguments to the derived-class constructor, I would prefer that. As of now I can't see a way past using both the template argument and a matching derived-class constructor argument to accomplish this task. Can you spot anything in the following code that I can be doing better to achieve the same goals? I'm rather new to generic-coding and templates.
#include <iostream>
typedef int a_arg_t;
typedef double b_arg_t;
typedef std::string foo_arg_t;
class TypeA {
public:
TypeA ();
TypeA (a_arg_t a) {
/* Do sosmething with the parameter passed in */
}
};
class TypeB {
public:
TypeB ();
TypeB (b_arg_t b) {
/* typeB's constructor - do something here */
}
};
// The base-class with a member-type to be determined by the template argument
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg) // initialize something here
{
/* do something for foo */
}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
// the derived class that should set the basse-member type (T Foo_T)
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
// the initialization of Foo_T has to be done outside the initializer list because it's not in scsope until here
Foo_T = TypeA(a_arg); // if an a_arg_t is passed in, then we set the Foo_T to TypeA, etc.
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo_T = TypeB(b_arg);
}
};
int main () {
b_arg_t b_arg;
a_arg_t a_arg;
foo_arg_t bar_arg;
Bar<TypeA> a (bar_arg, a_arg); // try creating the derived class using TypeA
Bar<TypeB> b (bar_arg, b_arg); // and another type for show
return 0;
}
| The Foo_T type will not be looked up in the base class when used in the derived (Bar) constructor.
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
Foo_T = TypeA(a_arg); TypeA, etc. // Won't compile, per the standard
}
This is per the C++ standard, which says unqualified names are generally non-dependent, and should be looked up when the template is fully defined.
Since a template base class definition is not known at that time (there could be fully specialised instances of the template being pulled in later in the compilation unit), unqualified names are never resolved to names in dependent base classes.
If you need a name from a base class when templates are involved, you have to either fully qualify them, or make them implicitly dependent in your derived class.
Foo< T >::Foo_T = TypeA(a_arg); // fully qualified will compile
or, make it dependent
this->Foo_T = TypeA(a_arg);
Since the this makes it template dependent, resolving the type is postponed till "phase 2" of template instantiation (and then, the base class is also fully known)
Note that if you wanted to use a function from the base class, you could have also added a using declaration..
(inside Bar())
some_foo_func(); // wouldn't work either
using Foo<T>::some_foo_func;
some_foo_func(); // would work however
|
1,117,755 | 1,117,767 | What is the difference between function template and template function? | What is the difference between function template and template function?
|
The term "function template" refers to a kind of template. The term "template function" is sometimes used to mean the same thing, and sometimes to mean a function instantiated from a function template. This ambiguity is best avoided by using "function template" for the former and something like "function template instance" or "instance of a function template" for the latter. Note that a function template is not a function. The same distinction applies to "class template" versus "template class".
From this FAQ (archive)
|
1,117,831 | 1,123,427 | Local System only ACL in Windows | I am using a named pipe for communications between two processes and want to restrict acess to any user on the local system in Windows.
I am building up and ACL for use in the SECURITY_ATTRIBUTES passed to CreateNamedPipe.
I am basing this code on that from Microsoft.
SID_IDENTIFIER_AUTHORITY siaLocal = SECURITY_LOCAL_SID_AUTHORITY;
if( !AllocateAndInitializeSid( &siaLocal, SECURITY_LOCAL_RID,
0, 0, 0, 0, 0, 0, 0, 0,
&pSidLocal ) )
{
break;
}
I then use that sid with AddAccessAllowedAce.
All of this completes successfully and I can create the named pipe however when a client process then tries to connect using CreateFile it fails with access denied.
How do I create an ACL with a SID that allows any user of the local machine to access it?
| I am afraid this is a cross between RTFM and c's complete lack of strict typing.
The second parameter for AllocateAndInitializeSid is actually a count of the sub authorities not the first sub authority.
So by changing the code to:
SID_IDENTIFIER_AUTHORITY siaLocal = SECURITY_LOCAL_SID_AUTHORITY;
if( !AllocateAndInitializeSid( &siaLocal, 1,
SECURITY_LOCAL_RID,
0, 0, 0, 0, 0, 0, 0,
&pSidLocal ) )
{
break;
}
I get the desired results.
I have tested this with different accounts and they can connect and by changing the Authority to SECURITY_NT_AUTHORITY and the sub authority to SECURITY_AUTHENTICATED_USER_RID I was able to connect from another computer to test that this ACL will actually allow and disallow different users.
|
1,117,873 | 1,118,283 | pointer to const vs usual pointer (for functions) | Is there any difference between pointer to const and usual pointer for functions? When it is suitable to use const qualifier for stand alone functions?
I wrote short sample to illustrate my question:
#include <iostream>
using namespace std;
int sum( int x, int y ) { return x + y; }
typedef int sum_func( int, int );
int main()
{
const sum_func* sum_func_cptr = ∑ // const function
sum_func* sum_func_ptr = ∑ // non-const function ?
// What is the difference between sum_func_cptr and sum_func_ptr
int x = sum_func_cptr( 2, 2 );
cout << x << endl;
int y = sum_func_ptr( 2, 2 );
cout << y << endl;
sum_func_cptr = 0;
sum_func_ptr = 0;
return 0;
}
g++ gives no warnings. That's why I ask.
| Your code is ill-formed with regard to C++03. You can not ever construct a const (or volatile) qualified function type. Whenever you do, your program becomes ill-formed.
This rule has been changed for C++1x, to make the compiler ignore the const / volatile. C++ compilers will usually already implement this rule even in C++03 mode. Thus, the following two will define the same function twice, and results in a compilation error.
typedef void Ft();
void f(Ft const*) { }
void f(Ft *) { } // another definition!
Here is the proof of my claim. C++03, 8.3.5/1
A cv-qualifier-seq shall only be part of the function type for a nonstatic member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type, i.e., it does not create a cv-qualified function type. In fact, if at any time in the determination of a type a cv-qualified function type is formed, the program is ill-formed.
Here is that text for C++1x, 8.3.5/7 n2914:
A cv-qualifier-seq shall only be part of the function type for a non-static member function, the function type to which a pointer to member refers, or the top-level function type of a function typedef declaration. The effect of a cv-qualifier-seq in a function declarator is not the same as adding cv-qualification on top of the function type. In the latter case, the cv-qualifiers are ignored.
The above says that the below is valid, though, and creates the function type for a function that can declare a const member function.
typedef void Ft() const;
struct X { Ft cMemFn; };
void X::cMemFn() const { }
|
1,118,203 | 1,181,799 | Error linking with GCC 4.3.2 on RHEL 5.3 and libstdc++.so. Any GCC gurus? | Trying to use the RHEL5.3 GCC 4.3.2 compiler to build my software on that platform. I get the following error no matter what I try when compiling with -O2, but it builds fine without optimization. Any ideas?
/usr/bin/ld: myapp: hidden symbol `void std::__ostream_fill<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, long)' isn't defined
/usr/bin/ld: final link failed: Nonrepresentable section on output
In RHEL5.3, I am using /usr/bin/g++43 for compilation and linking. The correct libstdc++.so is found here:
/usr/lib/gcc/i386-redhat-linux6E/4.3.2/libstdc++.so
which is a text file containing INPUT ( -lstdc++_nonshared /usr/lib/libstdc++.so.6 ).
Wouldn't that mismatch the system stdlibc++ 4.1 version?
| It turns out to be a GCC bug in RHEL 5.3 :-/. https://bugzilla.redhat.com/show_bug.cgi?id=493929. I sent an email to the maintainer, Jakub Jelinek, who said that RHEL 5.4 (which is due out soon) will have a fix and also will bump to GCC 4.4.
A workaround is to use -fno-inline, but this has some obvious drawbacks.
|
1,118,227 | 1,118,483 | glibmm timeout signal | I'm working on a plugin for a smaller application using gtkmm. The plugin I'm working on checks certain conditions (the date had changed and a new day started) after every minute and starts some actions if the conditions are true. In the initialization part of the plugin I have the following piece of code that uses Glib::SignalTimeout and sigc++:
testCounter = 0;
sigc::slot<bool> tslot = sigc::mem_fun(*this,
&NoteOfDayFactory::checkNewDay);
timeoutObj = Glib::signal_timeout()
.connect(tslot,CHECK_INTERVAL);
where testCounter is an attribute defined in the class that contains the initialization method and CHECK_INTERVAL is a constant equal to 1 minute. All the other variables present are defined in the class that contains the initialization code and the callback method.
The checkNewDay method is where the condition is tested and action taken if the day had changed:
bool NoteOfDayFactory::checkNewDay() {
std::cout << "Checking for new day every minute or so" << std::endl;
std::cout << "Before incrementing" << std::endl;
for(int i = 0; i < 100000; i++);
counter++;
std::cout << counter << " minutes elapsed" << std::endl;
return true; }
I put the small test code, presented above, before I used the real action, to test if everything goes well and the checkNewDay isn't called more than once every minute.
What I found puzzle me. After every minute elapses I get a number of let say 10 messages (at least) printed on the stdout but the variable increases only once every minute.
****** snip ****
Checking for new day every minute or so
Before incrementing
1 minutes elapsed
Checking for new day every minute or so
Before incrementing
1minutes elapsed
**** snip ****
Checking for new day every minute or so
Before incrementing
2 minutes elapsed
Checking for new day every minute or so
Before incrementing
2 minutes elapsed
**** snip ******
It behaves like the text was sent to 10 (or so) different buffers and printed out at once after every minute. Could somebody enlighten me and help me understand why is this happening, because I'm pretty sure that the callback is called only once every minute. Thank you!
| I've tried to reproduce with the following code :
#include <iostream>
#include <glibmm.h>
unsigned counter = 0;
bool checkNewDay()
{
std::cout << "Checking for new day ..." << std::endl;
counter++;
std::cout << "counter = " << counter << std::endl;
return true;
}
int main()
{
static const unsigned delayInMillis = 1000;
sigc::slot<bool> tslot = sigc::ptr_fun(&checkNewDay);
Glib::signal_timeout().connect(tslot, delayInMillis);
std::cout << "Starting Glib::MainLoop" << std::endl;
Glib::MainLoop::create(false)->run();
}
It outputs (as expected) :
Starting Glib::MainLoop
Checking for new day ...
counter = 1
Checking for new day ...
counter = 2
Checking for new day ...
counter = 3
Checking for new day ...
counter = 4
I suggest you try to reproduce with a simple example like mine , by eventually adding what is specific to your code.
I can not see why it should not work, unless perhaps if you call some Glib / Gtkmm methods that process events many times !? How is your main loop ?
I know this is not much help, but it works for me ...
|
1,118,272 | 1,118,299 | Is there a database implementation that has notifications and revisions? | I am looking for a database library that can be used within an editor to replace a custom document format. In my case the document would contain a functional program.
I want application data to be persistent even while editing, so that when the program crashes, no data is lost. I know that all databases offer that.
On top of that, I want to access and edit the document from multiple threads, processes, possibly even multiple computers.
Format: a simple key/value database would totally suffice. SQL usually needs to be wrapped, and if I can avoid pulling in a heavy ORM dependency, that would be splendid.
Revisions: I want to be able to roll back changes up to the first change to the document that has ever been made, not only in one session, but also between sessions/program runs.
I need notifications: each process must be able to be notified of changes to the document so it can update its view accordingly.
I see these requirements as rather basic, a foundation to solve the usual tough problems of an editing application: undo/redo, multiple views on the same data. Thus, the database system should be lightweight and undemanding.
Thank you for your insights in advance :)
| Berkeley DB is an undemanding, light-weight key-value database that supports locking and transactions. There are bindings for it in a lot of programming languages, including C++ and python. You'll have to implement revisions and notifications yourself, but that's actually not all that difficult.
|
1,118,428 | 1,118,943 | Portable periodic timer for period around 100ms | Hej!
I am looking for a portable way of periodically dispatching a task in a C++ project. The use of libraries such as boost should be avoided in this particular project.
The resolution requirement is not too serious: between 5Hz to 20Hz on an average Netbook.
The project uses OpenGL to render the HMI but since I am working on the backend part I am not too familiar with it.
Thanks your any advice or suggestions,
Arne
EDIT: What our 'Task' class actually does is creating a thread using either CreateThread(..) for windows or pthread_create(..) for linux.
| As most straightforward way to achieve this is to use Sleep(100ms) in a cycle, all you need is a portable Sleep. For Linux it can be implemented as follows
void Sleep(unsigned long ulMilliseconds)
{
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = ulMilliseconds * 1000;
select(1, NULL, NULL, NULL, &timeout);
}
|
1,118,482 | 1,118,739 | C++ TR1: how to use the normal_distribution? | I'm trying to use the C++ STD TechnicalReport1 extensions to generate numbers following a normal distribution, but this code (adapted from this article):
mt19937 eng;
eng.seed(SEED);
normal_distribution<double> dist;
// XXX if I use the one below it exits the for loop
// uniform_int<int> dist(1, 52);
for (unsigned int i = 0; i < 1000; ++i) {
cout << "Generating " << i << "-th value" << endl;
cout << dist(eng) << endl;
}
only prints 1 "Generating..." log message, then never exits the for loop! If I use the distribution I commented out instead, it terminates, so I'm wondering what I'm doing wrong. Any idea?
Thanks a lot!
| This definitely would not hang the program. But, not sure if it really meets your needs.
#include <random>
#include <iostream>
using namespace std;
typedef std::tr1::ranlux64_base_01 Myeng;
typedef std::tr1::normal_distribution<double> Mydist;
int main()
{
Myeng eng;
eng.seed(1000);
Mydist dist(1,10);
dist.reset(); // discard any cached values
for (int i = 0; i < 10; i++)
{
std::cout << "a random value == " << (int)dist(eng) << std::endl;
}
return (0);
}
|
1,118,680 | 1,118,696 | Explicit keyword on multi-arg constructor? | I recently came across some weird looking class that had three constructors:
class Class
{
public:
explicit Class(int );
Class(AnotherClass );
explicit Class(YetAnotherClass, AnotherClass );
// ...
}
This doesn't really make sense to me - I thought the explicit keyword is to protect compiler chosen construction from a foreign type.
Is this allowed? If it it, what does it mean?
| In C++11 multi-parameter constructors can be implicitly converted to with brace initialization.
However, before C++11 explicit only applied to single-argument constructors. For multiple-argument constructors, it was ignored and had no effect.
|
1,118,905 | 1,118,939 | Why am I getting a symbol lookup error? | I am writing a library, which is dynamically loaded in my main-application with dlsym.
I have the following files:
library.h
#include <ilibrary.h>
#include <igateway.h>
class LibraryImpl;
class Library: public ILibrary {
public:
static ILibrary* instance();
IGateway* getGateway() const;
protected:
Library();
virtual ~Library();
private:
static ILibrary* instance_;
LibraryImpl* library_;
};
extern "C" {
IMPORT_EXPORT ILibrary* getLibrary();
}
library.cpp
#include "library.h"
#include "business/BCGateway.h"
class LibraryImpl {
public:
IGateway* getGateway();
};
IGateway* LibraryImpl::getGateway() {
return BCGateway::instance();
}
ILibrary* Library::instance_ = NULL;
ILibrary* Library::instance() {
return instance_ ? instance_ : (instance_ = new Library);
}
Library::Library() {
library_ = new LibraryImpl();
}
Library::~Library() {
delete library_;
}
IGateway* Library::getGateway() const {
return library_->getGateway();
}
extern "C" {
IMPORT_EXPORT
ILibrary* getLibrary(){
return Library::instance();
}
}
business/BCGateway.h
#include <igateway.h>
class BCGateway: public IGateway {
public:
static IGateway* instance();
protected:
BCGateway();
private:
static IGateway* instance_;
};
business/BCGateway.cpp
#include "BCGateway.h"
IGateway* BCGateway::instance_ = NULL;
IGateway* BCGateway::instance(){
return instance_ ? instance_ : (instance_ = new BCGateway);
}
I can connect to the library and successfully load the Library-instance. But when I call library->getGateway() in my main-app I get the following error:
symbol lookup error: ./gateways/libSwisscomXtraZone.so: undefined symbol: _ZN9BCGateway8instanceEv
Can you please give me a hint, how I can resolve this? I'm stuck.
Thanks.
| I put the error through c++filt, it says that the mangled name stands for
BCGateway::instance()
This suggests that you call BCGateway::instance() somewhere and forgot to link against BCGateway.o or you even forgot to define BCGateway::instance().
|
1,119,134 | 1,119,334 | How do malloc() and free() work? | I want to know how malloc and free work.
int main() {
unsigned char *p = (unsigned char*)malloc(4*sizeof(unsigned char));
memset(p,0,4);
strcpy((char*)p,"abcdabcd"); // **deliberately storing 8bytes**
cout << p;
free(p); // Obvious Crash, but I need how it works and why crash.
cout << p;
return 0;
}
I would be really grateful if the answer is in depth at memory level, if it's possible.
| OK some answers about malloc were already posted.
The more interesting part is how free works (and in this direction, malloc too can be understood better).
In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).
So returning 40 Bytes to the OS will just not work. So what does free do?
Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.
The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.
There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.
Why does your code crash:
The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.
This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!
Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.
|
1,119,220 | 2,496,429 | Finding perfmon counter id via winreg | I have an app that collects Perfmon counter values through the API exposed in winreg.h - in order to collect Perfmon counter values I must make a call to RegQueryValueExW passing in the id of the Perfmon counter I'm interested in, and in order to obtain that ID I need to query the registry for the list of Perfmon counter names and go through looking for the one I'm interested in
C++ isn't my language of choice, so the following is a shaky example, probably with lots of syntax errors but you get the idea:
DWORD IdProcessIndex = 0;
WCHAR* RawStrings = new WCHAR[ len ];
WCHAR* pCurrent;
DWORD nLenInChars;
// Get the name id of the "ID Process" counter
RegQueryValueExW(HKEY_PERFORMANCE_DATA, COUNTER009, 0, 0, (PBYTE)RawStrings, &len)
pCurrent = (WCHAR*)RawStrings;
while ( (nLenInChars = wcslen(pCurrent)) != 0 && IdProcessIndex == 0 )
{
WCHAR* pName;
pName = pCurrent + nLenInChars + 1;
if ( wcscmp( pName, L"ID Process" ) == 0)
{
IdProcessIndex = _wtoi( pCurrent );
}
pCurrent = pName + wcslen( pName ) + 1;
}
// Get data for the "ID Process" counter
WCHAR strIdProcessIndex[32];
_itow( nIdProcessIndex, strIdProcessIndex, 10 );
RegQueryValueExW(HKEY_PERFORMANCE_DATA, strIdProcessIndex, NULL, NULL, (PBYTE)pData, &len)
Trouble is that on some machines (ones with the Windows CE dev kit installed) there is a second perfmon counter with the name "ID Process", and so the above finds the ID of the wrong counter.
I cant see any way to differentiate between the two other than the order that they are in - at the moment I think my best bet is to take the first counter that I find with a matching name, is there a better option?
(Its not possible to migrate this to .Net or anything like that)
| I realize that this is old, but in case it helps:
Tim is right, parsing the binary data yourself is difficult. Prepare yourself for a world of pain. I'd recommend PDH (encapsulates the registry accesses for you), or if that fails, WMI (though note that WMI is much slower).
You cannot get data for just a performance counter (ID Process, with index 784). You need to get it for the whole object (Process, with index 230).
The IDs for built in objects are guaranteed to be the same on all Windows installations. So if this is the only counter you need, just use 230. :)
|
1,119,357 | 1,120,022 | Platform C Preprocessor Definitions | I'm writing a small library in C++ that I need to be able to build on quite a few different platforms, including iPhone, Windows, Linux, Mac and Symbian S60. I've written most of the code so that it is platform-agnostic but there are some portions that must be written on a per-platform basis.
Currently I accomplish this by including a different header depending on the current platform but I'm having trouble fleshing this out because I'm not sure what preprocessor definitions are defined for all platforms. For windows I can generally rely on seeing WIN32 or _WIN32. For Linux I can rely on seeing _UNIX_ but I am less certain about the other platforms or their 64-bit variants. Does anyone have a list of the different definitions found on platforms or will I have to resort to a config file or gcc parameter?
| I have this sourceforge pre-compiler page in my bookmarks.
|
1,119,370 | 1,119,390 | Where do I find the definition of size_t? | I see variables defined with this type but I don't know where it comes from, nor what is its purpose. Why not use int or unsigned int? (What about other "similar" types? Void_t, etc).
| From Wikipedia
The stdlib.h and stddef.h header files define a datatype called size_t1 which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors,2 particularly as 64-bit architectures become more prevalent.
From C99 7.17.1/2
The following types and macros are defined in the standard header stddef.h
<snip>
size_t
which is the unsigned integer type of the result of the sizeof operator
|
1,119,375 | 1,119,464 | Why can't I const_cast the return of the conversion operator? | I've got a conversion operator that returns a const pointer, and I need to const_cast it. However, that doesn't work, at least under MSVC8. The following code reproduces my problem:
class MyClass {
public:
operator const int* () {
return 0;
}
};
int main() {
MyClass obj;
int* myPtr;
// compiles
const int* myConstPtr = obj;
// compiles
myPtr = const_cast<int*>(myConstPtr);
// doesn't compile (C2440: 'const_cast' : cannot convert from 'MyClass' to 'int *')
myPtr = const_cast<int*>(obj);
}
Why is that? It seems counter-intuitive. Thanks!
| To make it work you have to do :
myPtr = const_cast<int*>(static_cast<const int*>(obj));
When you const_cast directly, the compiler look for the cast operator to int*.
|
1,119,401 | 1,119,436 | How do I dynamically bind a socket to only one network interface? | Currently I do the following to listen on any available port on all interfaces:
// hints struct for the getaddrinfo call
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Fill in addrinfo with getaddrinfo
if (getaddrinfo(NULL, "0", &hints, &res) != 0) {
cerr << "Couldn't getaddrinfo." << endl;
exit(-1);
}
I would like to dynamically bind to only one interface, the non-loopback interface of the system.
How would I go about doing this?
| Take a look at SO_BINDTODEVICE. Tuxology has a good description of this
|
1,119,443 | 1,119,454 | Speed of C program execution | I got one problem at my exam for subject Principal of Programming Language. I thought for long time but i still did not understand the problem
Problem:
Below is a program C, that is executed in MSVC++ 6.0 environment on a PC with configuration ~ CPU Intel 1.8GHz, Ram 512MB
#define M 10000
#define N 5000
int a[M][N];
void main() {
int i, j;
time_t start, stop;
// Part A
start = time(0);
for (i = 0; i < M; i++)
for (j = 0; j < N; j++)
a[i][j] = 0;
stop = time(0);
printf("%d\n", stop - start);
// Part B
start = time(0);
for (j = 0; j < N; j++)
for (i = 0; i < M; i++)
a[i][j] = 0;
stop = time(0);
printf("%d\n", stop - start);
}
Explain why does part A only execute in 1s, but it took part B 8s to finish?
| Row-major order versus column-major order.
Recall first that all multi-dimensional arrays are represented in memory as a continguous block of memory. Thus the multidimensional array A(m,n) might be represented in memory as
a00 a01 a02 ... a0n a10 a11 a12 ... a1n a20 ... amn
In the first loop, you run through this block of memory sequentially. Thus, you run through the array traversing the elements in the following order
a00 a01 a02 ... a0n a10 a11 a12 ... a1n a20 ... amn
1 2 3 n n+1 n+2 n+3 ... 2n 2n+1 mn
In the second loop, you skip around in memory and run through the array traversing the elements in the following order
a00 a10 a20 ... am0 a01 a11 a21 ... am1 a02 ... amn
or, perhaps more clearly,
a00 a01 a02 ... a10 a11 a12 ... a20 ... amn
1 m+1 2m+1 2 m+2 2m+2 3 mn
All that skipping around really hurts you because you don't gain advantages from caching. When you run through the array sequentially, neighboring elements are loaded into the cache. When you skip around through the array, you don't get these benefits and instead keep getting cache misses harming performance.
|
1,119,574 | 1,123,502 | Unique Machine ID for a Windows CE Device | I need to generate unique machine ID for a CE 6.0 device. On Windows OS, I was using the WMI to obtain some hardware identifiers from which I constructed this ID. Apparently, WMI is not supported on Win CE so I am looking for alternatives.
At the moment I am playing with OS image that I have constructed in Platform Builder and testing my app in emulator, only later I will be delivered the real WinCE device.
I have tried both GetDeviceUniqueID and KernelIoControl(IOCTL_HAL_GET_DEVICEID,... but they both return ERROR_NOT_SUPPORTED ( 0x80070032 ).
Do I need to include some package from the wince catalog in order to enable this feature?
Is this limitation only on emulators? (i mean, could it be that OEM's are implementing this unique-id-feature for real devices?
Do you have any other idea how I could construct this value? Like getting hardware / OS serials etc. and how?
| If you're building the OS, then you need to implement the IOCTL so that KernelIoControl returns something. How its derived is completely up to you. I've seen the MAC as a base, as well as the serial number of on-board flash.
How you'd do that for your particular platform I can't say, but as an example for x86 you might clone the code at %WINCEROOT&\PLATFORM\COMMON\SRC\X86\COMMON\IOCTL\devinfo.c and modify the clone (don't modify the common code, obviously).
|
1,119,585 | 1,121,161 | VIM: is there an easy way to manage Visual Studio solutions / makefile projects from Vim? | I tried using Visual Studio instead of VIM(+plugins), but to be honest - the only advantage of VS over VIM is it's ability to automatically manage my project.
I know of existence of ViEmu for VS, but I would like to do the opposite - is there any way to manage projects from within VIM?
I tried both c.vim plugin and Project plugins, but:
I have a problem while using c.vim on windows (from what I remember, there is an error with "slashes" in filepath ).
Project allows to organize projects, but it lacks features for generating makefiles / msbuild files (or am I wrong?).
Are there any tips / solutions / hacks, which would allow me to use VIM to manage my projects? (ideally, using both makefiles and MSBuild files, but just one type of build files would be enough.)
| Maybe I don't understand the question.
VS is full features IDE - you edit, compile and debug without leaving it.
vim in contrast is not IDE - its very powerful text editor. Yet vim has some build-in functionality oriented for programmers (e.g. :make command, compilation, automatic indentation etc.). vim is coming from Unix world where there several build tools (make, scons, cmake etc.). As you know you can "integrete" them using plugins which mostly very far from to be complete.
I think what you tried to do in the beginning is the right thing - bring vim editing power to VS world.
|
1,119,683 | 1,119,916 | Live RX and TX rates in linux | I'm looking for a way to programatically (whether calling a library, or a standalone program) monitor live ip traffic in linux. I don't want totals, i want the current bandwidth that is being used. I'm looking for a tool similar (but non-graphical) to OS X's istat menu's network traffic monitor.
I'm fairly certain something like this exists, but I'm not sure where to look, and i'd rather not have to reinvent the wheel.
Is it as simple as monitoring a socket? Or do I need a utility that handles alot of overhead for me?
| We have byte and packet counters in /proc/net/dev, so:
import time
last={}
def diff(col): return counters[col] - last[iface][col]
while True:
print "\n%10s: %10s %10s %10s %10s"%("interface","bytes recv","bytes sent", "pkts recv", "pkts sent")
for line in open('/proc/net/dev').readlines()[2:]:
iface, counters = line.split(':')
counters = map(int,counters.split())
if iface in last:
print "%10s: %10d %10d %10d %10d"%(iface,diff(0), diff(8), diff(1), diff(9))
last[iface] = counters
time.sleep(1)
|
1,120,478 | 1,120,614 | Capturing a time in milliseconds | The following piece of code is used to print the time in the logs:
#define PRINTTIME() struct tm * tmptime;
time_t tmpGetTime;
time(&tmpGetTime);
tmptime = localtime(&tmpGetTime);
cout << tmptime->tm_mday << "/" <<tmptime->tm_mon+1 << "/" << 1900+tmptime->tm_year << " " << tmptime->tm_hour << ":" << tmptime->tm_min << ":" << tmptime->tm_sec<<">>";
Is there any way to add milliseconds to this?
| To have millisecond precision you have to use system calls specific to your OS.
In Linux you can use
#include <sys/time.h>
timeval tv;
gettimeofday(&tv, 0);
// then convert struct tv to your needed ms precision
timeval has microsecond precision.
In Windows you can use:
#include <Windows.h>
SYSTEMTIME st;
GetSystemTime(&st);
// then convert st to your precision needs
Of course you can use Boost to do that for you :)
|
1,120,721 | 1,120,829 | Where to find API documentation for NVIDIA 3D Vision? | I'd like to start coding for NVIDIA 3D Vision and wonder where can I find the documentation for it?
| The docs should be on the nVidia developer site, though I think that it may be called 3D sterio there. As there isn't a visible heading for either, the info you're looking for may be included in the OpenGL or DirectX docs.
|
1,120,813 | 1,120,835 | Am I going to be OK for threading with STL given these conditions? | I have a collection of the form:
map<key, list<object> >
I only ever insert at the back of the list and sometimes I read from the entire map (but I never write to the map, except at initialization).
As I understand it, none of the STL containers are thread safe, but I can only really have a maximum of one thread per key. Am I missing anything in assuming I'll be pretty safe with this arrangement?
| If the map is never modified at all during the multi-threaded scenario, then you're fine. If each thread looks at its own list, then that's thread-private data, so you're also fine.
Take care not to try and lookup keys with [] because that will insert (modify) if the key doesn't exist in the map yet.
However, I'm curious as to why you'd need this structure - why not keep a pointer/reference or the actual list object itself on the stack of each thread, given that it's private to each thread?
(If it's not, then you need proper synchronisation on the list.)
In fact you say you "read from the entire map" - presumably meaning that any random thread may try to iterate through any of the lists. So you definitely need to synchronise operations on the lists.
|
1,120,831 | 1,121,276 | Linking VS2005 static library with gcc in Windows | Is it possible to link a static library built with VS2005 into an application that is to be built with gcc (in Cygwin)?
| Unlike UNIX where there was no standard C++ ABI for years, Windows has had a standard C++ ABI from the beginning. So, yes, it's possible. But it can be difficult.
|
1,120,833 | 1,121,016 | Derived template-class access to base-class member-data | This question is a furtherance of the one asked in this thread.
Using the following class definitions:
template <class T>
class Foo {
public:
Foo (const foo_arg_t foo_arg) : _foo_arg(foo_arg)
{
/* do something for foo */
}
T Foo_T; // either a TypeA or a TypeB - TBD
foo_arg_t _foo_arg;
};
template <class T>
class Bar : public Foo<T> {
public:
Bar (const foo_arg_t bar_arg, const a_arg_t a_arg)
: Foo<T>(bar_arg) // base-class initializer
{
Foo<T>::Foo_T = T(a_arg);
}
Bar (const foo_arg_t bar_arg, const b_arg_t b_arg)
: Foo<T>(bar_arg)
{
Foo<T>::Foo_T = T(b_arg);
}
void BarFunc ();
};
template <class T>
void Bar<T>::BarFunc () {
std::cout << _foo_arg << std::endl; // This doesn't work - compiler error is: error: ‘_foo_arg’ was not declared in this scope
std::cout << Bar<T>::_foo_arg << std::endl; // This works!
}
When accessing the members of the template-class's base-class, it seems like I must always explicitly qualify the members using the template-style syntax of Bar<T>::_foo_arg. Is there a way to avoid this? Can a 'using' statement/directive come into play in a template class method to simplify the code?
Edit:
The scope issue is resolved by qualifying the variable with this-> syntax.
| You can use this-> to make clear that you are referring to a member of the class:
void Bar<T>::BarFunc () {
std::cout << this->_foo_arg << std::endl;
}
Alternatively you can also use "using" in the method:
void Bar<T>::BarFunc () {
using Bar<T>::_foo_arg; // Might not work in g++, IIRC
std::cout << _foo_arg << std::endl;
}
This makes it clear to the compiler that the member name depends on the template parameters so that it searches for the definition of that name in the right places. For more information also see this entry in the C++ Faq Lite.
|
1,120,903 | 1,121,519 | Keeping objects in sync across a network? | In my application, I have two DLLs. One is written in C# and the other in C++. They communicate with each other across a network. Each has a list of object instances that are expected to be in sync with each other at all times.
What network libraries are available for doing this?
| This is actually a fairly difficult problem to get done correctly, and as such, there are many ways to approach it. I think the best way to do it would be to use something like Protocol buffers, which has both a c++ and c# library. Depending on the size of your data, you could simply serialize the entire data object, and send it across the wire, and then de-serialize it on the other side, and then repeat this whenever the object changes.
Of course, then you might have problems with syncing if both sides change the object at the same time. In this case, you might have to do something like Google Wave does, and send diffs of the data, and merge the changes together.
|
1,121,032 | 1,121,139 | Detect if C++ binary is optimized | Is there a flag or other reliable method to detect if a compiled C++ binary was compiled with optimizations?
I'm okay with compiler-specific solutions.
Edit: This is for a build deployment system, which could accidentally deploy binaries that were not built properly. A water-tight solution is unlikely, but it will save some pain (and money) if this can be detected some of the time.
The compiler will often be gcc, sometimes sun, and if there's a MSVC solution, I don't want to rule that out for the benefit of the community.
| Recent versions of GCC have a way to report which flags were used to compile a binary (third bullet point).
There is a related command line switch (--fverbose-asm) that "only records the information in the assembler output file as comments, so the information never reaches the object file." The --frecord-gcc-switches switch "causes the command line that was used to invoke the compiler to be recorded into the object file that is being created."
|
1,121,052 | 1,121,089 | Can you put a library inside a namespace? | I am working with OpenCV and I would like to put the entire library inside it's own namespace. I've looked around quite a bit but haven't found an answer...
Can you do this without modifying the library source code? If then how?
| Basically no. You could attempt to do it by writing wrappers and macros, but it would be unlikely to work. If you really need to do this, a better approach is to fork the library and make the needed namespace additions. Of course, you would REALLY need to do it to take this approach, and I suspect you don't.
|
1,121,509 | 1,122,170 | C++ include file browser | I have a very large project with tons of convoluted header files that all include each other. There's also a massive number of third-party libraries that it depends on. I'm trying to straighten out the mess, but I'm having some trouble, since a lot of the time I'll remove one #include directive only to find that the stuff it was including is still included through one of the other files. Is there any tool that can help me understand this? I'd really like to be able to click on a .h file and ask it which CPP files it's included in (directly or indirectly), and the paths through which it is included, and likewise click a cpp file and ask it which .h files are included (directly and indirectly). I've never heard of a tool that does this, and a bit of quick googling hasn't turned anything up, but maybe I don't know what to search for.
| http://www.profactor.co.uk/includemanager.php
|
1,121,791 | 1,122,073 | Optimisation of division in gcc | Here's some code (full program follows later in the question):
template <typename T>
T fizzbuzz(T n) {
T count(0);
#if CONST
const T div(3);
#else
T div(3);
#endif
for (T i(0); i <= n; ++i) {
if (i % div == T(0)) count += i;
}
return count;
}
Now, if I call this template function with int, then I get a factor of 6 performance difference according to whether I define CONST or not:
$ gcc --version
gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
$ make -B wrappedint CPPFLAGS="-O3 -Wall -Werror -DWRAP=0 -DCONST=0" &&
time ./wrappedint
g++ -O3 -Wall -Werror -DWRAP=0 -DCONST=0 wrappedint.cpp -o wrappedi
nt
484573652
real 0m2.543s
user 0m2.059s
sys 0m0.046s
$ make -B wrappedint CPPFLAGS="-O3 -Wall -Werror -DWRAP=0 -DCONST=1" &&
time ./wrappedint
g++ -O3 -Wall -Werror -DWRAP=0 -DCONST=1 wrappedint.cpp -o wrappedi
nt
484573652
real 0m0.655s
user 0m0.327s
sys 0m0.046s
Examining the disassembly shows that in the fast (const) case, the modulo has been turned into a multiplication and shift type thing, whereas in the slow (non-const) case it's using idivl.
Even worse, if I try to wrap my integer in a class, then the optimisation doesn't happen whether I use const or not. The code always uses idivl and runs slow:
#include <iostream>
struct WrappedInt {
int v;
explicit WrappedInt(const int &val) : v(val) {}
bool operator<=(const WrappedInt &rhs) const { return v <= rhs.v; }
bool operator==(const WrappedInt &rhs) const { return v == rhs.v; }
WrappedInt &operator++() { ++v; return *this; }
WrappedInt &operator+=(const WrappedInt &rhs) { v += rhs.v; return *this; }
WrappedInt operator%(const WrappedInt &rhs) const
{ return WrappedInt(v%rhs.v); }
};
std::ostream &operator<<(std::ostream &s, WrappedInt w) {
return s << w.v;
}
template <typename T>
T fizzbuzz(T n) {
T count(0);
#if CONST
const T div(3);
#else
T div(3);
#endif
for (T i(0); i <= n; ++i) {
if (i % div == T(0)) count += i;
}
return count;
}
int main() {
#if WRAP
WrappedInt w(123456789);
std::cout << fizzbuzz(w) << "\n";
#else
std::cout << fizzbuzz<int>(123456789) << "\n";
#endif
}
My questions are:
1) Is there a simple principle of C++ itself, or gcc's optimisation, which explains why this happens, or is it just a case of "various heuristics run, this is the code you get"?
2) Is there any way to make the compiler realise that my locally-declared and never-referenced const WrappedInt can be treated as a compile-time const value? I want this thing to be a straight replacement for int in templates.
3) Is there a known way of wrapping an int such that the compiler can discard the wrapping when optimising? The goal is that WrappedInt will be a policy-based template. But if a "do-nothing" policy results in essentially arbitrary 6x speed penalties over int, I'm better off special-casing that situation and using int directly.
| I'm guessing its just the severely old GCC version you are running. The oldest compiler I have on my machine - gcc-4.1.2, performs the fast way with both the non-const and the wrap versions (and does so at only -O1).
|
1,121,971 | 1,121,997 | What is the purpose of the ## operator in C++, and what is it called? | I was looking through the DXUTCore project that comes with the DirectX March 2009 SDK, and noticed that instead of making normal accessor methods, they used macros to create the generic accessors, similar to the following:
#define GET_ACCESSOR( x, y ) inline x Get##y() { DXUTLock l; return m_state.m_##y;};
...
GET_ACCESSOR( WCHAR*, WindowTitle );
It seems that the ## operator just inserts the text from the second argument into the macro to create a function operating on a variable using that text. Is this something that is standard in C++ (i.e. not Microsoft specific)? Is its use considered good practice? And, what is that operator called?
| Token-pasting operator, used by the pre-processor to join two tokens into a single token.
|
1,122,096 | 1,122,128 | What is the underlying type of a c++ enum? | This may have been answered elsewhere but I could not find a suitable response.
I have this code:
enum enumWizardPage
{
WP_NONE = 0x00,
WP_CMDID = 0x01,
WP_LEAGUES = 0x02,
WP_TEAMS = 0x04,
WP_COMP = 0x08,
WP_DIVISIONS = 0x10,
WP_FORMULAS = 0x20,
WP_FINISHED = 0x40,
};
Which is legacy and I have to modify it by adding a few new values.
The issue is each value must be a unique bit so they may be OR combined to a bitmap.
The values are set using the #x## hex format, but I'm wondering if this is the max it can store?
What will be the effect, if any, if I change my code to
enum enumWizardPage
{
WP_NONE = 0x0000,
WP_CMDID = 0x0001,
WP_LEAGUES = 0x0002,
WP_TEAMS = 0x0004,
WP_COMP = 0x0008,
WP_DIVISIONS = 0x0010,
WP_FORMULAS = 0x0020,
WP_FINISHED = 0x0040,
};
| From N4659 C++ 7.2/5:
For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.
|
1,122,195 | 1,122,578 | c++ templatized interface | This is best described in pseudo-code:
class Thing {};
interface ThingGetter<T extends Thing> {
T getThing();
}
class Product extends Thing {};
class ProductGetter<Product> {
Product getThing() {
// Some product code
}
}
class SpecialProductGetter extends ProductGetter {
Product getThing() {
p = ProductGetter::getThing();
// Do some special stuff;
return p;
}
}
class NeatProductGetter extends ProductGetter {
Product getThing() {
p = ProductGetter::getThing();
// Do some neat stuff;
return p;
}
}
I will have other "things" with other getters for those as well.
I've tried codifying this in C++ but it doesn't like :
template <> class ThingGetter <Product> {
nor:
class NeatProductGetter : public ThingGetter <Product> {
Can you model this in C++ without making getThing return a Thing and then having to cast it like crazy?
If so, how? If not, what is the best way to do this?
Thanks!
| Since the question comes from someone with a Java background, I will interpret it in Java terms. You want to define a generic interface that will return an object derived from T:
template<typename T>
struct getter
{
virtual T* get() = 0; // just for the signature, no implementation
};
Note the changes: the function is declared virtual so that it will behave polimorphically in derived objects. The return value is a pointer instead of an object. If you keep an object in your interface, the compiler will slice (cut the non-base part of the returned object) the return. With some metaprogramming magic (or resorting to boost) you can have the compiler test the constraint that T derives from a given type.
Now the question is why you would like to do so... If you define a non-generic interface (abstract class) that returns a Thing by pointer you can just get the same semantics more easily:
struct Thing {};
struct AnotherThing : public Thing {};
struct getter
{
virtual Thing* get() = 0;
};
struct AnotherGetter : public getter
{
virtual AnotherThing* get() { return 0; }
};
struct Error : public getter
{
int get() { return 0; } // error conflicting return type for get()
};
struct AnotherError : public getter
{
};
int main() {
AnotherError e; // error, AnotherError is abstract (get is still pure virtual at this level)
}
The compiler will require all instantiable classes derived from getter to implement a get() method that returns a Thing by pointer (or a covariant return type: pointer to a class derived from Thing). If the derived class tries to return another type the compiler will flag it as an error.
The problem, as you post it is that if you use the interface, then the objects can only be handled as pointers to the base Thing class. Now, whether that is a problem or not is another question... In general, if you have correctly designed your hierarchy, you should be able to use the returned objects polimorphically without having to resort to down casting.
Note that if you are using the different getters at the most derived level in the hierarchy, each get() method returns the most derived element from the Thing hierarchy, at that point you will not need to down cast at all. Only if you use the different getters through the base getter interface you will get the same return type for all (Thing*)
It is important to note that templates are resolved completely at compile time. That means that trying to use templates to solve the need (do you really need it?) to downcast will not help you if you use the different getters through the interface (reference/pointers to the basic getter).
Maybe posting a little more details on your specific domain, where and how you intend to use this code, can help in providing more useful responses.
|
1,122,203 | 1,124,146 | How do I get all the shader constants (uniforms) from a ID3DXEffect? | I'm creating an effect using
hr = D3DXCreateEffectFromFile( g_D3D_Device,
shaderPath.c_str(),
macros,
NULL,
0,
NULL,
&pEffect,
&pBufferErrors );
I would like to get all the uniforms that this shader is using. In OpenGL I used glGetActiveUniform and glGetUniformLocation to get constant's size, type, name etc. Is there a D3DX9 equivalent function?
| D3DXHANDLE handle = m_pEffect->GetParameterByName( NULL, "Uniform Name" );
if ( handle != NULL )
{
D3DXPARAMETER_DESC desc;
if ( SUCCEEDED( m_pEffect->GetParameterDesc( handle, &desc ) ) )
{
// You now have pretty much all the details about the parameter there are in "desc".
}
}
You can also iterate through each parameter by doing the following:
UINT index = 0;
while( 1 )
{
D3DXHANDLE handle = m_pEffect->GetParameter( NULL, index );
if ( handle == NULL )
break;
// Get parameter desc as above.
index++;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.