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
|
|---|---|---|---|---|
555,774
| 555,784
|
Reconciling classes, inheritance, and C callbacks
|
In my C++ project, I've chosen to use a C library. In my zeal to have a well-abstracted and simple design, I've ended up doing a bit of a kludge. Part of my design requirement is that I can easily support multiple APIs and libraries for a given task (due, primarily, to my requirement for cross-platform support). So, I chose to create an abstract base class which would uniformly handle a given selection of libraries.
Consider this simplification of my design:
class BaseClass
{
public:
BaseClass() {}
~BaseClass() {}
bool init() { return doInit(); }
bool run() { return doWork(); }
void shutdown() { destroy(); }
private:
virtual bool doInit() = 0;
virtual bool doWork() = 0;
virtual void destroy() = 0;
};
And a class that inherits from it:
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass()
: BaseClass(), state_manager(new SomeOtherClass()) {}
int callbackA(int a, int b);
private:
virtual bool doInit();
virtual bool doWork();
virtual void destroy();
SomeOtherClass* state_manager;
};
// LSC.cpp:
bool LibrarySupportClass::doInit()
{
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&LibrarySupportClass::callbackA);
return true;
}
// ... and so on
The problem I've run into is that because this is a C library, I'm required to provide a C-compatible callback of the form int (*)(int, int), but the library doesn't support an extra userdata pointer for these callbacks. I would prefer doing all of these callbacks within the class because the class carries a state object.
What I ended up doing is...
static LibrarySupportClass* _inst_ptr = NULL;
static int callbackADispatch(int a, int b)
{
_inst_ptr->callbackA(a, b);
}
bool LibrarySupportClass::doInit()
{
_inst_ptr = this;
if (!libraryInit()) return false;
// the issue is that I can't do this:
libraryCallbackA(&callbackADispatch);
return true;
}
This will clearly do Bad Things(TM) if LibrarySupportClass is instantiated more than once, so I considered using the singleton design, but for this one reason, I can't justify that choice.
Is there a better way?
|
You can justify that choice: your justification is that the C library only supports one callback instance.
Singletons scare me: It's not clear how to correctly destroy a singleton, and inheritance just complicates matters. I'll take another look at this approach.
Here's how I'd do it.
LibrarySupportClass.h
class LibrarySupportClass : public BaseClass
{
public:
LibrarySupportClass();
~LibrarySupportClass();
static int static_callbackA(int a, int b);
int callbackA(int a, int b);
private:
//copy and assignment are rivate and not implemented
LibrarySupportClass(const LibrarySupportClass&);
LibrarySupportClass& operator=(const LibrarySupportClass&);
private:
static LibrarySupportClass* singleton_instance;
};
LibrarySupportClass.cpp
LibrarySupportClass* LibrarySupportClass::singleton_instance = 0;
int LibrarySupportClass::static_callbackA(int a, int b)
{
if (!singleton_instance)
{
WHAT? unexpected callback while no instance exists
}
else
{
return singleton_instance->callback(a, b);
}
}
LibrarySupportClass::LibrarySupportClass()
{
if (singleton_instance)
{
WHAT? unexpected creation of a second concurrent instance
throw some kind of exception here
}
singleton_instance = this;
}
LibrarySupportClass::~LibrarySupportClass()
{
singleton_instance = 0;
}
My point is that you don't need to give it the external interface of a canonical 'singleton' (which e.g. makes it difficult to destroy).
Instead, the fact that there is only one of it can be a private implementation detail, and enforced by a private implementation detail (e.g. by the throw statement in the constructor) ... assuming that the application code is already such that it will not try to create more than one instance of this class.
Having an API like this (instead of the more canonical 'singleton' API) means that you can for example create an instance of this class on the stack if you want to (provided you don't try to create more than one of it).
|
556,064
| 556,092
|
STL-like vector with arbitrary index range
|
What I want is something similar to STL vector when it comes to access complexity, reallocation on resize, etc. I want it to support arbitrary index range, for example there could be elements indexed from -2 to +7 or from +5 to +10. I want to be able to push_front efficiently. Also I want two-way resize...
I know I could write something like this myself, but if there is an already written library that supports this please tell me.
|
Deque is very much like a vector in that it supports random access and efficient insertion at the end and it also supports efficient insertion at the beginning.
Map supports access based on arbitrary keys, you can have any range you want, or even a sparsely populated array. Iteration over the collection is slow.
Unordered map (tr1) is similar to map except it supports better iteration.
As a general rule of thumb, use a vector (in your case adapt it to the behaviour you want) and only change when you have evidence that the vector is causing slowness.
|
556,255
| 556,366
|
How to throw good exceptions?
|
I heard you should never throw a string because there is a lack of information and you'll catch exceptions you dont expect to catch. What are good practice for throwing exceptions? do you inherit a base exception class? Do you have many exceptions or few? do you do MyExceptionClass& or const MyExceptionClass& ? etc. Also i know exceptions should never been thrown in destructors
i'll add that i understand design by contract and when to throw exception. I am asking how i should throw exceptions.
|
In my opinion, a function should throw an exception if it can't keep its "promise", if it has to break its "contract". The function's signature (name and parameters) determine its contract.
Given these two member functions:
const Apple* FindApple(const wchar_t* name) const;
const Apple& GetApple(const wchar_t* name) const;
The names of these functions as well as their return values indicate to me that in the case of FindApple the function is perfectly capable of returning NULL when the correct apple was not found, but in the case of GetApple you're expecting an apple to return. If that second function can't keep its promise, it must throw an exception.
Exceptions are meant for those exceptional conditions in which a function has no other way of reporting these conditions. If you decide to make it a part of the promise (read: function signature) then it can report that condition without throwing an exception.
Note that in the case of FindApple, it's up to the caller to decide how to handle the condition of "not finding the right apple" because it's no longer an exceptional condition.
You might be tempted to try to avoid all exceptions, but that means you have to account for all possible exceptional conditions, and you're placing the burden on the caller instead. The caller needs to check for "error conditions" then.
Ultimately, an exception needs to be handled, but only by the caller that knows how to handle a particular condition in a useful way. And I mean this in the widest possible interpretation: a service that gives up will try again later, a UI that provides a helpful error message, a web app that presents a "oops" screen but that recovers nicely, ... and so on.
Dave
|
556,277
| 556,340
|
Trim / remove a tab ( "\t" ) from a string
|
Can anyone suggest a way of stripping tab characters ( "\t"s ) from a string? CString or std::string.
So that "1E10 " for example becomes "1E10".
|
hackingwords' answer gets you halfway there. But std::remove() from <algorithm> doesn't actually make the string any shorter -- it just returns an iterator saying "the new sequence would end here." You need to call my_string().erase() to do that:
#include <string>
#include <algorithm> // For std::remove()
my_str.erase(std::remove(my_str.begin(), my_str.end(), '\t'), my_str.end());
|
556,309
| 566,047
|
How to embed lua in c++ via SWIG
|
Currently I have a set of SWIG wrappers for my classes and it all builds. I can create a lua virtual machine and load my wrappers, but at that point I'm flummoxed. Googling tells me how to shove put c++ in lua in swig, but not how to put lua in c++.
Really all I want to do is manage to instantiate a lua object and pass it my main game engine object pointer, from there I can manage
|
Take a look at the Programming in Lua book, it has a section on the Lua C API.
For calling Lua functions use lua_pcall, which is equivalent to lua_call (that has a short example) except it will catch Lua runtime errors.
You must have already loaded and run the script once (using eg. luaL_dofile) since the first step is for the script to define the functions for you to call. When it returns, you can access the script-defined functions with lua_getglobal.
|
556,525
| 556,596
|
Raw socket implementation in windows?
|
I need to create TCP/IP headers manually for my application. For that i used Raw socket. My system os is win xp (SP3).
My code compiles fine :) but it throws a run time error:
Initialising Winsock...Initialised successfully. Creating Raw TCP Socket...Raw TCP Socket Created successfully. Setting the socket in RAW mode...Successful. Enter hostname : 192.168.1.152
Resolving Hostname...Resolved. Enter Source IP : 192.168.1.151
Sending packet... Error sending Packet : 10022
I have set IP_HDRINCL to 1. What am i doing wrong? I switched off the firewall too but still get the same result.
|
I suggest using WinPcap for this purpose. Even when you figure out how to do this properly with the win32 API it is going to be horribly slow.
I've used WinPcap successfully to inject packets to a Gigabit ethernet port as fast as the hardware can handle.
|
556,655
| 556,716
|
Throwing/catching exceptions from C'tor of a static object in C++
|
I have a case in which I have to read an input file in the C'tor, but sometimes this file doesn't exist.
This object is usually held statically, so its C'tor is called while loading the dll.
I can't catch the exception I throw if the file doesn't exist because it's too early, and my executable crashes in an ugly way.
I know it's bad practice to throw exceptions out of a C'tor, but I can't go on if the file doesn't exist, so I have to.
Is there a way to catch the exception while loading the dll, and if not, is there any better solution for this scenario?
Thanks,
Gal
|
I assume the static object has the file scope (it is outside any function/class definition). You may consider moving it to an accessor function and accessing it only via that function, like this:
class Object;
Object& getObject()
{
static Object object;
return object;
}
The static instance of Object will be initialized upon the first calling of the getObject() method. If the Object's constructor throws, you can easily catch the exception. Just you need to remember wrapping every call of getObject() into a try/catch block (or suffer from the exception bubbling up the stack chain); that may be a bit inconvenient, but on the other hand you may decide to wrap just the logically "first" call, if you know which one it is in the program logic flow.
|
556,807
| 556,846
|
Does a Java to C++ converter/tool exist?
|
I always asked myself if it would be possible to make a Java to C++ converter.
Maybe a tool that converts the Java syntax to the C++ syntax?
I am aware that the languages differ, but simple things like loops where the semantics match 1 to 1.
Is there such a tool? Or is it possible to make one?
|
It's possible to do anything given enough time, money and resources. Is it practical? Beyond trivial examples not really. Or rather it depends on what constitutes an acceptable error rate.
The real problem is that the idioms are different in Java to C++. Java to C# for example would actually be far easier (because the idioms are much more similar). The biggest of course is that C++ has destructors and manually managed memory. Java uses finally blocks for this kind of behaviour and has garbage collection.
Also Java has a common Object supertype. C++ doesn't.
The generics to templates would be nigh on impossible I would imagine.
|
556,838
| 557,408
|
map complex find operation
|
I want to do the following:
Define a map between a string and any kind of object (may be a list, integer - anything).
The keys to the map can be as follow (the values are, again, not important):
"AAA/123" ==> 1
"AAA/" ==> 2
"BBB/" ==> 3
"CCC/*" ==> 4
"CCC/123" ==> 5
Now, the trick is I want to find the right values given the following strings:
"AAA/123" should give 1.
"AAA/111" should give 2.
"CCC/111" should give 4.
"CCC/123" should give 5.
"BBB/AAA/123" should give 3.
Any idea how I do that with C++ and possibly STL/boost ?
|
Here's a variant of litb answer (which was somehow deleted from the answers list) which might work given the '*' is removed:
template<typename Map> typename Map::const_iterator
find_prefix(Map const& map, typename Map::key_type const& key)
{
typename Map::const_iterator it = map.upper_bound(key);
while (it != map.begin())
{
--it;
if(key.substr(0, it->first.size()) == it->first)
return it;
}
return map.end(); // map contains no prefix
}
I forgot to add the code that uses it:
std::map<std::string, int> smap;
smap["AAA/"] = 1;
smap["BBB/"] = 2;
smap["AAA/AA"] = 3;
find_prefix(smap, "AAA/AB")->second; // ==> 1
find_prefix(smap, "AAA/AA")->second; // ==> 3
find_prefix(smap, "BBB/AB")->second; // ==> 2
find_prefix(smap, "CCC/AB"); // ==> smap.end()
any comment (and thanks to litb) ?
|
556,892
| 561,307
|
How can I launch the on-screen keyboard from my application on Vista and Windows 7
|
I have a problem, I have an application which has a toolbar icon to launch the system onscreen keyboard. This all works fine with the exception of Windows Vista and Windows 7 beta. The UAC appears to be getting in the way and preventing the osk.exe from running.
I have read that because it is used on the logon screen it will not prompt the user for authentication. If I turn the UAC off it works, however this is not an option as the customer wants it to run out of the box.
Is there anything I can do to get around this?
|
OK, it was more about specifics it turned out.
I was using Qt's QProcess::startDetached which I believe uses the CreateProcess function call on windows.
I changed the code to use the ShellExecute() function call and it works like a charm.
Strangely...
|
556,997
| 557,047
|
How can I create a guid in MFC
|
I need to be able to create guids on the fly. Is there a way to do that in MFC? I see how to do it in .net, but we haven't gone there yet. If not, do you have pointers to some code I can use?
|
GUID guid;
HRESULT hr = CoCreateGuid(&guid);
// Convert the GUID to a string
_TUCHAR * guidStr;
UuidToString(&guid, &guidStr);
The application is responsible for calling RpcStringFree to deallocate the memory allocated for the string returned in the StringUuid parameter.
|
557,081
| 557,774
|
How do I get the HMODULE for the currently executing code?
|
I have a static library that may get linked into either a .exe or a .dll. At runtime I want one of my library functions to get the HMODULE for whatever thing the static library code has been linked into.
I currently use the following trick (inspired from this forum):
const HMODULE GetCurrentModule()
{
MEMORY_BASIC_INFORMATION mbi = {0};
::VirtualQuery( GetCurrentModule, &mbi, sizeof(mbi) );
return reinterpret_cast<HMODULE>(mbi.AllocationBase);
}
Is there a better way to do this that doesn't look so hacky?
(Note: The purpose of this is to load some Win32 resources that I know my users will have linked in at the same time as my static library.)
|
HMODULE GetCurrentModule()
{ // NB: XP+ solution!
HMODULE hModule = NULL;
GetModuleHandleEx(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
(LPCTSTR)GetCurrentModule,
&hModule);
return hModule;
}
|
557,170
| 557,422
|
Bit Operation For Finding String Difference
|
The following string of mine tried to find difference between two strings.
But it's horribly slow as it iterate the length of string:
#include <string>
#include <vector>
#include <iostream>
using namespace std;
int hd(string s1, string s2) {
// hd stands for "Hamming Distance"
int dif = 0;
for (unsigned i = 0; i < s1.size(); i++ ) {
string b1 = s1.substr(i,1);
string b2 = s2.substr(i,1);
if (b1 != b2) {
dif++;
}
}
return dif;
}
int main() {
string string1 = "AAAAA";
string string2 = "ATATT";
string string3 = "AAAAA";
int theHD12 = hd(string1,string2);
cout << theHD12 << endl;
int theHD13 = hd(string1,string3);
cout << theHD13 << endl;
}
Is there a fast alternative to do that?
In Perl we can have the following approach:
sub hd {
return ($_[0] ^ $_[1]) =~ tr/\001-\255//;
}
which is much2 faster than iterating the position.
I wonder what's the equivalent of it in C++?
|
Fun with the STL:
#include <numeric> //inner_product
#include <functional> //plus, equal_to, not2
#include <string>
#include <stdexcept>
unsigned int
hd(const std::string& s1, const std::string& s2)
{
// TODO: What should we do if s1.size() != s2.size()?
if (s1.size() != s2.size()){
throw std::invalid_argument(
"Strings passed to hd() must have the same lenght"
);
}
return std::inner_product(
s1.begin(), s1.end(), s2.begin(),
0, std::plus<unsigned int>(),
std::not2(std::equal_to<std::string::value_type>())
);
}
|
557,317
| 557,331
|
Is __declspec(dllexport) needed in cpp files
|
Probably a simple question but I only have Linux to test this code on where __declspec(dllexport) is not needed. In the current code __declspec(dllexport) is in front of all files in the .h file but just in front of like 50% of the functions in the cpp file so I am wondering if they are really needed in the cpp file at all ?
|
No, its only needed in the header.
Here's a link with more info.
Expanding on what Vinay was saying, I've often seen a macro defined
#if defined(MODULENAME_IMPORT)
#define EXPORTED __declspec(dllimport)
#elif defined(MODULENAME_EXPORT)
#define EXPORTED __declspec(dllexport)
#endif
Then in your header you do
void EXPORTED foo();
set the defines accordingly in the project settings for the project doing the import/exporting.
|
557,466
| 557,475
|
How to create an auto startup c++ program
|
I am creating a program in c++, which I want to be able to have the option to have users let it auto start in windows. So when a user starts his computer, windows will auto start this program. I have read stuff about modifying the registry or putting it in the startup folder, but what would be the best "clean" way to do this?
|
Startup folder is clean enough.
Gives the user the possibility to remove it if needed.
|
557,553
| 557,569
|
C++ bound method queue (task manager/scheduler?)
|
Is there a method/pattern/library to do something like that (in pseudo-code):
task_queue.push_back(ObjectType object1, method1);
task_queue.push_back(OtherObjectType object2, method2);
so that I could do the something like:
for(int i=0; i<task_queue.size(); i++) {
task_queue[i].object -> method();
}
so that it would call:
obj1.method1();
obj2.method2();
Or is that an impossible dream?
And if there's a way to add a number of parameters to call - that would be the best.
Doug T. please see this Excellent answer!
Dave Van den Eynde's version works well too.
|
Yes you would want to combine boost::bind and boost::functions its very powerful stuff.
This version now compiles, thanks to Slava!
#include <boost/function.hpp>
#include <boost/bind.hpp>
#include <iostream>
#include <vector>
class CClass1
{
public:
void AMethod(int i, float f) { std::cout << "CClass1::AMethod(" << i <<");\n"; }
};
class CClass2
{
public:
void AnotherMethod(int i) { std::cout << "CClass2::AnotherMethod(" << i <<");\n"; }
};
int main() {
boost::function< void (int) > method1, method2;
CClass1 class1instance;
CClass2 class2instance;
method1 = boost::bind(&CClass1::AMethod, class1instance, _1, 6.0) ;
method2 = boost::bind(&CClass2::AnotherMethod, class2instance, _1) ;
// does class1instance.AMethod(5, 6.0)
method1(5);
// does class2instance.AMethod(5)
method2(5);
// stored in a vector of functions...
std::vector< boost::function<void(int)> > functionVec;
functionVec.push_back(method1);
functionVec.push_back(method2);
for ( int i = 0; i < functionVec.size(); ++i)
{
functionVec[i]( 5);
};
return 0;
};
|
557,800
| 557,869
|
Find the unix platform name
|
I want to be able to determine the output folder based on the platform name: AS3, AS4, AS5, SUN.
I couldn't figure out how to extract the platform name from the system. I experimented with:
uname -a
file /bin/bash
Thanks
Solution
./lsb_release -a
Kudos to Paul Dixon
|
Some linux systems will have support for lsb_release
|
558,223
| 558,259
|
va_copy -- porting to visual C++?
|
A previous question showed a nice way of printing to a string. The answer involved va_copy:
std::string format (const char *fmt, ...);
{
va_list ap;
va_start (ap, fmt);
std::string buf = vformat (fmt, ap);
va_end (ap);
return buf;
}
std::string vformat (const char *fmt, va_list ap)
{
// Allocate a buffer on the stack that's big enough for us almost
// all the time.
s ize_t size = 1024;
char buf[size];
// Try to vsnprintf into our buffer.
va_list apcopy;
va_copy (apcopy, ap);
int needed = vsnprintf (&buf[0], size, fmt, ap);
if (needed <= size) {
// It fit fine the first time, we're done.
return std::string (&buf[0]);
} else {
// vsnprintf reported that it wanted to write more characters
// than we allotted. So do a malloc of the right size and try again.
// This doesn't happen very often if we chose our initial size
// well.
std::vector <char> buf;
size = needed;
buf.resize (size);
needed = vsnprintf (&buf[0], size, fmt, apcopy);
return std::string (&buf[0]);
}
}
The problem I'm having is that the above code doesn't port to Visual C++ because it doesn't provide va_copy (or even __va_copy). So, does anyone know how to safely port the above code? Presumably, I need to do a va_copy copy because vsnprintf destructively modifies the passed va_list.
|
You should be able to get away with just doing a regular assignment:
va_list apcopy = ap;
It's technically non-portable and undefined behavior, but it will work with most compilers and architectures. In the x86 calling convention, va_lists are just pointers into the stack and are safe to copy.
|
558,366
| 558,408
|
Tracing write access to class instance/memory range in gdb
|
I am trying to debug a small operating system I have written in an university course in C++. At runtime somewhere one of my objects is getting corrupted. It seems like this happens due to accidentally writing to the wrong memory address. As I am unable to find the place where this happens from pure looking at the code, I need another way.
As this is an operating system, I cannot attach tools like valgrind to it, but I can run it in emulators (bochs/qemu) with gdb attached.
Is there a way in gdb to trace write access to a class instance or more general a specific memory range? I would like to break as soon as write access happens, so I can verify if this is valid or not.
|
You can put a watchpoint:
watch x
This will break when x is modified. x can be any type of variable. If you have:
class A;
A x;
Then gdb will break whenever x is modified.
You can actually put a watchpoint on any expression, and gdb will break when the expression changes. Be careful with this, though, because if the expression isn't something that the underlying hardware supports, gdb will have to evaluate this after every instruction, which leads to awful performance. For example, if A above is a class with many members then gdb can watch the entire instance x, but the way it'll work is:
execute an instruction
jump to the debug breakpoint
check if x has changed
return to the program
Naturally, this is very slow. If x is an int then gdb can use a hardware breakpoint.
If you have a specific memory address you can watch it too:
watch *0x1234
This will break when the contents of [0x1234] changes.
You can also set a read breakpoint using rwatch, or awatch to set a read/write breakpoint.
|
558,474
| 558,480
|
What makes more sense - char* string or char *string?
|
I'm learning C++ at the moment, and I'm coming across a lot of null-terminated strings. This has got me thinking, what makes more sense when declaring pointers:
char* string
or
char *string
? To me, the char* format makes more sense, because the type of "string" is a pointer to a char, rather than a char. However, I generally see the latter format. This applies to references as well, obviously.
Could someone tell me if there is a logical reason for the latter format?
|
In the following declaration:
char* string1, string2;
string1 is a character pointer, but string2 is a single character only. For this reason, the declaration is usually formatted like:
char *string1, string2;
which makes it slightly clearer that the * applies to string1 but not string2. Good practice is to avoid declaring multiple variables in one declaration, especially if some of them are pointers.
|
558,848
| 558,900
|
Can I force cache coherency on a multicore x86 CPU?
|
The other week, I wrote a little thread class and a one-way message pipe to allow communication between threads (two pipes per thread, obviously, for bidirectional communication). Everything worked fine on my Athlon 64 X2, but I was wondering if I'd run into any problems if both threads were looking at the same variable and the local cached value for this variable on each core was out of sync.
I know the volatile keyword will force a variable to refresh from memory, but is there a way on multicore x86 processors to force the caches of all cores to synchronize? Is this something I need to worry about, or will volatile and proper use of lightweight locking mechanisms (I was using _InterlockedExchange to set my volatile pipe variables) handle all cases where I want to write "lock free" code for multicore x86 CPUs?
I'm already aware of and have used Critical Sections, Mutexes, Events, and so on. I'm mostly wondering if there are x86 intrinsics that I'm not aware of which force or can be used to enforce cache coherency.
|
volatile only forces your code to re-read the value, it cannot control where the value is read from. If the value was recently read by your code then it will probably be in cache, in which case volatile will force it to be re-read from cache, NOT from memory.
There are not a lot of cache coherency instructions in x86. There are prefetch instructions like prefetchnta, but that doesn't affect the memory-ordering semantics. It used to be implemented by bringing the value to L1 cache without polluting L2, but things are more complicated for modern Intel designs with a large shared inclusive L3 cache.
x86 CPUs use a variation on the MESI protocol (MESIF for Intel, MOESI for AMD) to keep their caches coherent with each other (including the private L1 caches of different cores). A core that wants to write a cache line has to force other cores to invalidate their copy of it before it can change its own copy from Shared to Modified state.
You don't need any fence instructions (like MFENCE) to produce data in one thread and consume it in another on x86, because x86 loads/stores have acquire/release semantics built-in. You do need MFENCE (full barrier) to get sequential consistency. (A previous version of this answer suggested that clflush was needed, which is incorrect).
You do need to prevent compile-time reordering, because C++'s memory model is weakly-ordered. volatile is an old, bad way to do this; C++11 std::atomic is a much better way to write lock-free code.
|
559,025
| 559,118
|
Compiler-Programming: What are the most fundamental ingredients?
|
I am interested in writing a very minimalistic compiler.
I want to write a small piece of software (in C/C++) that fulfills the following criteria:
output in ELF format (*nix)
input is a single textfile
C-like grammar and syntax
no linker
no preprocessor
very small (max. 1-2 KLOC)
Language features:
native data types: char, int and floats
arrays (for all native data types)
variables
control structures (if-else)
functions
loops (would be nice)
simple algebra (div, add, sub, mul, boolean expressions, bit-shift, etc.)
inline asm (for system calls)
Can anybody tell me how to start? I don't know what parts a compiler consists of (at least not in the sense that I just could start right off the shelf) and how to program them. Thank you for your ideas.
|
Firstly, you need to decide whether you are going to make a compiler or an interpreter. A compiler translates your code into something that can be run either directly on hardware, in an interpreter, or get compiled into another language which then is interpreted in some way. Both types of languages are turing complete so they have the same expressive capabilities. I would suggest that you create a compiler which compiles your code into either .net or Java bytecode, as it gives you a very optimized interpreter to run on as well as a lot of standard libraries.
Once you made your decision there are some common steps to follow
Language definition Firstly, you have to define how your language should look syntactically.
Lexer The second step is to create the keywords of your code, known as tokens. Here, we are talking about very basic elements such as numbers, addition sign, and strings.
Parsing The next step is to create a grammar that matches your list of tokens. You can define your grammar using e.g. a context-free grammar. A number of tools can be fed with one of these grammars and create the parser for you. Usually, the parsed tokens are organized into a parse tree. A parse tree is the representation of your grammar as a data structure which you can move around in.
Compiling or Interpreting The last step is to run some logic on your parse tree. A simple way to make your own interpreter is to create some logic associated to each node type in your tree and walk through the tree either bottom-up or top-down. If you want to compile to another language you can insert the logic of how to translate the code in the nodes instead.
Wikipedia is great for learning more, you might want to start here.
Concerning real-world reading material I would suggest "Programming language processors in JAVA" by David A Watt & Deryck F Brown. I used that book in my compilers course and learning by example is great in this field.
|
559,179
| 559,191
|
linking to boost regex in gcc
|
i am trying to compile my program which uses regex on linux. I built the boost library in the
libs/regex/build
by typing
make -fgcc.mak
which created a directory gcc which contains the following four files
boost_regex-gcc-1_35
boost_regex-gcc-d-1_35
libboost_regex-gcc-1_35.a
libboost_regex-gcc-d-1_35.a
Now I want to use regex from my program which is in some arbitrary directory.
I #included boost/regex.hpp
I got the error which stated that regex.hpp is not found. Then I gave the -I option in the g++ compiler. I didn't get that error.
But I get the following error
undefined reference to `boost::re_detail::perl_matcher<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<boost::sub_match<__gnu_cxx::__normal_iterator<char const*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > > > >, boost::regex_traits<char, boost::cpp_regex_traits<char> > >::construct_init(boost::basic_regex<char, boost::regex_traits<char, boost::cpp_regex_traits<char> > > const&, boost::regex_constants::_match_flags)'
I googled and found that I need to somehow link one of the above 4 libraries to my program. How can I do it. Which one should I link and why?
|
Either add libboost_regex-gcc-1_35.a to your list of object files in your link step or add -static -lboost_regex-gcc-1_35 to the same. Also be sure that you have an -I switch pointing to your boost includes directory in your compile step. If the libraries are outside the typical search path (/usr/lib on *nix), add that directory to your link command with -Wl,-L/path/to/boost/libs for g++ or simply -L/path/to/boost/libs on ld.
|
559,274
| 559,285
|
Any program or trick to find the definition of a variable?
|
Many times when I am watching others code I just want to find where and how a variable is defined. Normally what I do now is look for the type of the variable until I find the definition, that is very time consuming. And I guess that there are some tools that can help me in this rutinary situation. Any suggestion in some tools or commands to help me in this task?.
I know that using a GUI and creating a project this is done automatically I am talking of a way to do this without a GUI. I am working with only text mode. I am running under Linux and I am using C/C++, but suggestions for other languages are welcome.
Thanks a lot.
A possible solution
Michel in one of his comments propose a simple an effective solution define again the variable, in that case in compilation time, the compiler will inform where is the previous definiton. Of course to apply this solution we need to think previously in the locality of the variable.
|
Edit: OK, you say you're using C++. I'm editing my response. I would use the C preprocessor and then grep for the variable. It will appear in the first place.
cpp -I...(preprocessor options here) file.cpp | grep variable
The C preprocessor will join all the includes that the program uses, and the definition has to be before any usage of that variable in the file. Not a perfect thing, but without an IDE or a complete language description/managing tool, you only have the text.
Another option would be using ctags. It understands the C and C++ syntaxes (among others), and can be searched for variables and functions using command line tools, emacs and vi, among others.
|
559,294
| 559,302
|
Direct 3D affecting data type double
|
I recently added some DirectX code to my program, and now my double data type variables only have the range/resolution of a float (.. or atleast less range/resolution than they used to). If I remove the direct3D initialization - "Direct3DCreate9(D3D_SDK_VERSION)" - the problem goes away. Any insight? Thanks.
|
Direct3D will modify the FPU state to force single precision mode.
If you want to preserve double-precision mode, use D3DCREATE_FPU_PRESERVE when you create the D3D device. That will have an effect on the performance of D3D though:
http://msdn.microsoft.com/en-us/library/bb172527(VS.85).aspx
|
559,440
| 559,459
|
getline() in C++ - _GNU_SOURCE not needed?
|
Firstly, I'm pretty new to C++. I believe that getline() isn't a standard C function, so #define _GNU_SOURCE is required to use it. I'm now using C++ and g++ tells me that _GNU_SOURCE is already defined:
$ g++ -Wall -Werror parser.cpp
parser.cpp:1:1: error: "_GNU_SOURCE" redefined
<command-line>: error: this is the location of the previous definition
Can anyone confirm if this is standard, or is its definition hidden somewhere in my setup? I'm not sure of the meaning of the final line quoted.
The file's includes are as follows, so presumably it's defined in one or more of these?
#include <iostream>
#include <string>
#include <cctype>
#include <cstdlib>
#include <list>
#include <sstream>
Thanks!
|
I think g++, from version 3, automagically defines _GNU_SOURCE. This is supported by your third line in the error stating that the first definition was done on the command line (with nary a -D_GNU_SOURCE in sight):
<command-line>: error: this is the location of the previous definition
If you don't want it, #undef it as the first line in your compilation unit. You may need it, however, in which case use:
#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
The reason you're getting the error is because you're re-defining it. It shouldn't be an error if you define it to what it already was. At least that's the case with C, it may be different with C++. Based on the GNU headers, I would say they're doing an implicit -D_GNU_SOURCE=1 which is why it thinks you're re-defining it to something else.
The following snippet should tell you its value provided you haven't changed it.
#define DBG(x) printf ("_GNU_SOURCE = [" #x "]\n")
DBG(_GNU_SOURCE); // first line in main.
|
559,522
| 559,595
|
Separate header files for concrete classes - C++
|
Background
I have an abstract class, something like
class IConverter{
public:
virtual void DoConvertion() = 0;
};
There will be many concrete classes which just implements DoConvertion method.
class TextConverter : public IConverter{
public:
virtual void DoConvertion(){
// my code goes here
}
};
class ImageConverter : public IConverter{
public:
virtual void DoConvertion(){
// my code goes here
}
};
There will be many concrete implementation like this. I have created a header file say, CharacterConverter.h which has the abstract class IConverter.
Question
Since my concrete classes just implement the DoConvertion method, is it required to create separate header files for each concrete class? I mean is it required to create ImageConverter.h, TextConverter.h and so on for all concrete classes? All these header files is going to contain the same code like IConverter abstract class.
Any thoughts?
|
Something you might consider, depending on the rest of your design, is a factory, where your abstract class has a static method (or multiple static methods, depending on how you implement it) that constructs the appropriate subclass and returns it as an IConverter*. With this, you can expose only the abstract definition in the header file, and have all the concrete class definitions and implementations in a single .cpp file along with the super class implementation. This gets a bit unwieldy if your subclass are large, but with smaller classes it reduces the number of files you have to manage.
But, as others have pointed out, it's ultimately a judgment call. The only performance issues would be related to compiling; more cpp files might take (slightly) longer to compile and more header files might increase dependency analysis. But there's no requirement that every header file have a matching cpp and vice verse.
Based on the comments, I'd recommend a structure like this:
IConverter.h ==> definition of IConverter
Converters.h ==> definitions of all subclasses
IConverter.cpp ==> include IConverter.h and Converters.h, contain implementation of IConverter abstract functionality (static factory method and any inheritable functionality)
TextConvter.cpp, ImagerConverter.cpp, etc. ==> seperate cpp files for each subclass, each containing IConverter.h and Converters.h
This allows you to only include the IConverter.h in any clients that use the factory and generic functionality. Putting all the other definitions in a single header allows you to consolidate if they're all basically the same. Separate cpp files allow you to take advantage of the compiler benefits mentioned by Brian. You could inline the subclass definitions in header files as mentioned, but that doesn't really buy you anything. Your compiler is usually smarter than you are when it comes to optimizations like inline.
|
559,762
| 559,913
|
How parse a string in C++
|
I want to parse the strings, so that to check whether they have specified syntax or not.
Example:
Str = Z344-R565l t
Here my requirement is after Z there should be a number and after that a - and after that R should be there followed by a number, followed by l, followed by a space and then finally t.
If any thing other than this it should be a error.
I have to parse many different kind of syntax like this. I would be awkward if write a function for each type of syntax required. I heard that yacc or lex can solve this problem.
Can any one please throw some light on my problem?
|
Use boost::regex
#include <string>
#include <boost/regex.hpp>
bool isMatch(std::string input){
boost::regex r("Z[0-9]*-R[0-9]*l t");
return boost::regex_search(input, r);
}
The other thing that you could do is supply a list of regex expressions in a file, one expression per line. Create a vector of boost::regex objects using the file input and iterate through the vector of patterns for each string you need to validate. It's not very efficient but it will work.
|
559,918
| 560,034
|
C++0x: Range overloads for standard algorithms?
|
std::sort(range(c));
as opposed to
std::sort(c.begin(), c.end();
Do you expect the next standard to provide range overloads for standard algorithms?
Boost's range iterators are something similar, and Bjarne Stroustrup's iseq()s mentioned in TC++PL3e are also the same idea. I have looked at the latest draft I could find but didn't see range overloads mentioned.
|
The History page provides a partial answer.
There has to be a compelling need to add overloads to the std namespace. Note, this is a Library Issue. You can search the archives to find if anyone has previously raised a request to add these to the library. If there isn't any you can submit a defect report. The current language does not, in any way, stop you from writing your own wrappers. So, the question boils down to whether a lot of others will also want this as a standard library supported feature or not. But that ain't all. Any extension, even to the library, is not just a technical choice, but is also guided by numerous other geo-political issues. You have to have a certain number of votes to get this in.
Frankly, I'd love to see this get in. However, remember this in no way is a novel/core feature that the library can't do without. So, keep your fingers crossed.
|
560,089
| 560,098
|
Unix Command For Benchmarking Code Running K times
|
Suppose I have a code executed in Unix this way:
$ ./mycode
My question is is there a way I can time the running time of my code
executed K times. The value of K = 1000 for example.
I am aware of Unix "time" command, but that only executed 1 instance.
|
try
$ time ( your commands )
write a loop to go in the parens to repeat your command as needed.
Update
Okay, we can solve the command line too long issue. This is bash syntax, if you're using another shell you may have to use expr(1).
$ time (
> while ((n++ < 100)); do echo "n = $n"; done
> )
real 0m0.001s
user 0m0.000s
sys 0m0.000s
|
560,091
| 560,112
|
Publish/Subscribe and Smart pointer
|
I would like to implement a simple Publish/Subscribe pattern where:
A single publisher publishes a token (a pointer to an object) to its subscribers. Publisher and subscribers are all independent threads. I plan to add thread-safe queue to each of the subscriber such that Publisher can keep distributing the tokens to the subscribers while they are processing the tokens.
As you can see, that means all of the subscribers actually share the same pointers (note: subscribers cannot modify the pointed object in anyway, so no problem there). Once the shared pointer is not used by any of the subscribers anymore, it would be really nice if the pointer could auto-delete itself once the last subscriber thread is done with it.
Is this a good place to use a smart pointer? If so, which ones of the smart pointers should I use?
I develop on Windows with MSVC2008, and am using Intel TBB, Boost and Qt.
|
If I assume your design is viable (it smells funny with zero context, but may well be correct), boost::shared_ptr might be the way to go.
http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/smart_ptr.htm
Edit: switch to ::shared_ptr from ::weak_ptr, because I am an idiot...
|
560,322
| 560,516
|
How else to achieve "templated function pointers"?
|
Is it possible to establish a set of templated function pointers, without the hassle of doing so manually? Here's an example to illustrate what the heck I'm talking about.
Let's say I have a frequently-called function "write" of which I have two implementations (write0 and write1) that I'd like to be able to switch between dynamically. These write functions are templated on the argument type. One way to do this is to just have a templated front-end function write() which internally uses an if statement.
This turns out to be fast enough for my needs, but now I was left wondering if I can do the same using function pointers (just for fun). The problem with this approach is that setting up the function pointers is a hassle. Are there any other ways to essentially achieve the ideal of write() but without the conditional (direct static dispatch)?
(Other "rules": I can't change the Msg classes to have write() methods, and I can't change the use site code to replace Msgs with adaptors for Msgs.)
FWIW, I found this article basically saying the same thing I'm saying here.
#include <iostream>
using namespace std;
template<typename T> void write0(T msg) { cout << "write0: " << msg.name() << endl; }
template<typename T> void write1(T msg) { cout << "write1: " << msg.name() << endl; }
// This isn't so bad, since it's just a conditional (which the processor will
// likely predict correctly most of the time).
bool use_write0;
template<typename T> void write(T msg) { if (use_write0) write0(msg); else write1(msg); }
struct MsgA { const char *name() { return "MsgA"; } };
struct MsgB { const char *name() { return "MsgB"; } };
struct MsgC { const char *name() { return "MsgC"; } };
struct MsgD { const char *name() { return "MsgD"; } };
// This doesn't work: templates may not be virtual.
#if 0
struct Writer { template<typename T> virtual void write(T msg) = 0; };
struct Writer0 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } };
struct Writer1 { template<typename T> virtual void write(T msg) { cout << "write0: " << msg.name() << endl; } };
#endif
int main(int argc, char **argv) {
use_write0 = argc == 1;
// I can do this:
write(MsgA());
// Can I achieve the following without the verbosity (manual setup, named
// template instantiations, etc.)?
void (*pwriteA)(MsgA) = use_write0 ? (void(*)(MsgA)) write0<MsgA> : (void(*)(MsgA)) write1<MsgA>;
void (*pwriteB)(MsgB) = use_write0 ? (void(*)(MsgB)) write0<MsgB> : (void(*)(MsgB)) write1<MsgB>;
void (*pwriteC)(MsgC) = use_write0 ? (void(*)(MsgC)) write0<MsgC> : (void(*)(MsgC)) write1<MsgC>;
void (*pwriteD)(MsgD) = use_write0 ? (void(*)(MsgD)) write0<MsgD> : (void(*)(MsgD)) write1<MsgD>;
pwriteA(MsgA());
pwriteB(MsgB());
pwriteC(MsgC());
pwriteD(MsgD());
return 0;
}
|
If you want to switch logging functions back and forth while the program runs, I think you have to manually set the function pointer for each type.
If it's enough to just choose the logging function at startup, it can be done in a fully generic way without even knowing for which types the function will be called later:
// writer functions
template<typename T> void write0(T msg) { std::cout << 0; };
template<typename T> void write1(T msg) { std::cout << 1; };
// global flag
bool use_write0;
// function pointers for all types
template<typename T>
struct dispatch {
typedef void (*write_t)(T);
static write_t ptr;
};
// main write function
template<typename T>
inline void write(T msg) {
(*dispatch<T>::ptr)(msg);
}
// the fun part
template<typename T>
void autoinit(T msg) {
if (use_write0)
dispatch<T>::ptr = &write0<T>;
else
dispatch<T>::ptr = &write1<T>;
// call again for dispatch to correct function
write(msg);
}
// initialization
template<typename T>
typename dispatch<T>::write_t dispatch<T>::ptr = &autoinit<T>;
// usage example
int main(int argc, char **argv) {
use_write0 = (argc == 1);
write("abc");
return 0;
}
For each type T the first call to write<T>() decides which writing function should be used. Later calls then directly use the function pointer to that function.
|
560,344
| 560,417
|
How does one disassemble Pro*C/C++ programs?
|
Is there a way to disassemble Pro*C/C++ executable files?
|
In general there should be disassemblers available for executables, regardless how they have been created (gcc, proC, handwritten, etc.) but decompiling an optimized binary most probably leads to unreadable or source.
Also, Pro C/C++ is not directly a compiler but outputs C/C++ code which then in turn is compiled by a platform native compiler (gcc, xlc, vc++, etc.).
Furthermore the generated code is often not directly compilable again without lots of manual corrections.
If you still want to try your luck, have a look at this list of x86 disassemblers for a start.
|
560,845
| 560,903
|
What are the often misunderstood concepts in C++?
|
What are the often misunderstood concepts in c++?
|
C++ is not C with classes!
And there is no language called C/C++. Everything goes downhill from there.
|
561,115
| 561,176
|
Problems writing a copy constructor for a smart pointer
|
The code I'm working with has its own smart pointer implementation which does simple reference counting. Yes, we shouldn't have our own implementation. Yes, we should be using one from boost or some such. Bear with me.
I found I wanted to write code like this:
...
CountedPointer<Base> base;
...
CountedPointer<Derived> derived;
...
base = derived;
However, the copy constructor for CountedPointer has a prototype like this:
CountedPointer(const CountedPointer<T> &other);
So the above code won't compile since it can't find a suitable constructor (or assignment operator - it's the same story there). I tried re-writing the copy constructor with a prototype like this:
template<U>
CountedPointer(const CountedPointer<U> &other);
However, I hit the problem that the copy constructor must access a private member of the object it's copying (i.e. the raw pointer) and if it's in a different specialisation of CountedPointer, they're not visible.
Alexandrescu avoids this problem in his library Loki by having accessor functions for the encapsulated pointer, but I'd prefer not to give direct access to the raw pointer if possible.
Is there any way I can write this to allow the derived to base copy, but not allow general access to the raw pointer?
Update:
I've implemented the accepted answer below, and it works well. I spent a while figuring out why my program seg-faulted horribly when I only provided the templated version of the copy constructor, replacing the original un-templated version. Eventually, I realised that the compiler doesn't regard the templated version as being a copy constructor, and provides a default one. The default one just dumbly copies the contents without updating the counter, so I end up with dangling pointers and double frees. The same sort of thing applies to the assignment operator.
|
Can't you make them friends? Like:
template<typename T>
class CountedPointer {
// ...
template<U>
CountedPointer(const CountedPointer<U> &other);
template<typename U> friend class CountedPointer;
};
|
561,339
| 561,352
|
A question about sizeof and class member function
|
class B
{
public:
int a;
void fn();
}
If I create an object of B, using
B* pb = new B;
Where is the memory of fn() locate?
Is there a pointer in object that pointing at the memory loaction of fn()?
If yes, why sizeof(B) returns the value as if there is no pointer in object at all?
|
Where is the memory of fn() locate?
Since it's a normal function, somewhere in the code section of your program. This location is the same for all instances of the class. In fact, it has got nothing to do with the instantiation of B via pb.
Is there a pointer in object that pointing at the memory loaction of fn()?
No. For a normal member function this isn't required since the address is known at compile time (or, at the latest, at link time); it therefore doesn't have to be stored separately at runtime.
For virtual functions, the situation is different. Virtual function pointers are stored in an array (called “virtual function-pointer table” or “vtable” for short). Each class has one such vtable and each instance to a class stores a pointer to that vtable. This is necessary because if a pointer/reference of type Base points to a sub-class Derived, the compiler has no way of knowing which function to call; rather, the correct function is calculated at runtime by looking it up in the associated vtable. The vtable pointer is also evident in the sizeof the object.
|
561,588
| 561,609
|
What is more efficient, i++ or ++i?
|
Exact Duplicate: Is there a performance difference between i++ and ++i in C++?
Exact Duplicate: Difference between i++ and ++i in a loop?
What is more efficient, i++ or ++i?
I have only used this in Java and C/C++, but I am really asking for all languages that this is implemented in.
In college I had a professor show us that ++i was more efficient, but it has been a couple of years, and I would like to get input from the Stack Overflow community.
|
i++ :
create a temporary copy of i
increment i
return the temporary copy
++i :
increment i
return i
With optimizations on, it is quite possible that the resulting assembly is identical, however ++i is more efficient.
edit : keep in mind that in C++, i may be whatever object that support the prefix and postfix ++ operator. For complex objects, the temporary copy cost is non negligible.
|
561,730
| 561,781
|
partial template specialization for dynamic dispatch
|
I am attempting to write a dynamic dispatcher for a function that's templated on integer values (not on types). While I could either write a code generator or use a big macro chain to create the dispatcher source, it seems that a templated solution would be more elegant.
I've stripped down my dispatcher to a simple form (which doesn't actually do any dispatching):
// works fine with full template specialization
template <int N>
struct TestDispatcher1D {
int f(int n) {
if (n == N) return n; // replace me with actual dispatch
TestDispatcher1D<N-1> t;
return t.f(n);
}
};
template<>
struct TestDispatcher1D<-1> {
int f(int n) { return -1; }
};
// partial template specialization is problematic
template <int M, int N>
struct TestDispatcher2D {
int f(int m, int n);
};
template<int M>
struct TestDispatcher2D<M,-1> {
int f(int m, int n) { return -1; }
};
template<int N>
struct TestDispatcher2D<-1,N> {
int f(int m, int n) { return -1; }
};
template<>
struct TestDispatcher2D<-1,-1> {
int f(int m, int n) { return -1; }
};
template <int M, int N>
int TestDispatcher2D<M,N>::f(int m, int n) {
if ((n == N) && (m == M)) return n + m; // replace me with actual dispatch
if (m < M) {
if (n < N) {
TestDispatcher2D<M-1,N-1> t;
return t(m,n);
} else {
TestDispatcher2D<M-1,N> t;
return t(m,n);
}
} else {
TestDispatcher2D<M,N-1> t;
return t(m,n);
}
}
// test code
void testIt() {
{
TestDispatcher1D<16> t;
t.f(16);
}
{
TestDispatcher1D<16>t;
t.f(0);
}
{
TestDispatcher2D<16,16>t;
t.f(8,8);
}
}
When compiling this on gcc 4.1.1, I get the following errors:
t.cpp: In member function 'int TestDispatcher2D::f(int, int) [with int M = 16, int N = 16]':
t.cpp:63: instantiated from here
t.cpp:40: error: no match for call to '(TestDispatcher2D) (int&, int&)'
t.cpp:63: instantiated from here
t.cpp:43: error: no match for call to '(TestDispatcher2D) (int&, int&)'
t.cpp:63: instantiated from here
t.cpp:47: error: no match for call to '(TestDispatcher2D) (int&, int&)'
Apparently, when I try to create the recursive objects, the compiler isn't treating this as a request to instantiate a new template.
Any suggestions?
|
You're simply not calling the f() function in your recursive call, you're trying to "call the object":
You write:
TestDispatcher2D<...> t;
return t(m,n);
But you want:
TestDispatcher2D<...> t;
return t.f(m,n);
|
561,839
| 561,847
|
What is the difference between 'WCHAR' and 'wchar_t'?
|
Is there any practical difference between WCHAR and wchar_t?
|
Well, one practical difference would be that WCHAR doesn't exist on my platform. For Windows only (and with no intention of ever porting the program to another platform) and with the necessary headers included, it's the same (since WCHAR is just a typedef).
|
561,949
| 562,021
|
What are some C++ Standard Library usage best practices?
|
I'm learning C++ and the book I'm reading (The C++ Programming Language) says to not reinvent the wheel, to rely on the standard libraries. In C, I often end up creating a linked list, and link list iteration over and over again (maybe I'm doing that wrong not sure), so the ideas of containers available in C++, and strings, and algorithms really appeal to me. However I have read a little online, and heard some criticisms from my friends and coworkers about STL, so I thought I maybe I'd pick some brains here.
What are some best practices for using STL, and what lessons have you learned about STL?
|
There is a companion book to the Effective C++ series, which is called "Effective STL". It's a good starting point for learning about best practises using the Standard C++ library (neé STL).
|
561,997
| 562,465
|
Determining exception type after the exception is caught?
|
Is there a way to determine the exception type even know you caught the exception with a catch all?
Example:
try
{
SomeBigFunction();
}
catch(...)
{
//Determine exception type here
}
|
You can actully determine type inside a catch(...), but it is not very useful:
#include <iostream>
#include <exception>
class E1 : public std::exception {};
class E2 : public std::exception {};
int main() {
try {
throw E2();
}
catch( ... ) {
try {
throw;
}
catch( const E1 & e ) {
std::cout << "E1\n";
}
catch( const E2 & e ) {
std::cout << "E2\n";
}
}
}
|
562,209
| 562,282
|
typedef std containers?
|
I wanted to do
typedef deque type; //error, use of class template requires template argument list
type<int> container_;
But that error is preventing me. How do I do this?
|
You can't (until C++0x). But it could be emulated with:
template<typename T>
struct ContainerOf
{
typedef std::deque<T> type;
};
used as:
ContainerOf<int>::type container_;
|
562,313
| 588,860
|
Automatically display vertical scrollbar in multiline text edit control
|
On a windows mobile device I have a mutliline text edit control that is set to read-only and has some static text displayed during it's display lifetime. I would like to only display a vertical scrollbar when it's actually useful (i.e. the text is larger than the display).
I can't easily figure out if the text is to large to display because of two reasons.
There is no horizontal scroll bar displayed so the text wraps.
Under windows mobile, the win32 routines to calculate the size of what text will display does not work correctly. They return a incorrect rectangle.
The edit control must tell the scroll bar what it's scroll range is at some point. I was wondering if I could get in between then and hide the scroll bar if it's not going to be used.
|
This is how I solved this problem.
First off:
It only works with read-only mode of a edit control (as you don't want the text to change often).
I think is specific to Windows Mobile MFC, big windows can handle this a lot better.
The solution is very very hacky.
Solution:
I have a standard CEdit bound to the control.
CEdit m_Message;
DDX_Control(pDX, IDC_MESSAGE,
m_Message);
During the InitDialog and OnSize calls, turn on the display of the scroll bar and setup a timer message.
m_Message.ShowScrollBar(SB_VERT,
TRUE);
SetTimer(DO_ADJUST_DISPLAY_STATE, 50,
0);
In the timer handling code, use the scroll information to determine if the scroll bar needs to be displayed.
If not being displayed, turn off the scroll bar and force the window to redisplay.
void CMessageDlg::OnTimer( UINT_PTR nIDEvent )
{
switch(nIDEvent)
{
case DO_ADJUST_DISPLAY_STATE:
KillTimer(nIDEvent);
// deselect all text
m_Message.SetSel(0, 0);
SCROLLINFO info;
m_Message.GetScrollInfo(SB_VERT, &info);
if(info.nPage > (UINT)info.nMax)
{
// need to re-display the non scroll bar version
m_Message.ShowScrollBar(SB_VERT, FALSE);
// I could not find any other way to force a redisplay
// correctly without display problems...
// first move the window to a know invisible area
// then wait (using a timer) for the window to move
// then move the window back to it's original position
RECT rt;
rt.left = 0;
rt.right = 5;
rt.top = 0;
rt.bottom = 5;
m_Message.MoveWindow(&rt);
SetTimer(DO_REDISPLAY_MESSAGE, 50, 0);
}
break;
case DO_REDISPLAY_MESSAGE:
KillTimer(nIDEvent);
// m_MessagePosition holds the original position
// worked out dynamically during the WM_SIZE
// processing
m_Message.MoveWindow(&m_MessagePosition);
break;
}
}
I hope that helps out other people who may have similar requirements.
|
562,482
| 562,562
|
How to manually decorate linker names in MSVC 2005?
|
Is there any way to manually decorate function names in MS C++? I'm going to guess any solution would be Microsoft-specific, and I'm cool with that.
Alternatively, is there a way to declare the function "??_M@YGXPAXIHP6EX0@Z@Z" so the compiler can understand it? FYI, undname lists it as:
void _ _ stdcall `eh vector destructor iterator'(void * , unsigned int, int, void (_ _thiscall * )(void * ))
Obviously, the compiler is not happy with apostrophes in my identifers.
EDIT:
The solution was actually extremely simple. I complied the obj's, and hexedited the desired decorated names right over my placeholder names, padding them with nulls. The linker ate it right up, no questions asked. The functions are stubs, calling external functions so I don't have to keep hexediting every time I make a small change.
Thanks for the ideas everyone.
|
If you declare your function as extern "C" and use the linker option that disables underscore prefix, the name you give in the code is the name you'll have in the .obj file. But this won't solve all your problems, since the compiler will balk when you try to declare a function with special characters in the name.
I guess the solution (which is a lot of work IMO) is to give to the desired functions unique names in the source code (like PLACEHOLDER_01) and then replace these in the .obj file. You'll need somehow to parse the object file and change the symbol names.
Notice also that `eh vector destructor iterator' is a mangled name, the real (symbol) name shouldn't have apostrophes or spaces in it. When dumping the .obj/.dll, you'll have to disable name-mangling.
|
562,588
| 562,640
|
Overriding function with enum/int
|
If there was a base class DeriveMe that had a function virtual void DoSomething(int) and a class that inherits DeriveMe called DerivedThat that had a function void DoSomething(SomeEnum)...would the DerivedThat override the base class DoSomething because enums evaluate to ints during compile time in C++?
I could try this by making DoSomething pure virtual and compile/run it to see if it works but this is my first stackoverflow question so I'd rather just ask it.
|
No, DerivedThat will hide the function from the base class, since the signatures don't match. enums do not evaluate to int, as they are a distinct type.
See the C++ FAQ, sections 23.9 and 29.19.
|
562,620
| 562,649
|
What advantages are there to developing a Win32 app in C++ over a .NET app in C#?
|
I learned windows programming using Visual C++, and the Win32 API. Nowadays, it seems most apps are being developed in .NET using C#. I understand that most of the time there isn't much performance difference between native code and managed code. So I'm wondering, if I were to start writing a new desktop app today, is there any reason (other than the fact that I'm more familiar with C++), that I might want to write it in non-managed C++ instead of .NET? Are there still some advantages to using C++ and native code? Or has that method been more-or-less replaced with .NET on the Windows platform?
Of course I know that people who are writing low-level device drivers and similar programs wouldn't do it in .NET. I'm asking with reference to typical client-facing apps that don't make direct hardware calls.
|
Performance (certain situations, such as graphics)
Memory footprint (as Mancuso said)
Use of existing libraries
No need for a runtime
Finer control
To list a few.
However, you may also want to look at the question from the opposite angle to fairly evaluate which language to use.
Additionally, you could use C++/CLI to incorporate both native and .net code.
|
562,701
| 562,773
|
Best way to determine if two path reference to same file in Windows?
|
How would I compare 2 strings to determine if they refer to the same path in Win32 using C/C++?
While this will handle a lot of cases it misses some things:
_tcsicmp(szPath1, szPath2) == 0
For example:
forward slashes / backslashes
relative / absolute paths.
[Edit] Title changed to match an existing C# question.
|
Open both files with CreateFile, call GetFileInformationByHandle for both, and compare dwVolumeSerialNumber, nFileIndexLow, nFileIndexHigh. If all three are equal they both point to the same file:
GetFileInformationByHandle function
BY_HANDLE_FILE_INFORMATION Structure
|
562,973
| 563,373
|
What are the symptoms of a stack overflow in a C++ program?
|
I just ran into an issue where a stack overflow in a threaded c++ program on HPUX caused a SEGV_MAPERR when a local object tried to call a very simple procedure. I was puzzled for a while, but luckily I talked to someone who recognized this as a stack size issue and we were able to fix the problem by increasing the stack size available to the threads.
How can I recognize when the stack overflows? Do the symptoms differ on windows/linux/hpux?
|
How can I recognize when the stack overflows?
If you know the stack size, where the stack starts and the direction it grows in memory, you can simply check the address of the stack pointer and see if it past the end of the stack. C++ does not allow direct access to the stack pointer. You could easily write a small function in assembly to perform this analysis and link it into you program.
|
563,000
| 567,886
|
Can optimizations affect the ability to debug a VC++ app using its PDB?
|
In order to be able to properly debug release builds a PDB file is needed. Can the PDB file become less usable when the compiler uses different kinds of optimizations (FPO, PGO, intrinsic functions, inlining etc.)? If so, is the effect of optimization severe or merely cause adjacent lines of code to get mixed up?
(I'm using VC2005, and will always choose debugability over optimized performance - but the question is general)
|
Yes, optimized code is less debuggable. Not only is some information missing, some information will be very misleading.
The biggest issue in my opinion is local variables. The compiler may use the same stack address or register for multiple variables throughout a function. As other posters mentioned, sometimes even figuring out what the "this" pointer is can take a bit of time. When debugging optimized code you may see the current line jumping around as you single step, since the compiler reorganized the generated code. If you use PGO, this jumping around will probably just get worse.
FPO shouldn't affect debuggability too much provided you have a PDB since the PDB contains all the info necessary to unwind the stack for FPO frames. FPO can be a problem when using tools that need to take stack traces without symbols. For many projects, the perf benefit of FPO nowadays doesn't outweigh the hit for diagnosability; for this reason, MS decided not to build Windows Vista with the FPO optimization (http://blogs.msdn.com/larryosterman/archive/2007/03/12/fpo.aspx).
I prefer to debug unoptimized code but this isn't always possible - some problems only repro with optimized code, customer crash dumps are from the released build, and getting a debug private deployed sometimes isn't possible. Often when debugging optimized code, I use the disassembly view - dissasembly never lies.
This all applies to windbg since I do all native code debugging with it. Visual Studio's debugger might handle some of these cases better.
|
563,168
| 563,177
|
monitor a program's memory usage in Linux
|
Are there any tools available in Linux which graphically or textually display memory usage for a program? For example, if I write a C++ program and would like to verify that objects are being allocated and deallocated properly in memory, are there applications available that would visually show the objects being instantiated and deleted? When I used to program in Visual Studio, I remember stepping through a program and using a debug pane to monitor memory usage and am looking for something similar to that in Linux.
|
It's not exactly what you are looking for, but have a look at Valgrind.
|
563,221
| 563,320
|
Is there an implicit default constructor in C++?
|
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?
|
If you do not define a constructor, the compiler will define a default constructor for you.
Construction
The implementation of this
default constructor is:
default construct the base class (if the base class does not have a default constructor, this is a compilation failure)
default construct each member variable in the order of declaration. (If a member does not have a default constructor, this is a compilation failure).
Note:
The POD data (int,float,pointer, etc.) do not have an explicit constructor but the default action is to do nothing (in the vane of C++ philosophy; we do not want to pay for something unless we explicitly ask for it).
Copy
If no destructor/copy Constructor/Copy Assignment operator is defined the compiler builds one of those for you (so a class always has a destructor/Copy Constructor/Assignment Operator (unless you cheat and explicitly declare one but don't define it)).
The default implementation is:
Destructor:
If user-defined destructor is defined, execute the code provided.
Call the destructor of each member in reverse order of declaration
Call the destructor of the base class.
Copy Constructor:
Call the Base class Copy Constructor.
Call the copy constructor for each member variable in the order of declaration.
Copy Assignment Operator:
Call the base class assignment operator
Call the copy assignment operator of each member variable in the order of declaration.
Return a reference to this.
Note Copy Construction/Assignment operator of POD Data is just copying the data (Hence the shallow copy problem associated with RAW pointers).
Move
If no destructor/copy Constructor/Copy Assignment/Move Constructor/Move Assignment operator is defined the compiler builds the move operators for you one of those for you.
The default implementation is:
Implicitly-declared move constructor
If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true:
Move Constructor:
Call the Base class Copy Constructor.
Call the move constructor for each member variable in the order of declaration.
Move Assignment Operator:
Call the base class assignment operator
Call the move assignment operator of each member variable in the order of declaration.
Return a reference to this.
|
563,414
| 563,445
|
How do you debug heavily templated code in c++?
|
I find it very hard to figure out what is wrong with my code when using C++ template meta-programming. It might be that I am just not very good at understanding the error messages, but as far as I'm aware I can't resort to putting in print statements or breakpoints to figure out what's going on.
What tips or advice can you offer when trying to figure out why something is not compiling other than just picking through the code manually and hoping it will come to me?
|
For the STL at least there are tools available that will output more human-friendly error messages. See http://www.bdsoft.com/tools/stlfilt.html
For non-STL templates you'll just have to learn what the errors mean. After you've seen them a dozen times it becomes easier to guess what the problem is. If you post them here maybe somebody can help you figure it out.
|
564,100
| 564,217
|
Checking the value of a Lua stack item from C++
|
how do I check the value of the top of the stack in Lua?
I have the following C++ code:
if (luaL_loadfile(L, filename) == NULL) {
return 0;// error..
}
lua_pcall(L,0,0,0); // execute the current script..
lua_getglobal(L,"variable");
if (!lua_isstring(L,-1)){ // fails this check..
lua_pop(L,1);
return 0; // error
}
The contents of the file in question is
-- A comment
variable = "MyString"
Any ideas?
|
The likely problem is that luaL_loadfile() is documented to return the same values as lua_load() or one additional error code. In either case, the return value is an int where 0 means success and a nonzero value is an error code.
So, the test luaL_loadfile(...) == NULL is true if the file was loaded, but the code calls that an error and returns.
The function lua_pcall() also returns a status code, and you may want to verify that as well.
Otherwise, the script as shown does create a global variable, and lua_getglobal() would retrieve that to the stack where it could be tested with lua_isstring(), or probably more usefully let you return its value if it is sufficiently string-like with lua_tostring(). The latter function will return either a const char * pointing at a nul-terminated string, or NULL if the value at the stack index can't be converted to a string. See the Lua reference manual as linked for the rest of the details and a caveat about using lua_tostring() inside a loop.
Edit: I added better links to the manual in a couple of places.
|
564,469
| 564,491
|
What is a good & free game engine?
|
For C++, Java, or Python, what are some good game + free game engines that are easy to pick up?
Any type of game engine is okay. I just want to get started somewhere by looking into different game engines and their capabilities.
|
For my Computer Graphics course in College we used the open source OGRE 3D engine. Not only is this an extremely robust 3D engine but it was a blast!
Develop a medium sized game using it and you will get a good taste of many of the different game programming specialties. You'll find yourself doing 3d modeling, sound effects, physics programming, AI, the works.
alt text http://www.mactabilisarts.com/Images/multiplayer%20games.jpg
Screenshot of a recent OGRE 3D Game
|
564,480
| 564,559
|
Embedding: mono vs lua
|
I am interested in hearing about peoples experience with embedding mono (open source implementation of .NET) in a C/C++ application. How is it to distribute such an application and what are the dependencies? I have tested on OS X and mono comes as a huge framework (hundreds of MB). Do users of my app all need this big framework or can it be stripped down or everything be compiled into the main executable.
I previously have experience with embedding Lua in a C++ app, and that works really well because I can link statically the whole lua interpreter in with my main executable. So I have no external dependencies. Is it possible to do something similar with mono?
Any Lua people here who can comment on how they found mono compared to Lua?
PS: By embedding I mean a C++ application which initializes a mono environment and loads a .NET assembly and executes it and then allows for communication between say C# code in assembly and C++ methods in main executable.
|
You should probably also take a look at Mono's Small Footprint page that describes how you can embed a smaller runtime. Heck, they do it themselves with Moonlight.
I hope that helps.
|
564,829
| 565,908
|
Launching a .Net winforms application interactively from a service
|
Environment - VS2008, Vista SP1.
I have written a process management service which can launch applications either in session 0 or the interactive console (usually 1). Please note this is NOT the normal mode of operation, it's for in-house debug purposes only. In the field, these processes will be safely hidden away in session 0. Security concerns do not apply.
Clearly people aren't reading this: security concerns do not apply. We have dozens of existing server apps (NOT services) written like this. We're not about to completely revamp these applications, we just need to be able to get at their inbuilt debug dialogs when running release versions in-house. I already know all about the canonical solution and pipes etc. If it was acceptable to add remote interfaces into all these apps, that's what we'd be doing.
I use the following code to do this:
ZeroMemory (&sui, sizeof(STARTUPINFO));
sui.cb = sizeof (STARTUPINFO);
sui.wShowWindow = pTask->GetWinStartState() ;
sui.dwFlags = STARTF_USESHOWWINDOW ;
ZeroMemory (&pi,sizeof(pi));
if (bInteractive)
{
HANDLE hToken = NULL;
DWORD dwSessionId = WTSGetActiveConsoleSessionId();
WTSQueryUserToken (dwSessionId, &hToken);
sui.lpDesktop = TEXT("winsta0\\default");
LPVOID pEnv = NULL;
DWORD dwCreationFlag = NORMAL_PRIORITY_CLASS | CREATE_NEW_CONSOLE;
HMODULE hModu = LoadLibrary(TEXT("Userenv.dll"));
if (hModu )
{
if (CreateEnvironmentBlock (&pEnv, hToken, FALSE))
dwCreationFlag |= CREATE_UNICODE_ENVIRONMENT;
else
pEnv = NULL;
}
bCreatedOk = CreateProcessAsUser (hToken,
NULL,
(LPTSTR)(pTask->GetExeName()),
NULL,
NULL,
FALSE,
dwCreationFlag,
pEnv,
NULL,
&sui,
&pi);
}
else
{
bCreatedOk = CreateProcess (NULL, ... blah...);
}
This all works fine and I can run and monitor native processes both in the Vista service session and the console. Great. Cakes and ale for everyone.
So here's the problem. If I try to run a winforms (C#) app interactively like this, it appears to run, shows up in Process Explorer as running in session 1, but on the desktop... nada. No window appears at all. The process runs up and shuts down all fine, but no window ever appears. The exact same winform exe run from explorer also shows up in session 1, but this time appears on the desktop just fine.
Any ideas ?
|
Despite the evident hysteria there is nothing wrong with launching an application from a service into an interactive session provided it is done with the same privileges as the interactive user or lower. Since you are launching as the interactive user there can be no privilege escalation.
What you are doing does work. I suspect that the issue has something to do with your STARTUPINFO struct. You appear to be creating your sui on the stack but you don't show what you are doing with it. Are you initializing it to all 0s, if not you may be getting some garbage from the stack that is causing the window not to show or to show at some co-ordinates off the screen.
|
564,933
| 565,428
|
C++ Header To Source?
|
I'm programming in C++ CLI with VS.Net C++ 2008. I'm seeking a tool that can create my C++ source definitions (*.cpp) from the header files. Does such a tool exist? please advise, thanks.
|
For pure C++ code, if its possible to add a 3rd party generator to the VS.Net frame work, then I would strongly recommend: lzz.
This tools takes a text file as input, and will provide a header and source file for you as appropriate. The following is the basic example from the web page:
// A.lzz
class A
{
public:
inline void f (int i) { ... }
void g (int j = 0) { ... }
};
bool operator == (A const & a1, A const & a2) { ... }
Lzz will generate a header file:
// A.h
#ifndef LZZ_A_h
#define LZZ_A_h
class A
{
public:
void f (int i);
void g (int j = 0);
};
inline void A::f (int i) { ... }
bool operator == (A const & a1, A const & a2);
#endif
And a source file:
// A.cpp
#include "A.h"
void A::g (int j) { ... }
bool operator == (A const & a1, A const & a2) { ... }
|
565,056
| 565,087
|
What is your favorite cross-platform solution to access multiple different databases (MySQL, Oracle...) in C/C++?
|
I am writing a simple C++ application which might be installed on Linux or Windows, and which will connect to a database. I want my application to be compatible at least with Oracle and MySQL (or PostgreSQL).
Which C or C++ library would you recommend to handle the database queries: I am open to any library, whether it's very thin (just execute SQL queries) or very fat (a whole object persistence layer, clustering, etc.).
One library per answer, please. A little description (pros & cons) would be great. Thanks a lot.
|
I enjoy using SOCI, it's very C++ like. When it comes to performance with respect to Oracle database, it's comparable with native OCI. It provides backend to some RDBMS:
Oracle
PostgreSQL
MySQL
And some more in the CVS repository.
It's fairly simple to use, the documentation is thorough and rationale is pretty clear. It supports connection pooling, has nice extensible way of converting between datatypes.
|
565,360
| 565,474
|
Overloading, strings, and default parameters
|
Refactoring legacy code, I came across this function (pseudocode):
int getMessage( char * buffer, int size = 300 );
Gee, look at that buffer just waiting to overflow. So I came up with a function using std::string, and thought it would be nice to use function overloading:
int getMessage( std::string & buffer );
So far, so good. But when I try to call the function with a string:
std::string buffer;
int rc = getMessage( buffer );
I get this error:
cannot convert 'std::string' to 'char*' for argument '1' to 'int getMessage(char*, int)'
Obviously, the compiler (GCC 4.1.2) tries hard to convert std::string to char* to satisfy the first function's parameter list (using the default value to satisfy the second parameter), gives up, but doesn't try the second function...
I wouldn't have a problem working around this issue, but I'd like to know why this fails, and whether there would be a way to make it work as intended.
|
As always, once the problem is solved, the solution is painfully trivial and should have been obvious all along.
So I came up with a function using std::string...
...in my working directory, which compiled just fine, but -I and -L in my makefile were still pointing at the previous version of the library, which was blissfully unaware of the new function.
Sorry for the bother. I've been an idiot. I hope this doesn't become a habit. ;-)
|
565,371
| 566,361
|
How to load a c++ dll file into Matlab
|
I have a C++ dll file that uses a lot of other c++ librarys (IPP, Opencv +++) that I need to load into matlab. How can I do this?
I have tried loadlibrary and mex. The load library does not work.
The mex finds the linux things (platform independent library) and tries to include them. And that does not work.
Does anyone have any good ideas?
|
loadlibrary should work. I use it all the time to call functions from dlls written in C++ with C wrappers.
What errors are you getting when you try to use loadlibrary?
Make sure that the exported functions of the dll are C functions, not C++ functions. If not, then write C wrappers.
More info on exactly what you are doing when using loadlibrary would be helpful.
|
565,459
| 565,523
|
C++ wrapper with same name?
|
How can I do a wrapper function which calls another function with exactly same name and parameters as the wrapper function itself in global namespace?
For example I have in A.h foo(int bar); and in A.cpp its implementation, and in B.h foo(int bar); and in B.cpp foo(int bar) { foo(bar) }
I want that the B.cpp's foo(bar) calls A.h's foo(int bar), not recursively itself.
How can I do this? I don't want to rename foo.
Update:
A.h is in global namespace and I cannot change it, so I guess using namespaces is not an option?
Update:
Namespaces solve the problem. I did not know you can call global namespace function with ::foo()
|
does B inherit/implement A at all?
If so you can use
int B::foo(int bar)
{
::foo(bar);
}
to access the foo in the global namespace
or if it does not inherit.. you can use the namespace on B only
namespace B
{
int foo(int bar) { ::foo(bar); }
};
|
565,516
| 565,578
|
What is the purpose of Browse Information generated by Visual Studio
|
I got a huge C++ third-party project with set of project in one solution. So build time is rather long and Browse Information generation takes a lot too. So what is the purpose of Browse Information? What functionality will be lost if i disable Browse information generation?
|
Visual Studio 6 required browse information to do the things that Doug T. mentioned.
Newer versions of visual studio can use the browse information file, but by default use a newer Intellisense database. For those versions, there is basically an Intellisense daemon that builds the database in the background instead of being directly embedded in the build process. It really helps to have more than one processor or core when using Intellisense. Otherwise it can really bog down your system.
|
565,765
| 566,465
|
implementing operator== when using inheritance
|
I have a base class which implements the == operator.
I want to write another class, inheriting the base class, and which should reimplement the == operator.
Here is some sample code :
#include <iostream>
#include <string>
class Person
{
public:
Person(std::string Name) { m_Name = Name; };
bool operator==(const Person& rPerson)
{
return m_Name == rPerson.m_Name;
}
private:
std::string m_Name;
};
class Employee : public Person
{
public:
Employee(std::string Name, int Id) : Person(Name) { m_Id = Id; };
bool operator==(const Employee& rEmployee)
{
return (Person::operator==(rEmployee)) && (m_Id == rEmployee.m_Id);
}
private:
int m_Id;
};
void main()
{
Employee* pEmployee1 = new Employee("Foo" , 1);
Employee* pEmployee2 = new Employee("Foo" , 2);
if (*pEmployee1 == *pEmployee2)
{
std::cout << "same employee\n";
}
else
{
std::cout << "different employee\n";
}
Person* pPerson1 = pEmployee1;
Person* pPerson2 = pEmployee2;
if (*pPerson1 == *pPerson2)
{
std::cout << "same person\n";
}
else
{
std::cout << "different person\n";
}
}
This sample code give the following result :
different employee
same person
Where I would like, even when handling Person* pointers, to make sure they are different.
How am I supposed to solve this problem ?
Thanks !
|
What you want to do is essentiall "virtualize" the comparison operator.
Since operators cannot be virtual (operators can be virtual), you will need to delegate it to something else. Here's one possible solution.
class Person
{
public:
/* ... */
bool operator==(const Person& rhs)
{
return m_Name == rPerson.m_Name && this->doCompare(rhs);
}
private:
virtual bool doCompare() = 0;
};
}
class Employee : public Person
{
/* ... */
private:
virtual bool doCompare(const Person& rhs)
{
bool bRetval = false;
const Employee* pRHSEmployee = dynamic_cast<const Employee*>(&rhs);
if (pEmployee)
{
bRetval = m_Id == pRHSEmployee->m_Id
}
return bRetval;
}
};
The question didn't make clear whether Person needs to be a concrete class. If so, you can make it not pure-virtual, and implement it to return true.
This also uses RTTI, which you may or may not be happy with.
|
565,804
| 642,638
|
max value for SO_RCVBUF in Windows?
|
Quick question, wondering if anyone knew what the limit is for SO_RCVBUF under Windows.
|
SO_RCVBUF in winsock is not limited by the TCP window size. At least for pre-Vista stacks. It would be limited by non-paged pool availability, which is a whole different topic.
So you can make it quite big, if you want to.
Obligatory unsolicited advice: If you are using a large buffer because you are receiving infrequently, I would look into asynchronous I/O with events/select/completion ports.
|
565,824
| 566,553
|
Can someone give me an example of a Unmanaged C++ HTML Client with proxy support?
|
Can someone give me an example of a Unmanaged C++ HTML Client with proxy support?
I want to do some get and posts inside my unmanaged c++ programs, ideally I would like to allow for proxy server configuration, or just use the IE defaults.
I am not looking for hand outs, just something to go by, as I can't seem to find too much on this.
|
Call WinHttpGetIEProxyConfigForCurrentUser to get the proxy configuration and then use the HTTP stack of your choice. I would avoid implementing your own psuedo HTTP stack, getting it right is more work then you probably think.
|
565,938
| 565,957
|
What container can I use to write binary?
|
I want to write a c array into a container and i prefer to modify it if possible.
I was thinking of using vector but it does seem to have a write(*pchararray, len); function. String looked like the next best thing but that too doesnt have a write function?
|
Given
char myarray[10];
You can use an STL iterator:
vector <char> v;
copy(myarray, myarray + 10, back_inserter(v));
You can use a constructor:
vector <char> v(myarray, myarray + 10);
You can resize and copy:
vector<char> v(10);
copy(myarray, myarray + 10, v.begin());
(and all these work similarly for string)
Thanks to comments/other answers :)
|
566,037
| 570,612
|
Filtering Eclipse's C++ Content Assist
|
I'm using Eclipse Ganymede (version 3.4.1) with a C++ project. Is there some way to filter the content assist list to only show methods and fields that are available in the current context?
If not, why not? Is there ever a situation where I would want to access the private fields, etc. in an object?
|
Doesn't look like it. There are at least a couple of bugs open regarding this. You're lucky it shows too much! It never seems to assists in any way for me.
The latest CDT (at the time of writing Helios, with CDT version 7.0.0.201006141710) has the 2nd of those bugs fixed. However private member variables still showed up on the completion list when I tried it out, as shown below.
It does seem to depend on the order of variable declaration in the class. If you have the private section before the public section the private variables are filtered out correctly. While not perfect, it's certainly a great deal better than it was in Ganymede.
|
566,040
| 566,072
|
Mac OS X equivalent for TerminateProcess(GetCurrentProcess,0);
|
I am looking for a simple and uncatchable way to terminate the Mac port of my C++ application. In Windows I was using
TerminateProcess(GetCurrentProcess, 0);
What's the equivalent command I can use with Mac OS X / XCode / GCC?
|
Actually you want _exit if you want to have the same semantics as TerminateProcess. exit semantics are more closely aligned with ExitProcess.
|
566,078
| 583,084
|
What's the best way to parse RSS/Atom feeds for an iPhone application?
|
So I understand that there are a few options available as far as parsing straight XML goes: NSXMLParser, TouchXML from TouchCode, etc. That's all fine, and seems to work fine for me.
The real problem here is that there are dozens of small variations in RSS feeds (and Atom feeds too), so supporting all possible permutations of feeds available out on the Internet gets very difficult to manage. I searched around for a library that would handle all of these low-level details for me, but came out without anything.
Since one could link to an external C/C++ library in Objective-C, I was wondering if there is a library out there that would be best suited for this task? Someone must have already created something like this, it's just difficult to find the "right" option from the thousands of results in Google.
Anyway, what's the best way to parse RSS/Atom feeds in an iPhone application?
|
"Best" is relative. The best performance you'll need to go the SAX route and implement the handlers. I don't know of anything out there open source available (start a google code project and release it for the rest of us to use!)
Whatever you do, it's probably a really bad idea to try and load the whole XML file into memory and act on it like a DOM. Chances are you'll get feeds that are much larger than you can handle on the device leading to frequent memory warnings and crashes.
|
566,225
| 566,654
|
How to compile windows base program with eclipse cdt(using VIsual Studio compiler)
|
i'd like to compile (debugging if possible) windows program in eclipse cdt with microsoft copmiler.
It's better to support eclipse tool-chain (in eclipse cdt)
It's impossible to find this solution in google, except using mingw's make and Visual Studio Makefile..
Are there anyone to have solution with this problem?
|
You want to use Wascana, an Eclipse/CDT distro targeted at Windows-development. Unfortunately the Windows-support is not complete; since it lacks a proper debugger.
|
566,587
| 567,479
|
How to find the cause for a USER 44 PANIC?
|
One of the products we develop is a phone app for nokia phones done in C++ and Symbian, we started getting "random" crashes a while a ago with a USER 44 panic.
I am pretty new to the symbian environment so I am looking for tools and recommendations to help finding the root of this bug.
Is there a equivalent of a "stack trace" that I can get?
Is there generic panic catching code that could give me some insight into it?
|
From http://www.symbian.com/developer/techlib/v9.1docs/doc_source/reference/N10352/UserPanics.html:
This panic is raised by the Free() and FreeZ() member functions of an RHeap.
It is caused when the cell being freed overlaps the next cell on the free
list (i.e. the first cell on the free list with an address higher than the
one being freed).
It means, your calling delete/delete[] (which in turn will call Free()/FreeZ()) with an invalid pointer. When debuging under Carbide the debuger should break on the line that causes the panic and you should be able to see the invalid deletion.
|
566,603
| 566,623
|
How to reach iteratively few variables which names differ only by number in C++?
|
I need a method helping me, to reach variables named like "comboBox1", "comboBox2" etc each by each in a loop. I'd like to change code like:
//proceed comboBox1
//proceed comboBox2
//proceed comboBox3
//proceed comboBox4
//proceed comboBox5
//proceed comboBox6
Into:
for (int i = 1; i < numberOfBoxes; i++) {
//proceed comboBox(i)
}
I tried to find somthing like 'eval', but google didn't give anything matching. I also tried preprocessing the name with operator ## but it seems there's no way to put current integer value to the macro.
|
The simplest solution is to put them all in an array and iterator over that:
// I've made up a type, but you get the idea.
std::vector<ComboBox *> combos;
combos.insert(comboBox1);
combos.insert(comboBox2);
combos.insert(comboBox3);
combos.insert(comboBox4);
combos.insert(comboBox5);
combos.insert(comboBox6);
Now you can iterate over combos. The main problem is that c++ doesn't have reflection. So you can't generated a string at runtime and get the address of an object or function like you can in some other languages.
EDIT: I just saw that you are using Qt. In that case, you should use:
QList<T> qFindChildren ( const QObject * obj, const QString & name );
or
QList<T> qFindChildren ( const QObject * obj, const QRegExp & regExp);
This lets you get a list based on runtime generated names. For example:
QList<QComboBox *> combos = qFindChildren(ui, QRegExp("combo[0-9]+"));
then you can just iterate over that!
|
567,142
| 567,264
|
public inheritance and tlb files
|
Say you have two assemblies (two dlls). The first contains a class called Base and the second contains a class called Derived which publicly inherits from Base.
When I use the tlb files to create C++ classes in Visual Studio 2005, I get Base and Derived classes, but one is not a subclass of the other. There doesn't seem to be any IS-A relationship. Is there a reason for this?
|
I'm assuming here, that the two assemblies communicate one with the other via COM, if that is indeed the case then you are correct, there is no IS-A relationship in COM in regard to CLASS inheritance, only in regard to Interface inheritance.
If you were to define an interface IBase and IDerived which derives from IBase, then you would be able to cast IDerived to IBase on the same object which implements both.
|
567,323
| 567,380
|
Learning C++ Language
|
I am a .net c# programmer but I want to learn .NET C++ also. I am a beginner for c++. Is there any site, book, or Video Tutorials from beginner to expert?
|
There's no such thing as ".Net c++".
Maybe you mean C++/CLI, which is Microsoft's language specification intended to supersede Managed Extensions for C++ (See Wikipedia). Managed extensions to C++ are its inferior and now defunct ancestor [thanks @dp for your comment].
Bear in mind when you choose your learning material that C++/CLI is not equal to the (standard) C++ programming language; so if you want to learn the former, you should edit the question title and tags.
(Note: This is not to be nitpicky, but to help. I think getting the right idea for each name, and the right name for each concept, is an important factor for consistent learning. And of course it's especially important if you search for information on the web.)
|
567,626
| 567,686
|
Unable to find operator via implicit conversion in C++
|
When writing a class to act as a wrapper around a heap-allocated object, I encountered a problem with implicit type conversion that can be reduced to this simple example.
In the code below the wrapper class manages a heap-allocated object and implicitly converts to a reference to that object. This allows the wrapper object to be passed as the argument to the function write(...) since implicit conversion takes place.
The compiler fails, however, when trying to resolve the call to operator<<(...), unless an explicit cast is made (checked with MSVC8.0, Intel 9.1 and gcc 4.2.1 compilers).
So, (1) why does the implicit conversion fail in this case? (2) could it be related to argument-dependent lookup? and (3) is there anything that can be done to make this work without the explicit cast?
#include <fstream>
template <typename T>
class wrapper
{
T* t;
public:
explicit wrapper(T * const p) : t(p) { }
~wrapper() { delete t; }
operator T & () const { return *t; }
};
void write(std::ostream& os)
{
os << "(1) Hello, world!\n";
}
int main()
{
wrapper<std::ostream> file(new std::ofstream("test.txt"));
write(file);
static_cast<std::ostream&>( file ) << "(2) Hello, world!\n";
// file << "(3) This line doesn't compile!\n";
}
|
It fails because you're trying to resolve an operator of your wrapper<T> class that doesn't exist. If you want it to work without the cast, you could put together something like this:
template<typename X> wrapper<T> &operator <<(X ¶m) const {
return t << param;
}
Unfortunately I don't know of a way to resolve the return type at compile time. Fortunately in most cases it's the same type as the object, including in this case with ostream.
EDIT: Modified code by suggestion from dash-tom-bang. Changed return type to wrapper<T> &.
|
567,682
| 567,714
|
Online compilers/runtime for Java, C++, Python and ObjC?
|
Does anyone know of a good online compiler/runtime (for C++, Java, Python, ObjC etc.) that I can access on the web?
What I'm looking for is something that would allow me to type in a program in a web form and to run the program and see the results online.
(Let's not get into the why for now. Suffice it to say for the moment that I don't always have access to a compiler/runtime, and firing up an IDE is just overkill for testing out some code snippets)
I know of codepad.org -- but I'm looking for something better.
|
http://codepad.org/
codepad.org is an online
compiler/interpreter, and a simple
collaboration tool. Paste your code
below, and codepad will run it and
give you a short URL you can use to
share it in chat or email.
Languages:
C
C++
D
Haskell
Lua
OCaml
PHP
Perl
Plain Text
Python
Ruby
Scheme
Tcl
|
567,788
| 567,819
|
C++ preprocessor unexpected compilation errors
|
Please look at the following file: (it is a complete file)
#ifndef TEES_ALGORITHM_LIBRARY_WRAPPER_H
#define TEES_ALGORITHM_LIBRARY_WRAPPER_H
#ifdef _TEES_COMPILE_AS_LIB
#include <dfa\Includes\DFC_algorithms.hpp>
#include <DFA\FuzzyClassifier\FuzzyAlgorithmIntialization\InitFuzzyAlgorithm.hpp>
typedef teesalgorithm::tees_fuzzy_algorithms algorithms_switchyard_class;
#else
#include <DFA\Includes\commercial_algorithms.hpp>
//An incomplete class to hide implementation
class algorithms_switchyard_class;
#endif
class AlgorithmLibraryWrapper {
algorithms_switchyard_class * algorithmPtr_;
typedef teesalgorithm::tees_paramObj paramObj_type;
typedef teesalgorithm::tees_errorObj errorObj_type;
typedef teesalgorithm::tees_statusObj statusObj_type;
typedef teesalgorithm::tees_dataObj dataObj_type;
typedef teesalgorithm::tees_outputObj outputObj_type;
public:
AlgorithmLibraryWrapper(const std::string& sAlgName, paramObj_type& paramObj, errorObj_type& errObj, statusObj_type& statusObj, const char* sFilePath);
static bool dataReader(const std::string& sFileName, dataObj_type& dataObj, errorObj_type& errObj, statusObj_type& statusObj);
bool runalgorithm(const dataObj_type& dataObj, outputObj_type& outObj, errorObj_type& errObj, statusObj_type& statusObj);
~AlgorithmLibraryWrapper();
};
#ifdef _TEES_USE_COMPILED_ALGORITHM_LIB
# ifdef _MSC_VER
#if _MSC_VER < 1400 // If VC 2003
#ifdef _DEBUG
#error No AlgorithmLibWrapper libraries compiled for this version of VC
#else
#error No AlgorithmLibWrapper libraries compiled for this version of VC
#endif
#elif defined(UNDER_CE) // Win CE
#ifdef _DEBUG
#pragma comment( lib, "AlgorithmLibWrapperCEd" )
#else
#pragma comment( lib, "AlgorithmLibWrapperCE" )
#endif
#else // If VC 2005
#ifdef _DEBUG
#pragma comment( lib, "AlgorithmLibWrapperd" )
#else
#pragma comment( lib, "AlgorithmLibWrapper" )
#endif
#endif
#endif
#endif
#endif //TEES_ALGORITHM_LIBRARY_WRAPPER_H
I am getting the following errors; I don't know why. I manually counted the preprocessor directives also.
AlgorithmLibraryWrapper.hpp:10:1: unterminated #ifdef
AlgorithmLibraryWrapper.hpp:7:1: unterminated #ifndef
I am using the poor vxWorks gcc compiler. Please let me know if the fault is mine or the compiler's.
|
It could be that the problem is in the included files (if there actually are unbalaced #if/#endifs.
I would try preprocessing with another compiler. You can use gcc for that, doesn't matter it wouldn't compile. Just get gcc (or MinGW if you're on Windows) and run
cpp -Iinclude_direcories your_file
Or, if you don't like gcc, get MSVC Express edition. Again, you can preprocess code that even doesn't compile, so no problem with nonworking library etc.
Most compilers have an option that will give you the output from the preprocessor so you can check what it's doing. For example,
gcc -E file.c >file.preproc
will give you the pre-processed source so you can check the balancing of #if against #endif.
|
568,218
| 568,226
|
How do I divide two integers inside a double variable?
|
I am working on a lab for school that runs 10 trails of 10000 5 card hands. I have to find flushes and pairs in each hands. I have to find the percentage of pairs and flushs per trail.
My problem is when I try to get the percentage of a pair of one trail for example
double percent = total_pairs/10000;
or
double percent = 5600/10000;
my output becomes 0 when I want to print out 2 decimal places I get the following
0.00
using this code
cout<<setiosflags(ios::fixed | ios::showpoint);
cout<<setprecision(2)<<percent<<endl;
but I still get zero I get actual numbers when I cast it like so
double percent = (double) 5600/10000;
is this correct because I don't want it to truncate my outputs or am I missing something
Hope you can understand me.
|
Is "total_pairs" an int? If so, the divide is done as integer division. You need to explicitly cast one of the numbers to a double (and the other will be automatically promoted to double):
double percent = ((double)total_pairs)/10000; // or just simply 10000.0
|
568,524
| 568,528
|
c++ outputting and inputting a single character
|
I am writing a program in c++ which implements a doubly-linked list that holds a single character in each node. I am inserting characters via the append function:
doubly_linked_list adam;
adam.append('a');
This function is implemented as follows:
//Append node
node* append(const item c){
//If the list is not empty...
if(length){
//maintain pointers to end nodes
node* old_last_node = last;
node* new_last_node = new node;
//re-assign the double link and exit link
old_last_node->next = new_last_node;
new_last_node->back = old_last_node;
new_last_node->next = NULL;
//re-assign the last pointer
last = new_last_node;
}
//If this is the first node
else{
//assign first and last to the new node
last = first = new node;
//assign nulls to the pointers on new node
first->next = first->back = NULL;
}
//increase length and exit
++length;
return last;
}
However, I think there is an issue, perhaps with the way C++ handles characters. When I go to print my list, somehow I never get the characters to print which I have appended to my list. This is what I'm using to print:
//Friendly output function
friend std::ostream& operator << (std::ostream& out_s, const doubly_linked_list& source_list){
//create iteration node pointer
node* traverse_position = source_list.first;
//iterate through, reading from start
for(int i = 1; i <= source_list.length; ++i){
//print the character
out_s << (traverse_position->data);
traverse_position = traverse_position->next;
}
//return the output stream
return out_s;
}
I just get crap when I print it. It prints characters that I never appended to my list - you know, just characters just from somewhere in the memory. What could possibly be causing this?
|
Where are you assigning the value c in the append() function? I fear you may have concentrated too much on the doubly-linked-list part and not enough on the storing-data part. :)
|
568,560
| 568,579
|
Possible memory leak?
|
Okay, so I have two classes, call them A and B--in that order in the code. Class B instantiates class A as an array, and class B also has an error message char* variable, which class A must set in the event of an error. I created a third class with a pure virtual function to set the errorMessage variable in B, then made B a child of that third class. Class A creates a pointer to the third class, call it C--when B initializes the array of A objects, it loops through them and invokes a function in A to set A's pointer to C-- it passes "this" to that function, and then A sets the pointer to C to "this," and since C is B's parent, A can set C->errorMessage (I had to do all this because A and B couldn't simultaneously be aware of each other at compile time).
Anyways it works fine, however, and when I pass command line parameters to main(int,char**), it works unless I pass seven, eight, or more than twelve parameters to it... I narrowed it down (through commenting out lines) to the line of code, in A, which sets the pointer to C, to the value passed to it by B. This made no sense to me... I suspected a memory leak or something, but it seems wrong and I have no idea how to fix it... Also I don't get why specifically seven, eight, and more than twelve arguments don't work, 1-6 and 9-12 work fine.
Here is my code (stripped down)--
//class C
class errorContainer{
public:
virtual ~errorContainer(){ }
virtual void reportError(int,char*)=0;
};
//Class A
class switchObject{
void reportError(int,char*);
errorContainer* errorReference;
public:
void bindErrorContainer(errorContainer*);
};
//Class A member function definitions
void switchObject::reportError(int errorCode,char* errorMessage){
errorReference->reportError(errorCode,errorMessage);
}
void switchObject::bindErrorContainer(errorContainer* newReference){
errorReference=newReference; //commenting out this line fixes the problem
}
//Class B
class switchSystem: public errorContainer{
int errorCode;
char* errorMessage;
public:
switchSystem(int); //MUST specify number of switches in this system.
void reportError(int,char*);
int errCode();
char* errMessage();
switchObject* switchList;
};
//Class B member function definitions
switchSystem::switchSystem(int swLimit){
int i;
switchList=new (nothrow) switchObject[swLimit];
for(i=0;i<swLimit;i++){
switchList[i].bindErrorContainer(this);
}
errorCode=0;
errorMessage="No errors.";
}
void switchSystem::reportError(int reportErrorCode,char* reportErrorMessage){
int len=0,i;
errorCode=reportErrorCode;
if(errorMessage){
delete[] errorMessage;
}
while(reportErrorMessage[len]!='\0'){
len++;
}
errorMessage=new char[len];
for(i=0;i<=len;i++){
errorMessage[i]=reportErrorMessage[i];
}
}
int switchSystem::errCode(){
return errorCode;
}
char* switchSystem::errMessage(){
return errorMessage;
}
Anyone know what I've done wrong here?
It's bugging the crap out of me... I can't seem to fix it.
---EDIT---
okay, I have it set up the way I do so that I can use it like this in main()
int main(int argc,char** argv){
switchSystem sw (2)
sw.switchList[0].argumentCount=2;
sw.switchList[1].argumentCount=0;
sw.switchList[0].identifier="a";
sw.switchList[1].identifier="switch";
sw.init(argc,argv);
if(sw.errCode()>0){
cout<< "Error "<< sw.errCode()<< ": "<< sw.errMessage()<< endl;
}
}
this program is supposed to read the command line arguments and handle user defined "switches"--like how most command line programs handle switches, but instead of testing for all of them at the beginning of main I wanted to try to write a class and some functions to do it for me--create a switchSystem object with the number of switches, set their identifiers, whether or not they take arguments, and then pass the command line arguments to "init()" to sort it out. Then test like, if(sw.isSet("switch")){ ... } etc.
|
reportError() should be declared virtual in switchSystem, as it is in errorContainer.
char* should instead be std::string to avoid all of that needless work.
Is there some reason that you can't use an std::vector<switchObject> instead of new[]?
You shouldn't delete[] errorMessage when it points to a static literal string. This leads to undefined behavior. (Translation: Bad Thing(TM).)
Why are you iteratively counting and copying the contents of a char*? This is begging for trouble. You're not doing anything to protect yourself from harm.
Why must switchObject pass a string to switchSystem? Wouldn't it be better to simply return an error code or throw some class derived from std::exception? Or perhaps it should send a string to a global logging facility?
I think perhaps you should rethink your design instead of trying to fix this.
|
568,596
| 568,627
|
Simple Makefile Problem (with a simple dependency)
|
I have 4 '.cpp' files and 1 header files:
Tools.cpp
Code1.cpp
Code2.cpp
Code3.cpp
and Tools.hh
Now all Code1.cpp, Code2.cpp, Code3.cpp
use functions stored in Tools.cpp.
Currently, what I do to compile all of them is using
this simple shell script:
#!/bin/bash
echo "compiling Code1.cpp";
g++ Code1.cpp Tools.cpp -o Code1
echo "compiling Code2.cpp";
g++ Code2.cpp Tools.cpp -o Code2
echo "compiling Code3.cpp";
g++ Code3.cpp Tools.cpp -o Code3
It all works fine.
Now I want to do that using a standard makefile.
But why this doesnt' work:
CXX = g++
TOOLSRC = Tools.cpp Code1.cpp Code2.cpp \
Code3.cpp
TOOLSINC = Tools.hh
all: Code1 Code2 Code3
Code1: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
Code2: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
Code3: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
The error I got is this:
ld: warning in makefile, file is not of required architecture
ld: duplicate symbol neighbors(std::vector<int, std::allocator<int> >&, int, int)in /var/folders/Yx/YxKmmyVPGpakdPL4St7X6++++TI/-Tmp-//ccQCrGHe.o and /var/folders/Yx/YxKmmyVPGpakdPL4St7X6++++TI/-Tmp-//ccreq9YU.o
collect2: ld returned 1 exit status
make: *** [FindNeighbours] Error 1
How can I correct the mistakes?
|
In these targets:
Code1: $(TOOLSRC) $(TOOLSINC) makefile
$(CXX) $^ -o $@
The resulting command will be:
g++ Tools.cpp Code1.cpp Code2.cpp Code3.cpp Tools.hh makefile -o Code1
This is clearly not what you want. g++ is attempting to compile both the header file and the makefile and doesn't know what to do with the makefile. You're also declaring dependencies on all three of your main units for each unit. So if Code3.cpp changes, Code1 will require recompilation. This is also undesirable.
Try something like this instead:
CXX = g++
all: Code1 Code2 Code3
%.o: %.cpp
$(CXX) $(CXXFLAGS) -c -o $@ $^
Code1: Code1.o Tools.o
$(CXX) -o $@ $^
Code2: Code1.o Tools.o
$(CXX) -o $@ $^
Code3: Code1.o Tools.o
$(CXX) -o $@ $^
|
568,668
| 568,688
|
What's your favorite g++ option?
|
I am a newbie in C++ programming.
When compiling I never use any option.
This is my day to day command:
g++ MyCode.cc -o MyCode
For safety practice what's the best option
to use?
|
g++ -W -Wall -Werror
Will display all errors and warnings possible and treat them as errors.
|
568,804
| 568,817
|
Do you have any good advice/links to a set of coding standards or best practices to follow?
|
For those of us that have programmed enough I’m sure we have come across many different flavours of coding standards that you can use when it comes to programming.
e.g. http://msdn.microsoft.com/en-us/library/ms229042.aspx
You might derive your coding standards for the current company you work for or from the original author of the code you’re working on. Coding styles are often used for specific program languages and some styles in one coding language might not be considered appropriate for others. Of course some coding standards can be applied across many different program languages.
Thank you for your time.
EDIT: As we know there are many related articles on this subject, but C# Coding standard / Best practices in SO has some very useful links in there which is worth a visit. (Check out the 2 links on .NET/C# guidelines by ESV - Accepted Answer)
|
Google has a posted style guide for C++ here which I consult sometimes. Just reading through the explanations and reasoning, despite whether you end up agreeing with some of the styles or not, may teach you some things you might not have thought about.
|
569,073
| 569,125
|
C++ std::map of template-class values
|
I'm attempting to declare a Row and a Column class, with the Row having a private std::map with values pointing to a templated Column. Something like this:
template <typename T> class DataType {
private:
T type;
};
template <typename T> class Field {
private:
T value;
DataType<T> type;
};
class Row {
private:
std::map<unsigned long,Field*> column;
};
Well, I suppose in principle the Row class shouldn't have to know which kind of Field (or Column) we'd like to use, i.e. whether it's a Field<int> in column 1 or a Field<double> in column 2. But I'm not sure what's the correct syntax for the Row::column declaration, or if the std::map is limited in this sense and I should be using something else.
I appretiate you suggestions and thank you for them in advance.
|
Field alone is not a type, but a template which can generate a family of types, such as Field<int> and Field<double>. All these fields are not related such that the one is somehow derived from the other or such. So you have to establish some relation between all these generated types. One way is to use a common non-template base class:
class FieldBase { };
template <typename T>
class Field : public FieldBase {
private:
T value;
DataType<T> type;
};
class Row {
private:
std::map<unsigned long,FieldBase*> column;
};
And consider using smart pointer instead of that raw pointer in the code. Anyway, now the problem is that the type-information is lost - whether you point to a Field<double> or to a Field<int> is not known anymore and can only be detected by keeping some sort of type-flag in the base which is set by the templated derived class - or by asking RTTI using
dynamic_cast<Field<int>*>(field) != 0
But that's ugly. Especially because what you want there is a value semantic. I.e you would want to be able to copy your row, and it would copy all the fields in it. And you would want to get a double when a double is stored - without first using RTTI to hack your way to the derived type.
One way of doing it is to use a discriminated union. That is basically an union for some arbitrary types and in addition a type-flag, which stores what value is currently stored in that field (e.g whether a double, int, ...). For example:
template <typename T>
class Field {
private:
T value;
DataType<T> type;
};
class Row {
private:
std::map<unsigned long,
boost::variant< Field<int>, Field<double> > >
column;
};
boost::variant does all the work for you. You can use visitation to make it call a functor using the right overload. Have a look at its manual
|
569,110
| 569,151
|
Why is memory still accessible after std::map::clear() is called?
|
I am observing strange behaviour of std::map::clear(). This method is supposed to call element's destructor when called, however memory is still accessible after call to clear().
For example:
struct A
{
~A() { x = 0; }
int x;
};
int main( void )
{
std::map< int, A * > my_map;
A *a = new A();
a->x = 5;
my_map.insert( std::make_pair< int, *A >( 0, a ) );
// addresses will be the same, will print 5
std::cout << a << " " << my_map[0] << " " << my_map[0]->x << std::endl;
my_map.clear();
// will be 0
std::cout << a->x << std::endl;
return 0;
}
The question is, why is variable a still accessible after its destructor was called by map::clear()? Do I need to write delete a; after calling my_map.clear() or is it safe to overwrite the contents of a?
Thanks in advance for your help,
sneg
|
std::map does not manage the memory pointed to by the pointer values - it's up to you to do it yourself. If you don't want to use smart pointers, you can write a general purpose free & clear function like this:
template <typename M> void FreeClear( M & amap )
for ( typename M::iterator it = amap.begin(); it != amap.end(); ++it ) {
delete it->second;
}
amap.clear();
}
And use it:
std::map< int, A * > my_map;
// populate
FreeClear( my_map )
;
|
569,481
| 569,556
|
Platform-independent concurrent programming libraries for C++
|
I am familiar with concurrent programming in Java which provides a lot of tools for this. However, C++ concurrent programming isn't so easy to start using.
What is the best way to start programming concurrently on C++? Are there any nice libraries which wrap concurrent programming primitives and provide you with more high-level constructs?
I tried QtConcurrent which provides you with nice MapReduce functionality but it is heavily biased towards concurrent computation using Qt so it's not a good choice if you don't want to use Qt.
Are there any other similar libraries? What do people use here?
Thanks for your help in advance,
sneg
|
There are several choices:
ACE which provides some concurrency constructs
Intel Threading Building Blocks
boost::threads
OpenMP
Qt Threading libraries
|
569,950
| 589,883
|
What causes Visual Basic Run-time error -2147319765 (8002802b) in Excel when an ActiveX control has been instanced?
|
I have created an ActiveX control using C++. I use Visual Basic code to instance the control in an Excel worksheet. I can only run the VB script once, subsequent runs cause the following runtime error when attempting to access the 'ActiveSheet' variable:
Microsoft Visual Basic
Run-time error '-2147319765 (8002802b)':
Automation error
Element not found
I am trying to work out what causes this error and how I can fix it?
As an experiment I tried creating a simple ActiveX control generated by Visual Studio wizards (in both VS 2005 & 2008). I didn't add or modify any code in this test case. The simple test case still causes this error.
Other ActiveX controls in the system don't cause this error (eg I tried instancing 'Bitmap Image') from VB code.
This is the VB code (a macro that I recorded, but hand-coded VB has the same issue):
Sub Macro1()
ActiveSheet.OLEObjects.Add(ClassType:="test.test_control.1" _
, Link:=False, DisplayAsIcon:=False).Select
End Sub
Can anyone give me an answer on this? Alternatively any pointers to resources that may help will be appreciated.
Thanks
|
After talking to Microsoft I found out the cause of the problem I was having.
When creating an ActiveX control using the VS 2005/2008 wizard you need to check the 'Connection points' check box in the 'Options' page. This adds, among other things, IConnectionPointContainerImpl as a base class for your ATL class, which in turn implements IConnectionPointContainer.
Failure to do this means that you can't insert your ActiveX control into an Excel document via Visual Basic more than once. The second time you execute the script you start getting the 'automation errors'.
The answer to the problem was simple enough and it worked, although I am still not sure how it actually relates to the 'automation error' and leaves me wondering why the error messages are not more informative.
|
570,669
| 570,694
|
Checking if a double (or float) is NaN in C++
|
Is there an isnan() function?
PS.: I'm in MinGW (if that makes a difference).
I had this solved by using isnan() from <math.h>, which doesn't exist in <cmath>, which I was #includeing at first.
|
According to the IEEE standard, NaN values have the odd property that comparisons involving them are always false. That is, for a float f, f != f will be true only if f is NaN.
Note that, as some comments below have pointed out, not all compilers respect this when optimizing code.
For any compiler which claims to use IEEE floating point, this trick should work. But I can't guarantee that it will work in practice. Check with your compiler, if in doubt.
|
570,693
| 570,717
|
Does using boost pointers change your OO design methodology?
|
After switching from C++ to C++ w/boost, do you think your OOD skills improved?
Do you notice patterns in "Normal" C++ code that you wouldn't consider that you've switched, or do you find that it enables a more abstract design?
I guess I'm really wondering if you just use it as a tool, or if you change your entire approach to OO design to make more efficient use of objects when using boost pointers.
Edit:summary
This question was kind of strange--I was asking because I've run into so much C++ code that was not at all OO. I'm fairly sure (with that and my work on it before moving to a managed language) that it's harder to think in OO in C++ than a managed language.
From looking at these posts, I'm guessing that you learn the value of OO before finding a need for a better way to manage memory, so by the time you start looking for something like Boost, you're already using OO methodologies pretty heavily.
I was kind of expecting a bunch of answers saying that it helped them think in OO, but now that I think about it, if you aren't using OO, boost pointers are not very helpful, and you wouldn't see the need for them (so you wouldn't have replied).
|
In a project in C++ I was doing about six years ago, we implemented our own boost-like automatic pointer scheme. It worked pretty well, except for the various bugs in it. (Sure wish we had used boost...)
Nonetheless, it really didn't change how we developed code. Object oriented design, with or without managed pointers, is very similar. There's times when you need to return objects, or times when pointers to objects are more important. The nice thing about smart pointers has only a small amount to do with how you design your application. Instead of passing a potentially dangerous memory leak around, you can pass that same data and be fairly certain that it's not going to leak.
In that respect, there are some things you can tend to do more with smart pointers: simplify your code. Instead of returning integers or basic structures every where, you can more freely pass complicated data structures or classes without worry. You can build more complex apps, faster, without having to worry so much. It lets you have the raw power of C and C++ when you need it (why would you be using C or C++ if you didn't need it?) and have the ease of memory management that's such an amazing productivity boost. If automatically managed memory wasn't useful, it wouldn't be in almost every other language on the planet!
|
571,359
| 571,397
|
how do I set the proper initial locale for a C++ program on Windows?
|
I'm fairly new to localized programming, and I'm trying to figure out how to set the proper initial locale for a newly-launched unmanaged C++ application (from within the app).
As far as I can tell, new applications start with the C locale, rather than the proper regional locale (English, German, etc). So what I need to do is call setlocale( LC_ALL, "???" ), but I'm not sure how to get the correct value for the second argument. It will be something like "English" or "German:Germany" - basically whatever locale was set by the user via the Regional and Language Options control panel. Just to be clear, I'm not looking for how to format the locale string, I'm looking for the correct locale string for the computer where the app is running.
I'm guessing that there's some Win32 API that would give me this, or perhaps a registry key that would contain the proper value. Does anybody know what I should be doing?
|
setlocale() is C, not C++. I vaguely remember seeing interference between the two on VC6, but that was a bug. Normally, setlocale() affects the behavior of the C functions only.
In C++, localization is controlled by the std::locale class. By default, locale-sensitive operations use the global locale, which is obtained by default-constructing a locale object, and can be set with std::locale::global(const std::locale&).
Constructing a locale object with an empty string (std::locale("")) creates a locale corresponding to the program's environment.
At program startup, the global locale is the "C" or "Classic" locale. To set the global locale to the program's environment locale (which I guess is what you're asking), you thus write:
std::locale::global(std::locale(""));
For example, my regional settings are currently set to French(Canada). Running this:
int main(void)
{
std::cout << std::locale().name() << std::endl;
std::locale::global(std::locale(""));
std::cout << std::locale().name() << std::endl;
std::locale::global(std::locale("C"));
std::cout << std::locale().name() << std::endl;
return 0;
}
prints:
C
French_Canada.1252
C
|
571,394
| 571,405
|
How to find out if an item is present in a std::vector?
|
All I want to do is to check whether an element exists in the vector or not, so I can deal with each case.
if ( item_present )
do_this();
else
do_that();
|
You can use std::find from <algorithm>:
#include <algorithm>
#include <vector>
vector<int> vec;
//can have other data types instead of int but must same datatype as item
std::find(vec.begin(), vec.end(), item) != vec.end()
This returns an iterator to the first element found. If not present, it returns an iterator to one-past-the-end. With your example:
#include <algorithm>
#include <vector>
if ( std::find(vec.begin(), vec.end(), item) != vec.end() )
do_this();
else
do_that();
|
571,568
| 571,589
|
Is there a way to include a header in every compilation unit without modifying every source file?
|
Given the following:
large project with thousands of C++ source files
no common header file (no one header that's included in every source file)
said project is compiled with g++ and managed by make
Is there any way to include a definition (e.g. macro) into every compilation unit without modifying every source file to include a new header file?
|
From man gcc:
-include file
Process file as if "#include "file"" appeared as the first line of
the primary source file. However, the first directory searched for
file is the preprocessor's working directory instead of the directory
containing the main source file. If not found there, it is
searched for in the remainder of the "#include "..."" search chain
as normal.
If multiple -include options are given, the files are included in
the order they appear on the command line.
|
571,652
| 571,728
|
What is the best way to handle multiple object dependencies in C++?
|
I'm building a C++ application, and I've got several utility objects that all of my classes need to use. These are things like the logging object, the global state object, the DAL object, etc...
Up until this point, I've been passing all of these objects around as references into my class constructors.
For example:
class Honda : public Car
{
public:
Honda ( const GlobalState & state,
const Log & logger,
const DAL & dal );
...
private:
const GlobalState & my_state;
const Log & my_logger;
const DAL & my_dal;
}
This gets tedious fast, because each time I add a utility object that all of my classes need to access, I have to go and change the constructors everywhere.
I've heard that the correct way to solve this problem is to create one struct that contains all the different utility objects and pass that around (as a reference) to all of the objects that need to access it.
Is this the right way to handle this problem? Thanks!
UPDATE: Thank you to everyone for the feedback. After some additional research, I've decided to continue using Dependency Injection.
|
You could make use of the Service Locator pattern. This article introduces both dependency injection (which you are currently using) and service locator.
However, consider this: the idea of dependency injection is to have a system where each component has a well-defined responsibility and minimizes knowledge of other components where possible. If the component needs other components to do its job, then these are explicitly passed to it. This makes the component simpler to understand, more likely to be correct, and easier to maintain.
If you regularly need to add components which need to be known throughout the system, then there may be something wrong with the design of the system (or the way new features are being added to it). The dependency injection pattern just results in this problem being explicitly visible.
|
571,799
| 572,012
|
Exporting functions from C++ dll to C# P/Invoke
|
I have built a C++ dll that I would like to call from C# code. I'm able to call one function, but the other throws an exception when the C# code tries to load the dll.
The header looks like this:
extern "C" __declspec(dllexport) BOOL Install();
extern "C" __declspec(dllexport) BOOL PPPConnect();
This produces a dll with slightly confusing exports table (what does foo = foo mean in the name field?):
File Type: DLL
Section contains the following exports for PPPManager.dll
00000000 characteristics
499F44F0 time date stamp Fri Feb 20 16:04:00 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 000078E4 Install = Install
2 1 000079DC PPPConnect = PPPConnect
My P/Invoke declarations look like this:
[DllImport("PPPManager.dll")]
private static extern bool Install();
[DllImport("PPPManager.dll")]
private static extern bool PPPConnect();
The call to Install returns with no exception, but when I call PPPConnect, I get a MissingMethodException - "Can't find an Entry Point 'PPPConnect' in a PInvoke DLL 'PPPManager.dll'."
I've tried removing the extern and declspec directives from the Install function declaration, so that PPPConnect is the only function exported, and this still doesn't let me call PPPConnect.
I have also tried doing the DllImport by ordinal; this gives the same result as calling by name - Install returns, but PPPConnect throws the exception "Can't find an Entry Point '#2'...".
The interop log gives:
[pinvokeimpl][preservesig]
bool invivodata.Common.System.IPAQUtils::Install();
BOOLEAN (I1_WINBOOL_VAL) Install();
JIT ERROR FOR PINVOKE METHOD (Managed -> Native):
[pinvokeimpl][preservesig]
bool invivodata.Common.System.IPAQUtils::PPPConnect();
BOOLEAN (I1_WINBOOL_VAL) PPPConnect();
This is well outside my area of expertise, so any suggestions or thoughts would be welcome.
Thanks,
Paul
edit:
It turns out that this code does work; the problem was with the latest dll not being propagated to the device. D'oh!
|
Are you using a .def file in your dll project to export those functions? If so, remove it and try again. This is just a guess because it looks like your exports are not what they should be when you do an extern "C" declspec(dllexports).
I tried this out with a simple C++ dll using
extern "C" __declspec(dllexport) BOOL Install();
extern "C" __declspec(dllexport) BOOL PPPConnect();
and a simple C# app using your PInvoke declarations and it worked fine.
When I did a dumpbin/exports on the dll I saw:
Dump of file PPPManager.dll
File Type: DLL
Section contains the following exports for PPPManager.dll
00000000 characteristics
499F6C2D time date stamp Fri Feb 20 20:51:25 2009
0.00 version
1 ordinal base
2 number of functions
2 number of names
ordinal hint RVA name
1 0 000110CD Install = @ILT+200(_Install)
2 1 00011069 PPPConnect = @ILT+100(_PPPConnect)
Notice that the exported names are different in my case.
|
571,890
| 571,899
|
container for quick name lookup
|
I want to store strings and issue each with a unique ID number (an index would be fine). I would only need one copy of each string and I require quick lookup. I check if the string exist in the table often enough that i notice a performance hit. Whats the best container to use for this and how do i lookup if the string exist?
|
I would suggest tr1::unordered_map. It is implemented as a hashmap so it has an expected complexity of O(1) for lookups and a worst case of O(n). There is also a boost implementation if your compiler doesn't support tr1.
#include <string>
#include <iostream>
#include <tr1/unordered_map>
using namespace std;
int main()
{
tr1::unordered_map<string, int> table;
table["One"] = 1;
table["Two"] = 2;
cout << "find(\"One\") == " << boolalpha << (table.find("One") != table.end()) << endl;
cout << "find(\"Three\") == " << boolalpha << (table.find("Three") != table.end()) << endl;
return 0;
}
|
572,255
| 572,264
|
Why should/shouldn't I use the "new" operator to instantiate a class, and why?
|
I understand that this may be construed as one of those "what's your preference" questions, but I really want to know why you would choose one of the following methods over the other.
Suppose you had a super complex class, such as:
class CDoSomthing {
public:
CDoSomthing::CDoSomthing(char *sUserName, char *sPassword)
{
//Do somthing...
}
CDoSomthing::~CDoSomthing()
{
//Do somthing...
}
};
How should I declare a local instance within a global function?
int main(void)
{
CDoSomthing *pDoSomthing = new CDoSomthing("UserName", "Password");
//Do somthing...
delete pDoSomthing;
}
-- or --
int main(void)
{
CDoSomthing DoSomthing("UserName", "Password");
//Do somthing...
return 0;
}
|
Prefer local variables, unless you need the object's lifetime to extend beyond the current block. (Local variables are the second option). It's just easier than worrying about memory management.
P.S. If you need a pointer, because you need it to pass to another function, just use the address-of operator:
SomeFunction(&DoSomthing);
|
572,684
| 572,766
|
Conditional Inclusion/Exclusion of Data Members Inside Class Templates
|
I want to optimize my Vector and Matrix classes (which are class templates to be exact) using SIMD instructions and compiler intrinsics. I only want to optimize for the case where the element type is "float". Using SIMD instructions requires touching the data members. Since I don't want to be bothered with the trouble of maintaining two separate classes, I want to be able to enable/disable some data members based on the type of the template parameter. Another advantage of this approach, in case it's applicable, is that I can use the same code from the general case for functions that I don't want to write a specialization for. Therefore, what I want to achieve in pseudo code is:
template< typename T >
class Vector3 {
if type( T ) == float:
union {
__m128 m128;
struct {
float x, y, z, pad;
};
};
else
T x, y, z;
endif
};
I know conditional inclusion of members functions is possible via the use of Boost.enable_if or similar facilities. What I'm looking for though, is conditional inclusion of data members. As always, your help is very much appreciated. Other valid suggestions are also welcome.
Thanks.
|
One solution that springs to mind is partially specialized templates, which is what Martin York posted, but with a twist.
I would recommend a special content_type-struct to supply the layout type, like so:
// content for non float types
template<typename T>
struct content_type {
typedef typename T member_type;
member_type x,y,z;
member_type& X { return x; }
// ...
// if access to optional members is needed, better use CT_ASSERT or similar
member_type& Pad { char assert_error_no_pad_here[0]; }
};
// content for float types
struct content_type<float> {
typedef typename float member_type;
member_type x, y, z, pad;
member_type& X { return x; }
// ...
member_type& Pad { return pad; }
};
template<typename T>
class Vector3 {
typedef typename content_type<T> layout_type;
typedef typename content_type<T>::member_type member_type;
layout_type _content;
public:
member_type& X { return _content.X(); }
memmber_type& Pad { return _content.Pad(); }
};
// or maybe, if memory layout is not important, just inherit (watch for virtual members)
template<typename T>
class Vector3 : public content_type<T> {
typedef typename content_type<T> layout_type;
typedef typename content_type<T>::member_type member_type;
};
The advantage is you only have to write Vector3 with all of its logic once.
You need a moderately recent compiler to do that correctly, though (MSVC>7, gcc>3)
|
572,685
| 572,705
|
In what scenarios should one declare a member function a friend?
|
In what kind of scenarios would we declare a member function as a 'friend function' ?..What exact purpose does 'friend function' which defies one of central concept of 'Encapsulation' of OOP serve?
|
You would use a friend function for the same sort of reasons that you would use a friend class, but on a member function (rather than entire class) basis. Some good explanations are in this thread.
While friend functions and classes do violate encapsulation, they can be useful in some scenarios. For example, you may want to allow a test harness to access class internals to allow you to do whitebox testing. Rather than opening up the entire class to the test harness, you could open up a particular function which accesses the internals required by the test harness. While this still violates encapsulation, it's less risky than opening up the entire class.
Also see this article for some more information about friend classes and functions.
|
572,734
| 572,822
|
Infile Handle in C++ (ala __DATA__ in Perl)
|
Does C++ have access to infile data through a filehandle? For example the typical idiom in Perl is:
while (<DATA>) {
chomp;
# do sth with $_
}
__DATA__
Foo
Bar
What's the way to do that in C++ ?
|
I wouldn't say it's idiomatic as I've never seen it in any C++ code, but you can use C++ string stream and C pre-processor string pasting to treat a multi-line string as an input stream:
#include <sstream>
#include <iostream>
using namespace std;
const string data =
"once upon a time, " \
"a young lass called Goldilocks\n" \
"went for a walk in the forest.\n";
int main ()
{
istringstream in (data);
for (string line; getline(in, line); )
cout << line << endl;
return 0;
}
|
572,831
| 572,841
|
Problem transmitting null character over sockets
|
I am writing a small Java server, and a matching client in C++, which implement a simple IM service over the STOMP protocol.
The protocol specifies that every frame (message that passes between server and client, if you will) must end with a null character, which in code I refer to as '\0', both in Java and in C++.
However, when I transmit a frame over TCP via sockets, the null character simply does not show up, on either side. I am working with UTF-8 encoding, and tried switching to ASCII, didn't help.
What am I doing wrong?
|
Wether you are encoding text in ASCII or UTF-8, you convert your "letters" to a stream of bytes (byte encodings). You need to add a ZERO byte to the end of the message strings.
[Guessing] You may be using a high-level library with a method like "WriteLine(String line)" to send the data over the network. The documentation for that method with describe what bytes are actually sent, which typically includes the message text encoding in the current encoding (ASCII, UTF-8, etc) followed by a line termination sequence, which is typically either the byte 13, 10m or a combination of them ('\n', '\r\n').
Use the low-level Write() method or WriteBytes() method (depending on your libraries). Convert the text to ASCII or UTF-8, add the zero byte to the end, and send exactly what you want to send.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.