question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
1,149,594 | 1,149,705 | get static int variable class name with typeid(*this).name for its own definition - C++ | When I need to get the class name inside of one of its methods I just call:
typeid(*this).name()
(then I split the result into tokens and get the class name)
Now I have to define a static member variable and need to get the class name for that.
But I`m not in a method!
So, I cannot use (*this).
Initially, I thought I could do something like:
#define INIT_STAT_VAR
const char * cname = typeid(*this).name;
int cname##::var = 1;
Any idea how I could get the class name for the static member variable definition?
( no, I cannot just write the name of the class directly for the definition ;] )
thanks!
| I don't think it is directly possible to do what you want - as a static method doesn't get an object pointer it can't call typeid on it. You could create a temporary object in the static method and use that on typeid, but that pretty much goes against having it as a static method.
Another solution (if you can guarantee that at least 1 instance of the class is defined) would be to create a static member variable which you initialise once in the Constructor, and then access from a static method. It's a little hacky, but works:
#include <typeinfo>
#include <string>
class Foo {
public:
Foo() {
if (name == NULL) {
const std::type_info& id = typeid(*this);
name = new std::string(id.name());
}
// Normal object creation.
}
static std::string getName() { return *name; }
private:
static std::string* name;
};
std::string* Foo::name = NULL;
|
1,149,620 | 1,149,622 | How to write to the Output window in Visual Studio? | Which function should I use to output text to the "Output" window in Visual Studio?
I tried printf() but it doesn't show up.
| OutputDebugString function will do it.
example code
void CClass::Output(const char* szFormat, ...)
{
char szBuff[1024];
va_list arg;
va_start(arg, szFormat);
_vsnprintf(szBuff, sizeof(szBuff), szFormat, arg);
va_end(arg);
OutputDebugString(szBuff);
}
|
1,149,697 | 1,349,710 | managed c++ find and replace syntax | I'm building an isapi filter that will grab any url requests with the prefix "http://localhost/" and redirect that url request to my message page "http://localhost/default.html."
Here's the solution:
if(urlString.Find("/") != -1)
{
urlString.Replace(urlString, "/default.html");
| the answer is: if(urlString.Find("/") != -1) { urlString.Replace(urlString, "/default.html");
|
1,149,801 | 1,150,227 | Check for update (compare remote XML file with a local variable) | I have an InnoSetup for my C# application. And I'd like the setup to check for updates before installing (to make sure the user always gets the latest version). To do this, I need a bit of C++ code to parse an xml file from a remote location (which contains a version string) and have a method return it.
From InnoSetup I can call the DLL and compare it to a local variable in the InnoSetup code.
Any clues on how to do this?
| If you have access to the server side, it might be better to not use XML, just return version string. If you can't avoid XML, you should write your C++ code (if that's you question, I suggest using TinyXML), then create a dll export for a function returning the version string.
|
1,149,826 | 1,149,840 | Get actual folder path | How I can get actual folder path where my program is without my exe file name in C++?
| The following function will give you the application path:
::GetModuleFileName(NULL, szAppPath, MAX_PATH);
Now to extract the folder, you need to find the last backslash:
char szApplicationPath[MAX_PATH] = "";
::GetModuleFileName(NULL, szApplicationPath, MAX_PATH);
//Get the folder part
CString strApplicationFolder;
strApplicationFolder = szApplicationPath;
strApplicationFolder = strApplicationFolder.Left(strApplicationFolder.ReverseFind("\\"));
|
1,149,856 | 1,150,853 | Choosing a 3D game engine | I want to start this as a hobby in developing a desktop game. I have found several engines, but I am not sure whether it does the initial job I am looking at.
Initially I want to do the following:
Create a figure (avatar), and let the user dress the avatar
Load the avatar in the game
In later stages, I want to develop this as a multi-player game.
What should I do?
| I also recommend Ogre. Ogre can do this, it provides everything needed in regards of mesh and animation support, but not as a drop-in solution. You have to write lots of code for this to be done.
For our project we implemented something like you do. The main character and any other character can be dressed with different weapons and armor and the visuals of the character avatar change accordingly.
As a start hint for how to go about this: In your modeling tool (Blender, Maya, 3ds max, etc.) you model your avatar and all its clothes you need and rig them to the same skeleton. Then export everything individually to Ogre's mesh format.
At runtime you can then attach the clothing meshes the user chooses to the skeleton instance so that they together form the avatar. This is not hard to do via Ogre-API, but for even easier access to this you can use MeshMagick Ogre extension's meshmerge tool. It has been developed for exactly this purpose.
If you want to change other characteristics like facial features, this is possible too, as Ogre supports vertex pose animations out of the box, so you can prepare pathes for certain characteristics of the face and let the user change the face by sliders or somthing like this. (e.g like in Oblivion)
One thing to be aware regarding Ogre: It is a 3d graphics engine, not a game engine. So you can draw stuff to the screen with it and animate and light and in any way change the visuals, but it doesn't do input or physics or sound. For this you have to use other libs and integrate them. Several pre-bundled game engines based on Ogre are available though.
|
1,149,919 | 1,149,925 | std::list<char> list_type to (char * data, int lenght) | I have some
std::list<char> list_type
Now I have to supply contents of the list as (char *data, int length). Is there convenient way to present list contents as pointer and length? Does <vector> has such interface?
Thank you in advance.
| You can do it with a vector, because its data is stored contiguously:
std::vector<char> vec;
char* data = &vec[0];
int length = static_cast<int>(vec.size());
For list, you have to copy the data to an array. Luckily, that too is fairly easy:
std::list<char> list:
int length = static_cast<int>(list.size());
char* data = new char[length]; // create the output array
std::copy(list.begin(), list.end(), data); // copy the contents of the list to the output array
Of course, you're then left with a dynamically allocated array you have to free again.
|
1,149,929 | 1,150,180 | How to add two numbers without using ++ or + or another arithmetic operator | How do I add two numbers without using ++ or + or any other arithmetic operator?
It was a question asked a long time ago in some campus interview. Anyway, today someone asked a question regarding some bit-manipulations, and in answers a beautiful quide Stanford bit twiddling was referred. I spend some time studying it and thought that there actually might be an answer to the question. I don't know, I could not find one. Does an answer exist?
| This is something I have written a while ago for fun. It uses a two's complement representation and implements addition using repeated shifts with a carry bit, implementing other operators mostly in terms of addition.
#include <stdlib.h> /* atoi() */
#include <stdio.h> /* (f)printf */
#include <assert.h> /* assert() */
int add(int x, int y) {
int carry = 0;
int result = 0;
int i;
for(i = 0; i < 32; ++i) {
int a = (x >> i) & 1;
int b = (y >> i) & 1;
result |= ((a ^ b) ^ carry) << i;
carry = (a & b) | (b & carry) | (carry & a);
}
return result;
}
int negate(int x) {
return add(~x, 1);
}
int subtract(int x, int y) {
return add(x, negate(y));
}
int is_even(int n) {
return !(n & 1);
}
int divide_by_two(int n) {
return n >> 1;
}
int multiply_by_two(int n) {
return n << 1;
}
int multiply(int x, int y) {
int result = 0;
if(x < 0 && y < 0) {
return multiply(negate(x), negate(y));
}
if(x >= 0 && y < 0) {
return multiply(y, x);
}
while(y > 0) {
if(is_even(y)) {
x = multiply_by_two(x);
y = divide_by_two(y);
} else {
result = add(result, x);
y = add(y, -1);
}
}
return result;
}
int main(int argc, char **argv) {
int from = -100, to = 100;
int i, j;
for(i = from; i <= to; ++i) {
assert(0 - i == negate(i));
assert(((i % 2) == 0) == is_even(i));
assert(i * 2 == multiply_by_two(i));
if(is_even(i)) {
assert(i / 2 == divide_by_two(i));
}
}
for(i = from; i <= to; ++i) {
for(j = from; j <= to; ++j) {
assert(i + j == add(i, j));
assert(i - j == subtract(i, j));
assert(i * j == multiply(i, j));
}
}
return 0;
}
|
1,149,994 | 1,150,676 | std::list, std::vector methods and malloc() | Working with stl:list and stl::vector types under interrupt handlers I want to avoid malloc() calls.
The question: What is a best way to prevent malloc() calls in STL list and vector? Is it enough to create structure with predefined size and then avoid push/pop/erase calls?
Thank you in advance
| As a testimonial: we use two methods mentioned in other answers at my workplace:
custom allocators: for our memory leak tracking system, our instrumenting profiler, and a few other systems, we preallocate and/or "pool" (see e.g. boost::pool) allocs using a provided Allocator -- usually for std::set or std::map, but the principle is the same for std::list.
reserve/resize: for std::vectors, it's very common practice for us to reserve or resize (the difference is important, but both can help avoid future allocs) ahead of time.
Mostly we do these two things to avoid fragmentation, decrease allocator overhead, eliminate the copy-on-grow penalty, etc. But sometimes (especially with e.g. the instrumenting profiler) we want to absolutely avoid allocation during an interrupt handler.
Usually, however, we avoid issues with interrupts and allocations in other manners:
get in/get out: try to avoid doing anything other than setting flags or trivial copies during interrupts; some times a static (or preallocated) buffer is a far better solution than a STL container. Holding interrupts for too long is usually a recipe for disaster.
disable interrupts during alloc/free: interrupts are queued up while we're allocating/freeing, instead of being dispatched immediately -- it's a feature of the CPU we're working with. Combined with a policy of selectively increasing the scope of that disabling/queuing (around e.g. std::list manipulation), we can sometimes get away with a interrupt-handler-as-producer, everything-else-as-consumer model, without overriding the allocator. If we're in the middle of consuming something from a std::list (e.g. a message received from the network hardware), interrupts are queued for as short a period as possible while pop off a copy of what we're about to process.
Note that lock-free data structures could be an alternative to the second bullet here, we haven't set up and done profiling to see if it would help. Designing your own is tricky business anyway.
Paranoia is the better part of valor for interrupt handlers: if you're not certain what you're doing will work, it's sometimes much better to approach the issue in an entirely different manner.
|
1,150,072 | 1,150,077 | Install CDT Plug-In On Eclipse Ganymede | How i can install the CDT plug-in (that you can develop in C++ under Eclipse) in my Eclipse Ganymede, remember that I use Windows Vista. Thanks!
| Use this official guide: http://wiki.eclipse.org/Getting_started_with_CDT_development
|
1,150,373 | 1,155,092 | Compile the Python interpreter statically? | I'm building a special-purpose embedded Python interpreter and want to avoid having dependencies on dynamic libraries so I want to compile the interpreter with static libraries instead (e.g. libc.a not libc.so).
I would also like to statically link all dynamic libraries that are part of the Python standard library. I know this can be done using Freeze.py, but is there an alternative so that it can be done in one step?
| I found this (mainly concerning static compilation of Python modules):
http://bytes.com/groups/python/23235-build-static-python-executable-linux
Which describes a file used for configuration located here:
<Python_Source>/Modules/Setup
If this file isn't present, it can be created by copying:
<Python_Source>/Modules/Setup.dist
The Setup file has tons of documentation in it and the README included with the source offers lots of good compilation information as well.
I haven't tried compiling yet, but I think with these resources, I should be successful when I try. I will post my results as a comment here.
Update
To get a pure-static python executable, you must also configure as follows:
./configure LDFLAGS="-static -static-libgcc" CPPFLAGS="-static"
Once you build with these flags enabled, you will likely get lots of warnings about "renaming because library isn't present". This means that you have not configured Modules/Setup correctly and need to:
a) add a single line (near the top) like this:
*static*
(that's asterisk/star the word "static" and asterisk with no spaces)
b) uncomment all modules that you want to be available statically (such as math, array, etc...)
You may also need to add specific linker flags (as mentioned in the link I posted above). My experience so far has been that the libraries are working without modification.
It may also be helpful to run make with as follows:
make 2>&1 | grep 'renaming'
This will show all modules that are failing to compile due to being statically linked.
|
1,150,464 | 1,150,750 | msvcr90d.dll not found in debug mode | I found MSVCR90D.dll not found in debug mode with Visual C++ 2008 question but none of given answers really gives answer to the question. Most of them point to turning off incremental linking but don't explain the true cause of the error and how it can be fixed without turning off incremental linking.
I'd like to mention that my situation is a little different than the one in the original question. I am using C++ compiler from Visual Studio 2008 but within Qt Creator not within Visual Studio.
Anyone?
| Below is output from compiler. It's strange that running build the second time succeeds. However I suspect the problem might be due to this error with running mt.exe which is responsible for embedding information from manifest into executable...
Generating Code...
link /LIBPATH:"c:\Qt\4.5.2-vc\lib" /NOLOGO /DEBUG /MANIFEST /MANIFESTFILE:"debug\formExtractor.intermediate.manifest" /SUBSYSTEM:WINDOWS "/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'" /OUT:debug\formExtractor.exe @.\nmD932.tmp
mt.exe -nologo -manifest "debug\formExtractor.intermediate.manifest" -outputresource:debug\formExtractor.exe;1
'mt.exe' is not recognized as an internal or external command,
operable program or batch file.
NMAKE : fatal error U1077: 'mt.exe' : return code '0x1'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\BIN\nmake.exe"' : return code '0x2'
Stop.
Exited with code 2.
UPDATE
Failing to run mt.exe during the linking process was indeed the cause of the problem. I added path to Windows SDK (C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin) to the PATH environment variable and I'm able to run executable now.
Comments to various answers;
@Shay
Output txt file from sxstrace is empty. Have no idea why. However there's the following information in the application log:
Faulting application formExtractor.exe, version 0.0.0.0, time stamp 0x4a638ee1, faulting module MSVCR90D.dll, version 6.0.6002.18005, time stamp 0x49e03824, exception code 0xc0000135, fault offset 0x0006f04e, process id 0xf68, application start time 0x01ca08ba801ac5cf.
Version 6.0.6002.18005?
What the heck is this?
@Kirill V. Lyadvinsky
Dependency Walker finds msvcr90d.dll used by qtwebkit4.dll file in
c:\windows\winsxs\x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb\MSVCR90D.DLL
but doesn't find (the other version of?) msvcr90d.dll file linked directly by the executable. However DW doesn't seem to show it's version anywhere, does it?
Contest of formExtractor.intermediate.manifest file
<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
<assembly xmlns='urn:schemas-microsoft-com:asm.v1' manifestVersion='1.0'>
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security>
<requestedPrivileges>
<requestedExecutionLevel level='asInvoker' uiAccess='false' />
</requestedPrivileges>
</security>
</trustInfo>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*' />
</dependentAssembly>
</dependency>
<dependency>
<dependentAssembly>
<assemblyIdentity type='win32' name='Microsoft.VC90.DebugCRT' version='9.0.21022.8' processorArchitecture='x86' publicKeyToken='1fc8b3b9a1e18e3b' />
</dependentAssembly>
</dependency>
</assembly>
From the manifest file it looks like the executable is being linked to a different version of msvcr90d.dll than the qtwebkit4.dll. What's strange is the fact that both versions of msvcr90d.dll are present in c:\windows\winsxs folder in the following sub folders
x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.21022.8_none_96748342450f6aa2
and
x86_microsoft.vc90.debugcrt_1fc8b3b9a1e18e3b_9.0.30729.1_none_bb1f6aa1308c35eb
Any ideas?
@knight666
I'm using Qt framework which I compiled using exactly the compiler I'm using now so I think there's no mismatch here. Additionally Dependency Walker shows the missing msvcr90d.dll file is linked directly to the executable so it's not a fault of any 3rd party library I think.
|
1,150,649 | 1,151,539 | trouble deleting keys/values on STL hash_map when duplicate keys | I am using C++ hash_map to store some C-style string pairs. And all keys should be unique for this case...
My problem is a serious memory leak when stress testing this over multiple runs.
When none of these keys in the test are not identical, there is no memory leak. But with identical keys its a different story...
The hash_map (this is Google's sparsehash but it implements the SGI functions entirely)
sparse_hash_map<const char*, char *, hash<const char*>, eqstr> values;
I searched and could not find a function to replace a key/val pair that has an identical key.
values[k]=v;
will only add a new pair, even if the key is the same. (a behavior I think should be toggleable) - this is nothing but a hash_map.insert()
So I have a function to check if the key exists, and if it does replace the val, and if not just add a new pair:
char *confFile::replaceOrStoreVal( char *k, char *v ) {
char *ret = NULL;
values.set_deleted_key(_DIST_KEY);
sparse_hash_map<const char*, char *, hash<const char*>, eqstr>::iterator it =
values.find(k);
if(it == values.end())
values[k] = v;
else {
// ret = it->second; // option 1
//it->second = v; // end option 1
//option 2
char *t = (char *) it->first;
ret = it->second;
values.erase( iter ); <--- seg fault here
free(t);
values[k] = v; // end option 2
}
return ret;
} ... and ret is later free()ed
initially pairs are added like this:
old = replaceOrStoreVal(recordname, value);
It crashes on the first duplicate key.
2 ways I have tried this. Option 1 results in a segfault on erase (something that also puzzles me). Option 2 just doesn't fix the problem, still have a memory leak. Maybe I am just doing this all wrong.
Yes, I know I could use C++ strings, but I don't want to. Trying to keep this real light, for an embedded system. Any help is appreciated...
| You can change a value directly inside hash_map through iterator:
ret = it->second;
it->second = v; // end option 2
}
It will be faster and safer solution.
You can also try another hash_map method to erase by key, not by iterator:
size_type erase(const key_type& k)
|
1,150,833 | 1,150,901 | What did QWidget* QApplication::mainWidget() become in Qt4? | I am porting an application from Qt3 to Qt4, and need a Qt4 replacement for QApplication::mainWidget() which used to return the top-level widget in Qt3. Does anyone know how to do this in Qt4?
| Technically, any widget initialized with NULL is a top level widget so QApplication shouldn't assume that one of them is better than another.
The way I usually do it is to save a pointer to the "real" main widget somewhere, even a global variable or a singleton and reference it when needed.
|
1,151,358 | 1,151,367 | Operator Overloading for Objects in Multiple Classes | So can you overload operators to handle objects in multiple classes (specifically private members.)
For example if I wanted == to check if a private member in Class A is equal to objects in a vector in Class B.
For example:
bool Book::operator==(const Book& check){
return(((ISBN1 == check.ISBN1) && (ISBN2 == check.ISBN2) && (ISBN3 == check.ISBN3)
&& (ISBN4 == check.ISBN4)) || (title_ == check.title_));}
Everything in that overload is part of the Book class, however what if I wanted to do something like this.
if(*this == bookcheckout[i])
with bookcheckout being part of a Library class. The == would fail in trying to compare title_ to a title_ stored in a vector of the Library class.
It's odd because I have the program doing the exact same thing in two different places, but in one place it's working and in the other it isn't.
Answered: had to have the function that the operator was in be a member function of the same class that the operator was a member function of
| If you make operator friend or member of one class, it will be able to access its private members. To access privates of both, operator will have to be free standing friend of both.
That is a bit unwieldy, so consider making public interface for interesting things instead.
(suppressed all puns about accessing private parts of multiple entities)
Here is how you can make a very friendly operator, but again, this is not a good solution.
(didn't compile the code)
class B;
class A
{
friend bool operator==(const A&, const B&);
private:
int private_;
};
class B
{
friend bool operator==(const A&, const B&);
private:
int private_;
};
bool operator==(const A& a, const B& b)
{
return a.private_ == b.private_;
} class B;
This is a better way -- just make public getters and use them in operator.
class A
{
public:
int GetPrivate() const { return private_; }
private:
int private_;
};
class B
{
public:
int GetPrivate() const { return private_; }
private:
int private_;
};
bool operator==(const A& a, const B& b)
{
return a.GetPrivate() == b.GetPrivate();
}
You also can make operator to be part of one of the classes, if you need privates from it alone.
Read up on operator overloading syntax for more.
|
1,151,582 | 1,151,638 | pthread function from a class | Let's say I have a class such as
class c {
// ...
void *print(void *){ cout << "Hello"; }
}
And then I have a vector of c
vector<c> classes; pthread_t t1;
classes.push_back(c());
classes.push_back(c());
Now, I want to create a thread on c.print();
And the following is giving me the problem below:
pthread_create(&t1, NULL, &c[0].print, NULL);
Error Output: cannot convert ‘void* (tree_item::*)(void*)’ to ‘void*
(*)(void*)’ for argument ‘3’ to ‘int pthread_create(pthread_t*, const
pthread_attr_t*, void* (*)(void*), void*)’
| You can't do it the way you've written it because C++ class member functions have a hidden this parameter passed in. pthread_create() has no idea what value of this to use, so if you try to get around the compiler by casting the method to a function pointer of the appropriate type, you'll get a segmetnation fault. You have to use a static class method (which has no this parameter), or a plain ordinary function to bootstrap the class:
class C
{
public:
void *hello(void)
{
std::cout << "Hello, world!" << std::endl;
return 0;
}
static void *hello_helper(void *context)
{
return ((C *)context)->hello();
}
};
...
C c;
pthread_t t;
pthread_create(&t, NULL, &C::hello_helper, &c);
|
1,151,680 | 1,151,740 | C++ Auto Class Implementation in Editor | Much of my time spent developing C++ applications is wasted implementing class definitions. By that I mean the prototyping of classes then creating their respective implementations.
For example:
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const X& x, const Y& Y);
~Foo ();
void PerformXYZ (int Count);
};
#endif
And now I'll have to copy and paste, then add the repetitive Foo:: onto each function.
Foo::Foo (const X& x, const Y& Y)
{
}
Foo::~Foo ()
{
}
void Foo::PerformXYZ (int Count)
{
}
For now I copy the function declarations over to their respective *.cpp files, remove empty lines, then replace ';' with "\n{\n\n}\n". However, I still have to specify the namespace for each function.
Are there tools in Eclipse, Vim or any other IDE/editor that take this burden off a developer?
| In Visual Studio there are tools to add functions and variable. Tools automates the process in question. But I never use them :)
In the Visual Assist X there is the feature that helps to add implementation for methods. It is the best solution.
|
1,151,777 | 1,151,793 | Fast Bitwise Question in C++ | I'm looking for a fast way to setup a method of returning a bitmask based on a number. Basically, 4 one bits need to be emitted pre number input. Here's a good idea of what I mean:
foo(1); // returns 0x000F
foo(2); // returns 0x00FF
foo(3); // returns 0x0FFF
foo(4); // returns 0xFFFF
I could just use a big switch statement, but I don't know how wide the input type is in advance. (This is a template function)
Here was the first thing I tried:
template <typename T> T foo(unsigned short length)
{
T result = 0xF;
for (unsigned short idx = length; idx > 0; idx--)
{
result = (result << 4 | 0xF);
}
return result;
}
but it spends a lot of time doing maintenence on the for loop. Any clever ways of doing this I've not thought of?
Billy3
| How about something like:
template <typename T> T foo(unsigned short length)
{
return (T(1) << (length * 4)) - 1;
}
|
1,151,787 | 1,152,672 | Is there any automated way to implement post-constructor and pre-destructor virtual method calls? | Due to the well-known issues with calling virtual methods from inside constructors and destructors, I commonly end up with classes that need a final-setup method to be called just after their constructor, and a pre-teardown method to be called just before their destructor, like this:
MyObject * obj = new MyObject;
obj->Initialize(); // virtual method call, required after ctor for (obj) to run properly
[...]
obj->AboutToDelete(); // virtual method call, required before dtor for (obj) to clean up properly
delete obj;
This works, but it carries with it the risk that the caller will forget to call either or both of those methods at the appropriate times.
So the question is: Is there any way in C++ to get those methods to be called automatically, so the caller doesn't have to remember to do call them? (I'm guessing there isn't, but I thought I'd ask anyway just in case there is some clever way to do it)
| The main problem with adding post-constructors to C++ is that nobody has yet established how to deal with post-post-constructors, post-post-post-constructors, etc.
The underlying theory is that objects have invariants. This invariant is established by the constructor. Once it has been established, methods of that class can be called. With the introduction of designs that would require post-constructors, you are introducing situations in which class invariants do not become established once the constructor has run. Therefore, it would be equally unsafe to allow calls to virtual functions from post-constructors, and you immediately lose the one apparent benefit they seemed to have.
As your example shows (probably without you realizing), they're not needed:
MyObject * obj = new MyObject;
obj->Initialize(); // virtual method call, required after ctor for (obj) to run properly
obj->AboutToDelete(); // virtual method call, required before dtor for (obj) to clean up properly
delete obj;
Let's show why these methods are not needed. These two calls can invoke virtual functions from MyObject or one of its bases. However, MyObject::MyObject() can safely call those functions too. There is nothing that happens after MyObject::MyObject() returns which would make obj->Initialize() safe. So either obj->Initialize() is wrong or its call can be moved to MyObject::MyObject(). The same logic applies in reverse to obj->AboutToDelete(). The most derived destructor will run first and it can still call all virtual functions, including AboutToDelete().
|
1,151,849 | 1,151,955 | Why does QGraphicsItem::scenePos() keep returning (0,0) | I have been toying with this piece of code:
QGraphicsLineItem * anotherLine = this->addLine(50,50, 100, 100);
qDebug() << anotherLine->scenePos();
QGraphicsLineItem * anotherLine2 = this->addLine(80,10, 300, 300);
qDebug() << anotherLine2->scenePos();
Where the this pointer refers to a QGraphicsScene. In both cases, I get QPointF(0,0) for both output.From reading the document, I thought scenePos() is supposed to return the position of the line within the scene, not where it is within its local coordinate system. What am I doing wrong?
| After reading the QT 4.5 documentation carefully on addLine, I realize what I have been doing wrong. According to the doc:
Note that the item's geometry is
provided in item coordinates, and its
position is initialized to (0, 0)
So if I specify addLine(50,50, 100, 100), I am actually modifying its local item coordinate. The assumption I made that it will be treated as a scene coordinate is wrong or unfounded. What I should be doing is this
// Create a line of length 100
QGraphicsItem * anotherLine = addLine(0,0, 100, 100);
// move it to where I want it to be within the scene
anotherLine->setPos(50,50);
So if I am adding a line by drawing within the scene, I need to reset its centre to (0,0) then use setPos() to move it to where I want it to be in the scene.
Hope this helps anyone who stumble upon the same problem.
|
1,152,000 | 1,152,003 | stringstream extraction not working | I seem to be having a problem with extracting data from a stringstream. The start of my extraction seems to be missing the first two characters.
I have something similar to the following code:
std::stringstream ss(
std::stringstream::in |
std::stringstream::out
);
bool bValid;
double dValue;
double dTime;
for( (int i = 0; i < 5; i++ )
{
bValid = getValid();
dValue = getValue();
dTime = getTime();
// add data to stream
ss << bValid;
ss << dValue;
ss << dTime;
}
int strsize = ss.str().size();
char* data = new char[strsize];
std::strcpy(data, ss.str().c_str());
// then do stuff with data
// ...... store data in an Xml Node as CDATA
// read data back
std::stringstream ssnew( std::stringstream in | std::stringstream out );
ss.clear();
ss << getCharData(); // returns a char* and puts it in stream.
for( int i = 0; i < 5; i++ )
{
ssnew >> bValid; // do something with bValid
ssnew >> dValue; // do something with dValue
ssnew >> dTime; // do something with dTime
}
I am having a problem that when I use the extraction operator when reading data from "ssnew" it seems to skip the first two characters. In the debugger, for example, it is showing that the stringstream has "001.111.62.2003... etc". However, after the first "ssnew >> bValid" bValid becomes "true" and dValue becomes "0.111" and dTime becomes "0.62" indicating that the first two zeros in the stream are being ignored. Why isn't it starting at the beginning of the stream?
Cheers,
Seth
| Try:
// add data to stream
ss << bValid << " ";
ss << dValue << " ";
ss << dTime << " ";
|
1,152,048 | 1,158,194 | How to calculate determinant matrix with lapack++ (2.5+) | What is the best (fastest) way to calculate the determinant of a (non symmetric, squared) LaMatGenDouble matrix with the lapack++ library?
| One way to calculate the determinant is using the LU decomposition:
LaVectorLongInt pivots(A.cols());
LUFactorizeIP(A, pivots);
double detA = 1;
for (int i = 0; i < A.cols(); ++i)
detA *= A(i, i);
Warning, A will change, so making a copy is probably advised.
|
1,152,224 | 1,152,274 | Please explain two lines to me | typedef vector<double>::size_type vec_sz;
vec_sz size = homework.size();
| The first line creates an alias of the vector<double>::size_type type. The typedef keyword is often used to make "new" data types names that are often shorter than the original, or have a clearer name for the given application.
The second line should be pretty self-explanatory after that.
|
1,152,333 | 1,152,396 | Force compiler to not optimize side-effect-less statements | I was reading some old game programming books and as some of you might know, back in that day it was usually faster to do bit hacks than do things the standard way. (Converting float to int, mask sign bit, convert back for absolute value, instead of just calling fabs(), for example)
Nowadays is almost always better to just use the standard library math functions, since these tiny things are hardly the cause of most bottlenecks anyway.
But I still want to do a comparison, just for curiosity's sake. So I want to make sure when I profile, I'm not getting skewed results. As such, I'd like to make sure the compiler does not optimize out statements that have no side effect, such as:
void float_to_int(float f)
{
int i = static_cast<int>(f); // has no side-effects
}
Is there a way to do this? As far as I can tell, doing something like i += 10 will still have no side-effect and as such won't solve the problem.
The only thing I can think of is having a global variable, int dummy;, and after the cast doing something like dummy += i, so the value of i is used. But I feel like this dummy operation will get in the way of the results I want.
I'm using Visual Studio 2008 / G++ (3.4.4).
Edit
To clarify, I would like to have all optimizations maxed out, to get good profile results. The problem is that with this the statements with no side-effect will be optimized out, hence the situation.
Edit Again
To clarify once more, read this: I'm not trying to micro-optimize this in some sort of production code.
We all know that the old tricks aren't very useful anymore, I'm merely curious how not useful they are. Just plain curiosity. Sure, life could go on without me knowing just how these old hacks perform against modern day CPU's, but it never hurts to know.
So telling me "these tricks aren't useful anymore, stop trying to micro-optimize blah blah" is an answer completely missing the point. I know they aren't useful, I don't use them.
Premature quoting of Knuth is the root of all annoyance.
| Compilers are unfortunately allowed to optimise as much as they like, even without any explicit switches, if the code behaves as if no optimisation takes place. However, you can often trick them into not doing so if you indicate that value might be used later, so I would change your code to:
int float_to_int(float f)
{
return static_cast<int>(f); // has no side-effects
}
As others have suggested, you will need to examine the assemnler output to check that this approach actually works.
|
1,152,470 | 1,152,485 | vector -> Usage of member functions begin() and end() vs the operator[] | While using the vector why do we sometime use the operator[] like homework[mid] but other times use homework.begin(). Also, homework.end() not homework[end], but that's like begin. Is it just accessing the elements differently? It's more confusing this way, don't you agree?
| vector::operator[] retrieves the Nth element of the vector. Such an operator is defined only for select STL container classes.
vector.end() is a method returning an iterator. Iterators are special entities for working with STL containers, vector included. vector::end() points onto the element immediately following the last element of the vector - it's often treated as a value to campare the iterator against to determine whether the whole container has been traversed.
|
1,152,497 | 1,152,504 | Is there a boost smart pointer class that can be configured not to delete at destruction? | I have a list of smart pointers. I want some of these smart pointers to act as regular pointers, meaning they are simply a reference to an instance and are not involved in its deallocation. They might for example point to instances allocated on the stack. The other smart pointers in the list should act as regular boost::shared_ptr.
Here is how the class might look:
template<class T> smart_ptr {
private:
T *p;
boost::shared_ptr<T> sp;
public:
smart_ptr(T *p): p(p), shared(0) { } // p will not be deleted
smart_ptr(boost::shared_ptr<T> &sp): p(sp.get()), sp(sp) { }
T *get() const { return p; }
}
If there is a boost class that does this, I would prefer to use it instead of writing a class myself. It appears there are none, or am I mistaken?
| One constructor for shared_ptr takes the destructor method, and you can pass in an empty functor.
Using Custom Deallocator in boost::shared_ptr
(You want just an empty function.)
|
1,152,511 | 1,215,807 | Any reason to overload global new and delete? | Unless you're programming parts of an OS or an embedded system are there any reasons to do so? I can imagine that for some particular classes that are created and destroyed frequently overloading memory management functions or introducing a pool of objects might lower the overhead, but doing these things globally?
Addition
I've just found a bug in an overloaded delete function - memory wasn't always freed. And that was in a not-so memory critical application. Also, disabling these overloads decreases performance by ~0.5% only.
| We overload the global new and delete operators where I work for many reasons:
pooling all small allocations -- decreases overhead, decreases fragmentation, can increase performance for small-alloc-heavy apps
framing allocations with a known lifetime -- ignore all the frees until the very end of this period, then free all of them together (admittedly we do this more with local operator overloads than global)
alignment adjustment -- to cacheline boundaries, etc
alloc fill -- helping to expose usage of uninitialized variables
free fill -- helping to expose usage of previously deleted memory
delayed free -- increasing the effectiveness of free fill, occasionally increasing performance
sentinels or fenceposts -- helping to expose buffer overruns, underruns, and the occasional wild pointer
redirecting allocations -- to account for NUMA, special memory areas, or even to keep separate systems separate in memory (for e.g. embedded scripting languages or DSLs)
garbage collection or cleanup -- again useful for those embedded scripting languages
heap verification -- you can walk through the heap data structure every N allocs/frees to make sure everything looks ok
accounting, including leak tracking and usage snapshots/statistics (stacks, allocation ages, etc)
The idea of new/delete accounting is really flexible and powerful: you can, for example, record the entire callstack for the active thread whenever an alloc occurs, and aggregate statistics about that. You could ship the stack info over the network if you don't have space to keep it locally for whatever reason. The types of info you can gather here are only limited by your imagination (and performance, of course).
We use global overloads because it's convenient to hang lots of common debugging functionality there, as well as make sweeping improvements across the entire app, based on the statistics we gather from those same overloads.
We still do use custom allocators for individual types too; in many cases the speedup or capabilities you can get by providing custom allocators for e.g. a single point-of-use of an STL data structure far exceeds the general speedup you can get from the global overloads.
Take a look at some of the allocators and debugging systems that are out there for C/C++ and you'll rapidly come up with these and other ideas:
valgrind
electricfence
dmalloc
dlmalloc
Application Verifier
Insure++
BoundsChecker
...and many others... (the gamedev industry is a great place to look)
(One old but seminal book is Writing Solid Code, which discusses many of the reasons you might want to provide custom allocators in C, most of which are still very relevant.)
Obviously if you can use any of these fine tools you will want to do so rather than rolling your own.
There are situations in which it is faster, easier, less of a business/legal hassle, nothing's available for your platform yet, or just more instructive: dig in and write a global overload.
|
1,152,828 | 1,153,013 | doxygen: how do I document \enum values out-of-line? | To be precise: I know how to dox enums at the point of declaration, I want to dox them out-of-line instead.
I want to keep the header file free of doxygen comments; they're all in the .cpp file. This is not a problem for functions, classes, typedefs and so on. I can also document the enum itself like this:
/*!
\enum MyClass::MyEnum
Foo Bar Baz
\value FirstEnumValue <- doesn't work
*/
but how do I document the values of the enum there?
Thanks!
| You need to use \var according to the docs
|
1,152,958 | 3,145,027 | What is a "nearly-empty" class? | Compile the following class
class Interface
{
virtual void doIt() = 0;
virtual ~Interface() = 0;
};
inline Interface::~Interface() {}
using gcc -fdump-class-hierarchy.
gcc emits
Class Interface
size=4 align=4
base size=4 base align=4
Interface (0x1a779c0) 0 nearly-empty
vptr=((& Interface::_ZTV9Interface) + 8u)
What is the significance of "nearly-empty"? What does it mean?
| The C++ ABI provides a definition of "nearly empty" classes and an interesting discussion of how they affect vtable construction:
A class that contains a virtual pointer, but no other data except (possibly) virtual bases. In particular, it:
has no non-static data members other than zero-width bitfields,
has no direct base classes that are not either empty, nearly empty, or virtual,
has at most one non-virtual, nearly empty direct base class, and
has no proper base class that is empty, not morally virtual, and at an offset other than zero.
I ran across this while researching the effect of nearly empty virtual bases on object size, vtable size, and virtual call overhead.
|
1,153,052 | 1,153,262 | How to programmatically get the resolution of a window and that of the system in Linux? | I'm trying to get the resolution of the screen as well as the resolution of a specific window (in which a program is running) on Linux system. I don't need to modify the resolution, I only need the current values. As far as I know, we can call some system functions to do so on Windows, how can we do that on Linux, preferably using C/C++ language? Thanks in advance.
update: Actually, I don't need to do a GUI, although I know Qt and GTK+ can do it, I'm reluctant to include an external library for just getting the resolution.
| In X11, you'd need to call the Xlib's XGetWindowAttributes to get the various window info, including the size and position relative to parent. For an example of how it is used, you can google for 'xwininfo.c'.
That said, probably you are going to use some more highlevel framework to do your window programming - and the chances are high that it already has some other primitives for this, see an example for Qt - so you might want to give a bit more background about the question.
|
1,153,064 | 1,153,143 | Memory Management on Objects in a C++ Collection | I have a map that relates integers to vectors (of objects). These vectors represent a set of tasks to perform. In order to reduce the amount of copying going on while using this map and vector I've set them up to make use of pointers.
std::map<int, std::vector<MyObject *> *> myMap;
During initialization of the class that holds myMap, I populate myMap by creating a new vector filled with new MyObjects.
What I'm concerned with, however, is memory management. Now I have these various objects sitting out on the heap somewhere and I am responsible for cleaning them up when I'm done with them. I also know that I will NEVER be done with them until the program is finished. But what about in 10 weeks when someone decides that a clever way to modify this app involves removing items from the map/vectors. This would cause a memory leak.
My question is how can I handle the proper deallocation of these objects so that even if they get removed via an STL function that the objects get successfully deallocated?
Your help is much appreciated, let me know if I've missed anything critical!
Thanks!
| I agree the use of smart pointers is a good way to go, but there are at least two alternatives:
a) Copying may not be as expensive as you think it is. Try implementing a map of values
std::map<int, std::vector<MyObject>> myMap;
b) Replace the vector with a class of your own that wraps the vector. In that classes destructor, handle the deallocation. You could also provide methods for adding and removing MyObjects.
|
1,153,090 | 1,153,130 | How to detect that a given PE file (exe or dll) is 64 bit or 32 bit | I need to detect whether a given .dll or .exe file is 32 bit or 64 bit
At the moment I have only one solution: read the PE Header from the specified file and take the 'Machine' field from there.
( Specification: Microsoft Portable Executable and Common Object File Format Specification (.docx file) at section "3.3. COFF File Header (Object and Image)" )
This field can take up to about 20 values. Three of them are:
IMAGE_FILE_MACHINE_I386 ( == 32bit )
IMAGE_FILE_MACHINE_IA64 ( == 64bit )
IMAGE_FILE_MACHINE_AMD64 ( == 64bit )
My questions:
1) Is 'Machine' to bitness mapping correct or did I miss something? Are there any other caveats?
2) Is there easier way to detect 32/64 bitness (probably some specific field in PE format I didn't notice or some special system function)?
| GetBinaryType(...) returns SCS_32BIT_BINARY for a 32-bit Windows-based application
and SCS_64BIT_BINARY for a 64-bit Windows-based application.
|
1,153,101 | 1,153,116 | compiling c++ with gcc/g++ compiler | I'm new to c++ and i want to compile my testprogram .
i have now 3 files "main.cpp" "parse.cpp" "parse.h"
how can i compile it with one command?
| Compile them both at the same time and place result in a.out
$ g++ file.cpp other.cpp
Compile them both at the same time and place results in prog2
$ g++ file.cpp other.cpp -o prog2
Compile each separately and then link them into a.out
$ g++ -c file.cpp
$ g++ -c other.cpp
$ g++ file.o other.o
Compile each separately and then link them into prog2
$ g++ -c file.cpp
$ g++ -c other.cpp
$ g++ file.o other.o -o prog2
|
1,153,209 | 1,153,236 | Why does Qt include empty class definitions of existing classes in the header files? | I am reading through the examples on the Qt page and am wondering why they add references to already existing classes in their code example:
#ifndef HTTPWINDOW_H
#define HTTPWINDOW_H
#include <QDialog>
class QFile;
class QHttp;
class QHttpResponseHeader;
class QLabel;
class QLineEdit;
class QProgressDialog;
class QPushButton;
class HttpWindow : public QDialog
{
...
| Those are forward declarations. Using them can (in some cases) obviate the need to #include the relevant header files, thus speeding up compilation. The Standard C++ library does something similar with the <iosfwd> header.
|
1,153,362 | 1,555,933 | Using Common Header Files in eVC++ 3 | I'm learning C++ and i have the eVT(eMbedded Visual Tools) installed in my computer, because of the eVB 3(eMbedded Visual Basic) for my VB pocket programs, but i'm learning C++, then i want to use the eVC++ 3 for develop some command line aplications, then only to test i created an HelloWorld aplication, just for test, but when i try to compile it gave me this error:
Fatal error C1083: Cannot open include file: 'iostream': No such file or directory
Error executing clarm.exe.
Remember that i can't update to eVC++ 4, because i want to build programs for Windows CE 3.1
Thanks!
| Recently i see some eVC++ example and as i can see, eVC++(remember: Plus Plus) only uses C(Without ++) code.
|
1,153,501 | 1,153,629 | Java solution for C++ style compiler directive | I have a Java array:
String[] myArray = {"1", "2"};
Depending on a condition that is known at compile time I would like to assign different values:
String[] myArray = {"A", "B", "C"};
In C++ I would use something like
#ifdef ABC
// ABC stuff here
#else
// 123 stuff here
#endif
but what to do in Java?
| class Foo {
static final boolean ABC = true;
public void someMehod() {
if (ABC) { // #ifdef ABC
} else { // #else
} // #endif
}
}
since ABC is both static and final the compiler evaluates it at compile-time, effectively acting like a pre-processor.
|
1,153,548 | 1,153,585 | minimum double value in C/C++ | Is there a standard and/or portable way to represent the smallest negative value (e.g. to use negative infinity) in a C(++) program?
DBL_MIN in float.h is the smallest positive number.
| -DBL_MAX in ANSI C, which is defined in float.h.
|
1,153,900 | 1,154,009 | Unresolved External Symbol |
Possible Duplicate:
What is an undefined reference/unresolved external symbol error and how do I fix it?
I am working on wrapping a large number of .h and .lib files from native C++ to Managed C++ for eventual use as a referenced .dll in C#.
I have the .lib files linked in and everything has been going smoothly so far. Upon wrapping the latest .h file, I hit a snag when 2 functions came back with the link error:
error LNK2019: unresolved external symbol __imp__htonl@4 referenced in function
"public: void __thiscall Field::setCharacter(unsigned char,int)"
(?setCharacter@Field@@QAEXEH@Z) myutils.lib
I have referenced myutils.lib in the linker options, so that shouldn't be the issue.
What's strange is that I have about 20 functions in this particular .h file and all of the rest are linking just fine except for 3 functions.
Any ideas?
| The missing symbol is __imp__htonl@4, which is a C++ mangled name for htonl, which is a function that converts a long value from host to network order. The @4 is used to mangle the input parameters and is part of C++ support for overloaded functions to allow the linker to resolve the right function w/o name collisions.
Make sure that you are linked to the network library that you are referencing this symbol from. Presumably your package is using some special definition of this symbol, instead of the MACRO that it usually is.
|
1,153,986 | 1,154,004 | Using VB for Artificial Intelligence | Do you think VB is a good language for AI? I originally did AI using mainly Lisp and C/C++ when performance was needed, but recently have been doing some VB programming.
VB has the following advantages:
1. Good debugger (essential!)
2. Good inspector (watch facility)
3. Easy syntax (Intellisense comparable to structure editors of late 80's Lisp environments).
4. Easy to integrate with 3rd party software.
5. Compiles to fast code (CLR performance pretty good)
6. Fast development.
By the way, thanks for all the useful replies. I've upvoted everyone who contributed.
| Which VB are you talking about here? If you're talking VB.NET then yes, and no.. I would suggest C# or maybe F#.. F# is a functional language and hence is generally better suited for many of the patterns you'll be dealing with when programming AI. The newer versions of C# also have support for language features such as lambda expressions, anonymous delagates et al which may also benefit you!
|
1,154,187 | 1,154,199 | USB Communication API | Is there a decent USB communication API? Preferably cross-platform (Linux if not, I guess)
I don't have a specific use in mind, I just want to learn about using the USB ports for future electronics projects. I realize this is very general, I'll try to refine the question as the answers point me in the right direction.
Thanks.
| libusb should work for you .. cross platform, user-space USB tools.
|
1,154,212 | 1,154,683 | How could I print the contents of any container in a generic way? | I am trying to write a piece of code for fun using C++ templates.
#include <iostream>
#include <vector>
template <class Container>
std::ostream& operator<<(std::ostream& o, const Container& container)
{
typename Container::const_iterator beg = container.begin();
o << "["; // 1
while(beg != container.end())
{
o << " " << *beg++; // 2
}
o << " ]"; // 3
return o;
}
int main()
{
std::vector<int> list;
list.push_back(0);
list.push_back(0);
std::cout << list;
return 0;
}
The above code doesn't compile :)
At 1, 2, 3 the same error is produced : error C2593: 'operator <<' is ambiguous
All what I am trying to do is overloading the << operator to work with any container. Does that make sense ? How would that be done If possible, if not why ?
EDIT :: Thanks for corrections :) 'sth' way is a good solution.
I am just curious if this ambiguity -as Neil explained- would go away if we could use C++0x Concepts ?
| You can restrict your operator<< to only apply to templated containers by specifying that the Container template parameter is itself templated. Since the C++ std containers also have an allocator template parameter you also have to include this as a template parameter of Container.
template
< typename T
, template<typename ELEM, typename ALLOC=std::allocator<ELEM> > class Container
>
std::ostream& operator<< (std::ostream& o, const Container<T>& container)
{
typename Container<T>::const_iterator beg = container.begin();
o << "["; // 1
while(beg != container.end())
{
o << " " << *beg++; // 2
}
o << " ]"; // 3
return o;
}
int main()
{
std::vector<int> list;
list.push_back(0);
list.push_back(0);
std::cout << list;
return 0;
}
|
1,154,221 | 1,154,296 | Why are doubles added incorrectly in a specific Visual Studio 2008 project? | Trying to port java code to C++ I've stumbled over some weird behaviour. I can't get double addition to work (even though compiler option /fp:strict which means "correct" floating point math is set in Visual Studio 2008).
double a = 0.4;
/* a: 0.40000000000000002, correct */
double b = 0.0 + 0.4;
/* b: 0.40000000596046448, incorrect
(0 + 0.4 is the same). It's not even close to correct. */
double c = 0;
float f = 0.4f;
c += f;
/* c: 0.40000000596046448 too */
In a different test project I set up it works fine (/fp:strict behaves according to IEEE754).
Using Visual Studio 2008 (standard) with No optimization and FP: strict.
Any ideas? Is it really truncating to floats? This project really needs same behaviour on both java and C++ side. I got all values by reading from debug window in VC++.
Solution: _fpreset(); // Barry Kelly's idea solved it. A library was setting the FP precision to low.
| The only thing I can think of is perhaps you are linking against a library or DLL which has modified the CPU precision via the control word.
Have you tried calling _fpreset() from float.h before the problematic computation?
|
1,154,447 | 1,155,711 | Is there an operating system API wrapper library for c++? | Does sombebody know a C++ library for accessing different operating system APIs?
I'm thinking about a wrapper to access OS specific functions. Something like:
osAPI.MessageBox(); // calls MessageBox() in Win32, equivalent in Mac
OS Linux etc...
Since I think it's hard to realize this for different OSes for now it would be also ok to have a nice C++ wrapper class for WinAPI.
| Boost offers libraries for networking (Boost.Asio), threads (Boost.Thread), time, dates, file system traversal, shared memory, memory mapped files, etc.
ACE also has abstractions for networking, threads, time, file system stuff, shared memory, etc.
AFAIK, neither has GUI abstractions or DB abstractions either.
Others have mentioned Qt, wxWidgets and so forth.
|
1,154,593 | 1,154,669 | String memory management during the assignment stored in the map | I have a string and I would like to put a reference to that string into a map.
string m_tmp;
map<pair<string, string>, string&> m;
m[pair<string, string>("Foo","Bar")]= m_tmp;
then, I change the m_tmp;
m_tmp="DFDFD";
Will the map (on all conforming platforms) still reference m_tmp with a new value?
According to the dummy program below, the address of s does not change (linux AS4, gcc 3.4). Is the memory management in this regard equivalent across the platforms?
#include<string>
#include<iostream>
using namespace std;
int main()
{
string s="Sasha";
cout<<&s<<endl;
s="Bar";
cout<<&s<<endl;
s="Foo";
cout<<&s<<endl;
}
| Why dont you do this instead:
map<pair<string, string>, shared_ptr<string> > m;
Looks safer to me.
|
1,154,618 | 1,154,717 | line drawing routine | How to optimize this line drawing routine ? Will memcpy work faster ?
void ScreenDriver::HorizontalLine(int wXStart, int wXEnd, int wYPos,
COLORVAL Color, int wWidth)
{
int iLen = wXEnd - wXStart + 1;
if (iLen <= 0)
{
return;
}
while(wWidth-- > 0)
{
COLORVAL *Put = mpScanPointers[wYPos] + wXStart;
int iLen1 = iLen;
while(iLen1--)
{
*Put++ = Color;
}
wYPos++;
}
}
| I think you mean to say "memset" instead of "memcpy". Replacing this bit of the code:
while (iLen--)
{
*Put++ = Color;
}
with
memset(Put, Color, iLen);
could be faster but so much depends on your target CPU, memory architecture and the typical values of iLen encountered. It's not likely to be a big win, but if you've got the time I encourage you to measure the alternatives as that kind of exercise is the only way to really understand optimization.
Of course, this memset() use will only work if COLORVAL is character sized.
|
1,154,795 | 1,154,829 | Kill self if hWnd doesn't exist | I have a c++ console application that launches another application and communicates with it via com. I have the spawned window's hWnd and I want the console app to kill itself if the COM app is no longer open. How could I go about doing this?
| Since you are already communicating between the applications, you should set up a signal, when the window is closed it sends a 'I'm dead' message over to the console App. Your console app can then close appropriately.
If you want to do this by checking the hWnd, you could simply use the 'IsWindow()' function which will let you know if the hWnd is no longer valid. You would have to do this via a polling construct.
Another option, this one more useful if the other App wasn't yours is to install a hook and watch for the window to be destroyed. If you want to do this go have a look at windows hooks, a CBT hook would be appropriate, you can easily watch for windows being destroyed.
|
1,154,974 | 1,163,708 | C++0x will no longer have concepts. Opinions? How will this affect you? | At the July 2009 C++0x meeting in Frankfurt, it was decided to remove concepts from C++0x. Personally, I am disappointed but I'd rather have an implementable C++0x than no C++0x. They said they will be added at a later date.
What are your opinions on this decision/issue? How will it affect you?
| Personally I'm not too unhappy of the removal as the purpose of concepts were to mainly improve compile time error messages, as Jeremy Siek, one of the co-authors of the Concepts proposal, writes (http://lambda-the-ultimate.org/node/3518#comment-50071):
While the Concepts proposal was not
perfect (can any extension to C++
really ever be perfect?), it would
have provided a very usable and
helpful extension to the language, an
extension that would drastically
reduce the infamous error messages
that current users of template
libraries are plagued with.
Of course concepts had more purpose than just enable the compilers to give shorter error messages, but currently I think we all can live without them.
EDIT: Herb Sutter also writes on his blog:
Q: Wasn’t this C++0x’s one big
feature?
A: No. Concepts would be great, but
for most users, the presence or
absence of concepts will make no
difference to their experience with
C++0x except for quality of error
messages.
Q: Aren’t concepts about adding major
new expressive power to the language,
and so enable major new kinds of
programs or programming styles?
A: Not really. Concepts are almost
entirely about getting better error
messages.
|
1,154,991 | 1,158,071 | Load binary file using fstream | I'm trying to load binary file using fstream in the following way:
#include <iostream>
#include <fstream>
#include <iterator>
#include <vector>
using namespace std;
int main()
{
basic_fstream<uint32_t> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, uint32_t>( file ), istream_iterator<uint32_t, uint32_t>() );
cout << buffer.size() << endl;
return 0;
}
But it doesn't work. In Ubuntu it crashed with std::bad_cast exception. In MSVC++ 2008 it just prints 0.
I know that I could use file.read to load file, but I want to use iterator and operator>> to load parts of the file. Is that possible? Why the code above doesn't work?
|
istream_iterator wants basic_istream as argument.
It is impossible to overload operator>> inside basic_istream class.
Defining global operator>> will lead to compile time conflicts with class member operator>>.
You could specialize basic_istream for type uint32_t. But for specialization you should rewrite all fuctionons of basic_istream class. Instead you could define dummy class x and specialize basic_istream for it as in the following code:
using namespace std;
struct x {};
namespace std {
template<class traits>
class basic_istream<x, traits> : public basic_ifstream<uint32_t>
{
public:
explicit basic_istream<x, traits>(const wchar_t* _Filename,
ios_base::openmode _Mode,
int _Prot = (int)ios_base::_Openprot) : basic_ifstream<uint32_t>( _Filename, _Mode, _Prot ) {}
basic_istream<x, traits>& operator>>(uint32_t& data)
{
read(&data, 1);
return *this;
}
};
} // namespace std
int main()
{
basic_istream<x> file( "somefile.dat", ios::in|ios::binary );
vector<uint32_t> buffer;
buffer.assign( istream_iterator<uint32_t, x>( file ), istream_iterator<uint32_t, x>() );
cout << buffer.size() << endl;
return 0;
}
|
1,155,142 | 1,155,148 | Why do I get an error in "forming reference to reference type" map? | What is the alternative if I need to use a reference, and the data I am passing I cannot change the type of, hence I cannot really store a pointer to it?
Code:
#include <map>
#include<iostream>
#include<string>
using namespace std;
int main()
{
string test;
pair<string, string> p=pair<string, string>("Foo","Bar");
map<pair<string, string>, string&> m;
m[make_pair("aa","bb")]=test;
return 0;
}
Error:
$ g++ MapPair.cpp
/usr/include/c++/3.2.3/bits/stl_map.h:
In instantiation of
std::map<std::pair<std::string,
std::string>, std::string&,
std::less<std::pair<std::string,
std::string> >,
std::allocator<std::pair<const
std::pair<std::string, std::string>,
std::string&> > >': MapPair.cpp:15:
instantiated from here
/usr/include/c++/3.2.3/bits/stl_map.h:221:
forming reference to reference type
std::string&' MapPair.cpp: In
function int main()': MapPair.cpp:16:
no match for
std::map, std::string&,
std::less >,
std::allocator,
std::string&> > >& [std::pair]' operator
/usr/include/c++/3.2.3/bits/stl_pair.h:
At global scope:
/usr/include/c++/3.2.3/bits/stl_pair.h:
In instantiation of std::pair<const
std::pair<std::string, std::string>,
std::string&>':
/usr/include/c++/3.2.3/bits/stl_tree.h:122:
instantiated from
std::_Rb_tree_node
What am I doing wrong to cause this errror?
| You cannot store references. References are just aliases to another variable.
The map needs a copy of the string to store:
map<pair<string, string>, string> m;
The reason you are getting that particular error is because somewhere in map, it's going to do an operation on the mapped_type which in your case is string&. One of those operations (like in operator[], for example) will return a reference to the mapped_type:
mapped_type& operator[](const key_type&)
Which, with your mapped_type, would be:
string&& operator[](const key_type& _Keyval)
And you cannot have a reference to a reference:
Standard 8.3.4:
There shall be no references to references, no arrays of references, and no pointers to references.
On a side note, I would recommend you use typedef's so your code is easier to read:
int main()
{
typedef pair<string, string> StringPair;
typedef map<StringPair, string> StringPairMap;
string test;
StringPair p("Foo","Bar");
StringPairMap m;
m[make_pair("aa","bb")] = test;
return 0;
}
|
1,155,340 | 1,155,737 | Migrating from Visual C++ 6 to Visual C++ 2008 express | I'm tring to migrate my code from VCpp 6 to VCpp 2008 express but when I build the solution I receive this error message:
icl: warning: problem with
Microsoft compilation of
'c:\Desenvolvimento\DFF\Base\\version.cpp'
1>C:\Arquivos de programas\Microsoft
Visual Studio
9.0\VC\include\string.h(69): error: expected a ";" 1>
__DEFINE_CPP_OVERLOAD_STANDARD_FUNC_0_1(char> *,
__RETURN_POLICY_DST, __EMPTY_DECLSPEC, _strset, _Inout_z_,
char, _Dest, _In_ int, _Value)
There are a lot of errors like this, sometimes expecting ";", sometimes ")".
Thanks,
Leandro Lima
| The error was occuring because in the
Visual C++ 6 I called Intel compiler from
a .bat file to create a version number
for my project. Now I'm using
Microsoft compiler and I forgot to change the call.
|
1,155,539 | 1,156,742 | How do I generate a Poisson Process? | Original Question:
I want to generate a Poisson process. If the number of arrivals by time t is N(t) and I have a Poisson distribution with parameter λ how do I generate N(t)? How would I do this in C++?
Clarification:
I originally wanted to generate the process using a Poisson distribution. But, I was confused about what parameter from the process I needed; I thought I could use N(t) but that tells me how many arrivals have occurred on the interval (0,t] which wasn't what I wanted. So, then I thought I could use N(t2)-N(t1) to get the number of arrivals on the interval [t1,t2]. Since N(t)~Poisson(t x λ) I could use Poisson(t2 x λ)-Poisson(t1 x λ) but I don't want the number of arrivals in an interval.
Rather, I want to generate the explicit times that arrivals occur at.
I could do this by making the interval [t2,t1] sufficiently small so that each interval has only one arrival (which occurs as |t2-t1| -> 0).
| Here's sample code for generating Poisson samples using C++ TR1.
If you want a Poisson process, times between arrivals are exponentially distributed, and exponential values can be generated trivially with the inverse CDF method: -k*log(u) where u is a uniform random variable and k is the mean of the exponential.
|
1,155,553 | 1,197,198 | Alternatives to LogonUser for network impersonation (C++) | Are there any alternatives to LogonUser and for impersonating given account in order to access network resources? I'm looking for the method of impersonation which would let me connect to machine in foreign domains (or, workgroup machines for the same matter).
For initial data I have: machine name, username (or domain\username), cleartext password.
I know there's a way to establish connection using WNetAddConnection to a \\machinename\ipc$, then most network functions will run in a context of that account, however win2008 added another twist and some functions still use the account, that thread is running under.
I'm also aware, that there's some way to get an impersonation token using SSPI. Have anyone experimented with those tokens, are they good for accessing shares, SCM, remote registry and stuff? Is is what WNetAddConnection is using?
EDIT: To clarify, the reason I cannot use LogonUser is because I need to impersonate user in a non-trusted domain or workgroup
EDIT2: Another clarification: the item I'm trying to implement is similar to psexec, e.g.:
program should not modify host or active directory configuration (e.g.: create temporary local users, etc). Moreover assumption cannot be made that it is running on DC or not
there can be no assumptions made about which software is pre-installed on the remote host, only condition given is that windows file sharing is enabled on target
Account/password is known to be working on target, but target machine may be in local domain, foreign domain, not in domain at all.
EDIT3: I would really love to hear more about SSPI InitializeSecurityContext / AcquireCredentialsHandle option. Is there anybody who has been working with this API extensively? Is it possible to use the tokens returned with impersonation, so that a thread can access network shares and copy files, etc? Can someone post a working code snippet?
EDIT4: Thanks to Marsh Ray, problem got resolved. If anyone is looking to see the proof-of-concept code, it is here
| If you're wanting to "access network resources" outside of your forest, do that with WNetAddConnection2/3 as you mentioned, or use the standard RPC APIs with RPC_ C__ AUTHN__ GSS__ NEGOTIATE and and explicit credentials structure.
Normally, "impersonation" is something that happens on the server side. The server side will be able to impersonate the connection as the account you're connecting as.
But the key is this: impersonation only makes sense for impersonating an account the server can access in his local SAM/domain/forest directory. If the client and server are in different forests, they clearly can't agree on the SID of an account for an impersonation token (except for the case of well-known SIDs like Administrator which serve mainly to confuse this kind of thing), and that seems necessary to check against DACLs etc.
Perhaps what you want is to call LogonUserEx with the LOGON32__ LOGON__ NEW__ CREDENTIALS flag. This should succeed (even in a different forest - it doesn't actually authenticate the credentials you give it) giving you a token with the username/password you specified. You may have to use DuplicateToken to turn this into an impersonation token. Then you can use SetThreadToken to replace the token on your thread.
IMHO this isn't really "impersonation", you're just using the credentials outright, but it allows you to access network resources transparently as the arbitrary username/password you supply.
Edit: Oh yeah, be aware that there is no protection against man-in-the-middle on this type of connection. The client especially cannot strongly authenticate the server (short of heroics like IPSEC), so in theory you can't trust anything the server tells you.
|
1,155,661 | 1,155,673 | Anything like the c# params in c++? | That is the question.
Background: C# Params
In C#, you can declare the last parameter in a method / function as 'params', which must be a single-dimension array, e.g.:
public void SomeMethod(int fixedParam, params string[] variableParams)
{
if (variableParams != null)
{
foreach(var item in variableParams)
{
Console.WriteLine(item);
}
}
}
This then essentially allows syntactic sugar at the call site to implicitly build an array of zero or more elements:
SomeMethod(1234); // << Zero variableParams
SomeMethod(1234, "Foo", "Bar", "Baz"); // << 3 variableParams
It is however still permissable to bypass the sugar and pass an array explicitly:
SomeMethod(1234, new []{"Foo", "Bar", "Baz"});
| For unmanaged C++ with the same convenient syntax, no.
But there is support for variable argument lists to functions in C++.
Basically you declare a function with the last parameter being an ellipsis (...), and within the body of the function use the va_start()/va_arg() calls to parse out the supplied parameter list.
This mechanism is not type safe, and the caller could pass anything, so you should clearly document the public interface of the function and what you expect to be passed in.
For managed C++ code, see Reed's comments.
|
1,155,753 | 1,155,776 | How are objects passed to functions C++, by value or by reference? | Coming from C#, where class instances are passed by reference (that is, a copy of the reference is passed when you call a function, instead of a copy of the value), I'd like to know how this works in C++. In the following case, _poly = poly, is it copying the value of poly to _poly, or what?
#include <vector>
using namespace std;
class polynomial {
vector<int> _poly;
public:
void Set(vector<int> poly);
};
void polynomial::Set(vector<int> poly) {
_poly = poly; <----------------
}
| poly's values will be copied into _poly -- but you will have made an extra copy in the process. A better way to do it is to pass by const reference:
void polynomial::Set(const vector<int>& poly) {
_poly = poly;
}
EDIT I mentioned in comments about copy-and-swap. Another way to implement what you want is
void polynomial::Set(vector<int> poly) {
_poly.swap(poly);
}
This gives you the additional benefit of having the strong exception guarantee instead of the basic guarantee. In some cases the code might be faster, too, but I see this as more of a bonus. The only thing is that this code might be called "harder to read", since one has to realize that there's an implicit copy.
|
1,155,989 | 1,160,099 | How to add submenu to a CMenu in MFC? | I have an MFC app that uses CMenu for the main menu bar.
I haven't been able to create submenus successfully.
I can have the first level of File, Edit, View, etc and their sub menus, but I can't create a submenu off of one of those menus.
For example, I would like to be able to go File->Recent Items->list of items in submenu
I can do this easily enough with the resource editor in VS, but this needs to be done dynamically.
Am I using the right class in CMenu? Any suggestions on what to try?
I haven't found any decent tutorials. Even pointing me towards the right one would be helpful.
| Use your resource editor to add a submenu containing one placeholder item. You can then programatically grab a reference to this submenu, add items to it and delete the placeholder item:
CMenu *subMenu = mainMenu.GetSubMenu( menuPosition );
if( subMenu )
{
for( unsigned i = 0; i < stringArray.size(); i++ )
{
subMenu->AppendMenu( MF_STRING, 400 + i, stringArray[i]);
}
subMenu->DeleteMenu( ID_SUBMENU_PLACEHOLDER, MF_BYCOMMAND );
}
|
1,156,003 | 1,156,297 | c++ namespace collision with gtest and boost | If I include both gtest/gtest.h and boost/math/distributions/poisson.hpp I get
/opt/local/include/boost/tr1/tuple.hpp:63: error: ‘tuple’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:67: error: ‘make_tuple’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:68: error: ‘tie’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:72: error: ‘tuple_size’ is already declared in this scope
/opt/local/include/boost/tr1/tuple.hpp:73: error: ‘tuple_element’ is already declared in this scope
How do I prevent these two library namespaces from colliding?
| Try building with BOOST_HAS_TR1_TUPLE defined. It looks like both boost and your std libraries are defining std::tr1::tuple and I can't see how to disable the std version. Looking at the boost header though it appears that BOOST_HAS_TR1_TUPLE needs to be defined to tell boost that std::tr1::tuple is already defined.
I got similar errors to yours when I tried to compile a file including both those headers and then they disappeared when I defined BOOST_HAS_TR1_TUPLE.
|
1,156,020 | 1,156,047 | Must every test-case undo their operation at the end? | The question may be a little vague but here's an example of what I want to know (pseudocode):
//start test-case for CreateObject function
{
// initialization of parameters
MyObject *obj = CreateObject();
// test results
}
//end test-case for CreateObject function
Is it necessary in this case to also deallocate the memory by calling "DestroyObject" function? [this is the particular case that gave birth to this question]
My personal opinion would be no, that I shouldn't undo what the function did, but if many tests would be carried out I could remain without memory/resources for that test-suite (not likely to happen but ...).
What do you think? In this case and also in a general case.
Thanks,
Iulian
| In this case, you should deallocate the memory your test case has allocated. That way, you can use a tool that lets you run your tests and confirms that no memory was leaked. Letting your test code leak memory means that this would fail, and you wouldn't be able to tell for certain that the leak was in the test and not in your production code.
As to the more general situation, tests should clean up what they've done. Most unit testing frameworks let you implement a tearDown() method to do this. That way, if one test fails you'll know it's an issue with that test and not an interaction with another test.
|
1,156,267 | 1,156,285 | Where is <inttypes.h> in Visual Studio 2005? | I'd like to use the C99 header file inttypes.h in a Visual Studio project (I'd like to printf 64 bit numbers).
However, this file does not seem to exist in my install.
Is this just not part of VS2005? Are there any alternatives?
| It's at google. VS doesn't come with <inttypes.h>
|
1,156,489 | 1,156,518 | Way of overloading operator without changing original values? | I'm wondering if you can overload an operator and use it without changing the object's original values.
Edited code example:
class Rational{
public:
Rational(double n, double d):numerator_(n), denominator_(d){};
Rational(){}; // default constructor
double numerator() const { return numerator_; } // accessor
double denominator() const { return denominator_; } // accessor
private:
double numerator_;
double denominator_;
};
const Rational operator+(const Rational& a, const Rational& b)
{
Rational tmp;
tmp.denominator_ = (a.denominator() * b.denominator());
tmp.numerator_ = (a.numerator() * b.denominator());
tmp.numerator_ += (b.numerator() * a.denominator());
return tmp;
}
I made the accessors const methods, but I'm still getting a privacy error for every tmp.denominator_ / numerator_.
| What you're looking for are the "binary" addition and subtraction operators:
const Rational operator+(const Rational& A, const Rational& B)
{
Rational result;
...
return result;
}
update (in response to new code and comments):
You are getting that error because your accessor functions are not declared as constant functions, so the compiler has to assume that they might modify the original object. Change your accessors as follows, and you should be good to go:
double numerator() const { return numerator_; }
double denominator() const { return denominator_; }
update
To properly handle privacy issues, you should declare the binary operator+ function as a friend of the Rational class. Here is how it would look:
class Rational {
public:
Rational(double n, double d):numerator_(n), denominator_(d) {};
Rational() {}; // default constructor
double numerator() const { return numerator_; } // accessor
double denominator() const { return denominator_; } // accessor
friend Rational operator+(const Rational& A, const Rational& B);
private:
double numerator_;
double denominator_;
};
const Rational operator+(const Rational& a, const Rational& b)
{
Rational result;
result.denominator_ = (a.denominator_ * b.denominator_);
result.numerator_ = (a.numerator_ * b.denominator_);
result.numerator_ += (b.numerator_ * a.denominator_);
return result;
}
|
1,156,652 | 1,156,766 | Encapsulate Windows message loop into a DLL | I would like to have a DLL with window creation and management code in a way that the developer could just add a named main.h header and load the DLL to be able to instance a window.
#include "dllheader.h"
void user_main();
main = user_main; // attach user main to the dll callback
int user_main() {
Window *w = new Window();
}
on the DLL side the code should look like
void (*main)() = NULL;
int WinMain(...) {
if(main)
main(); // call the user defined funcion
while(!done) {
if(messageWaiting()) {
processMessage();
}
}
}
Why? because I want to deploy a window wrapper and avoid to have the user writting the WinMain entry point. But a DLL project have a DLL main and a win32 project that uses a DLL complaim if linker doesnt find a winMain entry point.
Is there a know solution for this kind of arrange?
| Every Win32 application must have an entry point (usally WinMain). So you can't put the entry point in the DLL, because it's not really part of the EXE. However the entry point can be in a statically linked library. When the static library gets linked, the entry point becomes part of the EXE.
But my suggestion is to avoid all this complexity. Just make the users of your DLL call something like this:
int WinMain( HINSTANCE hInstance, HINSTANCE hPrev, LPSTR lpCmdLine, int nCmdShow )
{
return WrapperDllMain( hInstance, hPrev, lpCmdLine, nCmdShow, &user_main );
}
The code is simple and easy to write. It's not much effort on the part of the DLL users. You have total control over the message loop (and the entire process lifetime).
|
1,156,746 | 1,156,757 | Integrate Adobe AIR With C++ | I'm learning C++ and before this i was reading some tutorials in the internet of the Adobe AIR development, but if Adobe AIR is so much easy to learn and C++ is a very flexible and good language it's possible to integrate those two languages in a same project. Thanks!
| It's in the works.
For now, you use either JavaScript or ActionScript.
An alternative to AIR is Titanium. Its language choices are JavaScript, Ruby, and Python.
|
1,156,756 | 1,157,063 | Joining keys/values from C++ STL associative containers | I have a join function that operates on STL strings. I want to be able to apply it to to a container like this:
getFoos(const std::multimap<std::string, std::string>& map) {
return join_values(",", map.equal_range("foo"));
In other words, find all matching keys in the collection and concatenate the values into a single string with the given separator. Same thing with lower_bound() and upper_bound() for a range of keys, begin()/end() for the entire contents of the container, etc..
The closest I could get is the following:
template <typename T>
struct join_range_values : public T::const_iterator::value_type::second_type {
typedef typename T::const_iterator::value_type pair_type;
typedef typename pair_type::second_type value_type;
join_range_values(const value_type& sep) : sep(sep) { }
void operator()(const pair_type& p) {
// this function is actually more complex...
*this += sep;
*this += p.second;
}
private:
const value_type sep;
};
template <typename T>
typename T::const_iterator::value_type::second_type join_values(
const typename T::const_iterator::value_type::second_type& sep,
const std::pair<typename T::const_iterator, typename T::const_iterator>& range) {
return std::for_each(range.first, range.second, join_range_values<T>(sep));
}
(I realize that inheriting from std::string or whatever the key/value types are is generally considered a bad idea, but I'm not overloading or overriding any functions, and I don't need a virtual destructor. I'm doing so only so that I can directly use the result of for_each without having to define an implicit conversion operator.)
There are very similar definitions for join_range_keys, using first_type and p.first in place of second_type and p.second. I'm assuming a similar definition will work for joining std::set and std::multiset keys, but I have not had any need for that.
I can apply these functions to containers with strings of various types. Any combination of map and multimap with any combination of string and wstring for the key and value types seems to work:
typedef std::multimap<std::string, std::string> NNMap;
const NNMap col;
const std::string a = join_keys<NNMap>(",", col.equal_range("foo"));
const std::string b = join_values<NNMap>(",", col.equal_range("foo"));
typedef std::multimap<std::string, std::wstring> NWMap;
const NWMap wcol;
const std::string c = join_keys<NWMap>(",", wcol.equal_range("foo"));
const std::wstring d = join_values<NWMap>(L",", wcol.equal_range("foo"));
typedef std::multimap<std::wstring, std::wstring> WWMap;
const WWMap wwcol;
const std::wstring e = join_keys<WWMap>(L",", wwcol.equal_range(L"foo"));
const std::wstring f = join_values<WWMap>(L",", wwcol.equal_range(L"foo"));
This leaves me with several questions:
Am I missing some easier way to accomplish the same thing? The function signature especially seems overly complicated.
Is there a way to have join_values automatically deduce the template parameter type so that I don't need to call it with join_values<MapType> every time?
How can I refactor the join_values and join_keys functions and functors to avoid duplicating most of the code?
I did find a slightly simpler solution based on std::accumulate, but it seems to require two complete copy operations of the entire string for each element in the range, so it's much less efficient, as far as I can tell.
template <typename T>
struct join_value_range_accum : public T::const_iterator::value_type::second_type
{
typedef typename T::const_iterator::value_type::second_type value_type;
join_value_range_accum(const value_type& sep) : sep(sep) {}
using value_type::operator=;
value_type operator+(const typename T::const_iterator::value_type& p)
{
return *this + sep + p.second;
}
private:
const value_type sep;
};
typedef std::multimap<std::string, std::string> Map;
Map::_Pairii range = map.equal_range("foo");
std::accumulate(range.first, range.second, join_value_range_accum<Map>(","));
| The STL algorithms typically work with iterators, not containers, so I would suggest something like the following.
template <typename T, typename Iterator>
T join(
const T sep,
Iterator b,
Iterator e)
{
T t;
while (b != e)
t = t + *b++ + sep;
return t;
}
Then, you need an iterator that will pull out keys or values. Here's an example:
template <typename Key, typename Iterator>
struct KeyIterator
{
KeyIterator(
Iterator i)
:_i(i)
{
}
KeyIterator operator++()
{
++_i;
return *this;
}
bool operator==(
KeyIterator ki)
{
return _i = ki._i;
}
typename Iterator::value_type operator*()
{
return _i->first;
}
};
How to use:
string s = join(",", KeyIterator(my_map.begin()), KeyIterator(my_map.end()));
|
1,156,783 | 1,156,795 | How to increase the gcc executable stack size? | I have large Boost/Spirit metaprogram that is blowing gcc's stack when I try to compile it.
How can I increase gcc's stack size, so I can compile this program?
Note: There's no infinite recursion going on, but there is enough incidental recursion to exhaust gcc's stack.
| On Linux, you can expand the stack size in /etc/security/limits.conf.
You can check your current stack size by using
$ ulimit -s
8192
Then expand the stack to be double than that:
youruser soft stack 16384
And then relog.
This will increase stack size for all executable you're running, not just GCC's.
|
1,157,107 | 1,157,131 | Enter File Name When Executing Program In C++ | I'm learning C++, then i was searching for some codes for learn something in the area that i love: File I/O, but i want to know how i can tweak my code for the user type the file that he wants to see, like in wget, but with my program like this:
C:\> FileSize test.txt
The code of my program is here:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main () {
long begin,end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
Thanks!
| In the example below argv contains command line arguments as null terminated string array and argc contains an integer telling you how many arguments where passed.
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
long begin,end;
if( argc < 2 )
{
cout << "No file was passed. Usage: myprog.exe filetotest.txt";
return 1;
}
ifstream myfile ( argv[1] );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size is: " << (end-begin) << " bytes.\n";
return 0;
}
|
1,157,235 | 1,157,244 | Is this a good practice? "/*/something/*/something//*/" | /*/ comment here
do some thing.
/*/
do some thing.
//*/
Why people write code like that? Is this a good practice?
| It's usually only used when testing something out for the moment. That is, you should never commit code like that to version control, because it can be confusing.
For example, if you are testing two different computation methods, you can use this to switch between them. Personally I have rarely done this, if at all.
For those that don't know, you can toggle between the two code sections by adding one forward slash:
/*/ comment here
do some thing.
/*/
do some thing else.
//*/
//*/ comment here
do some thing.
/*/
do some thing else.
//*/
|
1,157,357 | 1,157,435 | Qt: Add UI Elements using Qt Script | Is it possible to add new GUI elements into a Qt program using QtScript? For instance assuming the variable "layout" is a vertical layout would this be acceptable?
var label = new QLabel("Text");
layout.addWidget(label);
| Qt doesn't ship with QtScript bindings; which bindings are you using?
If you're using the bindings generator on Qt Labs, yes, this code would work fine, assuming you arranged for the `layout' variable to be imported into your script engine.
|
1,157,591 | 1,157,622 | What type of exception should I throw? | After going through some links on exception handling (1, 2, and 3), I know that C++ programs can throw pretty much anything as exceptions (int, char*, string, exception class). I know that std::exception is the base class for standard exceptions thrown by the program. However, I'm trying to design a try...catch block as such:
try
{
MyFunc();
}
catch (certain exceptions)
{
// deal with the exception accordingly
}
catch (the rest of the exceptions)
{
// deal with these accordingly
}
while MyFunc() contains the following:
void MyFunc()
{
...
if (certain condition is true) throw exception;
...
}
The trouble is that in that part of MyFunc function, I'm not sure what type of exception I should throw. To keep the code clean by implementing my own exceptions class, I have no idea what would be a good way to implement such exceptions class.
| You would derive your own class from std::exception, so that there is some way of uniformly handling exceptions.
If this seems like overkill, you can throw std::logic_error or one of the other standard exception types intended for applications to use.
You could also use these as base classes for your own more specific exceptions: this saves a little work because they take care of implementing the what method for you.
Note that deep exception hierarchies can be unusable, because you're basically making a guess in advance about how to categorize the errors, and your clients may disagree.
|
1,157,689 | 1,163,172 | Finding the nearest used index before a specified index in an array (Fast) | This question is related to Array of pairs of 3 bit elements
This array has 52 pairs (about 40 bytes), and I want to find the first pair before the specified one that has it's values different from 0 (used pair).
The obvious solution would be to check each pair < than this one (scan from right to left), but this seems to be very inefficient if there are many unused pairs (set to 0).
This image may explain better the situation:
Pairs 0, 1 and 51 are used.
I want to find the first used pair before 51 (which is 1 here).
I tried tricks like
if(*((int *)&array[arrayPos]) == 0) {
arrayPos -= sizeof(int);
pairPos -= ???
}
The problem here is that subtracting from pairPos is not that simple, because of the 6 bits/pair, so I ended with a lookup table based on some relations between pairPos and arrayPos, and all this made the solution perform like the trivial one.
Is there any way to make this lookup faster ? Another problem is that there is only 1 unused byte... maybe I can make space for another 4. If there were at least 7 I could use a bitmap of the array and it would be much faster to skip over unused pairs.
| The best solution I found was:
1. make the items 1 byte (not 6 bits than before) - thanks Skizz
2. use a bitmap to see which item is the nearest on the left. This was much faster than going back with the technique described by djna.
The speed improvements are impressive:
in one test case, from 13s it's now 6.5s
in another one, from 7.4s to 3.6s
The performance has doubled :D
Thanks again for your answers!
|
1,158,084 | 1,158,306 | temporary object, function parameters and implicit cast | In the following scenario:
struct Foo
{
// ...
operator Bar() {... } // implicit cast to Bar
}
Foo GetFoo() { ... }
void CallMeBar(Bar x) { ... }
// ...
CallMeBar( GetFoo() );
[edit] fixed the cast operator, d'oh[/edit]
GetFoo returns a temporary object of Type Foo. Does this object survive until after CallMe returns? What does the standard say?
I understand that if CallMe would accept Foo, the temporary object would not be destroyed until after CallMe returns. I am not sure, however, fi the implicit cast changes this, and only the temporary Bar is guaranteed to survive.
A typical case would be Foo = CString, Bar = char *, i.e. Bar referencing data held by (and freed by) Foo.
| Regardless of the cast, the temporary object(s) will "survive" the call to CallMe() function because of the C++ standard:
12.2.3 [...] Temporary objects are destroyed as the last step in evaluating the fullexpression (1.9) that (lexically) contains the point where they were created. [...]
1.9.12 A fullexpression is an expression that is not a subexpression of another expression.
|
1,158,373 | 1,158,438 | Getting the number of logged on users in Windows | Let's say I have 3 logged on users. I have a test application which I use to enumerate the WTS sessions on the local computer, using WTSEnumerateSessions. After that, I display the information contained in each of the returned WTS_SESSION_INFO structure.
On Windows XP, there are 3 structures displayed: Session 0, 1, and 3 (for each logged on user), with the name "Console" corresponding to the active user under which I run the test application, and an empty string as the name for the other sessions. For example, if I run the application under the first user, I get Session 0 (Console), Session 1 (), Session 2 ().
On Windows Vista, there are 5 structures displayed: Session 0 (Services), Session 1 (Console), Session 2 (), Session 3 (), Session 65536 (RDP-Tcp). On another computer with Windows Vista, I get only the first four sessions (without 65536, RDP-Tcp).
I would like to know if there is a way (better way) of finding out how many logged on users are on the local machine.
Thanks in advance!
| http://www.codeproject.com/KB/system/logonsessions.aspx
Same information available on Getting user name/password of the logged in user in Windows
Try going through this articles:- ( this is for using ASP ...)
http://support.microsoft.com/default...b;EN-US;308157
http://www.c-sharpcorner.com/Code/20...cationWithAD.asp
|
1,158,374 | 1,194,024 | Portable Compare And Swap (atomic operations) C/C++ library? | Is there any small library, that wrapps various processors' CAS-like operations into macros or functions, that are portable across multiple compilers?
PS. The atomic.hpp library is inside boost::interprocess::detail namespace. The author refuses to make it a public, well maintained library.
Lets reopen the question, and see if there are any other options?
| Intel Threading Building Blocks has a nice portable atomic<T> template which does what you want. But whether it is a small library or not can of course be debated..
|
1,158,390 | 1,158,489 | Binding to a member variable | I am confused as to what boost::bind does when we bind to member variables. With binding to member function, we essentially create a function object, and then call it passing to it the arguments that are provided or delayed and substituted via placeholders.
But what does this expression do behind the scenes:
boost::bind(&std::pair::second, _1);
What gets substituted in place of the placeholder _1?
I found this while reading this example from an article on boost::bind:
void print_string(const std::string& s) {
std::cout << s << '\n';
}
std::map<int,std::string> my_map;
my_map[0]="Boost";
my_map[1]="Bind";
std::for_each(
my_map.begin(),
my_map.end(),
boost::bind(&print_string, boost::bind(
&std::map<int,std::string>::value_type::second,_1)));
source
| Behind the scenes it is using a member pointer and applying it to the passed in argument. It is quite complex in the context of binds, so here is a simple example of pointer to member usage:
int main()
{
std::pair< int, int > p1 = make_pair( 1, 2 );
std::pair< int, int > p2 = make_pair( 2, 4 );
int std::pair<int,int>::*ptr = &std::pair<int,int>::second; // pointer to second member
std::cout << p1.*ptr << std::endl; // 2 dereference pointer to member
std::cout << p2.*ptr << std::endl; // 4 dereference pointer to member
}
Behind the scenes bind is composing different calls. The resulting functor takes the dereference of std::map<>::iterator (of type std::pair< const key_type, value_type >). That is passed to the inner bind, that dereferences the member pointer, thus returning (*it).second to the outer bind that passes that value to the print_string method for the final call: print_string( (*it).second ).
(*it) is actually the _1 you asked about. All _# are placeholders, that is, the result of bind will be a functor that will take as many arguments as different placeholders exist in the order defined by the number of placeholder. In the example you gave, the resulting functor takes a single argument _1.
|
1,158,410 | 1,158,415 | How to handle incorrect values in a constructor? | Please note that this is asking a question about constructors, not about classes which handle time.
Suppose I have a class like this:
class Time
{
protected:
unsigned int m_hour;
unsigned int m_minute;
unsigned int m_second;
public:
Time(unsigned int hour, unsigned int minute, unsigned int second);
};
While I would want a to be constructed successfully, I would want the constructor of b to fail.
Time a = Time(12,34,56);
Time b = Time(12,34,65); // second is larger than 60
However, this is not possible, because constructors do not return any values and will always succeed.
How would the constructor tell the program that it is not happy? I have thought of a few methods:
have the constructor throw an exception, and have handlers in the calling function to handle it.
have a flag in the class and set it to true only if the values are acceptable by the constructor, and have the program check the flag immediately after construction.
have a separate (probably static) function to call to check the input parameters immediately before calling the constructor.
redesign the class so that it can be constructed from any input parameters.
Which of these methods is most common in industry? Or is there anything I may have missed?
| The typical solution is to throw an exception.
The logic behind that is the following: the constructor is a method that transforms a chunk of memory into a valid object. Either it succeeds (finishes normally) and you have a valid object or you need some non-ignorable indicator of a problem. Exceptions are the only way to make the problem non-ignorable in C++.
|
1,158,519 | 1,158,542 | Crash when using C# Assembly from Managed C++ DLL | On a Windows XP system, I'm writing a Mangaged C++ library which calls code in a C# Assembly. Unfortunately, as soon as I start referencing a symbol in the C# Assembly, running the Managed C++ library fails with this error (I copied this from the XP crash dialog):
EventType : clr20r3
P1 : treeviewdemo.exe
P2 : 0.0.0.0
P3 : 4a5d6d62
P4 : system.windows.forms
P5 : 2.0.0.0
P6 : 4889dee7
P7 : 12fc
P8 : ac
P9 : system.io.filenotfoundexception
The Manged C++ library is basically just:
#using "C:\\MyCSharpAssembly.dll";
__declspec(dllexport) void callMangagedCode() {
ManagedObject ^o = nullptr;
}
The '#using' itself doesn't seem to cause any problem, but as soon as I start using symbols form the C# DLL, I get problems. Does anybody know what's going on?
The system.io.filenotfoundexception part makes me think that some DLL is not being found, but I have no idea which or where it's looking.
| Are all the dependencies of MyCSharpAssembly.dll available on the same path? If you are not sure, try loading the C-Sharp Assembly in ILDasm Tool to find out what are its dependencies.
As a sanity check, also check that whether this C-Sharp DLL can be loaded from another C-Sharp executable or not.
|
1,158,705 | 1,158,765 | MSVCP90.dll not found? | in my project if compile project in release, it asks me MSVCP90.dll.
if it is debug, it does not...
have you ever met such a situation?
and do you know why this .dll is desired? or what configuration makes it to be desired?
thanks for any advice..
| i realized that i already installed Microsoft Visual C++ 2008 Redistributable Package so i just repaired but it did not solved the problem.
then i looked for the configuration and saw that "Generate Manifest" is "No" in Release when it was "Yes" in Debug.
so i changed and tried again then it worked.
i did not know that this configuration may affect like that, (and i dont remember when i changed it)
anyway.. thanks for your other answers...
|
1,159,042 | 1,159,086 | Is there any user-mode multi-threading library/framework for C++ under Linux? | I am looking for user-mode multi-threading library/framework for C++ under Linux. I am familiar with boost::thread and ACE_Thread_Manager but AFAIK both of them eventually use OS native thread's support.
Suggestions will be highly appreciated.
| Is MTasker the kind of thing you're looking for? It's also a cooperative multi-tasking library. You might also want to consider just whipping up some state machines.
Also check out State Threads and MIT Pthreads.
This tool will assist in the generation of hierarchical state machines, which could be used for this purpose: CHSM
|
1,159,100 | 1,159,139 | Put A String In A ifstream Method | I'm learning C++ and i'm getting some troubles when i'm trying to use a String in a ifstream method, like this:
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
ifstream file ( filename );
Here is the full code:
// obtaining file size
#include <iostream>
#include <fstream>
using namespace std;
int main ( int argc, char** argv )
{
string file;
long begin,end;
cout << "Enter the name of the file: ";
cin >> file;
ifstream myfile ( file );
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "File size is: " << (end-begin) << " Bytes.\n";
return 0;
}
And here is the error of the Eclipse, the x before the method:
no matching function for call to `std::basic_ifstream<char, std::char_traits<char> >::basic_ifstream(std::string&)'
But when i try to compile in Eclipse it put an x before the method, that indicates an error in the syntax, but what is wrong in the syntax? Thanks!
| You should pass char* to ifstream constructor, use c_str() function.
// includes !!!
#include <fstream>
#include <iostream>
#include <string>
using namespace std;
int main()
{
string filename;
cout << "Enter the name of the file: ";
cin >> filename;
ifstream file ( filename.c_str() ); // c_str !!!
}
|
1,159,429 | 1,202,533 | class_id in boost::archive::xml_oarchive | Is it possible for XML serialization to use more human friendly class_id as GUID, described using BOOST_CLASS_EXPORT_GUID ???
Consider serializing class:
SomeClass* b=new SomeClass("c");
{
boost::archive::xml_oarchive oa(cout);
oa.register_type<SomeClass>();
oa << boost::serialization::make_nvp("b",b);
}
Output will be like:
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<!DOCTYPE boost_serialization>
<boost_serialization signature="serialization::archive" version="5">
<b class_id="0" tracking_level="1" version="0" object_id="_0">
<name>c</name>
</b>
</boost_serialization>
When you remove class_id="0" this will not deserialize. I would prefer class_id="SomeClass" or something similar.
| Yes, the solution is to serialize your class in a name-value-pair. See this item at boost documentation.
If you want two diferent behaviours, you will have to implement them. Try with template specialization:
template<class Archive>
void serialize(Archive & ar, const unsigned int version)
{
ar & degrees;
ar & minutes;
ar & seconds;
}
template<class Archive>
void serialize_with_name(Archive & ar, const unsigned int version)
{
ar & make_nvp("degrees", degrees);
ar & make_nvp("minutes", minutes);
ar & make_nvp("seconds", seconds);
}
template<>
void serialize<>(xml_iarchive & ar, const unsigned int version)
{
serialize_with_name(ar, version);
}
template<>
void serialize<>(xml_oarchive & ar, const unsigned int version)
{
serialize_with_name(ar, version);
}
By default object_id_type is unsigned int (basic_archive.hpp). If you want something diferent you need to implement your own archive class.
|
1,159,753 | 1,159,972 | Constructor of class in template | I have a object cache class like this:
#include "boost/thread/mutex.hpp"
#include "boost/unordered_map.hpp"
template <typename type1, typename type2>
class objectCache
{
public:
objectCache()
{
IDCounter = 0;
}
~objectCache()
{
for ( it=free_objects.begin() ; it != free_objects.end(); it++ )
delete (*it).second;
for ( it=busy_objects.begin() ; it != busy_objects.end(); it++ )
delete (*it).second;
}
type1* objectCache::Get()
{
boost::mutex::scoped_lock(io_mutex);
if(free_objects.size() > 0)
{
it = free_objects.begin();
type1 *temp = (*it).second;
busy_objects[(*it).first] = temp;
free_objects.erase(free_objects.begin());
return temp;
}
type1 * temp = new type2;
++IDCounter;
busy_objects[IDCounter] = temp;
return temp;
}
void objectCache::Pushback(type1)
{
boost::mutex::scoped_lock(io_mutex);
free_objects[ID] = socket;
it = busy_objects.find(ID);
busy_objects.erase(it);
}
protected:
private:
boost::mutex io_mutex;
long long IDCounter;
boost::unordered_map<long long, type1*> free_objects;
boost::unordered_map<long long, type1*> busy_objects;
typename boost::unordered_map<long long, type1*>::iterator it;
};
class A{
public:
A(int num){
number = num;
}
int number;
};
int main(int argc, char* argv[])
{
objectCache<a, a(1)> intcache;
A* temp = intcache.Get();
cout <<temp->number <<endl;
system("pause");
return 0;
}
I known that "typename type2" was unnecessary but I need a way to pass a class object that have a constructor with parameter like class A to the template.
or their was another way to do this ? please help.
| Rather than passing an explicit value, pass in an object that creates your instance for you:
template <typename type1>
struct DefaultInstanceCreator {
type1 * operator ()() const {
return new type1;
}
};
template < typename type1
, typename InstanceCreator = DefaultInstanceCreator<type1> >
class objectCache {
public:
objectCache (InstanceCreator const & instCreator)
: instCreator_ (instCreator) {
}
type1* Get() {
type1 * temp = instCreator_ ();
}
private:
InstanceCreator instCreator_;
};
Then your object can have it's own specific creator:
class A {
public:
A(int num){
number = num;
}
int number;
public:
struct CreateInstance {
CreateInstance (int value)
: value_ (value) {
}
A * operator ()() const {
return new A(value_);
}
int value_;
};
};
int main(int argc, char* argv[]) {
objectCache<A, A::CreateInstance> intcache ( A::CreateInstance (1) );
A* temp = intcache.Get();
return 0;
}
The advantage of this approach is that you can use your cache with objects that have different numbers of arguments to their constructors.
|
1,159,992 | 1,161,346 | Decompression and extraction of files from streaming archive on the fly | I'm writing a browser plugin, similiar to Flash and Java in that it starts downloading a file (.jar or .swf) as soon as it gets displayed. Java waits (I believe) until the entire jar files is loaded, but Flash does not. I want the same ability, but with a compressed archive file. I would like to access files in the archive as soon as the bytes necessary for their decompression are downloaded.
For example I'm downloading the archive into a memory buffer, and as soon as the first file is possible to decompress, I want to be able to decompress it (also to a memory buffer).
Are there any formats/libraries that support this?
EDIT: If possible, I'd prefer a single file format instead of separate ones for compression and archiving, like gz/bzip2 and tar.
| There are 2 issues here
How to write the code.
What format to use.
On the file format, You can't use the .ZIP format because .ZIP puts the table of contents at the end of the file. That means you'd have to download the entire file before you can know what's in it. Zip has headers you can scan for but those headers are not the official list of what's in the file.
Zip explicitly puts the table of contents at the end because it allows fast adding a files.
Assume you have a zip file with contains files 'a', 'b', and 'c'. You want to update 'c'. It's perfectly valid in zip to read the table of contents, append the new c, write a new table of contents pointing to the new 'c' but the old 'c' is still in the file. If you scan for headers you'll end up seeing the old 'c' since it's still in the file.
This feature of appending was an explicit design goal of zip. It comes from the 1980s when a zip could span multiple floppy discs. If you needed to add a file it would suck to have to read all N discs just to re-write the entire zip file. So instead the format just lets you append updated files to the end which means it only needs the last disc. It just reads the old TOC, appends the new files, writes a new TOC.
Gzipped tar files don't have this problem. Tar files are stored header, file, header file, and the compression is on top of that so it's possible to decompress as the file it's downloaded and use the files as they become available. You can create gzipped tar files easily in windows using winrar (commercial) or 7-zip (free) and on linux, osx and cygwin use the tar command.
On the code to write,
O3D does this and is open source so you can look at the code
http://o3d.googlecode.com
The decompression code is in o3d/import/cross/...
It targets the NPAPI using some glue which can be found in o3d/plugin/cross
|
1,161,142 | 1,193,644 | Not receiving callbacks from the Java Access Bridge | I'm trying to use the Java Access Bridge to get information about Swing components from inside a C++ app. However, none of the callbacks I register ever get called. I tried enuming the windows an then calling IsJavaWindow() on each handle, but it always returns false. Any ideas on why it apparently is not working?
I presume it's a problem with my app rather than the bridge installation because the demo Monkey and Ferret programs work, initializeAccessBridge() returns true, and the debugger reveals that the WindowsAccessBridge dll is loaded.
I'm using Java 6, update 13 on Windows Vista and I think version 2.0.1 of the access bridge.
JavaAccess::JavaAccess(void)
{
using namespace std;
BOOL isInitialized = initializeAccessBridge();
if(isInitialized)
{
cout << "Bridge Initialized!" << endl;
}
else
{
cout << "Initialization failed!" << endl;
return;
}
EnumWindows((WNDENUMPROC)EnumWndProc, NULL);
SetJavaShutdown(OnJavaShutdown);
SetFocusGained(OnFocusGained);
SetMouseClicked(OnMouseClicked);
}
JavaAccess::~JavaAccess(void)
{
shutdownAccessBridge();
}
void JavaAccess::OnJavaShutdown( long vmID )
{
using namespace std;
cout << "Java shutdown!" << endl;
}
void JavaAccess::OnFocusGained( long vmID, FocusEvent event, AccessibleContext context )
{
using namespace std;
cout << "Focus Gained!" << endl;
ReleaseJavaObject(vmID, event);
ReleaseJavaObject(vmID, context);
}
void JavaAccess::OnMouseClicked( long vmID, jobject event, jobject source )
{
std::cout << "Mouse clicked!" << std::endl;
ReleaseJavaObject(vmID, event);
ReleaseJavaObject(vmID, source);
}
BOOL CALLBACK JavaAccess::EnumWndProc( HWND hwnd, LPARAM lparam )
{
if (IsJavaWindow(hwnd))
{
std::cout << "Found Java Window!" << std::endl;
return FALSE;
}
else
{
std::cout << "Still looking" << std::endl;
return TRUE;
}
}
All of the callbacks are static functions.
| I have been fighting this one as well, and have just found a solution that actually makes sense. I ended up having to build a debug version of the WindowsAccessBridge.dll and used the debugger to step into it to watch what was happening.
The call to 'initializeAccessBridge' REQUIRES you to have an active windows message pump.
Inside 'initializeAccessBridge', it (eventually) creates a hidden dialog window (using CreateDialog). Once the dialog is created, it performs a PostMessage with a registered message. The JavaVM side of the access bridge responds to this message, and posts back another message to the dialog that was created (it appears to be a 'hello' type handshake between your app and the java VM). As such, if your application doesn't have an active message pump, the return message from the JavaVM never gets received by your app.
This is important as until this message is received, the bridge is never properly initialized and as such all calls to 'IsJavaWindow' fail (internally, the bridge initializes an internal structure once the message is received -- as such, no active message pump, no initializing). I'm guessing that this is why you never receive callback messages as well.
Not only that, but you must call initializeAccessBridge at a point where the message pump can process messages before you can call IsJavaWindow.
This is why JavaFerret and JavaMonkey work -- they initialize at startup, and then enumerate on response to a menu message, well after the bridge has received the initialization message via the message pump.
The way I was able to solve this in my MFC dialog app (and our MFC-based application), is to make sure that you call 'initializeAccessBridge' at a point such that the built-in MFC message pump can push the 'hello' message back to this hidden dialog BEFORE you use it. In the simple MFC dialog case, it meant calling initializeAccessBridge in OnInitDialog, and calling the enum procedure in response to a button call (for example). If you want the enum to occur as soon as the dialog appears, you could use a timer to fire (eg. 10ms) after the OnInitDialog completes to allow processing of the initialization message.
If you are planning to use this in a console app, you will need to write your own custom message pump to handle the initialization message.
Anyway, I hope this is clear enough! Whilst there is no way to know whether this is the 'correct' way (other than to pay for a Sun engineer to tell us), it definitely solved my problem.
Cheers -- Darren.
oh. and btw I found an obscure Sun page that mentioned something about the AccessBridge only working for awt-based java apps (but given that Sun hasn't updated any documentation since 2004 this may have changed). I'm not a java programmer -- for testing I grabbed a number of free Java applications (as well as the ones that came with the jdk) and tried out my test application. It worked for all of the ones I tried -- YMMV. Good luck!
|
1,161,182 | 1,161,330 | C++ w/ static template methods | Template methods as in NOT C++ templates.
So, say that you would like to do some searching with different algorithms - Linear and Binary for instance. And you would also like to run those searches through some common routines so that you could, for instance, automatically record the time that a given search took and so on.
The template method pattern fills the bill beautifully. The only problem is that as far as I've managed to dig around, you can't actually implement this behaviour via static methods with C++, 'cause you would also need to make the methods virtual(?) Which is of course a bit of a bummer because I don't have any need to alter the state of the search object. I would just like to pin all the searching-thingies to its own namespace.
So the question is: Would one want to use something like function/method pointers instead? Or would one just use namespaces to do the job?
It's pretty hard to live with this kind of (dare I say) limitations with C++, as something like this would be a breeze with Java.
Edit:
Oh yeah, and since this is a school assignment, the use of external libraries (other than STL) isn't really an option. Sorry for the hassle.
| I don't see why you'd need the template method pattern.
Why not just define those algorithms as functors that can be passed to your benchmarking function?
struct BinarySearch { // functor implementing a specific search algorithm
template <typename iter_type>
void operator()(iter_type first, iter_type last){ ....}
};
template <typename data_type, typename search_type>
void BenchmarkSearch(data_type& data, search_type search){ // general benchmarking/bookkeeping function
// init timer
search(data);
// compute elapsed time
}
and then call it like this:
int main(){
std::vector<int> vec;
vec.push_back(43);
vec.push_back(2);
vec.push_back(8);
vec.push_back(13);
BenchmarkSearch(vec, BinarySearch());
BenchmarkSearch(vec, LinearSearch()); // assuming more search algorithms are defined
BenchmarkSearch(vec, SomeOtherSearch();
}
Of course, another approach, which is a bit closer to what you initially wanted, could be to use CRTP (A pretty clever pattern for emulating virtual functions at compile-time - and it works with static methods too):
template <typename T>
struct SearchBase { // base class implementing general bookkeeping
static void Search() {
// do general bookkeeping, initialize timers, whatever you need
T::Search(); // Call derived search function
// Wrap up, do whatever bookkeeping is left
}
}
struct LinearSearch : SearchBase<LinearSearch> // derived class implementing the specific search algorithms
{
static void Search(){
// Perform the actual search
}
};
Then you can call the static functions:
SearchBase<LinearSearch>::Search();
SearchBase<BinarySearch>::Search();
SearchBase<SomeOtherSearch>::Search();
As a final note, it might be worth mentioning that both of these approaches should carry zero overhead. Unlike anything involving virtual functions, the compiler is fully aware of which functions are called here, and can and will inline them, resulting in code that is just as efficient as if you'd hand-coded each case.
|
1,161,295 | 1,161,312 | Reading .docx in C++ | I'm trying to create a program that reads a .docx file and posts it content to a blog/forum for personal use. I finally have figured out how to use libcurl to do (what I figured) was the harder part of the program. Now I just have to read the .docx file, but have come under a snag. I can't seem to find any documentation on how to do this. Any ideas?
| The easiest way is to use Word to do this. It has limitations on licensing.
The SO question Creating, opening and printing a word file from C++ has some good references.
Edit:
According to these questions/answers can unzip the Open XML file and process the XML file directly:
How can I read a Word 2007 .docx file?
If you use .NET there are more (C#) questions to read:
How to grab text from word (docx) document in C#?
How to load MS Word document in C# (.NET)?
How can I programatically use C# to append multiple DOCX files together?
|
1,161,582 | 1,161,621 | Makefile, source in multiple directories, dependency problem | I am experimenting with makefile...mainly when sources are in many directories
I have following situation...
project/src/ contains directory A, B, Main
Directory A contains A.h and A.cpp; B contains B.cpp and B.h; and Test contains test.cpp
A.cpp includes A.h; B.cpp includes B.h and Main.cpp includes A.h, B.h
project/lib contains libA.a libB.a
Makefile for A and B is fine...no problem with that...i am creating libs from objects and
then copying them into lib directory
eg. makefile for directory A, and similar for B
all:test
test : A.cpp A.hh
g++ -c A.cpp -o A
ar cru libA.a A.o
cp libA.a pathto/project/lib
I have makefile for Main directory as
all: test
test: test.o
g++ -I.. -L../../lib test.o -o test -lA -lB
test.o : test.cpp
g++ -c test.cpp -o test.o
Everything works fine...only thing that I want to solve is that final executable 'test'
depends on objects from libA and libB, so when A.h or A.cpp or B.h or B.cpp changes, it should be made again
So, I now changed my makefile as
test: test.o ../../libA.a ../../libB.a
g++ -I.. -L../../lib test.o -o test -lA -lB
Now, problem is how I can modify this so that it will make test again only when its
dependencies are newer than the 'test'.
There is no direct rule to make libA and libB, which Makefile requires and complains about;
since I am copying these libs from directory A and B into directory project/lib.
So, I guess one solution would be to call make in respective directory A and B when anything is new than 'test' but how do I exactly do that ? Or, any other better solution is appreciated.
Thanks a lot :)
EDIT
Here what I did and it solved the problem
.PHONY : libA libB
../../libA.a : libA
libA :
cd pathtoDirA; $(MAKE)
../../libB.a : libB
libB :
cd pathtoDirB; $(MAKE)
| You really need to add a rule which knows how to make libA and libB, then add the dependency from test onto that rule. The rule can either call make in that directory (recursive make), or explicitly encode the rules for building the libs in your makefile. The first one is more traditional and is pretty simple to understand. It works with almost all situations you will encounter in the field, but there are some potential issues that can arise if you have more complex build setup (I would probably go with it anyway because it is simpler).
|
1,161,887 | 1,161,908 | What happens if I cast a double to an int, but the value of the double is out of range? | What happens if I cast a double to an int, but the value of the double is out of range?
Lets say I do something like this?
double d = double(INT_MIN) - 10000.0;
int a = (int)d;
What is the value of a? Is it undefined?
| Precisely. Quoting from the Standard, 4.9, "The behavior is undefined if the truncated value cannot be represented in the destination type."
|
1,162,050 | 1,163,681 | CreateRemoteThread, LoadLibrary, and PostThreadMessage. What's the proper IPC method? | Alright, I'm injecting some code into another process using the CreateRemoteThread/LoadLibrary "trick".
I end up with a thread id, and a process with a DLL of my choice spinning up. At least in theory, the DLL does nothing at the moment so verifying this is a little tricky. For the time being I'm willing to accept it on faith alone. Besides, this question needs to be answered before I push to hard in this direction.
Basically, you can't block in DllMain. However, all I've got to communicate with the remote thread is its id. This practically begs for PostThreadMessage/GetMessage shenanigans which block. I could spin up another thread in DllMain, but I have no way of communicating its id back to the creating thread and no way of passing the another thread's id to the remote one.
In a nutshell, if I'm creating a remote thread in a process how should I be communicating with the original process?
| Step zero; the injected DLL should have an entry point, lets call it Init() that takes a LPCWSTR as its single parameter and returns an int; i.e. the same signature as LoadLibrary() and therefore equally valid as a thread start function address...
Step one; inject using load library and a remote thread. Do nothing clever in the injected DLLs DLLMain(). Store the HMODULE that is returned as the exit code of the injecting thread, this is the HMODULE of the injected DLL and the return value of LoadLibrary().
Note that this is no longer a reliable approach on x64 if /DYNAMICBASE and ASLR (Address space layout randomisation) is enabled as the HMODULE on x64 is larger than the DWORD value returned from GetThreadExitCode() and the address space changes mean that it's no longer as likely that the HMODULE's value is small enough to fit into the DWORD. See the comments below and the linked question (here) for a work around using shared memory to communicate the HMODULE
Step two; load the injected DLL using LoadLibrary into the process that is doing the injecting. Then find the offset of your Init() entrypoint in your address space and subtract from it the HMODULE of your injected DLL in your address space. You now have the relative offset of the Init() function. Take the HMODULE of the injected DLL in the target process (i.e. the value you saved in step one) and add the relative address of Init() to it. You now have the address of Init() in your target process.
Step three; call Init() in the target process using the same 'remote thread' approach that you used to call LoadLibrary(). You can pass a string to the Init() call, this can be anything you fancy.
What I tend to do is pass a unique string key that I use as part of a named pipe name. The Injected DLL and the injecting process now both know the name of a named pipe and you can communicate between them. The Init() function isn't DLLMain() and doesn't suffer from the restrictions that affect DLLMain() (as it's not called from within LoadLibrary, etc) and so you can do normal stuff in it. Once the injected DLL and the injecting process are connected via a named pipe you can pass commands and data results back and forth as you like. Since you pass the Init() function a string you can make sure that the named pipe is unique for this particular instance of your injecting process and this particular injected DLL which means you can run multiple instances of the injecting process at the same time and each process can inject into multiple target processes and all of these communication channels are unique and controllable.
|
1,162,059 | 1,211,079 | How to make custon data source in QlikView? | I have just started to develop in QlikView so I'm completely a newbie.
The problem that I have is that I need to create a c++ dll that can be used as a custom data source for QlikView, I already created the dll and QlikView can see it, but I don't know how should I do to make my data available to QlikView.
The data that I want to use is obtained as a request from the server, and the code is inside the c++ dll.
I had some examples that my boss got from QlikView tech department, they are SalesForce example and EbayDll example but they are kind of confusing, so I was wondering if you can point me to another example that may be easier to follow, or if you can give me some pointers that help me accomplish what I'm trying to do.
| Just if someone is interested, I posted the same question in the QlikView Forum and the answer that I got was
"Get the version 9 SDK. It includes doc and a sample for a Custom Data Source. The SDK is available on a QV Server installation. If not already installed, I believe you can download the QVS9 and just install the SDK portion on your workstation."
The example contained in the SDK actually help me out a lot.
|
1,162,068 | 1,162,076 | Redirect both cout and stdout to a string in C++ for Unit Testing | I'm working on getting some legacy code under unit tests and sometimes the only way to sense an existing program behavior is from the console output.
I see lots of examples online for how to redirect stdout to another file in C++, but is there a way I can redirect it to an in-memory stream so my tests don't have to rely on the disk?
I'd like to get anything that the legacy code sends to stdout into a std::string so I can easily .find on the output.
Edit
The legacy code is so bad that it users a mixture of cout << .. and printf. Here is what I have so far:
void TestSuite::setUp(void)
{
oldStdoutBuf = std::cout.rdbuf();
std::cout.rdbuf(consoleOutput.rdbuf());
}
void TestSuite::tearDown(void)
{
std::cout.rdbuf(oldStdoutBuf);
}
The problem is that this does not capture output using printf. I would like something that gets both. Any ideas?
| std::stringstream may be what you're looking for.
UPDATE
Alright, this is a bit of hack, but maybe you could do this to grab the printf output:
char huge_string_buf[MASSIVE_SIZE];
freopen("NUL", "a", stdout);
setbuf(stdout, huge_string_buffer);
Note you should use "/dev/null" for linux instead of "NUL". That will rapidly start to fill up huge_string_buffer. If you want to be able to continue redirecting output after the buffer is full you'll have to call fflush(), otherwise it will throw an error. See std::setbuf for more info.
|
1,162,139 | 1,162,169 | Copying C++ API header files to a common directory | I have a Visual Studio 2008 solution comprised of several projects. Only some header files in each project represents API to the library built from the project.
Is there a way in Visual Studio to copy the files to a common directory prior compilation?
(I want to do it in order prevent including unintentionally header file I'm not supposed to)
Thanks
Dima
| Yes, on the project menu, select properties->configuration properties->build events->pre-build event. In the command line section you can enter a copy command with your source and destination paths. You may find the $solutiondir macro useful when enterting your paths.
|
1,162,262 | 1,162,291 | How can I simulate a C++ union in C#? | I have a small question about structures with the LayoutKind.Explicit attribute set. I declared the struct as you can see, with a fieldTotal with 64 bits, being fieldFirst the first 32 bytes and fieldSecond the last 32 bytes. After setting both fieldfirst and fieldSecond to Int32.MaxValue, I'd expect fieldTotal to be Int64.MaxValue, which actually doesn't happen. Why is this? I know C# does not really support C++ unions, maybe it will only read the values well when interoping, but when we try to set the values ourselves it simply won't handle it really well?
[StructLayout(LayoutKind.Explicit)]
struct STRUCT {
[FieldOffset(0)]
public Int64 fieldTotal;
[FieldOffset(0)]
public Int32 fieldFirst;
[FieldOffset(32)]
public Int32 fieldSecond;
}
STRUCT str = new STRUCT();
str.fieldFirst = Int32.MaxValue;
str.fieldSecond = Int32.MaxValue;
Console.WriteLine(str.fieldTotal); // <----- I'd expect both these values
Console.WriteLine(Int64.MaxValue); // <----- to be the same.
Console.ReadKey();
| The reason is that FieldOffsetAttribute takes a number of bytes as parameter -- not number of bits. This works as expected:
[StructLayout(LayoutKind.Explicit)]
struct STRUCT
{
[FieldOffset(0)]
public Int64 fieldTotal;
[FieldOffset(0)]
public Int32 fieldFirst;
[FieldOffset(4)]
public Int32 fieldSecond;
}
|
1,162,279 | 1,164,739 | Streaming over a TCP/IP connection | I find myself constantly running into a situation where I have a set of messages that I need to send over a TCP/IP connection. I have never found a good solution for the design of the message class. I would like to have a message base class where all messages derive from it. Since each message will have different fields, this would allow me to access the fields through member variables or methods. Something like...
class message_base
{
public:
message_base();
virtual ~message_base();
unsigned int type;
};
class message_control : public message_base
{
public:
message_control();
virtual ~message_control();
unsigned int action;
};
This way I can create a message_control and access the action member for assigning to and reading from. I can also pass the messages around without writing too much code.
The problem arises when I need to send the messages. If I override the operator<< and operator>> then I can send the messages over one variable at a time. The problem with that solution is that with so many calls to send data, the context switches will slam the processor. Also, the streaming operator ends up the the socket class and not in the message class where I would prefer it lived.
socket& socket::operator<<(message_control& message)
{
sock << type;
sock << action;
}
If I pack the data in a buffer, I get away from C++ and more into the realm of C and find myself making generous use of pointers and the like. And, modifying the code is difficult and error prone. And, the streaming operator is still in the socket class and not the message class.
socket& socket::operator<<(message_control& message)
{
byte* buffer = new byte[sizeof(message.type) + sizeof(message.action)];
memcpy(buffer, message.type, sizeof(message.type));
memcpy(buffer + sizeof(message.type), message.action, sizeof(message.action));
sock.send(buffer);
}
My last attempt used an intermediate class to handle packing and unpacking the members in a buffer. The messages could implement operator<< and operator>> to the buffer class and then the buffer class is sent to the socket. This works but doesn't feel right.
class socket
{
public:
socket();
~socket();
socket& operator<<(buffer& buff);
};
class buffer
{
public:
buffer() {m_buffer = new byte[initial_size];}
~buffer() {delete [] m_buffer;}
buffer& operator<<(unsigned int value);
private:
byte* m_buffer;
};
void message_control::serialize(buffer& buff)
{
buff << type;
buff << action;
}
I can't help but feel there is an elegant solution to this problem. I can't find any design patterns that match what I am trying to accomplish. Has anyone experienced this problem and come up with a going design that doesn't make you feel like you would be better off with good old pointers and an array of bytes?
Update
I failed to mention in my original post that I am most often dealing with very well define wire protocols. That is why I typically need to roll my own solution and can't use any of the wonderful toolkits available for messaging over a network connection.
| "The problem with that solution is that with so many calls to send data, the context switches will slam the processor. Also, the streaming operator ends up the the socket class and not in the message class where I would prefer it lived."
The solution to the second problem is to define operator<< as a non-member function in the namespace which contains the message class, instead of as a member function of the socket class. ADL will find it.
The solution to the first problem is to buffer the data within your process, and then flush at the end of each message. If Nagle buffering isn't preventing context switches, then you might be able to achieve this by messing with the socket, I don't know. What you certainly can do, though, is prepare each message before sending in a more C++-ish way. Replace:
sock << type;
sock << action;
with:
stringstream ss;
ss << type;
ss << action;
sock << ss.str();
|
1,162,401 | 1,162,910 | Is it possible to access values of non-type template parameters in specialized template class? | Is it possible to access values of non-type template parameters in specialized template class?
If I have template class with specialization:
template <int major, int minor> struct A {
void f() { cout << major << endl; }
}
template <> struct A<4,0> {
void f() { cout << ??? << endl; }
}
I know it the above case it is simple to hardcode values 4 and 0 instead of using variables but what I have a larger class that I'm specializing and I would like to be able to access the values.
Is it possible in A<4,0> to access major and minor values (4 and 0)? Or do I have to assign them on template instantiation as constants:
template <> struct A<4,0> {
static const int major = 4;
static const int minor = 0;
...
}
| This kind of problem can be solved by having a separate set of "Traits" structs.
// A default Traits class has no information
template<class T> struct Traits
{
};
// A convenient way to get the Traits of the type of a given value without
// having to explicitly write out the type
template<typename T> Traits<T> GetTraits(const T&)
{
return Traits<T>();
}
template <int major, int minor> struct A
{
void f()
{
cout << major << endl;
}
};
// Specialisation of the traits for any A<int, int>
template<int N1, int N2> struct Traits<A<N1, N2> >
{
enum { major = N1, minor = N2 };
};
template <> struct A<4,0>
{
void f()
{
cout << GetTraits(*this).major << endl;
}
};
|
1,162,619 | 1,162,786 | Fastest quote-escaping implementation? | I'm working on some code that is normalizing a lot of data. At the end of processing, a number of key="value" pairs is written out to a file.
The "value" part could be anything, so at the point of output the values must have any embedded quotes escaped as \".
Right now, I'm using the following:
outstream << boost::regex_replace(src, rxquotesearch, quoterepl);
// (where rxquotesearch is boost::regex("\"") and quoterepl is "\\\\\"")
However, gprof shows I'm spending most of my execution time in this method, since I have to call it for every value for every line.
I'm curious if there is a faster way than this. I can't use std::replace since I'm replacing one character with two.
Thanks for any advice.
| If speed is a concern you should use a hand-written function to do this. Notice the use of reserve() to try to keep memory (re)allocation to a minimum.
string escape_quotes(const string &before)
{
string after;
after.reserve(before.length() + 4);
for (string::size_type i = 0; i < before.length(); ++i) {
switch (before[i]) {
case '"':
case '\\':
after += '\\';
// Fall through.
default:
after += before[i];
}
}
return after;
}
|
1,162,646 | 1,162,806 | Microsoft Visual C++ 2003, 2005-- Are They .Net or Unmanaged? | It's kind of confusing when it comes to Microsoft Visual C++.
How to tell whether a Microsoft Visual C++ project is a .Net project, or a native C++ project?
| usually if the switch /clr:xxx is present it is managed code
I say usually since if you apply /clr:xxx on unmanaged C++ code you get a warning
|
1,162,698 | 1,162,723 | How I Can Print The IP Of The Host | I'm learning C++ and i want to know how i can print the IP adress of the host machine, but remember that my program is a command line aplication(cmd), but i don't want the code, but some links here i can learn this, not copy and paste. Thanks!
| Check this out: Socket Programming.
Winsock looks like a good choice.
|
1,162,810 | 1,195,406 | Compiling MySQL custom engine in Visual Studio 2008 | I have compilation errors while compiling MySQL sample of storage engine from MySQL 5.1.36 sources. Looks to me that I set all paths to include subdirectories but that seems not enough.
Here are the errors:
1>c:\users\roman\desktop\mysql-5.1.36\sql\field.h(1455) : error C2065: 'FRM_VER' : undeclared identifier
1>c:\users\roman\desktop\mysql-5.1.36\sql\item_cmpfunc.h(1395) : error C2146: syntax error : missing ';' before identifier 'preg'
1>c:\users\roman\desktop\mysql-5.1.36\sql\item_cmpfunc.h(1395) : error C4430: missing type specifier
- int assumed. Note: C++ does not support default-int
1>c:\users\roman\desktop\mysql-5.1.36\sql\item_cmpfunc.h(1395) : error C4430: missing type specifier
- int assumed. Note: C++ does not support default-int
| I had to include mysql_version.h.in library that contain all appropriate variables like FRM_VER, etc. That resolved the errors metioned above.
|
1,162,933 | 1,162,945 | Create header file from COM TLB | Given a managed COM object and an associated tlb file, I would like to access it from some unmanaged C++ code WITHOUT using the TLB/import command. But use a header file.
Is there a way to extract a header file from a TLB?
Thanks
| I found it (on a whim). The OLE/COM Viewer allows you to save a TLB file as a header, C, or IDL file! Very cool!
Thanks!
|
1,163,236 | 1,163,315 | Signal/Slot vs. direct function calls | So I have starting to learn Qt 4.5 and found the Signal/Slot mechanism to be of help. However, now I find myself to be considering two types of architecture.
This is the one I would use
class IDataBlock
{
public:
virtual void updateBlock(std::string& someData) = 0;
}
class Updater
{
private:
void updateData(IDataBlock &someblock)
{
....
someblock.updateBlock(data);
....
}
}
Note: code inlined for brevity.
Now with signals I could just
void Updater::updateData()
{
...
emit updatedData(data);
}
This is cleaner, reduces the need of an interface, but should I do it just because I could? The first block of code requires more typing and more classes, but it shows a relationship. With the second block of code, everything is more "formless". Which one is more desirable, and if it is a case-by-case basis, what are the guidelines?
| Emmitting a signal costs few switches and some additional function calls (depending on what and how is connected), but overhead should be minimal.
Provider of a signal has no control over who its clients are and even if they all actually got the signal by the time emit returns.
This is very convenient and allows complete decoupling, but can also lead to problems when order of execution matters or when you want to return something.
Never pass in pointers to temporary data (unless you know exactly what you are doing and even then...). If you must, pass address of your member variable -- Qt provides a way to delay destruction of object untill after all events for it are processed.
Signals also might requre event loop to be running (unless connection is direct I think).
Overall they make a lot of sense in event driven applications (actually it quickly becomes very annoying without them).
If you already using Qt in a project, definitely use them. If dependency on Qt is unacceptable, boost has a similar mechanism.
|
1,163,242 | 1,163,255 | "class std::map used without template paramaters" error | I'd have to say I'm no expert on using the STL. Here's my problem, I have a class Called LdapClientManager which maintains a number of LDAP clients that are managed by ID. The container holding the LdapClients is declared as a member variable i.e.
typedef std::map<int, LdapClient *> LdapClientMap;
LdapClientMap _ldapClientMap;
The following function fails to compile with the error:
LdapClient * LdapClientManager::getLdapClient(unsigned int templateID)
{
// Do we have an LdapClient
LdapClientMap::const_iterator it = _ldapClientMap.find(templateID);
if (it == std::map::end) {
// no existing client, lets create it
LdapClient * ldapClient = new LdapClient();
if (ldapClient == NULL) {
// TODO: handle out of memory condition
}
_ldapClientMap[templateID] = ldapClient;
return ldapClient;
}
return it->second;
}
Unfortunately I get the following error at compile time, what does it mean. I haven't found a solution in google as yet.
LdapClientManager.cc: In member function LdapClient*
LdapClientManager::getLdapClient(unsigned int)':
LdapClientManager.cc:33:template class std::map' used without template parameters
| Replace std::map::end with _ldapClientMap.end().
Also, new never returns 0, it throws an exception if the allocation fails.
Note that the program can be made much shorter.
LdapClient * LdapClientManager::getLdapClient(unsigned int templateID)
{
LdapClient *& value = _ldapClientMap[templateID];
if (value == 0)
value = new LdapClient();
return value;
}
|
1,163,503 | 1,163,519 | What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32? | Can any body tell me what is the difference between regsvr32 and RegAsm? My Dll is in C#, so how can I import the classes to c++?
| regsvr32 will load the library and try to call the DllRegisterServer() from that library. It doesn't care what DllRegisterServer() actually does - it just calls that function and checks the returned value. You use it to register COM servers in unmanaged DLLs. It can't generate a .tlb file.
regasm will register a COM-exposed .NET assembly as a COM server. You use it for .NET assemblies. It can generate a .tlb file given the assembly only - it inspects the type infromation stored in the assembly and includes the COM-exposed entities into the type library.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.