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 |
|---|---|---|---|---|
2,369,676 | 2,369,700 | C++ program gets undefined reference to a dynamic C library during linking | I've created a dynamic networking library in C. When I try to link it in my C++ program I get an undefined reference the first time I call one of my functions in the library. What I can't understand is that I created a little test program in C that uses the library and it links just fine.
Could someone help with my problem? Here are the steps I've taken to create my library and link it.
Library creation:
Code my library
Compile with the line: gcc -c -fPIC -g -Wall ./libnet.c
Link my library object file and create the shared object file with the line: gcc -shared -o libnet.so -g -Wall ./libnet.o
Move my library to the appropriate folders and set LD_LIBRARY_PATH:
I copy my library to two directories. One directory is the test C program that links properly and one is the C++ program that doesn't link properly.
I set the environment variable LD_LIBRARY_PATH to both the directories that use the library
Compile and link my program:
Code my program
Compile all my .cpp files with the line: g++ -c -g -Wall ./
Link together all my object files and the shared library to create my program with the line: g++ -o -g -Wall -L./ -lnet
Here is the make file that I use. Maybe I have something wrong in here?
PPFLAGS = -g -Wall
TARGET = msgfrwdserver
OBJS = msgfrwdserver.o
msgfrwdhelper.o msgfrwd.o climsgfrwd.o
LIBS = libnet.so
CPPLP =
-L/usr/home/chris/development/legends/servers/monitor
-L/usr/home/chris/development/legends/servers/msgfrwd
CPPFILES = ./msgfrwdserver.cpp
./msgfrwdhelper.cpp
./classes/msgfrwd.cpp
./classes/climsgfrwd.cpp
CPPIP = -I./classes
-I/usr/home/chris/development/legends/libnet
all: ${OBJS} ${TARGET}
${TARGET}: ${OBJS} ${LIBS}
g++ -o
${TARGET} ${PPFLAGS} -L./ -lnet
${CPPIP} ${OBJS}
msgfrwdserver.o: ./msgfrwdserver.cpp
g++ -c ${PPFLAGS} ${CPPIP}
./msgfrwdserver.cpp
msgfrwdhelper.o:
./msgfrwdhelper.cpp
g++ -c ${PPFLAGS}
./msgfrwdhelper.cpp
msgfrwd.o:
./classes/msgfrwd.cpp
g++ -c
${PPFLAGS} ./classes/msgfrwd.cpp
climsgfrwd.o: ./classes/climsgfrwd.cpp
g++ -c ${PPFLAGS} ${CPPIP}
./classes/climsgfrwd.cpp
clean: rm
-rf ${TARGET} *.o *~ .core ./classes/~
I really have no idea what the problem could be. Any help would be much appreciated. Do I have to do something differently to get a C library to work with a C++ program?
Sorry that the make file is messy. I didn't exactly translate well when I tried to block quote it or say it was a code sample.
| C library functions must have en extern "C" definition in order to call them from C++ to turn of name-mangeling.
extern "C"
{
int test();
}
With the extern , the the Microsoft C++ compiler will look for the symbol "_test", otherwise it will look for "?test@@YAHXZ" (The C++ name-mangeled version of int test() )
|
2,369,761 | 2,369,835 | find the position of a string in another string |
Possible Duplicate:
substring algorithm
Given two strings, A and B, how to find the first position of B in A?
For instance, A = " ab123cdefgcde"; B= "cde"
Then the first position of B in A is 5.
Is there any trick to solve this problem or just search A from the start?
| The problem that you are solving is the "exact string matching" problem. The naive solution runs in O(n^2) time, but you can do much better than that. Some linear-time algorithms to solve this problem are Knuth-Morris-Pratt (KMP), Boyer-Moore, and Apostolico-Giancarlo. Another way to solve it is by constructing a finite state automaton that enters an accepting state when it sees the pattern string. The best possible solution is O(n), and all those have that worst-case running time. You do have to scan the string from one end to the other; however, it is possible to skip a fraction of the characters (which Boyer-Moore and Apostolico-Giancarlo will do), since some mismatches can imply other mismatches.
If you need to code this yourself, I recommend you go with the Knuth-Morris-Pratt algorithm, since it is a little bit more intuitive and easier to implement than the other solutions I've mentioned. Most programming languges, though, have an "indexOf" or "find" function that will solve this for you.
|
2,369,802 | 2,370,154 | How do I include bitmaps on items I've added to the end of a context menu? | I'm currently writing a Windows Explorer Shell Extension. Everything is ok so far but I'm having trouble to insert menu items WITH MenuItemBitmaps at the end of the context menu.
Here is the code I used without the bitmaps:
HRESULT CSimpleShlExt::QueryContextMenu(HMENU hmenu, UINT /*uMenuIndex*/, UINT uidFirstCmd, UINT /*uidLastCmd*/, UINT uFlags)
{
InsertMenu(hmenu, -1, MF_SEPARATOR, uidFirstCmd++, _T(""));
InsertMenu(hmenu, -1, MF_STRING | MF_BYPOSITION, uidFirstCmd++, _T("SimpleShlExt Test Item"));
InsertMenu(hmenu, -1, MF_STRING | MF_BYPOSITION, uidFirstCmd++, _T("SimpleShlExt Test Item 2"));
return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, 3); // 3 because we do have three menu items!!!
}
This code does what I want. It adds a separator and two menu items at the end of the context menu when I right click in the Windows explorer.
I can also add bitmaps to these menu items with this code:
HRESULT CSimpleShlExt::QueryContextMenu(HMENU hmenu, UINT uMenuIndex, UINT uidFirstCmd, UINT /*uidLastCmd*/, UINT uFlags)
{
// load the bitmap from the resource
HBITMAP hBitmap = (HBITMAP)LoadImage((HMODULE)_AtlBaseModule.m_hInst,
MAKEINTRESOURCE(IDB_BITMAP), IMAGE_BITMAP, 16, 16, 0);
InsertMenu(hmenu, uMenuIndex++, MF_SEPARATOR, uidFirstCmd++, _T(""));
InsertMenu(hmenu, uMenuIndex++, MF_STRING | MF_BYPOSITION, uidFirstCmd++, _T("SimpleShlExt Test Item"));
SetMenuItemBitmaps(hmenu, uMenuIndex - 1, MF_BITMAP | MF_BYPOSITION, hBitmap, hBitmap);
InsertMenu(hmenu, uMenuIndex++, MF_STRING | MF_BYPOSITION, uidFirstCmd++, _T("SimpleShlExt Test Item 2"));
SetMenuItemBitmaps(hmenu, uMenuIndex - 1, MF_BITMAP | MF_BYPOSITION, hBitmap, hBitmap);
return MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_NULL, 3); // 3 because we do have three menu items!!!
}
But now the menu items are placed somewhere in the middle of the context menu and not at the end. Simply setting -1 instead of uMenuIndex doesn't work. The menu items are indeed placed at the end but the bitmaps are not shown.
Any ideas?
| The documentation for SetMenuItemBitmaps says nothing about accepting -1 as a valid position like InsertMenu does. You know the command IDs of the items you've added, and you know they're unique, so add the bitmaps by command instead of by position.
InsertMenu(hmenu, -1, MF_STRING | MF_BYPOSITION, uidFirstCmd, _T("SimpleShlExt Test Item"));
SetMenuItemBitmaps(hmenu, uidFirstCmd, MF_BITMAP | MF_BYCOMMAND, hBitmap, hBitmap);
++uidFirstCmd;
You're ignoring the instructions that the menu host has given you regarding where to put your menu items. The only reason you've seen success so far is because the menu host hasn't added any other items after you added yours, and all the other menu extensions have played by the rules and added their items where they were told. If they decide to ignore the rules like you, then they might end up at the end instead of yours.
|
2,369,806 | 2,420,366 | Simulating mouse clicks on Mac OS X does not work for some applications | I'm writing an application for Mac OS X 10.6 and later in C++. One part of the application needs to simulate mouse movement and mouse clicks. I do this currently by posting CGEvent objects using CGEventPost(kCGHIDEventTap, event);.
This works, for the most part - I can simulate mouse movement and clicks just fine, but it seems to fail in some areas. For example:
In Mozilla Firefox and Safari, I can click on all the menus, but cannot click on a link within a website. When I try, the link is highlighted, but the browser never follows the link. However, I can right-click on a link, select "open link in new tab", and everything works as expected. Solved - creating the mouse event using CGEventCreateMouseEvent(...) makes the event work within web browser.
I can click on the "Dashboard" icon to brink up the dashboard, but I cannot click on the "i" button on any of the dashboard widgets. Similarly, clicking on any of the search results from the spotlight search widget doesn't work either.
This inconsistency is along application boundaries. What might be the cause?
| What you need to do to convince these applications that you have in fact generated a click is to explicitly set the value of the "click state" field on the mouse up event to 1 (it defaults to 0). The following code will do it:
CGEventSetIntegerValueField(event, kCGMouseEventClickState, 1);
It also has to be set to 1 for the mouse down, but by using CGEventCreateMouseEvent() rather than CGEventCreate() that gets done for you.
I have tested this and it works in the 'i' buttons in the dashboard and the Spotlight search results.
(As an aside, if you were simulating a double click you would need to set the click state to 2 for both the mouse down and mouse up events of the second click.)
|
2,369,976 | 2,504,035 | is it safe to to destroy a socket object while an asyn_read might be going on in boost.ASIO? | In the following code:
tcp::socket socket(io_service);
tcp::endpoint ep(boost::asio::ip::address::from_string(addr), i);
socket.async_connect(ep, &connect_handler);
socket.close();
is it correct to close the socket object, or should I close it only in the connect_handler(), resort to shared_ptr to prolong the life of of the socket object?
Thanks.
| Closing the socket isn't much of an issue, but the socket being destructed and deallocated is. One way to deal with it is to just make sure the socket outlives the io_service where work is being done. In other words, you just make sure to not delete it until after the io_service has exited. Obviously this won't work in every situation.
In a variety of conditions it can be difficult to impossible to tell when all work is really done on the socket when it's active within the io_service, and ASIO doesn't provide any mechanism to explicitly remove or disconnect the object's callbacks so they don't get called. So you should consider holding the connection in a shared_ptr, which will keep the connection object until the last reference inside the io_service has been released.
Meanwhile your handler functors should handle all possible errors passed in, including the connection being destroyed.
|
2,370,090 | 2,370,428 | Protobuf-net - serializing .NET GUID - how to read this in C++? | I have serialized an object using Protobuf-net , in my .NET application, with relative ease.
I also get the .proto file that protobuf-net generated, using GetProto() command.
In the .NET generated .proto file, my GUID fields get a type of "bcl.guid".
Now I wish to compile the .proto file in C++ so I can deserialize the data.
However, C++ protoc.exe compiler does not know how to interpret bcl.guid, and throws an error message "VideoAudioStructs.proto:11:13: "Guid" is not defined."
What do I do with this?
| protobuf-net encodes this as a pair of fixed-length 64 bit values at fields 1 and 2. I haven't tried it for interop purposes, but you could try importing the (bespoke) bcl.proto (I think this is in the deployment folder; if not let me know and I'll add it; otherwise it is in the trunk).
But conceptually it is just:
message guid {
optional fixed64 lo = 1; // the first 8 bytes of the guid
optional fixed64 hi = 2; // the second 8 bytes of the guid
}
If you get any problems, a fallback approach would be to send it (instead) as a bytes chunk, by adding a shim property. Let me know if you want an example of that.
|
2,370,132 | 2,370,167 | filling an array with random number | I'm trying to fill an array of 20 ints with numbers from 1-20 in random sequence.
here's my code:
int lookup[20]={0};
int array[20]={0};
srand(time(NULL));
for(int i=0;i<20;++i){
bool done=false;
while(!done){
int n=rand()%20;
if(lookup[n]==0){
array[i]=n;
lookup[n]=1;
done=true;
}
}
}
I've created a lookup array to check if the random number is not yet chosen and stored it in array. As you can see I've created 2 loops, one for traversing array and the while for choosing the random number. In every while loop iteration the number may reappear and causing another while loop. Is there faster way to do this?
| You could fill the array in sequence and then shuffle it. That would prevent having to ever do more than 20 random number generations.
Fisher-Yates shuffle: can be done in O(n) time.
From wikipedia:
Properly implemented, the Fisher–Yates shuffle is unbiased, so that every permutation is equally likely. The modern version of the algorithm is also rather efficient, requiring only time proportional to the number of items being shuffled and no additional storage space.
|
2,370,513 | 2,370,578 | How to get instance of nested class in C++ | I have the following code:
class outer
{
struct inner
{
int var1;
int var2;
inner() { var1 = 1; var2 = 2; }
};
inner inner_instance;
public:
const inner *get_inner() { return &inner_instance; }
};
int main(int argc, char *argv[])
{
// 1
outer outer_instance;
cout << outer_instance.get_inner()->var1 << endl;
// 2
// this cannot be compiled because outer::inner is private
//const outer::inner *inner_ref = outer_instance.get_inner();
//cout << inner_ref->var1;
// 3
const int *inner_var2 = (int *) outer_instance.get_inner();
inner_var2++;
cout << *inner_var2 << endl;
return 0;
}
I understand why No.2 cannot be compiled. I just do not know what is the design idea of the compiler that allows access to the public fields of a private nested class but not the nested class itself, like No.1. The instance data is still in the memory. If I know the structure of such private nested class, I can still achieve assigning like No.3 does.
Does that mean it is better not to return pointer or reference of a private nested class in a public function? And if I really have to return something about the nested class to the outer world, make it public?
Thanks!
| Put the struct inner definition in the public if you want to use it outside outer class.
class outer
{
public:
struct inner
{
int var1;
int var2;
inner() { var1 = 1; var2 = 2; }
};
private:
inner inner_instance;
public:
const inner *get_inner() { return &inner_instance; }
};
|
2,370,557 | 2,371,708 | How to hide completely a QGridLayout? | I have a button followed by a QGridLayout full of widgets.
I want to show/hide QGridLayout at every button click, but reading documentation of QGridLayout I see there's no show()/hide() implementation, also no setVisible() method available.
How do I achieve this?
| You didn't mention which version of Qt you're using. (I'm looking at the 4.4 documentation.)
I haven't tried this, but here are two ideas:
QGridLayout inherits the function QLayoutItem::widget(). If your layout is a widget, this will return a QWidget* on which you can call show() or hide().
If your QGridLayout is not a QWidget, you can nest it within a QWidget, and you can show() / hide() that widget instead.
|
2,370,611 | 2,370,739 | Does splitting C++ code into multiple translation units introduce overhead on the executable size? | I have some code shared among multiple projects in a static library. Even with function-level linking I get more object code than I'd like to in the output - see another question about that.
Surely the most straightforward solution to decreasing the amount of object code linked into the final executable would be to split the translation units so that I get more .obj files each with less object code. I can even go to extremes - put each function into a separate translation unit.
Let's pretend I don't care of the mess induced by having ten times more .cpp files and I don't care of possible link time growth.
Will such splitting into many object files introduce overhead on the executable size? Will the executable become bigger simply because there were ten times more .obj files (but overall they have exactly the same functions and variables) linked into it?
| Things which are more likely to affect your final EXE size (not exhaustive list):
Whether you static or dynamically link to libraries (dynamic link is smaller since the library code is not inside your EXE)
It's possible use of many template classes eg. vector<A>, vector<B>, vector<C> will cause code bloat, since each instantiation of vector with different types is compiled separately
Compiler settings, eg. optimisation, size vs. speed, inlining (lots of inlining can make code larger), whole program optimisation if supported
Linker settings, eg. if supported, removing redundant or identical data. Can help reduce size.
In short splitting code up in to more translation units probably will have no effect - same code, just reorganised. It might even make things worse if your compiler does not take in to account whole program optimisation, since each translation unit has less information about your program in it.
|
2,370,986 | 2,371,023 | What does returning zero by convention mean? | This is likely a stupid question but I always find myself wondering which is the standard.
In most (not to say all) C++ first examples you may see the main function returning 0 value. This means the operation went ok or not?
0 --> OK
1 --> No OK.
Other --> ?
Which is the standard way of doing it?
By the way, is it better to return an integer or a boolean in this case?
Thank you guys!
| 0 or EXIT_SUCCESS means success. EXIT_FAILURE means failure. Any other value is implementation defined, and is not guaranteed to be supported. In particular, std::exit(1) or return 1; are not actually guaranteed to indicate failure, although on most common systems they will.
EXIT_SUCCESS and EXIT_FAILURE are defined in <cstdlib>.
Edit: I suppose it might be useful to give a system-specific example:
The GNU make utility returns an exit status to the operating system:
0: The exit status is zero if make is successful.
2: The exit status is two if make encounters any errors. It will print messages describing the particular errors.
1: The exit status is one if you use the `-q' flag and make determines that some target is not already up to date.
The ability to set multiple different values of failure means you can specify exactly how your program failed. There are two caveats, however:
There is no convention for failure status codes, afaik
This will work on "normal" OSes (windows, os x, unix), but it's not guaranteed by the C++ standard; so it might not work if you tried porting to VMS or some embedded system.
|
2,371,123 | 2,387,752 | Get output of CMD line program from C++ (specifically netstat) | I want to be able to run "netstat -n" and grab the output somehow so I can then write it out to another file.
How can I do this in C++ on Windows CE
Thankyou
Chris
| I solved this by essentially calling netstat from the cmd prompt, piping the output to a file, and then using it from there. I believe Kerido's answer to be right but this is how I got it working.
This code then launches cmd.exe and telling it to run netstat -n. Note that the /c is required else cmd.exe will not launch the code
int retVal = CreateProcessW(L"cmd.exe", L"/c netstat -n > \"/netstatoutput.txt\"", NULL, NULL, NULL, CREATE_NEW_CONSOLE, NULL, NULL, NULL, NULL);
|
2,371,176 | 2,371,324 | C++ private virtual inheritance problem | In the following code, it seems class C does not have access to A's constructor, which is required because of the virtual inheritance. Yet, the code still compiles and runs. Why does it work?
class A {};
class B: private virtual A {};
class C: public B {};
int main() {
C c;
return 0;
}
Moreover, if I remove the default constructor from A, e.g.
class A {
public:
A(int) {}
};
class B: private virtual A {
public:
B() : A(3) {}
};
then
class C: public B {};
would (unexpectedly) compile, but
class C: public B {
public:
C() {}
};
would not compile, as expected.
Code compiled with "g++ (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)", but it has been verified to behave the same with other compilers as well.
| According to C++ Core Issue #7 class with a virtual private base can't be derived from. This is a bug in compiler.
|
2,371,433 | 2,371,535 | How to get the pointer to a shared_ptr? | I am now hacking an old C code, try to make it more C++/Boost style:
there is a resource allocation function looks like:
my_src_type* src;
my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL);
i try to wrap src by a shared_ptr:
shared_ptr<my_src_type> pSrc;
I forgot to mention just now. I need to do this as a loop
std::map<string, shared_ptr<my_src_type> > dict;
my_src_type* raw_ptr;
BOOST_FOREACH(std::string topic, all_topics)
{
my_src_create(&raw_ptr, ctx, topic, handle_src_event, NULL, NULL);
boost::shared_ptr<my_src_type> pSrc(raw_ptr);
dict[topic] = pSrc;
}
Can I do it like this?
| No.
Basically, you have to do it the old C way and then convert the result to a shared_pointer somehow.
You can do it by simply initializing the shared_pointer
my_src_type* pSrc;
my_src_create(&src, ctx, topic, handle_src_event, NULL, NULL);
shared_ptr<my_src_type> sp(pSrc);
but beware, this will fail if the my_src_create function can return an already existing object. Also, if there is a my_src_destroy function, it won't be called.
IMHO the cleanest way is to wrap your structure in a C++ class:
class MySrc {
my_src_type* pSrc;
public:
MySrc(...) { my_src_create(&pSrc, ...); }
~MySrc() { my_src_destroy(&pSrc); }
private:
MySrc(const MySrc&);
void operator=(const MySrc&); // disallow copying
};
and then use shared pointer for MySrc the ususal way.
|
2,371,560 | 2,371,613 | What is the easiest way to insert Data into a mysql DB with C++? |
Do i need external libraries ?
is there any minimalistic example ?
| The easiest way is to use the C API which is usually installed along with the MySQL Server. On Windows, for example, it's in "C:\Program Files\MySQL\MySQL Server 5.0" (see "include" and "lib" directory).
If you are looking for examples that demonstrate how to use the C API, take a look at these clients. You can find these in the client directory in the MySQL source distribution.
The client API is called mysqlclient, you can find the documentation here.
But you can also use other libraries like the C++ wrapper on sourceforge. Or an ODBC abstraction like contained in cross-platform toolkits (e.g. wxDb in wxWidgets).
|
2,371,668 | 2,371,698 | Is returning a string literal address from a function safe and portable? | I need a function to return a string that will only be accessed read-only. The string contents is known at compile time so that I will use a string literal anyway.
I can return something like std::string:
std::string myFunction()
{
return "string";
}
or return const char*:
const char* myFunction()
{
return "string";
}
Is the second alternative safe and portable in this scenario?
|
Is the second alternative safe and portable in this scenario?
Yes! The storage allocation of string literals is static and they persist for the lifetime of the application.
|
2,371,833 | 2,371,916 | binary_search, find_if and <functional> | std::find_if takes a predicate in one of it's overloaded function. Binders make it possible to write EqualityComparators for user-defined types and use them either for dynamic comparison or static comparison.
In contrast the binary search functions of the standard library take a comparator and a const T& to the value that should be used for comparison. This feels inconsistent to me and could possibly more inefficient as the comparator has to be called with both arguments every time instead of having the constant argument bound to it. While it could be possible to implement std::binary_search in a way to use std::bind this would require all comparators to inherit from std::binary_function. Most code I've seen doesn't do that.
Is there a possible benefit from letting comparators inherit from std::binary_function when using it with algorithms that take a const T& as a value instead of letting me use the binders? Is there a reason for not providing predicate overloads in those functions?
| A single-argument predicate version of std::binary_search wouldn't be able to complete in O(log n) time.
Consider the old game "guess the letter I'm thinking of". You could ask: "Is it A?" "Is it B?".. and so on until you reached the letter. That's a linear, or O(n), algorithm. But smarter would be to ask "Is it before M?" "Is it before G?" "Is it before I?" and so on until you get to the letter in question. That's a logarithmic, or O(log n), algorithm.
This is what std::binary_search does, and to do this in needs to be able to distinguish three conditions:
Candidate C is the searched-for item X
Candidate C is greater than X
Candidate C is less than X
A one-argument predicate P(x) says only "x has property P" or "x doesn't have property P". You can't get three results from this boolean function.
A comparator (say, <) lets you get three results by calculating C < X and also X < C. Then you have three possibilities:
!(C < X) && !(X < C) C is equal to X
C < X && !(X < C) C is less than X
!(C < X) && X < C C is greater than X
Note that both X and C get bound to both parameters of < at different times, which is why you can't just bind X to one argument of < and use that.
Edit: thanks to jpalecek for reminding me binary_search uses <, not <=.
Edit edit: thanks to Rob Kennedy for clarification.
|
2,371,897 | 2,371,915 | Weird problem porting application. Undefined reference errors in standard libraries | I've recently been trying to port a C++ application. I believe I have all of it's dependencies and such and it all compiles. But then, when it goes to link it I get a lot of weird undefined reference errors.
/usr/local/lib/libglibmm-2.4.so.7.0: undefined reference to `std::basic_istream<char, std::char_traits<char> >::seekg(long, std::_Ios_Seekdir)'
/usr/local/lib/libglibmm-2.4.so.7.0: undefined reference to `std::basic_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t> >::_S_empty_rep_storage'
/usr/local/lib/libxml++-2.6.so.0.1: undefined reference to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::_S_empty_rep_storage'
/usr/local/lib/libxml++-2.6.so.0.1: undefined reference to `std::__default_alloc_template<true, 0>::deallocate(void*, unsigned long)'
What can cause this kind of errors? What do the linking errors mean? I can't really understand the complicated template error messages that gcc gives..
The linking command in it's entirety:
gmake[3]: Entering directory `/home/earlz/synfig-0.62.00/src/tool'
/bin/sh ../../libtool --tag=CXX --mode=link eg++ -I/usr/local/include/libxml++-2.6 -I/usr/local/lib/libxml++-2.6/include -I/usr/local/include/libxml2 -I/usr/local/include -I/usr/local/include/glibmm-2.4 -I/usr/local/lib/glibmm-2.4/include -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include/sigc++-2.0 -I/usr/local/lib/sigc++-2.0/include -I/usr/local/include -I/usr/local/include/sigc++-2.0 -I/usr/local/lib/sigc++-2.0/include -DSYNFIG_NO_DEPRECATED -DLOCALEDIR=\"/usr/local/share/locale\" -DNDEBUG -O2 -W -Wall -o synfig synfig-main.o ../synfig/libsynfig.la -L/usr/local/lib -lxml++-2.6 -lxml2 -lglibmm-2.4 -lgobject-2.0 -lglib-2.0 -lintl -liconv -lsigc-2.0 -lpthread -L/usr/local/lib -lsigc-2.0 -L/usr/local/lib -lintl -L/usr/local/lib -liconv -lpthread
libtool: link: eg++ -I/usr/local/include/libxml++-2.6 -I/usr/local/lib/libxml++-2.6/include -I/usr/local/include/libxml2 -I/usr/local/include -I/usr/local/include/glibmm-2.4 -I/usr/local/lib/glibmm-2.4/include -I/usr/local/include/glib-2.0 -I/usr/local/lib/glib-2.0/include -I/usr/local/include/sigc++-2.0 -I/usr/local/lib/sigc++-2.0/include -I/usr/local/include -I/usr/local/include/sigc++-2.0 -I/usr/local/lib/sigc++-2.0/include -DSYNFIG_NO_DEPRECATED -DLOCALEDIR=\"/usr/local/share/locale\" -DNDEBUG -O2 -W -Wall -o .libs/synfig synfig-main.o -L../synfig/.libs -lsynfig -L/usr/local/lib -lxml++-2.6 -lxml2 -lm -lz -lglibmm-2.4 -lgmodule-2.0 -lgobject-2.0 -lglib-2.0 -lpcre -lsigc-2.0 -lintl -liconv -lpthread -Wl,-rpath,/usr/local/lib
Also, I do not get any kind of linking errors about missing files, just stuff about weird string and filestream stuff missing
| Use g++ to link C++ applications, that add C++ standard libraries to the link phase.
|
2,372,014 | 2,387,003 | llvm clang 2.6: "not using the clang compiler for C++ inputs " | LLVM 2.6 + clang.
Trying to compile C++ file and got:
clang: warning: not using the clang compiler for C++ inputs
How can I start clang in C++ mode?
| I would get the trunk code. C++ support has been much improved since 2.6.
The clang driver Makefile in tools/clang/tools/driver uses the CLANG_IS_PRODUCTION define to control whether C++ is on or off. CLANG_IS_PRODUCTION means C++ off. The default for a trunk build is no CLANG_IS_PRODUCTION (i.e. a development build).
|
2,372,027 | 2,372,071 | Compiler complains about BOOST_CHECK_THROW on constructor | The following does not compile:
class Foo {
public:
Foo( boost::shared_ptr< Bar > arg );
};
// in test-case
boost::shared_ptr< Bar > bar;
BOOST_CHECK_THROW( Foo( bar ), std::logic_error ); // compiler error here
The implementation of Bar does not matter. The compiler complains, that Foo does not have an appropriate default constructor (VC++ 2005). If I add a default constructor, it works, and it actually gets called. Why does this statement require a default constructor?
| This occurs because BOOST_CHECK_THROW is a macro, and Foo(bar) is being expanded to a statement. The compiler sees this statement and interprets it as a variable declaration Foo bar; which requires a default constructor.
The solution is to give the variable a name:
BOOST_CHECK_THROW( Foo temp( bar ), std::logic_error );
In other words BOOST_CHECK_THROW will expand to something like
try
{
Foo(bar);
// ... fail test ...
}
catch( std::logic_error )
{
// ... pass test ...
}
and the compiler is interpreting Foo(bar); as the declaration of a variable called bar. One can check this with a simple program:
struct Test
{
Test(int *x) {}
};
int main()
{
int *x=0;
Test(x);
return 0;
}
which gives the following errors with g++
test.cpp: In function ‘int main()’:
test.cpp:10: error: conflicting declaration ‘Test x’
test.cpp:9: error: ‘x’ has a previous declaration as ‘int* x’
|
2,372,272 | 2,381,671 | Qt4: Locking the mouse cursor in place while manipulating QGraphicsItem | I'm writing a little GUI utility in Qt4 which uses a QGraphicsScene. One of the items tracks the mouse in the horizontal plane as you move it around, and holding down a modifier key allows you to change the item's rotation. When rotating items I'd like the mouse cursor to change to a curvy arrow (or something) and lock visually in place, so moving it affects the item but not the mouse cursor itself.
Releasing the modifier would place the (previously invisible) cursor back to it's original point: this is to prevent the item "jumping" to the mouse's new horizontal position afterwards, which is my main problem.
I've really got no idea how to implement this in Qt4 that doesn't involve doing horrible things like:
When the modifier is pressed store the current mouse position
Switch the cursor to a bitmap of nothing
Somehow draw a fake cursor in the original place (!?)
Delete the fake cursor and switch the mouse position back when done
Be very grateful if anyone can think of a better way to achieve this. I'm not too wedded to the whole fixed mouse cursor idea in the first place but it's the only way I can think to get around this one problem with a control scheme that otherwise works pretty nicely.
Edit: I tried the crap scheme I outlined above and ran into problems moving the position of the mouse programmatically. Still trying to remember where I've used a similar system before: basically it was a rotary knob. You clicked it and moved the mouse up and down, which rotated the knob. When you released the mouse button the pointer was back where you'd initially put it, on the knob.
| How about using an event filter to catch QMouseEvents, while this is going on?
|
2,372,291 | 2,372,354 | how failed constructor roll over to destroy the completed objects? | I know that when a constructor fails, the completed member objects will be destroyed. There is no memory leak.
My question is that how does compiler do that? How can compiler know what member is constructed? Does it make any record of it? Does the compiler really destroy everything in this case? How does it guarantee this?
| How the compiler does that is up to the compiler.
But yes, you are guaranteed that any constructed objects will be destructed (in the reverse order they were constructed). §15.2/2:
An object that is partially constructed or partially destroyed will have destructors executed for all of its fully constructed subobjects, that is, for subobjects for which the constructor has completed execution and the destructor has not yet begun execution. Should a constructor for an element of an automatic array throw an exception, only the constructed elements of that array will be destroyed. If the object or array was allocated in a new-expression, the matching deallocation function (3.7.3.2, 5.3.4, 12.5), if any, is called to free the storage occupied by the object.
|
2,372,315 | 2,372,368 | How to implement strlen as fast as possible | Assume that you're working a x86 32-bits system. Your task is to implement the strlen as fast as possible.
There're two problems you've to take care:
1. address alignment.
2. read memory with machine word length(4 bytes).
It's not hard to find the first alignment address in the given string.
Then we can read memory once with the 4 bytes, and count up it the total length. But we should stop once there's a zero byte in the 4 bytes, and count the left bytes before zero byte. In order to check the zero byte in a fast way, there's a code snippet from glibc:
unsigned long int longword, himagic, lomagic;
himagic = 0x80808080L;
lomagic = 0x01010101L;
// There's zero byte in 4 bytes.
if (((longword - lomagic) & ~longword & himagic) != 0) {
// do left thing...
}
I used it in Visual C++, to compare with CRT's implementation. The CRT's is much more faster than the above one.
I'm not familiar with CRT's implementation, did they use a faster way to check the zero byte?
| First CRT's one is written directly in assembler. you can see it's source code here C:\Program Files\Microsoft Visual Studio 9.0\VC\crt\src\intel\strlen.asm (this is for VS 2008)
|
2,372,339 | 2,372,367 | Why do we follow opposite conventions while returning from main()? | I have gone through this and this,
but the question I am asking here is that why is 0 considered a Success?
We always associate 0 with false, don't we?
| Because there are more fail cases than success cases.
Usually, there is only one reason we succeed (because we're successful :)), but there are a whole lot of reasons why we could fail. So 0 means success, and everything else means failure, and the value could be used to report the reason.
For functions in your code, this is different, because you are the one specifying the interface, and thus can just use a bool if it suffices. For main, there is one fixed interface for returns, and there may be programs that just report succeed/fail, but others that need more fine error reporting. To satisfy them all, we will have multiple error cases.
|
2,372,459 | 2,372,540 | Checking return value of a C++ executable through shell script | I am running a shell script on windows with cygwin in which I execute a program multiple times with different arguments each time. Sometimes, the program generates segmentation fault for some input arguments. I want to generate a text file in which the shell script can write for which of the inputs, the program failed. Basically I want to check return value of the program each time it runs. Here I am assuming that when program fails, it returns a different value from that when it succeeds. I am not sure about this. The executable is a C++ program.
Is it possible to do this? Please guide. If possible, please provide a code snippet for shell script.
Also, please tell what all values are returned.
My script is .sh file.
| You can test the return value using shell's if command:
if program; then
echo Success
else
echo Fail
fi
or by using "and" or "or" lists to do extra commands only if yours succeeds or failed:
program && echo Success
program || echo Fail
Note that the test succeeds if the program returns 0 for success, which is slightly counterintuitive if you're used to C/C++ conditions succeeding for non-zero values.
|
2,372,468 | 2,372,638 | Triple checked locking? | So in the meanwhile we know that double-checked-locking as is does not work in C++, at least not in a portable manner.
I just realised I have a fragile implementation in a lazy-quadtree that I use for a terrain ray tracer. So I tried to find a way to still use lazy initialization in a safe manner, as I wouldn't like to quadruple memory usage and re-order large parts of implemented algorithms.
This traversal is inspired by the pattern on page 12 of C++ and the Perils of Double-Checked Locking, but tries to do it cheaper:
(pseudo code!)
struct Foo {
bool childCreated[4];
Mutex mutex[4];
Foo child[4];
void traverse (...) {
...
if (!childCreated[c]) {
// get updated view
#pragma flush childCreated[c]
if (!childCreated[c]) {
ScopedLock sl (mutex[c]);
if (!childCreated[c]) {
create (c);
#pragma flush childCreated[c]
childCreated[c] = true;
}
}
}
}
}
It is assumed that #pragma flush would also serve as a hard sequence point where compilers and processors won't be allowed to re-order operations across them.
Which problems do you see?
edit: Version 2, trying to take into account Vlads answer (introduce third flush):
(pseudo code!)
struct Foo {
bool childCreated[4];
Mutex mutex[4];
Foo child[4];
void traverse (...) {
...
if (!childCreated[c]) {
// get updated view
#pragma flush childCreated[c]
if (!childCreated[c]) {
ScopedLock sl (mutex[c]);
#pragma flush childCreated[c]
if (!childCreated[c]) {
create (c);
#pragma flush childCreated[c]
childCreated[c] = true;
}
}
}
}
}
edit: Version 3, I somehow find this pretty equivalent to Version 2, because I am not using the child itself but a primitive flag to check for validity, basically relying on a memory barrier between creating a child and writing to that flag.
(pseudo code!)
struct Foo {
bool childCreated[4];
Mutex mutex[4];
Foo child[4];
void traverse (...) {
...
if (!childCreated[c]) {
ScopedLock sl (mutex[c]);
#pragma flush childCreated[c]
if (!childCreated[c]) {
create (c);
#pragma flush childCreated[c]
childCreated[c] = true;
}
}
}
}
| It seems that your pattern is not correct. Consider the case when thread #1 executes till after the first #pragma flush. Then the control switches to the thread #2, which goes on and creates a c, the control is taken back just before second #pragma flush. Now the first thread wakes up, and creates the child anew.
Edit: sorry, wrong: it will be unable to take the lock.
Edit 2: no, still correct, because the value will be not flushed in thread #1
|
2,372,491 | 2,372,504 | insert object into a set | I want to insert a vector into a set like this:
set<vector<prmEdge> > cammini;
vector<prmEdge> vecEdge;
cammini.insert(vecEdge);
I have a compilation error like this:
prmPlanner.cpp:1285: instantiated from here
/usr/include/c++/4.2/bits/stl_algobase.h:853: error: no match for ‘operator<’ in ‘__first1.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = const prmEdge*, _Container = std::vector<prmEdge, std::allocator<prmEdge> >]() < __first2.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = const prmEdge*, _Container = std::vector<prmEdge, std::allocator<prmEdge> >]()’
/usr/include/c++/4.2/bits/stl_algobase.h:855: error: no match for ‘operator<’ in ‘__first2.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = const prmEdge*, _Container = std::vector<prmEdge, std::allocator<prmEdge> >]() < __first1.__gnu_cxx::__normal_iterator<_Iterator, _Container>::operator* [with _Iterator = const prmEdge*, _Container = std::vector<prmEdge, std::allocator<prmEdge> >]()’
make[1]: *** [prmPlanner.o] Errore 1
What should I do?
Could somebody help me??
Thank you very much
| It doesn't know how to compare vectors. You should supply operator< for vector<prmEdge> (or for prmEdge to automatically use std::lexicographical_compare for vectors) or use unordered_set if you don't actually need sorted set of vectors.
|
2,372,529 | 2,373,143 | What causes name collision in an IDL file? | We have an idl file with multiple interfaces defined, two of which have someting like this:
[
object,
uuid(79E24BAA-DC12-4caf-91DD-2A4D47FED30A),
helpstring("ISomeInterface Interface"),
pointer_default(unique)
]
interface ISomeInterface: IUnknown
{
[propget, id(2)]
HRESULT SOMEMethod([out, retval] BSTR* pValue);
};
[
object,
uuid(834421B6-511D-457D-B50C-69E7E1B65471),
dual,
nonextensible,
helpstring("IACompleteDifferentInterface Interface"),
pointer_default(unique)
]
interface IACompleteDifferentInterface : IDispatch
{
[propget, helpstring("property SomeMethod")]
HRESULT SomeMethod([out, retval] BSTR* pVal);
[propput, helpstring("property SomeMethod")]
HRESULT SomeMethod([in] BSTR newVal);
}
They are two completely unrelated interfaces, that happen to have one method with the same name (although with different casing as shown).
Everything seems ok, however when we try to compile a project that calls
ISomeInterface -> SOMEMethod
we get an error saying it doesn't exist. If we call
ISomeInterface -> SomeMethod
it compiles just fine.
If we rename either method it also compiles ok. I wouldn't expect a naming collision in two different interfaces but that appears to be what's happening.
We can fix it by simply renaming one of them, but i'd really like to understand the problem. Can anyone explain it for me?
Thanks
| Psychic debugging powerz tells me that you are using the type library in a managed project. The .NET type library importer (Tlbimp.exe) has an obscure bug, it improperly capitalizes a method or property name if it appears more than once in the library. It uses the capitalization of the first one it encounters.
The first approach is to ignore it, the managed code could just use the identifier with the wrong capitalization. Or you could upgrade the importer, I'm fairly sure this bug was fixed in this one.
|
2,372,543 | 2,372,570 | Determining the correct size for a C++ array | I need to be able to set the size of an array based on the number of bytes in a file.
For example, I want to do this:
// Obtain the file size.
fseek (fp, 0, SEEK_END);
size_t file_size = ftell(fp);
rewind(fp);
// Create the buffer to hold the file contents.
char buff[file_size];
However, I get a compile time error saying that the size of the buffer has to be a constant.
How can I accomplish this?
| Use a vector.
std::vector<char> buff(file_size);
The entire vector is filled with '\0' first, automatically. But the performance "lost" might not be noticable. It's certainly safer and more comfortable. Then access it like a usual array. You may even pass the pointer to the data to legacy C functions
legacy(&buff[0]); // valid!
|
2,372,644 | 2,372,737 | How much can this c/c++ loop be optimized? | I am a newbie on optimization. I have been reading some reference on how to optimize c++ code but I have a hard time applying it to real code. Therefore I just want to gather some real world optimization technique on how to squeeze as much juice from the CPU/Memory as possible from the loop below
double sum = 0, *array;
array = (double*) malloc(T * sizeof(double));
for(int t = 0; t < T; ++t){
sum += fun(a,b,c,d,e,f,sum);
*(array+t) = sum;
}
where a,b,c,d,e,f are double and T is int. Anything including but not limited to memory alignment, parallelism, openmp/MPI, and SSE instructions are welcome. Compiler is standard gcc, microsoft, or commonly available compiler. If the solution is compiler specific, please specific compiler and any option flag associate with your solution.
Thanks!
PS: Forgot to mention properties fun. Please assume that it is a simple function with no loop inside, and compose of only basic arithmetic operation. Simply think of it as an inline function.
EDIT2: since the details of fun is important, please forget the parameter c, d, e, f and assume fun is defined as
inline double fun(a,b, sum){
return sum + a* ( b - sum);
}
| Since sum depends on its previous values in a non-trivial way, it is impossible to parallelize the code (so OpenMP and MPI are out).
Memory alignment and SSE should be enforced/used automatically with appropriate compiler settings.
Besides inlining fun and unrolling the loop (by compiling in -O3) there is not much we can do if fun is completely general.
Since fun(a,b,sum) = sum + a*(b-sum), we have the closed form
ab t+1
array[t] = ———— ( 1 - (2-a) )
a-1
which can be vectorized and parallelized, but the division and exponentiation can be very expensive.
Nevertheless, with the closed form we can start the loop from any index, e.g. create 2 threads one from t = 0 to T/2-1, another from t = T/2 to T-1, which perform the original loop, but the initial sum is computed using the above closed form solution. Also, if only a few values from the array is needed this can be computed lazily.
And for SSE, you could first fill the array first with (2-a)^(t+1), and then apply x :-> x - 1 to the whole array, and then apply x :-> x * c to the whole array where c = a*b/(1-a), but there may be automatic vectorization already.
|
2,372,671 | 2,372,781 | How would I import a function template using PInvoke? | In my C# code, I need to call a function from a C++ Dll that I wrote.The function is generic.
So , should I just import it like this:
[DllImport("myDll.dll")]
private static extern TypeName functionName<TypeName>( int arg1, int arg2 );
Is this correct syntax?
Thanks.
| This cannot work, there is no main-stream C++ compiler that makes templates exportable. Furthermore, templates are instantiated by the C++ compiler through type erasure, similar to the way Java generics works. In other words, the concrete callable functions have to be embedded in the DLL by the C++ compiler. They are no longer generic.
As an alternative, you can write a ref class in the C++/CLI language. That produces a true .NET generic class, usable by any .NET language that supports generics.
|
2,372,714 | 2,372,730 | local variables of static member functions | Today we came accross a problem concerning static member functions in an multithreaded environment. The question we asked ourselves and couldn't find a satisfying answer is:
are local varialbes of static member functions static as well?
// header
class A
{
static int test();
}
// implementation
int A::test()
{
int a = rand();
int b = rand();
int c = a + b;
return c;
}
Say you have two threads both calling A::test(). Is it possible that while thread 1 proccesses c = a + b thread 2 enters test() and changes the value of a by assigning the new return value of rand() or in other words do both threads operate an the some memory locations for a, b and c?
| No. The stack frames are independent for each thread's invocation of the function, and each gets its own locals. (You do need to be careful if you're accessing actual shared data e.g. static members in the class.)
|
2,372,780 | 2,372,820 | Memory Freeing Inqury | Additional thanks extend to Daniel Newby for answering my memory usage question (and Martin York for explaining it a bit more). It is definitely the answer I was looking for, but more of my other questions were answered by others.
Thanks everyone
for clearing up all of my concerns. Very pleased to see things running how I expect them to run.
I've run into something that I'm not exactly sure about.
In my program, I'm not using malloc() or free(). I'm making instances of my classes with new and I've made sure each one runs it's destructor when it's delete'd, however, there are no free() calls or even setting their pointers (to things inside a global scope, or other classes) to NULL or 0.
What I mean by "I've made sure", is not that I call each destructor. I only use delete to call on the destructor to run, but I have variables that increase by 1 everytime an object is created, and everytime it's destructor is run. This is how I've made sure the amount of objects I created are equal to the amount of destructors called.
Should I be using malloc() and free() anyway? Should I be NULLing pointers to things that I still want to exist?
A second question is why, when I look at my task manager, does my process never "drop" memory? It used to never stop gaining, and then I started deleting everything properly. Or so I thought.
Wouldn't free() or delete make the memory usage go down?
What practices should I pursue about malloc'ing and free'ing memory with linked lists?
| There's rarely a reason to use malloc() and free() in a C++ program. Stick with new and delete. Note that unlike languages with garbage collection, setting a pointer to NULL or 0 in C++ has nothing to do with deallocating the memory.
|
2,372,926 | 2,373,040 | Locating what lib is linking to the debug CRT | We link our app with numerous different static libs, the problem is that one of these libs is in turn linking with the VC90.DebugCRT even in release. Some libs we don't even have the source to, so it would be nice if there's a way to locate what lib is the actual culprit. I've toyed around some with dumpbin, but am unable to find a way to track down the offending lib.
Any help greatly appreciated.
| The linker's /verbose:lib can help. Recompile your entire solution with this option set under Project>Properties>Linker>Command Line and look through the log to see who links with who.
|
2,372,962 | 2,373,103 | Storing vector in a struct C++ | Why can't I do this:
struct sName {
vector<int> x;
};
It takes only three pointers to store a vector, so I should be able to do this?
| You mentioned this failed in a switch statement. You'll need to wrap it up in an extra pair of braces:
int type = UNKNOWN;
switch(type)
{
case UNKNOWN:
cout << "try again" << endl;
break;
case KNOWN:
{ // Note the extra braces here...
struct sName
{
vector<int> x;
} myVector;
} // and here
}
Alternatively, you could have already declared the structure, and are just trying to declare and initialize a local variable. This isn't a problem unique to struct, it'll happen anytime you try to initialize a variable inside a case:
struct sName
{
vector<int> x;
};
int type = UNKNOWN;
switch(type)
{
case UNKNOWN:
cout << "try again" << endl;
break;
case KNOWN:
{ // Note the extra braces here...
sName myVector;
} // and here
case OTHER:
int invalid = 0; // this will also fail without the extra pair of braces
break;
}
|
2,373,094 | 2,373,162 | Loading large multi-sample audio files into memory for playback - how to avoid temporary freezing | I am writing an application needs to use large audio multi-samples, usually around 50 mb in size. One file contains approximately 80 individual short sound recordings, which can get played back by my application at any time. For this reason all the audio data gets loaded into memory for quick access.
However, when loading one of these files, it can take many seconds to put into memory, meaning my program if temporarily frozen. What is a good way to avoid this happening? It must be compatible with Windows and OS X. It freezes at this : myMultiSampleClass->open(); which has to do a lot of dynamic memory allocation and reading from the file using ifstream.
I have thought of two possible options:
Open the file and load it into memory in another thread so my application process does not freeze. I have looked into the Boost library to do this but need to do quite a lot of reading before I am ready to implement. All I would need to do is call the open() function in the thread then destroy the thread afterwards.
Come up with a scheme to make sure I don't load the entire file into memory at any one time, I just load on the fly so to speak. The problem is any sample could be triggered at any time. I know some other software has this kind of system in place but I'm not sure how it works. It depends a lot on individual computer specifications, it could work great on my computer but someone with a slow HDD/Memory could get very bad results. One idea I had was to load x samples of each audio recording into memory, then if I need to play, begin playback of the samples that already exist whilst loading the rest of the audio into memory.
Any ideas or criticisms? Thanks in advance :-)
| I like solution 1 as a first attempt -- simple & to the point.
If you are under Windows, you can do asynchronous file operations -- what they call OVERLAPPED -- to tell the OS to load a file & let you know when it's ready.
|
2,373,183 | 2,373,256 | is there a new equalivant of _malloca | I am a big fan of the _malloca but I can't use it with classes. Is there a stack based dynamic allocation method for classes.
Is this a bad idea, another vestige of c which should ideologically be opposed or just continue to use it for limited purposes.
| You can use _malloca with classes by allocating the memory (with _malloca) then constructing the class using placement new.
void* stackMemory = _malloca(sizeof(MyClass));
if( stackMemory ) {
MyClass* myClass = new(stackMemory) MyClass(args);
myClass->~MyClass();
}
Whether you should do this is another matter...
|
2,373,207 | 2,373,299 | Am I using delete correctly here? | I've just started combining my knowledge of C++ classes and dynamic arrays. I was given the advice that "any time I use the new operator" I should delete. I also know how destructors work, so I think this code is correct:
main.cpp
...
int main()
{
PicLib *lib = new PicLib;
beginStorage(lib);
return 0;
}
void beginStorage(PicLib *lib)
{
...
if (command != 'q')
{
//let's assume I add a whole bunch
//of stuff to PicLib and have some fun here
beginStorage(lib);
}
else
{
delete lib;
lib = NULL;
cout << "Ciao" << endl;
}
}
PicLib.cpp
...
PicLib::PicLib()
{
database = new Pic[MAX_DATABASE];
num_pics = 0;
}
PicLib::~PicLib()
{
delete[] database;
database = NULL;
num_pics = 0;
}
...
I fill my PicLib with a Pic class, containing more dynamic arrays. Pic's destructor deletes them in the same manner seen above. I think that delete [] database gets rid of all those classes properly.
So is the delete in main.cpp necessary? Everything looking hunky dory here?
| There are a couple of problems:
int main()
{
PicLib *lib = new PicLib;
beginStorage(lib);
return 0;
}
It is best to allocate and delete memory in the same scope so that it is easy to spot.
But in this case just declare it locally (and pass by reference):
int main()
{
PicLib lib;
beginStorage(lib);
return 0;
}
In beginStorage()
But I see no reason to manipulate a pointer. Pass it by reference and just use it locally.
void beginStorage(PicLib& lib)
{
....
}
In the PicLib class you have a RAW pointer: databases.
If you have a RAW pointer that you own (you create and destroy it) then you must override the compiler generated versions of the copy constructor and assignment operator. But in this case I see no reason touse a pointer it would be easier to just use a vector:
class PivLib
{
private:
std::vector<Pic> databases;
};
|
2,373,476 | 2,373,925 | Heap corruption issues | Inside my template function I have the following code:
TypeName myFunction()
{
TypeName result;
void * storage = malloc( sizeof( TypeName ) );
/*Magic code that stores a value in the space pointed to by storage*/
result = *(TypeName *)storage;
free( storage );
return result;
}
This causes an "HEAP CORRUPTION DETECTED" error.If I don't call the free() function, the error doesn't occur, but I am afraid that I am creating a memory leak.what would be the proper way to return the value of "storage" and then deallocate the memory?
| What about:
TypeName myFunction() {
TypeName result;
void* storage = &result;
/*Magic code that stores a value in the space pointed to by storage*/
return result;
}
Here, all your variables will be stored on the stack so you shouldn't encounter heap-related problems (depending on what exactly your "magic" code does).
Is there a reason why you have your storage array separate from result? If the results will simply be copied into result, it would make more sense (IMHO) to only use one object (and either keep a void* pointer to it or type-cast &result as needed).
If there is a reason to use a separate storage and result, you will probably get better milage using TypeName storage = new TypeName and delete instead of malloc(4) and free.
|
2,373,526 | 2,373,834 | problem with memcpy'ing from shared memory in boost.interprocess | This is driving me wild with frustration. I am just trying to create a shared memory buffer class that uses in shared memory created through Boost.Interprocess where I can read/store data. I wrote the following to test the functionality
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <iostream>
using namespace std;
using namespace boost::interprocess;
int main( int argc, char* argv[] ) {
shared_memory_object::remove( "MyName" );
// Create a shared memory object
shared_memory_object shm ( create_only, "MyName", read_write );
// Set size for the shared memory region
shm.truncate(1000);
// Map the whole shared memory in this process
mapped_region region(shm, read_write);
// Get pointer to the beginning of the mapped shared memory region
int* start_ptr;
start_ptr = static_cast<int*>(region.get_address());
// Write data into the buffer
int* write_ptr = start_ptr;
for( int i= 0; i<10; i++ ) {
cout << "Write data: " << i << endl;
memcpy( write_ptr, &i, sizeof(int) );
write_ptr++;
}
// Read data from the buffer
int* read_ptr = start_ptr;
int* data;
for( int i= 0; i<10; i++ ) {
memcpy( data, read_ptr, sizeof(int) );
cout << "Read data: " << *data << endl;
read_ptr++;
}
shared_memory_object::remove( "MyName" );
return 0;
}
When I run this, it writes the data OK, but segfaults on the first memcpy in the read loop. gdb says the following:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00007fffffe007c5 in __memcpy ()
(gdb) where
#0 0x00007fffffe007c5 in __memcpy ()
#1 0x0000000100000e45 in main (argc=1, argv=0x7fff5fbff9d0) at try.cpp:36
The functionality is so simple, I don't know what I'm missing. Any help will be much appreciated.
| data isn't being set to point at anything. (Make sure the program is being compiled with all warnings enabled.) It looks like it shouldn't be a pointer anyway.
The second loop should perhaps be:
int* read_ptr = start_ptr;
int data;
for( int i= 0; i<10; i++ ) {
memcpy( &data, read_ptr, sizeof(int) );
cout << "Read data: " << data << endl;
read_ptr++;
}
|
2,373,540 | 2,373,591 | fast java/python/C++ ipc | I notice this thread: Fastish Python/Jython IPC, and I have a similar problem, but in different language.
I have a Java front-end and a C++ back-end, which I am thinking about rewrite it in Python in some near future. What will be the best IPC? I prefer socket to HTTP, as I am trying to avoid the HTTP overhead. And XML-RPC is an example one to avoid!
Are there any library to deal with cross platform RPC (JSON/XML etc.)?
Newbie in this field, thanks ahead!
| For the C++ backend you can use xmlrpc++ (LGPL'ed) - I'm planning to use it myself. It has very clean code so you can modify it easily if you need to.
As for the frontends in Java/Python, you could make use of Apache XML-RPC (don't know anything about it) or Python's xmlrpclib (very easy to use).
XML-RPC should be cross-platform. I've tried xmlrpc++ as server and xmlrpclib as client and it seems to work correctly, even when using faults, i.e. passing errors to the client.
|
2,373,767 | 2,373,799 | limit the creation of object on heap and stack in C++ | I have a question about how to limit the creation of object on heap or stack? For example, how to make sure an object not living on heap? how to make sure an object not living on stack?
Thanks!
| To prevent accidental creation of an object on the heap, give it private operators new. For example:
class X {
private:
void *operator new(size_t);
void *operator new[](size_t);
};
To prevent accidental creation on the stack, make all constructors private, and/or make the destructor private, and provide friend or static functions that perform the same functionality. For example, here's one that does both:
class X {
public:
static X *New() {return new X;}
static X *New(int i) {return new X(i);}
void Delete(X *x) {delete x;}
private:
X();
X(int i);
~X();
};
|
2,373,859 | 2,373,895 | C++ static const and initialization (is there a fiasco) | I am returning to C++ after a long absence and I am stumbling a little over my understanding of the fairly well known static initialization problem.
Let's say I have a simple class Vector2 as given below (note that I am aware that x and y should be private with getters and setters, these have just been omitted for brevity):
class Vector2 {
public:
Vector2(float x, float y) :x(x), y(y) {};
float x,y;
}
Now, if I want to specify a static const member to represent a Vector2 with x and y set to 1, I am unsure on how to proceed - will static const members fall foul of the static initialization problem or will the act of making them const mean they are ok? I am toying with the following possibilities:
Possibility 1:
// .h
class Vector2 {
public:
Vector2(float x, float y) :x(x), y(y) {}
static const Vector2 ONE;
float x,y;
};
// .cpp
const Vector2 Vector2::ONE = Vector2(1.f, 1.f);
Possibility 2:
// .h
class Vector2 {
public:
Vector2(float x, float y) :x(x), y(y) {}
static const Vector2& getOne();
float x,y;
private:
static const Vector2 ONE;
};
// .cpp
const Vector2 Vector2::ONE = Vector2(1.f, 1.f);
static const Vector2& Vector2::getOne() {
return ONE;
}
Possibility 3:
// .h
class Vector2 {
public:
Vector2(float x, float y) :x(x), y(y) {}
static const Vector2& getOne();
float x,y;
};
// .cpp
const Vector2& Vector2::getOne() {
static Vector2 one(1.f,1.f);
return one;
}
Now, my preferred way to write this would be as in possibility 2, just because it is a more comfortable syntax for me. However, if I call the getOne() method from another static method in another class am I going to risk crashing and burning? As I say, it is because I am using a static const rather than a plain static that I am asking this question as I have found much on plain static class member issues, but nothing on const static issues.
I suspect that I gain nothing by the fact that I am using static const and will need to go with Possibility 3 to be safe, but I just want to ask in case someone can shed some light on this for me.
I realise I am probably opening myself up to a slew of links pointing to exactly what I am asking, but I have looked and not found before posting this.
Any help will be gratefully appreciated.
| All of them, except possibility 3, suffer from the static initialization order fiasco. This is because your class is not a POD. In C++0x, this problem can be solved by marking the constructor constexpr, but in C++03 there is no such solution.
You can remove the constructor to solve the problem in C++03, and initialize using
const Vector2 Vector2::ONE = { 1.f, 1.f };
This is initializing a POD, and all initializers in the list are constant expression (for the purpose of static initialization). The intialization of them happen before any code is run that might access it before being initialized.
3.6.2:
Objects with static storage duration (3.7.1) shall be zero-initialized (8.5) before any other initialization takes place. Zero-initialization and initialization with a constant expression are collectively called static initialization; all other initialization is dynamic initialization. Objects of POD types (3.9) with static storage duration initialized with constant expressions (5.19) shall be initialized before any dynamic initialization takes place.
8.5.1/14:
When an aggregate with static storage duration is initialized with a brace-enclosed initializer-list, if all the member initializer expressions are constant expressions, and the aggregate is a POD type, the initialization shall be done during the static phase of initialization (3.6.2); otherwise, it is unspecified whether the initialization of members with constant expressions takes place during the static phase or during the dynamic phase of initialization.
|
2,373,861 | 2,374,282 | Is C++ still actively used for general purpose development? |
Possible Duplicate:
Which sector of software industry uses C++?
C++ was for many years the holy grail of mission critical high performance development. However, it seems that for the past 10 years like much of the development world has moved to Java and C#. My quesiton is this, is C++ effectively relegated to embedded systems, OS, Browser and other special purpose development? Should I let this skillset go the way of the VB 6 and other skillsets that are no longer showing the same level of demand and value in the market? I love C++ and would love to update my knowledge in it, but I wouldn't even know where to begin to try to apply it to common business problems today.
Regards.
| First of all, I doubt anybody can give a definitive answer -- there's just no way to tell exactly how much any particular language is really used. Nearly anything you can measure is a secondary measurement, such as how many people are advertising jobs using that language. The problem is that this tends to show relatively new languages as dominating to a much greater degree than is real.
That said, my belief is as follows. At one time, C++ was the hot new language on the block, and there was a bubble when it dominated the market. That bubble deflated quite a while ago. Since then, use of C++ has been growing on an absolute basis, but the market has been growing (quite a bit) faster so its shrinking on a relative basis.
There are a couple of reasons this doesn't show up in most secondary measures such as job advertisements though. A couple of the obvious ones include:
Many teams producing C++ have now had years to "settle in", so the turnover rate is relatively low.
It's now well established where it's used, so positions tend to be filled by internal promotions.
There's another effect I almost hesitate to mention, but it's true no matter how little a lot of people like it: there are both programmers and managers who are more excited about "new" than effective. This leads to a large group of wannabes who are constantly on the move to the latest and greatest "technology" (whether that happens to be a language, framework, platform, or whatever). They get a job, loaf (or worse, actually write some code), then move on to their next victim...er...employer. They cause a lot of "churn", and inflate the number of job advertisements, but produce little or nothing of any real value. That group moved from C++ to Java a long time ago, and have long since moved from Java to C# to Ruby on Rails to Hadoop to whatever the managers are excited about this week.
Lest I sound excessively negative, I should add that along the way, a few of them really find something they're good at, and (mostly) tend to stay with that. Unfortunately, for every one who does, there are at least five more new graduates to join the throng...
|
2,374,009 | 2,374,051 | Calling this->get/this->set methods versus directly accesing member variables in C++ | Suppose I have a class Foo, with a private variable bar_ containing some state for Foo. If necessary, I may write public get/set methods for bar_. Naturally, I avoid this as much as possible to maintain encapsulation.
Assuming I have these get/set methods, whenever I have to access or modify bar_ within a method belonging to Foo, I usually do it directly to bar_, instead of using the get/set methods, which I use for accessing bar_ from outside the class. I have no justification other than concerns regarding the speed of directly accessing the variable versus calling the methods, but I suspect that if the get/set methods are defined inline (which they are) it shouldn't make a difference. Does it make a difference? Does constness play a role in this?
So far I haven't had any problems with this, but I have a lingering feeling I am Doing It Wrong. Are there any compelling arguments for not doing it? Any guidelines regarding this?
|
I have no justification other than concerns regarding the speed of directly accessing the variable versus calling the methods, but I suspect that if the get/set methods are defined inline (which they are) it shouldn't make a difference. Does it make a difference? Does constness play a role in this?
The inline keyword hardly plays a role in whether or not the compiler does any inlining. The use for the keyword in that regard is essentially deprecated. Modern compilers inline like crazy, and they know when to do it better tan any programmer does.
Any compiler worth dirt will say "Hm, call this function to get this member variable; hey I can just get the member variable!" You're worrying about nothing. This happens regardless of any inline keywords.
That said, I almost always use the member functions. If I change how a variable behaves when it's accessed, I now "automatically" apply that everywhere it's used. Clean code should be your goal, though, not a dogmatic "always skip functions" or not.
Anytime I just want a variable value, I use the corresponding member variable. (i.e, if I were writing std::vector, if I needed to check if the size was less than something, I'd say size() < x). But if it's cleaner to use the variable directly, do that instead, such as mSize++.
const-ness is irrelevant. If you're in a non-const function, you'll use the non-const version of your getter, same with const. Obviously, using the members directly maintains const-ness. There is no difference.
|
2,374,065 | 2,374,138 | Some questions about default values in C++ | I have some questions about the default values in a function parameter list
Is the default value a part of the signature? What about parameter type of the default parameters?
Where are the default value stored? In the stack or or global heap or in the constant data segment?
| No, default argument is not a part of signature and is not a part of the function type.
Parameter type is a part of signature. But default argument type has no effect of parameter type, i.e default argument type has no effect on signature.
Default arguments are not "stored" anywhere specifically. Default arguments are "syntactic sugar" that exists (as default arguments) only during the program's compilation. If during the compilation compiler notices that some argument is missing, it will use the default argument, as specified by you. The evaluation of the default argument is done in the context of the caller. If you specify a temporary object as a default argument, a separate temporary will be created every time you call the function using the default argument and destroyed immediately after the calling expression ends.
void foo(T t = T());
// A new temporary will be used as an argument every time you call it as `foo()`
foo();
// Equivalent to `foo(T())`. A temporary is created here, passed as an argument and
// destroyed afterwards, just like an explicit temporary would be
If you specify an existing object with static storage duration as a default argument, then it will be stored wherever you define it.
T global;
void foo(T& t = global);
// In this case you are using a global object as a default argument
// It is you who "store" it wherever you want to store it
foo();
// Equivalent to `foo(global)`
If you declare default arguments but never actually use them, i.e. if you specify the arguments explicitly every time, then the compiled program will have no trace of these arguments whatsoever (which is why I called them compile-time "syntactic sugar").
P.S. To include what Johannes says in the comment below: even though the default argument (when used) is evaluated in the context of the caller at the moment of the call, it is not done by "textual substitution" as in might appear from my examples above. Most notably, the name lookup for the names used in default arguments is done at the point when the default argument is specified in the function declaration, not at the point of the evaluation in the caller.
|
2,374,073 | 2,375,847 | Memory management for collections of widgets in Qt | Sorry for the dumb question, but I'm working with Qt and C++ for the first time, and working through the tutorial and some samples.
One thing that was mentioned was that Qt stuff doesn't need to be explicitly deleted. So, main question, does this also apply to collections of Qt stuff? Like say I want a dynamic number of MyWidgets, so I keep a vector or whatever of them. Are they still taken care of for me?
As a side question, what is going on to make it so I don't have to worry about destructors?
| Qt has an interesting object model for sure. When I first started it made me uneasy that there were so many new Foo calls and no deletes.
http://qt.nokia.com/doc/4.6/object.html Is a good place to start reading up on the object model.
Things of interest:
QObject subclasses have their assignment and copy-ctor methods disabled. The chain of object child-parents is maintained internally by QObject.
Generally when instantiating a QObject subclass (if you don't plan on managing its pointer yourself) you will provide another QObject pointer as the parent. This 'parent' then takes over the management of the child you just made. You can call setParent() on a QObject to change who "owns" it. There are very few methods in Qt that will change the parent of an object, and they all explicitly state that they do in the docs.
So to answer your specific question: it depends on how you made all of your MyWidget instances.
If you made each one with a parent, then no you don't have to delete them. The parent will delete them when it gets deleted.
If you're keeping a QList<MyWidget*> collection of them, and you didn't give them a parent, then you should delete them yourself.
|
2,374,227 | 2,378,083 | Any tips for structuring C++ code using win32? | I am trying to improve my coding skills by making my code more structured and readable. I code the GUI (thanks edit). I have been reading through Firefox's open source code to improve but it uses GTK+ and not much Win32.
Where can I find an open source (professional) program that is coded in Win32?
One more thing: When should one write pseudocode? I've never done this before, but I know it's much like outlining an essay. Should pseudocode be written before coding the project? or just functions?
Thanks
| Try this : http://www.relisoft.com/win32/index.htm
This guy rebuild classes against the win32 raw api. He gives a good application structure overview, while keeping the layer and abstraction thin.
|
2,374,341 | 2,374,444 | LinkedList copy constructor implementation details | I'm starting to learn C++ and as an exercise decide to implement a simple LinkedList class (Below there is part of the code). I have a question regarding the way the copy constructor should be implemented and the best way the data on the original LinkedList should be accessed.
template <typename T>
class LinkedList {
struct Node {
T data;
Node *next;
Node(T t, Node *n) : data(t), next(n) {};
};
public:
LinkedList();
LinkedList(const LinkedList&);
~LinkedList();
//member functions
int size() const; //done
bool empty() const; //done
void append(const T&); //done
void prepend(const T&); //done
void insert(const T&, int i);
bool contains(const T&) const; //done
bool removeOne(const T&); //done
int removeAll(const T&); //done
void clear(); //done
T& last(); //done
const T& last() const; //done
T& first(); //done
const T& first() const; //done
void removeFirst(); //done
T takeFirst(); //done
void removeLast();
T takeLast();
//delete when finished
void print();
//end delete
//operators
bool operator ==(const LinkedList<T> &other) const; //done
bool operator !=(const LinkedList<T> &other) const; //done
LinkedList<T>& operator =(const LinkedList<T> &other); //done
private:
Node* m_head;
Node* m_tail;
int m_size;
};
template<typename T>
LinkedList<T>::LinkedList() : m_head(0), m_tail(0), m_size(0) {
}
...
Should my copy constructor access the data on each node of the original LinkedList directly?
template<typename T>
LinkedList<T>::LinkedList(const LinkedList& l) {
m_head = 0;
m_tail = 0;
m_size = 0;
Node *n = l.m_head;
// construct list from given list
while(n) {
append(n->data);
n = n->next;
}
}
Or should I access the data through the corresponding accessor? (I know that I don't have the accessor(s) defined).
Also, I intend to create a custom iterator so that it can be possible to iterate over the LinkedList. Should I use in the copy constructor to access the data on each node?
Another question (completely off-topic, I know), when and/or why should we declare a pointer to a LinkedList
LinkedList<int> *l = new LinkedList<int>();
instead of
LinkedList<int> l;
| I assume append will properly handle the initial head/tail details, yes? If so, what you have now is great and simple: Go through the other list, and take its item and add a copy to my list. Perfect.
Well, almost. Use an initializer list to initialize member variables:
template<typename T>
LinkedList<T>::LinkedList(const LinkedList& l) :
m_head(0), m_tail(0), m_size(0)
{
// ...
}
Also, maybe a matter of style, this woks instead of a while loop:
// construct list from given list
for (Node *n = l.m_head; n != 0; n = n->next)
append(m->data);
In fact, I'd recommend this instead. When you have iterators, you'd do something like:
for (const_iterator iter = l.begin(); iter != l.end(); ++iter)
append(*iter);
It just follows the style of a for-loop better. (Initialize something, check something, do something). Though for iterators, it'll probably be different. (More later)
Or should I access the data through the corresponding accessor? (I know that I don't have the accessor(s) defined).
Also, I intend to create a custom iterator so that it can be possible to iterate over the LinkedList. Should I use in the copy constructor to access the data on each node?
Those iterators are your accessors. You don't want to expose your internal head-tail pointers, that a recipe for disaster. The purpose of the class is to not expose the details. That said, iterators are the abstract wrapper around those details.
Once you have your iterators, then you could use them to iterate through the list instead of pointer arithmetic. This ties in to this recently asked question. In general, you should use your abstractions to deal with your data. So yes once you have your iterators
in place, you should use those to iterate across the data.
Most classes that provide iterators also provide a way to insert data given a beginning and ending iterator. This is usually called insert, like this: insert(iterBegin, iterEnd). This loops through the iterators, appending it's data to the list.
If you had such functionality, your copy-constructor would simply be:
insert(l.begin(), l.end()); // insert the other list's entire range
Where insert is implemented like the for-loop we had above.
Another question (completely off-topic, I know), when and/or why should we declare a pointer to a LinkedList
LinkedList *l = new LinkedList(); instead of LinkedList l;
The first is dynamic allocation, the second is automatic (stack) allocation. You should prefer stack allocation. It's almost always faster, and safer too (since you don't need to delete anything). In fact, a concept called RAII relies on automatic storage, so destructors are guaranteed to run.
Only use dynamic allocation when you have to.
|
2,374,506 | 2,386,898 | Preprocessor variable when using Adobe Alchemy | I'm porting a cross-platform lib I use to Alchemy. One particular file has a block of code similar to this :
#if defined(WIN32)
// Do some Windows-specific stuff
#elif defined(__linux__)
// Do some linux-specific stuff
#endif
I now need to add Flash-specific code (NOP in some cases), but so far I've been unable to find what does Alchemy's GCC define to identify itself! I tried FLASH and a couple others but nothing seems to work.
BTW, is it me or Alchemy's documentation is almost non-existent?
| Nevermind. I ended up adding -DFLASH to my makefiles.
|
2,374,719 | 2,374,739 | why weak_ptr can break cyclic reference? | I learnt a lot about weak_ptr working with share_ptr to break cyclic reference. How does it work? How to use that? Can any body give me an example? I am totally lost here.
One more question, what's a strong pointer?
| It is not included in the reference count, so the resource can be freed even when weak pointers exist. When using a weak_ptr, you acquire a shared_ptr from it, temporarily increasing the reference count. If the resource has already been freed, acquiring the shared_ptr will fail.
Q2: shared_ptr is a strong pointer. As long as any of them exist, the resource cannot be freed.
|
2,374,847 | 2,375,046 | Passing member function pointer to member object in c++ | I have a problem with using a pointer to function in C++. Here is my example:
#include <iostream>
using namespace std;
class bar
{
public:
void (*funcP)();
};
class foo
{
public:
bar myBar;
void hello(){cout << "hello" << endl;};
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
testFoo.myBar.funcP = &byebye; //OK
testFoo.myBar.funcP = &testFoo.hello; //ERROR
return 0;
}
Compilator returns an error at testFoo.myBar.funcP = &testFoo.hello;:
ISO C++ forbids taking the address of a bound member function to form a
pointer to member function. Say
'&foo::hello'
cannot convert 'void (foo::)()' to 'void ()()' in assignment
So i tried it like this:
class bar
{
public:
void (*foo::funcP)();
};
But now the compilator adds one more:
'foo' has not been declared
Is there a way make it work?
Thanks in advance for suggestions
| Taking everyone's suggestions together, your final solution will look like:
#include <iostream>
using std::cout;
usind std::endl;
class foo; // tell the compiler there's a foo out there.
class bar
{
public:
// If you want to store a pointer to each type of function you'll
// need two different pointers here:
void (*freeFunctionPointer)();
void (foo::*memberFunctionPointer)();
};
class foo
{
public:
bar myBar;
void hello(){ cout << "hello" << endl; }
};
void byebye()
{
cout << "bye" << endl;
}
int main()
{
foo testFoo;
testFoo.myBar.freeFunctionPointer = &byebye;
testFoo.myBar.memberFunctionPointer = &foo::hello;
((testFoo).*(testFoo.myBar.memberFunctionPointer))(); // calls foo::hello()
testFoo.myBar.freeFunctionPointer(); // calls byebye()
return 0;
}
The C++ FAQ Lite has some guidance on how to simplify the syntax.
Taking Chris' idea and running with it, you could get yourself something like this:
#include <iostream>
using std::cout; using std::endl;
class foo;
typedef void (*FreeFn)();
typedef void (foo::*MemberFn)();
class bar
{
public:
bar() : freeFn(NULL), memberFn(NULL) {}
void operator()(foo* other)
{
if (freeFn != NULL) { freeFn(); }
else if (memberFn != NULL) { ((other)->*(memberFn))(); }
else { cout << "No function attached!" << endl; }
}
void setFreeFn(FreeFn value) { freeFn = value; memberFn = NULL; }
void setMemberFn(MemberFn value) { memberFn = value; freeFn = NULL; }
private:
FreeFn freeFn;
MemberFn memberFn;
};
class foo
{
public:
bar myBar;
void hello() { cout << "foo::hello()" << endl; }
void operator()() { myBar(this); }
};
void bye() { cout << "bye()" << endl; }
int main()
{
foo testFoo;
testFoo();
testFoo.myBar.setMemberFn(&foo::hello);
testFoo();
testFoo.myBar.setFreeFn(&bye);
testFoo();
return 0;
}
|
2,374,944 | 2,374,961 | Running batch script as windows service | We have a java application which run as server running on a remote windows system which is started though a batch script which includes some initialization configurations.
To avoid login into the system every time and starting / stopping the service I planned to add that batch script as a "Windows Service" and use it remotely through command prompt. After number of failed attempts I came to know there is no simple way of doing it without using third party software which I am not allowed to to use due software usage restrictions.
As a solution I have written a C / C++ program which can be added as a service and used. The program works file. Now I am trying to run a batch script [using system() method ] using this code but the batch script is not getting executed. Where as it works fine in stand alone mode.
Courtesy: http://www.devx.com/cplus/Article/9857
Kindly help me in rectifying the issue.
Batch Script:
batscr.bat
ECHO Error Log Open >C:\MyServices\ERR.LOG
ECHO Error 1 >>C:\MyServices\ERR.LOG
ECHO Message 1 >>C:\MyServices\ERR.LOG
================================================
Standalone C program to execute the batch script
BatchExe.cpp
#include
#include
void main()
{
system("C:\\MyServices\\batscr.bat");
}
=======================
Program for the service
StartScript.cpp
#include
#include
#include
#define SLEEP_TIME 5000
#define LOGFILE "C:\\MyServices\\memstatus.txt"
SERVICE_STATUS ServiceStatus;
SERVICE_STATUS_HANDLE hStatus;
void ServiceMain(int argc, char** argv);
void ControlHandler(DWORD request);
void InitService();
void main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = "StartScript";
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
// Start the control dispatcher thread for our service
StartServiceCtrlDispatcher(ServiceTable);
}
void ServiceMain(int argc, char** argv)
{
int error;
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler(
"StartScript",
(LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
// Registering Control Handler failed
return;
}
// Initialize Service
InitService();
// We report the running status to SCM.
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
// Service initialization
void InitService()
{
system("C:\\MyServices\\batscr.bat");
return;
}
// Control handler function
void ControlHandler(DWORD request)
{
switch(request)
{
case SERVICE_CONTROL_STOP:
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
case SERVICE_CONTROL_SHUTDOWN:
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwCurrentState = SERVICE_STOPPED;
SetServiceStatus (hStatus, &ServiceStatus);
return;
default:
break;
}
// Report current status
SetServiceStatus (hStatus, &ServiceStatus);
return;
}
Thanks and Regards ...
| this may help you a little bit
Link here
... it's quite a common problem.
|
2,375,065 | 2,375,144 | Visual Studio: What exactly are lib files (used for)? | I'm learning C++ and came across those *.lib files that are obviously used by the linker. I had to set some additional dependencies for OpenGL.
What exactly are library files in this context used for?
What are their contents?
How are they generated?
Is there anything else worth knowing about them?
Or are they just nothing more than relocateable object code similiar to *.obj files?
| In simple terms, yes - .lib files are just a collection of .obj files.
There is a slight complication on Windows that you can have two classes of lib files.
Static lib files essentially contain a collection of .obj and are linked with your program to provide all the functions inside the .lib. They are mainly a convenience to save you having as many files to deal with.
There are also stub .lib which provide just the definitions of functions which are contained in a .dll file.
The .lib file is used at compile time to tell the compiler what to expect from the function, but the code is loaded at run time from the dll.
|
2,375,132 | 2,375,468 | ReleaseSemaphore does not release the semaphore | (In short: main()'s WaitForSingleObject hangs in the program below).
I'm trying to write a piece of code that dispatches threads and waits for them to finish before it resumes. Instead of creating the threads every time, which is costly, I put them to sleep. The main thread creates X threads in CREATE_SUSPENDED state.
The synch is done with a semaphore with X as MaximumCount. The semaphore's counter is put down to zero and the threads are dispatched. The threds perform some silly loop and call ReleaseSemaphore before they go to sleep. Then the main thread uses WaitForSingleObject X times to be sure every thread finished its job and is sleeping. Then it loops and does it all again.
From time to time the program does not exit. When I beak the program I can see that WaitForSingleObject hangs. This means that a thread's ReleaseSemaphore did not work. Nothing is printf'ed so supposedly nothing went wrong.
Maybe two threads shouldn't call ReleaseSemaphore at the exact same time, but that would nullify the purpose of semaphores...
I just don't grok it...
Other solutions to synch threads are gratefully accepted!
#define TRY 100
#define LOOP 100
HANDLE *ids;
HANDLE semaphore;
DWORD WINAPI Count(__in LPVOID lpParameter)
{
float x = 1.0f;
while(1)
{
for (int i=1 ; i<LOOP ; i++)
x = sqrt((float)i*x);
while (ReleaseSemaphore(semaphore,1,NULL) == FALSE)
printf(" ReleaseSemaphore error : %d ", GetLastError());
SuspendThread(ids[(int) lpParameter]);
}
return (DWORD)(int)x;
}
int main()
{
SYSTEM_INFO sysinfo;
GetSystemInfo( &sysinfo );
int numCPU = sysinfo.dwNumberOfProcessors;
semaphore = CreateSemaphore(NULL, numCPU, numCPU, NULL);
ids = new HANDLE[numCPU];
for (int j=0 ; j<numCPU ; j++)
ids[j] = CreateThread(NULL, 0, Count, (LPVOID)j, CREATE_SUSPENDED, NULL);
for (int j=0 ; j<TRY ; j++)
{
for (int i=0 ; i<numCPU ; i++)
{
if (WaitForSingleObject(semaphore,1) == WAIT_TIMEOUT)
printf("Timed out !!!\n");
ResumeThread(ids[i]);
}
for (int i=0 ; i<numCPU ; i++)
WaitForSingleObject(semaphore,INFINITE);
ReleaseSemaphore(semaphore,numCPU,NULL);
}
CloseHandle(semaphore);
printf("Done\n");
getc(stdin);
}
| the problem happens in the following case:
the main thread resumes the worker threads:
for (int i=0 ; i<numCPU ; i++)
{
if (WaitForSingleObject(semaphore,1) == WAIT_TIMEOUT)
printf("Timed out !!!\n");
ResumeThread(ids[i]);
}
the worker threads do their work and release the semaphore:
for (int i=1 ; i<LOOP ; i++)
x = sqrt((float)i*x);
while (ReleaseSemaphore(semaphore,1,NULL) == FALSE)
the main thread waits for all worker threads and resets the semaphore:
for (int i=0 ; i<numCPU ; i++)
WaitForSingleObject(semaphore,INFINITE);
ReleaseSemaphore(semaphore,numCPU,NULL);
the main thread goes into the next round, trying to resume the worker threads (note that the worker threads haven't event suspended themselves yet! this is where the problem starts... you are trying to resume threads that aren't necessarily suspended yet):
for (int i=0 ; i<numCPU ; i++)
{
if (WaitForSingleObject(semaphore,1) == WAIT_TIMEOUT)
printf("Timed out !!!\n");
ResumeThread(ids[i]);
}
finally the worker threads suspend themselves (although they should already start the next round):
SuspendThread(ids[(int) lpParameter]);
and the main thread waits forever since all workers are suspended now:
for (int i=0 ; i<numCPU ; i++)
WaitForSingleObject(semaphore,INFINITE);
here's a link that shows how to correctly solve producer/consumer problems:
http://en.wikipedia.org/wiki/Producer-consumer_problem
also i think critical sections are much faster than semaphores and mutexes. they're also easier to understand in most cases (imo).
|
2,375,442 | 2,375,453 | _T("x") not acting as it should | I am running into lots of problems with Unicode at the moment. As I understand it, TCHAR is defined to be either a wchar_t or a char depending on whether _UNICODE is defined somewhere, and there are various other functions to help with this. Apparently _T("x") should evaulate 'x' to either a wchar_t or a char depending on how stuff is set up. I have the following code:
TCHAR desiredClassName = _T("ChatClass");
and it is giving me the following unfriendly error message:
error C2440: 'initializing' : cannot convert from 'const wchar_t [10]' to 'TCHAR'
This doesn't really make any sense to me. Surely TCHAR should be a wchar_t thing here? Why is it not?
Incidentally I don't really care about working with Unicode at all, but apparently windows.h or something similar is forcing me to. If there is some handy FAQ somewhere on the internet that explains all these various different types of char arrays and Strings in their various different formats in a way that a newbie could understand, it would be appreciated.
| That should be a TCHAR*, not a TCHAR.
|
2,375,533 | 2,375,555 | C++ wrapper with overloaded = operator | I'm trying to develop a pretty simple (for now) wrapper class around int, and was hoping to overload the = operator to achieve something like the following:
class IntWrapper
{
...
private:
int val;
}
int main ( )
{
IntWrapper a;
int b;
a = 5; // uses overloaded = to implement setter
b = a; // uses overloaded = to implement getter
}
I'm gathering however that this can't be done. Implementing the setter is pretty straightforward, something like:
class IntWrapper
{
...
IntWrapper& operator = (int rhs) { this.val = rhs; return *this; }
...
}
However, from a bit of Googling I'm gathering there's no way to do the getter in this way. My understanding is that this is because the = operator can only be overridden to assign to a variable, and since int is a primitive type we cannot override its default implementation of =. Is this correct? If not, how do I go about writing the getter?
If that is correct, does anyone have any elegant suggestions for something similar? About the nearest I can find is overloading a conversion operator:
class IntWrapper
{
...
operator int( ) { return this.val; }
...
}
int main ( )
{
...
b = (int) a;
...
}
To me though that seems pretty pointless, as its barely any better than a simple getVal() method.
Thanks for any suggestions!
| You don't need a cast to invoke the conversion function. A plain
b = a;
will invoke it too. That way, i can see how that's more convenient to use than a getVal function. Although i generally don't use conversion functions. I would prefer an explicit getVal function. In particular consider this one
struct W {
W(int);
operator int();
};
int main() {
W w = 42;
int a = true ? 0 : w; // Ambiguity! What conversion direction?
}
It quickly gets out of hand...
|
2,375,622 | 2,375,680 | Performance of Calling Unmanaged .dll from C# | How long is the typical overhead added by calling a .dll written in C++ from a C# application using the following syntax?
[DllImport("abc.dll", EntryPoint = "xcFoo", CallingConvention = CallingConvention.Cdecl)]
public extern static Result Foo(out IntPtr session,
[MarshalAs(UnmanagedType.FunctionPtr)]ObjectCallback callback,
UInt64 turnKey,
string serverAddress,
string userId,
string password);
Is there a more efficient way to do it?
| Check out this article on how to improve interop performance. What to do and what best to avoid.
http://msdn.microsoft.com/en-us/library/ms998551.aspx
|
2,375,640 | 2,375,662 | what errors will report if I overload operators incorrectly? | I know that we can't overload operator with other meaning, we can't create new operators, and we can't overload without user-defined class. If I overload operators incorrectly? what errors will report? compiler errors or runtime error?
If I overload **, what would happen?
| You can overload only existing operators. There is no operator ** in C++.
If you try, the compiler would complain.
Operator overloads are checked at the compile time. If it compiles, it's just a kind of function, so the possible runtime errors are the same as for any other function.
|
2,375,682 | 2,375,693 | Which pointer to delete? | I'm trying to multithread something and i have my program set up such that i have a structure/class of variables that will be passed into each thread for processing.
In this class, there are variables that hold pointers to arrays some threads have common arrays from which they read data off of, instead of duplicating those arrays, pointers are given to each function that direct them to one array. These common arrays are initialized in the main program and then the variables in an array of classes are pointed to that array which is then in turn passed off to a thread.
My question is at which level (main program or thread) should i use the delete command to terminate that array? Also, what happens to the other pointers when i do that? are they automatically deleted as well or do i have to manually keep track of those. Lastly, what happens if i accidentally delete an array while another thread is still using it?
Thanks,
-Faken
| If you delete an array which other thread is still using, you get undefined behaviour, mist probably a crash.
For your case I would recommend to clean up in the main thread, after all the worker threads are finished.
Another possibility would be to use a shared pointer, which would automatically free the resources as soon as no thread is using them (though beware that you need to protect your access to the shared pointer -- for shared_ptr in MSVC's standard library it's protected automatically).
|
2,375,784 | 2,375,838 | How to check whether my custom hashing is good in hash_map? | I've written a custom hashing for my custom key in stdext::hash_map and would like to check whether the hasher is good. I'm using STL supplied with VS 2008. A typical check, as I know, is to check the uniformity of distribution among buckets.
How should I organize such a check correctly? A solution that comes to my mind is to modify STL sources to add a method to hash_map that walks through buckets and does the subject. Is there are any better ways?
Maybe, derive from hash_map and create there such method?
| I'd run one (large) dataset through stl::hash_map. Once done, I'd collect the results for all buckets using the following method
From hash_map:
size_type elems_in_bucket (size_type __n) const;
Finally, I would do compute the standard deviation (SD) of the elem-to-bucket distribution.
I'd do the above for different hash functions. Whichever hash function results in minimum SD is the winner (for this dataset).
|
2,375,872 | 2,377,260 | Real life use for Qt (outside of Nokia) | Is Qt an interesting platform for business apps development, outside of Nokia phones ?
Why ? Strong points ?
Thanks
| I like Qt because:
Very well-designed framework, e.g. signal-slot, model-view, graphics view/scene/item/proxy, painter/paint device/paint engine..., too many to be listed here!
Excellent documentation!
Cross platform language/API, as well as tools like UI designer, creator, and so on.
Rich features, e.g. graphics framework, network library, database engine, and so on.
Active community, and active development.
There should be more. If you have ever used it, you'll find it's easy to build your framework upon Qt.
I didn't have any complain to Qt. If I have to say at least one disadvantage here, "convention". You must adopt the convention of Qt, e.g. You have to use moc to make the meta object of your objects, and it's easier for developers to use Qt's vector, list, auto_ptr than STL, tr1. But I never found any issue caused by that. On the contrary, it works very well.
In my opinion, Qt is the state-of-the-art C++ framework in this modern world!
P.S. There are a lot of commercial applications built on Qt. You can find it under Qt's official website. But I'd like add one more here: Perforce, one of the top commercial source code management tools, built its client tool on Qt for Windows/Linux/Mac.
|
2,375,882 | 2,375,957 | How to call a pointer to method from another method | I had this problem some time ago and I gave up but lately it returned.
#include <iostream>
class element2D;
class node2D
{
public:
void (element2D::*FunctionPtr)();
void otherMethod()
{ std::cout << "hello" << std::endl;
((this)->*(this->FunctionPtr))(); //ERROR<-------------------
}
};
class element2D
{
public:
node2D myNode;
void doSomething(){ std::cout << "do something" << std::endl; }
};
int main()
{
element2D myElement;
myElement.myNode.FunctionPtr = &element2D::doSomething; //OK
((myElement).*(myElement.myNode.FunctionPtr))(); //OK
return 0;
}
I'm getting error at marked line:
pointer to member type 'void (element2D::)()' incompatible with object type 'node2D'
I would be really thankful for help. There was similar question today which partially helped me: link.
But it doesn't seem to be the full answer to my problem.
Actually these two problems have only one difference - point where the function is called.
Thanks for your time
| "this" is a pointer to node2D but FunctionPtr refers to a member of element2D -- that is the error.
#if 0 // broken version
void otherMethod()
{ std::cout << "hello" << std::endl;
((this)->*(this->FunctionPtr))(); //ERROR<-------------------
}
#else // fixed version
void otherMethod( element2D * that )
{ std::cout << "hello" << std::endl;
((that)->*(this->FunctionPtr))();
}
#endif
Then you call it with something like:
myElement.myNode.otherMethod( &myElement );
There are things you could do to improve on this, but this should get you started.
|
2,375,891 | 2,375,960 | IPhone compilation of ported code problems: sub class of template parameter base class inaccessible | check this out:
template <class T>
class Test: public T
{
public:
void TestFunc()
{
T::SubClass bob;
}
};
this fails when compiling for iPhone (expected ';' before 'bob'). works on other platforms
this is a simplified example of what we are actually trying to do, which is inherit from an std::map<> and inside that class, create an iterator.
| Very often encountered issue. Put typename:
template <class T>
class Test: public T
{
public:
void TestFunc()
{
typename T::SubClass bob;
}
};
T::SubClass is a dependent name. While parsing the template, the compiler doesn't know yet whether it will be a type. For still being able to parse it (and collect information won thereby), it assumes it is not a type. But then, the line must be an expression, and misses an operator between the two names. typename will tell it the name is a type, and the line then becomes a declaration.
It may not be apparent why it fails above because the whole line cannot be an expression. But there are other situation where this isn't possible to decide on the form of the whole statement:
T::SubClass * bob;
Is that a multiplication, or a pointer declaration? The compiler will assume it is a multiplication. If later when instantiating the template it figures out that T::SubClass names a type, it will rise an error message. typename will also here tell the compiler to parse this as a declaration instead of an expression (by taking T::SubClass as a type).
Notice some compilers may still work without typename (if i remember right, the MSVC compiler is one of them). I think this should come with the restriction that those compilers won't do two-phase name lookup: They will parse the complete template at instantiation time, and all names, even those that were not visible in the definition of the template, will be found (as opposed to what the Standard says, that treats name lookup at definition/instantiation differently).
Visit the Template FAQ for further assistance: C++ Templates FAQ
|
2,375,969 | 2,415,249 | IPhone compilation of ported code problems: variable given same name as typedef'd type failing | check this out:
this compiles fine on iPhone:
typedef int ATYPE;
void AFunc()
{
ATYPE ATYPE;
ATYPE = 1337;
}
this compiles fine on iPhone:
typedef int ATYPE;
typedef ATYPE _ATYPE;
struct AStruct
{
_ATYPE ATYPE;
};
void AFunc()
{
AStruct bob;
bob.ATYPE = 1337;
}
but this does NOT:
typedef int ATYPE;
struct AStruct
{
ATYPE ATYPE;
};
void AFunc()
{
AStruct bob;
bob.ATYPE = 1337;
}
the above compiles fine on other platforms though.
I suppose we can work around it by doing that second example, but does anyone know why this is?
| Well, if you don't like my previous answer, here's the alternate one. The online Comeau C++ compiler at http://www.comeaucomputing.com/tryitout/ compiles your third example without error. Given that that's typically considered a gold standard among C++ compilers, this suggests that this may well be a bug in the G++ compiler in the iPhone SDK (and, of course, in the other versions of G++ that I referenced in my comment).
If that's true -- and I don't have the C++ spec at hand to argue the fine details -- the answer to your "why?" question is, "Because G++ has a weird corner-case bug. Please file an issue in the GCC bug tracker about this, so that someone will fix it."
|
2,376,130 | 2,376,141 | Adding to a Memory Address Error | This doesn't compile in VSC++ 2008.
void* toSendMemory2 = toSendMemory + 4;
I am at a loss at why, though I am sure it's very stupid of me. :P
| When you add N to a T* the pointer will be incremented by sizeof(T) * N bytes. sizeof(void) is nonsensical, so pointer arithmetic over void* is not allowed.
|
2,376,193 | 2,376,300 | How to write an object to file in C++ | I have an object with several text strings as members. I want to write this object to the file all at once, instead of writing each string to file. How can I do that?
| You can override operator>> and operator<< to read/write to stream.
Example Entry struct with some values:
struct Entry2
{
string original;
string currency;
Entry2() {}
Entry2(string& in);
Entry2(string& original, string& currency)
: original(original), currency(currency)
{}
};
istream& operator>>(istream& is, Entry2& en);
ostream& operator<<(ostream& os, const Entry2& en);
Implementation:
using namespace std;
istream& operator>>(istream& is, Entry2& en)
{
is >> en.original;
is >> en.currency;
return is;
}
ostream& operator<<(ostream& os, const Entry2& en)
{
os << en.original << " " << en.currency;
return os;
}
Then you open filestream, and for each object you call:
ifstream in(filename.c_str());
Entry2 e;
in >> e;
//if you want to use read:
//in.read(reinterpret_cast<const char*>(&e),sizeof(e));
in.close();
Or output:
Entry2 e;
// set values in e
ofstream out(filename.c_str());
out << e;
out.close();
Or if you want to use stream read and write then you just replace relevant code in operators implementation.
When the variables are private inside your struct/class then you need to declare operators as friend methods.
You implement any format/separators that you like. When your string include spaces use getline() that takes a string and stream instead of >> because operator>> uses spaces as delimiters by default. Depends on your separators.
|
2,376,334 | 2,376,580 | C++: How do I pass a container of derived classes to a function expecting a container of their base classes? | HI! Anyone know how I can make the line "chug(derlist);" in the code below work?
#include <iostream>
#include <list>
using namespace std;
class Base
{
public:
virtual void chug() { cout << "Base chug\n"; }
};
class Derived : public Base
{
public:
virtual void chug() { cout << "Derived chug\n"; }
void foo() { cout << "Derived foo\n"; }
};
void chug(list<Base*>& alist)
{
for (list<Base*>::iterator i = alist.begin(), z = alist.end(); i != z; ++i)
(*i)->chug();
}
int main()
{
list<Base*> baselist;
list<Derived*> derlist;
baselist.push_back(new Base);
baselist.push_back(new Base);
derlist.push_back(new Derived);
derlist.push_back(new Derived);
chug(baselist);
// chug(derlist); // How do I make this work?
return 0;
}
The reason I need this is basically, I have a container of very complex objects, which I need to pass to certain functions that only care about one or two virtual functions in those complex objects.
I know the short answer is "you can't," I'm really looking for any tricks/idioms that people use to get around this problem.
Thanks in advance.
| Your question is odd; the subject asks "how do I put items in a container without losing polymorphism" - but that is begging the question; items in containers do not lose polymorphism. You just have a container of the base type and everything works.
From your sample, it looks what you're asking is "how do I convert a container of child pointers to a container of base pointers?" - and the answer to that is, you can't. child pointers are convertible to base pointers, containers of child pointers are not. They are unrelated types. Although, note that a shared_ptr is convertible to shared_ptr, but only because they have extra magic to make that work. The containers have no such magic.
One answer would be to make chug a template function (disclaimer: I'm not on a computer with a compiler, so I haven't tried compiling this):
template<typename C, typename T>
void chug(const C<T>& container)
{
typedef typename C<T>::iterator iter;
for(iter i = container.begin(); i < container.end(); ++i)
{
(*i)->chug();
}
}
Then chug can take any container of any type, as long as it's a container of pointers and has a chug method.
|
2,376,446 | 2,376,599 | C++ stream operator question | I suppose this might be simple question for all the gurus here but I somehow couldn't figure out the answer.
I want to be able to write csv cells to stream as simple as this:
stream << 1 << 2 << "Tom" << std::endl;
which would create output like 1,2,Tom. How can I achieve that? I figured that I need to create custom streambuf (as I don't think it's the right way to do it on stream level, it would be real pain just to overload << for all the types) but I'm not sure how << is normally implemented. Does it call put or write or what. Should I override those or what? Or did I just miss something completely?
I'd appreciate any help :)
Cheers,
| Getting something like 98% of the way there isn't terribly difficult:
#include <iostream>
class add_comma {
std::ostream &os;
bool begin;
typedef add_comma &ref;
public:
add_comma(std::ostream &o) : os(o), begin(true) {}
template <class T>
ref operator<<(T const &t) {
if (!begin)
os << ",";
os << "\"" << t << "\"";
begin = false;
return *this;
}
ref operator<<(std::ostream &manip(std::ostream &o) ) {
if (&manip == &std::endl)
reset();
manip(os);
return *this;
}
void reset() { begin = true; }
operator void *() { return (void *)os; }
};
int main() {
add_comma a(std::cout);
a << 1 << 2 << "This is a string" << std::endl;
a << 3 << 4 << "Another string" << std::endl;
return 0;
}
Edit: I've fixed the code to at least some degree -- it now only puts commas between items that are written, not at the beginning of a line. It only, however, recognizes "endl" as signaling the beginning of a new record -- a newline in a string literal, for example, won't work.
|
2,376,448 | 2,376,456 | The written versions of the logical operators | This is the only place I've ever seen and, or and not listed as actual operators in C++. When I wrote up a test program in NetBeans, I got the red underlining as if there was a syntax error and figured the website was wrong, but it is NetBeans which is wrong because it compiled and ran as expected.
I can see ! being favored over not but the readability of and && or seems greater than their grammatical brothers. Why do these versions of the logical operators exist and why does seemingly no one use it? Is this truly valid C++ or some sort of compatibility with C that was included with the language?
| They originated in C in the header <iso646.h>. At the time there were keyboards that couldn't type the required symbols for && (for example), so the header contained #define's that would assist them in doing so, by (in our example) defining and to be &&. Of course, as time went by this became less used.
In C++, they became what are known as alternate tokens. You do not need to include anything to use these tokens in a compliant compiler (as such, the C++-ified version of the C header, <ciso646>, is blank). Alternate tokens are just like regular tokens, except for spelling. So during parsing and is exactly the same as &&, it's just a different way of spelling the same thing.
As for their use: because they are rarely used, using them is often more surprising and confusing than it is helpful. I'm sure if it were normal, they would be much easier to read, but people are so used to && and || anything else just gets distracting.
EDIT: I have seen a very slight increase in their usage since I posted this, however. I still avoid them.
|
2,376,468 | 2,376,567 | Visual Studio 2005 and Tinyxml - xml file location | For some reason my Tinyxml file which is created via visual studio 2005 (c++) is saved on my desktop instead of the debug folder or in the program's root folder.
if anyone knows about some way to tell vs2005 to save the tinyxml create file somewhere else?
I tried that with eclipse and it saved the file in the program's root folder, which is what I'm trying to do.
thanks.
EDIT:
I'm doing a BHO (Browser Helper Object), this is an add-on Internet Explorer. so when I run my program the 'exe' is iexplore.exe from c:\program files\Intenet Explorer
| You normally shouldn't aspire to write data files to your program directory. Rather than leaving the output directory to chance, you should explicitly tell TinyXml where you want the file created by passing in the whole path when you call SaveFile.
|
2,376,824 | 2,376,908 | libcurl HTTP request to save respond into variable - c++ | I'm trying to save the returned data from HTTP request into a variable.
The code below will automatically print the respond of the request, but I need it to save the respond to a char or string.
int main(void)
{
char * result;
CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
}
return 0;
}
| I think you will have to write a function to pass as a write callback via CURLOPT_WRITEFUNCTION (see this). Alternatively you could create a temporary file and pass its file descriptor via CURLOPT_WRITEDATA (the next option listed on that page). Then you would read back the data from the temporary file into a string. Not the prettiest of solutions, but at least you don't have to mess with buffers and function pointers.
EDIT: Since you don't want to write to a file, something like this might work:
#include <string>
size_t write_to_string(void *ptr, size_t size, size_t count, void *stream) {
((string*)stream)->append((char*)ptr, 0, size*count);
return size*count;
}
int main(void) {
// ...
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, "http://www.browsarity.com/");
string response;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_to_string);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
res = curl_easy_perform(curl);
curl_easy_cleanup(curl);
// The "response" variable should now contain the contents of the HTTP response
}
return 0;
}
DISCLAIMER: I haven't tested this, and I'm a bit rusty on C++, but you can try it out.
|
2,376,835 | 2,381,113 | Qt: Background thread refreshing UI thread | I have a background thread and the thread calls some methods that update the UI (in order to show progress bars and show additional info in text areas).
If I modify some UI widget values, a "Cannot send events to objects owned by a different thread" assertion error is raised.
Looking at forums, I read that I could use QMetaObject::invokeMethod method but it just works if I pass it the Qt::DirectConnection flag that actually raises the same error shown above.
If I use Qt::QueuedConnection or Qt::AutoConnection, the invokeMethod returns false.
My code looks similar to this:
.h:
class A : public QMainWindow
{
Q_OBJECT
QProgressBar* pb;
public slots:
bool m(bool, int);
};
class B
{
A* a;
public:
void handleEvent();
};
.cpp:
bool A::m(bool x, int y)
{
pb->setValue(y);
return x;
}
void B::handleEvent()
{
//a->m(true, 12); //raises an assertion error
bool r;
//bool ret = QMetaObject::invokeMethod(a, "m", Qt::DirectConnection, Q_RETURN_ARG(bool, r), Q_ARG(bool, true), Q_ARG(int, 12)); //raises the same assertion error error
bool ret = QMetaObject::invokeMethod(a, "m", Qt::AutoConnection, Q_RETURN_ARG(bool, r), Q_ARG(bool, true), Q_ARG(int, 12)); //is ignored and ret contains false.
}
Do you know what is going on or what i am doing wrong? or maybe, can someone suggest me another approach to deal with my newbie problem?
Thanks in advance,
Ernesto
| I haven't used invokeMethod() myself, but to do this, I usually just use signals and slots. For instance, you could create a signal as a member of class B that is connected to the slot in class A that updates the progress:
class B : public QObject
{
Q_OBJECT
A* a;
signals:
void update_signal(bool, int);
public:
void handleEvent();
};
B::B()
{
//assuming a already points to the correct place...
connect(this, SIGNAL(update_signal(bool,int),
a, SLOT(m(bool,int)), Qt::QueuedConnection);
}
void B::handleEvent()
{
emit update_signal(true, 12);
}
A::m() will have to return void in this case but that is not a problem because when using a queued connection, you cannot get a return value anyway since the call is asynchronous (emit update_signal(true,12) may return before the slot function is called making it impossible to have a return value ready).
You can actually perform this connection anywhere as long as you have pointers to an object of type A and an object of type B. This makes the signals and slots very flexible since you could completely decouple A from B, yet still allow them to communicate through signals and slots. For instance:
class B : public QObject
{
Q_OBJECT
signals:
void update_signal(bool, int);
public:
void handleEvent();
};
void B::handleEvent()
{
emit update_signal(true, 12);
}
class A : public QMainWindow
{
Q_OBJECT
QProgressBar* pb;
public slots:
void m(bool, int);
};
void A::m(bool x, int y)
{
pb->setValue(y);
}
int main()
{
A* a = new A();
B* b = new B();
QObject::connect(b, SIGNAL(update_signal(bool, int)),
a, SLOT(m(bool, int)), Qt::QueuedConnection);
//...
}
In this case, b does not have to store a pointer or know anything about a yet they can communicate through a thin well-defined channel.
|
2,376,862 | 2,376,881 | How to do compare and increment atomically? | In my attempt to develope a thread-safe C++ weak pointer template class, I need to check a flag that indicating the object is still alive, if yes then increment the object's reference count and I need to do the both steps atomically.
I know the existance of intrinsics functions provided by the compiler, for instance _InterlockedCompareExchange() and _InterlockedIncrement(). But what I want is an interlockedCompareIncrement() function, is there an efficient way to simulate this intrinsic using other primitives, at least on the Windows x86 platform?
| Suppose that value is your flag variable. It should be declared volatile.
long curvalue;
long newvalue;
do
{
curvalue = value;
newvalue = curvalue + 1;
}
while( _InterlockedCompareExchange( &value, newvalue, curvalue ) != curvalue );
As you see you can generalize this to whatever kind of arithmetic you need by changing the operations that are applied to calculate newvalue.
If you want to compare two values at the same time, your best bet is to pack both values into a single variable, and then operate on that single variable. Since you're using a flag combined with a reference count, I'd recommend using the lowest bit of value as the 'alive' flag, and then increment/decrement by 2 at a time. This allows you to encode both the flag and the reference count into a single 32-bit variable.
|
2,376,899 | 2,376,907 | Understanding the memory content of a union | Suppose I define a union like this:
#include <stdio.h>
int main() {
union u {
int i;
float f;
};
union u tst;
tst.f = 23.45;
printf("%d\n", tst.i);
return 0;
}
Can somebody tell me what the memory where tst is stored will look like?
I am trying to understand the output 1102813594 that this program produces.
| It depends on the implementation (compiler, OS, etc.) but you can use the debugger to actually see the memory contents if you want.
For example, in my MSVC 2008:
0x00415748 9a 99 bb 41
is the memory contents. Read from LSB on the left side (Intel, little-endian machine), this is 0x41bb999a or indeed 1102813594.
Generally, however, the integer and float are stored in the same bytes. Depending on how you access the union, you get the integer or floating point interpretation of those bytes. The size of the memory space, again, depends on the implementation, although it's usually the largest of its constituents aligned to some fixed boundary.
Why is the value such as it is in your (or mine) case? You should read about floating-point number representation for that (look up ieee 754)
|
2,376,915 | 2,376,988 | How to print out the memory contents of a variable in C? | Suppose I do a
double d = 234.5;
I want to see the memory contents of d [the whole 8 bytes]
How do I do that?
| double d = 234.5;
/* 1. use a union */
union u {
double d;
unsigned char c[sizeof(double)];
};
union u tmp;
size_t i;
tmp.d = d;
for (i=0; i < sizeof(double); ++i)
printf("%02x\n", tmp.c[i]);
/* 2. memcpy */
unsigned char data[sizeof d];
size_t i;
memcpy(data, &d, sizeof d);
for (i=0; i < sizeof d; ++i)
printf("%02x\n", data[i]);
/* 3. Use a pointer to an unsigned char to examine the bytes */
unsigned char *p = (unsigned char *)&d;
size_t i;
for (i=0; i < sizeof d; ++i)
printf("%02x\n", p[i]);
All the methods show you the bytes—but the same double value may print the bytes differently on different systems, e.g., due to different encodings (rare), or different endianness.
|
2,376,954 | 2,376,986 | problem with iterator manipulation | i have a std::map and i am using iterator to find a certain key,value pair. After finding it i am unable to get the position of the key,value pair from the iterator. By doing another find i can get it, but i want a work around for this.
//mycode is this
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
//here i need to return the size_t value of the iterator i
}
}
NOTE: edited size_t as the position of key,value pair
| If you want to return the "position" of the result:
#include <iterator>
// ...
std::map<std::string,myclass*> mymap;
size_t myfind(const std::string &s)
{
std::map<std:string,myclass*>::iterator i=mymap.find(s);
if((i==mymap.end())||((*i).second==0))
{
std::cout<<"some error\n";
}
else
{
return std::distance(mymap.begin(), i);
}
}
However, you are probably better off just returning the iterator!
|
2,377,043 | 2,425,451 | VS 2008 C++ build output? | Why when I watch the build output from a VC++ project in VS do I see:
1>Compiling...
1>a.cpp
1>b.cpp
1>c.cpp
1>d.cpp
1>e.cpp
[etc...]
1>Generating code...
1>x.cpp
1>y.cpp
[etc...]
The output looks as though several compilation units are being handled before any code is generated. Is this really going on? I'm trying to improve build times, and by using pre-compiled headers, I've gotten great speedups for each ".cpp" file, but there is a relatively long pause during the "Generating Code..." message. I do not have "Whole Program Optimization" nor "Link Time Code Generation" turned on. If this is the case, then why? Why doesn't VC++ compile each ".cpp" individually (which would include the code generation phase)? If this isn't just an illusion of the output, is there cross-compilation-unit optimization potentially going on here? There don't appear to be any compiler options to control that behavior (I know about WPO and LTCG, as mentioned above).
EDIT:
The build log just shows the ".obj" files in the output directory, one per line. There is no indication of "Compiling..." vs. "Generating code..." steps.
EDIT:
I have confirmed that this behavior has nothing to do with the "maximum number of parallel project builds" setting in Tools -> Options -> Projects and Solutions -> Build and Run. Nor is it related to the MSBuild project build output verbosity setting. Indeed if I cancel the build before the "Generating code..." step, none of the ".obj" files will exist for the most recent set of "compiled" files. This implies that the compiler truly is handling multiple translation units together. Why is this?
| Compiler architecture
The compiler is not generating code from the source directly, it first compiles it into an intermediate form (see compiler front-end) and then generates the code from the intermediate form, including any optimizations (see compiler back-end).
Visual Studio compiler process spawning
In a Visual Studio build compiler process (cl.exe) is executed to compile multiple source files sharing the same command line options in one command. The compiler first performs "compilation" sequentially for each file (this is most likely front-end), but "Generating code" (probably back-end) is done together for all files once compilation is done with them.
You can confirm this by watching cl.exe with Process Explorer.
Why code generation for multiple files at once
My guess is Code generation being done for multiple files at once is done to make the build process faster, as it includes some things which can be done only once for multiple sources, like instantiating templates - it has no use to instantiate them multiple times, as all instances but one would be discarded anyway.
Whole program optimization
In theory it would be possible to perform some cross-compilation-unit optimization as well at this point, but it is not done - no such optimizations are ever done unless enabled with /LTCG, and with LTCG the whole Code generation is done for the whole program at once (hence the Whole Program Optimization name).
Note: it seems as if WPO is done by linker, as it produces exe from obj files, but this a kind of illusion - the obj files are not real object files, they contain the intermediate representation, and the "linker" is not a real linker, as it is not only linking the existing code, it is generating and optimizing the code as well.
|
2,377,062 | 2,383,315 | Visual C++ BigInt and SecureRandom? Is there a BigInt library with modPow? | I have to port some crypto code to visual c++ from java which (visual c++) I am not very familiar with. I found a library at http://sourceforge.net/projects/cpp-bigint/ that I can use for big integers.
However it does not have an equivalent to javas SecureRandom class. I did find a project in c++ called beecrypt but could not get it to work with Visual Studio 2008.
Does anyone have any experience with these types of libraries? I saw gmp too but couldn't find one that worked with visual studio off the bat.
Before I head down the wrong road any advice?
Thanks!
----UPDATE-------
I seem to have a proof of concept working with the cpp-bigint from above with small numbers. In the library there is no modPow function. For now I created a for loop like:
for(RossiBigInt i("0",DEC_DIGIT); i< r; i++)
{
x = x * g;
x = x % p;
}
This gives me x = g^r mod p but it is very slow. Does anyone know of other BitInteger libraries with the modPow function or know a faster way for me to compute this?
Thanks!
| The modPow function can be evaluated efficiently with a "square and multiply" algorithm. In Java it would look like this (if Java's BigInteger did not already have it):
/* Compute x^n mod m. */
static BigInteger modPow(BigInteger x, BigInteger n, BigInteger m)
{
if (n.signum() < 0)
throw new IllegalArgumentException("bwah, negative exponent");
BigInteger r = BigInteger.ONE;
for (int i = n.bitLength() - 1; i >= 0; i --) {
if (n.testBit(i))
r = r.multiply(x).mod(m);
if (i > 0)
r = r.multiply(r).mod(m);
}
return r;
}
With this, the number of loop iteration is equal to the length, in bits, of the exponent, so that the computational time is acceptable.
You still get one or two modular reductions per iteration, so this will not be the fastest exponentiation algorithm ever (modular reductions are substantially more expensive than multiplication). Typical modPow() implementations use Montgomery reduction, which is a clever trick which merges all modular reduction into a single similar operation at the end.
If you have time, implementing your own modular exponentiation would be very pedagogical; you would start by reading chapter 14 of the "Handbook of Applied Cryptography", freely downloadable from this site. However, in this harsh world where mundane considerations of budget often limit creativity and free time, you would probably be happy with an already implemented library. GMP is known to be quite good, but somewhat difficult to use on Windows. You may have better luck with NTL.
|
2,377,286 | 2,377,389 | C++/C/Java: Anagrams - from original string to target; | I'm trying to solve this problem : http://uva.onlinejudge.org/external/7/732.html.
For the given example, they give us the original word, for example TRIT and the target "anagramed" string, TIRT.
Objective: We have to output all the valid sequences of 'i' and 'o' (push and pop's, respectively) which produce the target string from the source string.
So, I was thinking of calculate all permutations of "i" and "o" , but cutting this cases:
1) if current permutation begins with an 'o', stop checking, since all the of the next permutations will begin with this pop command and popping something from an empty stack is an invalid command.
2) if an 'o' command is found in the middle of the checking and there is nothing in the stack, skip that case.
3) if an 'i' command is found and there is nothing in the input string, skip that case.
4) if an 'o' command is found and currently expected character is not the character just popped out, then skip that case, since this will never reach to the target string.
5) don't search if the input and target strings have different lengths.
but I think it might get me TLE anyway...
I know the theory: permutations perhaps and backtracking all the way.
I just have too many difficulties implementing it.
could anyone please share with me some code and or ideas please?
P.S.: Any suggestion that may decrease some execution time will be welcome , of course.
| This first iteration solution is instructive. It's not the most efficient since it uses String all over the place, but it's a good place to start.
import java.util.*;
public class StackAnagram {
static void anagram(String s1, String s2, String stack, String instr) {
if (s2.isEmpty()) {
if (s1.isEmpty() && stack.isEmpty()) {
System.out.println(instr.trim());
}
return;
}
if (!s1.isEmpty()) {
anagram(s1.substring(1), s2, s1.charAt(0) + stack, instr + "i ");
}
if (!stack.isEmpty() && stack.charAt(0) == s2.charAt(0)) {
anagram(s1, s2.substring(1), stack.substring(1), instr + "o ");
}
}
static void anagram(String s1, String s2) {
System.out.println("[");
anagram(s1, s2, "", "");
System.out.println("]");
}
public static void main(String args[]) {
anagram("madam", "adamm");
anagram("bahama", "bahama");
anagram("long", "short");
anagram("eric", "rice");
anagram("ericc", "rice");
}
}
|
2,377,296 | 2,377,308 | Modifying a window's textbox control's text | Case in point : I've got a handle to a window (for instance, using the getForegroundWindow() API function). This window's got a textbox (possibly a richtext control). Would it be possible to modify the textbox's text through an Windows API call ? More specifically, I'd like to replace its text with some of my own.
| Once you have the handle to the parent window, you need to get the handle to the editcontrol.
If the editcontrol has a known, consistent identifier, use GetDlgItem to get its HWND. Otherwise you will need to resort to FindWindowEx.
Once you have the HWND of the editcontrol, you can use SendMessage to send a WM_SETTEXT message it. For rich text controls, use the EM_SETTEXTEX message.
|
2,377,327 | 2,377,437 | Creating a Trapezoid using a character inputted by the user. (Console App) | I am trying to create a trapezoid using user inputted options. I know my code may not be the best way but so far it works! My problem is i need the base of the trapezoid to be touching the left side of the output window. What am i doing wrong?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int topw, height, width, rowCount = 0, temp;
char fill;
cout << "Please type in the top width: ";
cin >> topw;
cout << "Please type in the height: ";
cin >> height;
cout << "Please type in the character: ";
cin >> fill;
width = topw + (2 * (height - 1));
cout<<setw(width);
for(int i = 0; i < topw;i++)
{
cout << fill;
}
cout << endl;
rowCount++;
width--;
temp = topw + 1;
while(rowCount < height)
{
cout<<setw(width);
for(int i = 0; i <= temp; i++)
{
cout << fill;
}
cout << endl;
rowCount++;
width--;
temp = temp +2;
}
}
| setw sets the width for the next operation, not the entire line. So, the width of a single cout << fill is set to the value. This is giving you the padding, but you need to set setw to 0 for the final row.
also, there seems to be some redundant code try:
int main()
{
int topw, height, width, rowCount = 0, temp;
char fill;
cout << "Please type in the top width: ";
cin >> topw;
cout << "Please type in the height: ";
cin >> height;
cout << "Please type in the character: ";
cin >> fill;
width = height;
cout<<setw(width);
temp = topw;
while(rowCount < height)
{
cout<<setw(width);
for(int i = 0; i < temp; i++)
{
cout << fill;
}
cout << endl;
rowCount++;
width--;
temp = temp +2;
}
}
|
2,377,392 | 2,416,667 | Javascript Refuses to Call ActiveX Method, Agrees to Call Another | I have an ActiveX object which extends some functions. I have a web page that loads the ActiveX object and calls its methods in Javascript. The ActiveX object has two method; the problem is that Javascript can successfully call one of them but fails to call the other; citing Object doesn't support this property or method which is nonsense because I made a VB6.0 application that successfully calls this other method, so the two functions are indeed extended correctly and performing their job.
And yes, the Internet Explorer security zones are all set and everything, as I wrote above the javascript code can call one method but refuses to call the other.
Any idea why Javascript is being a headcase?
| The answer was pretty simple. In the IDL file the function was declared as a property (propget) without taking any input arguments. In the Javascript code, I was calling actvx3obj.ATR(); when in fact I should have been calling actvx3obj.ATR; because it is a property get method that takes no argument.
I'm posting this in the hopes that someone with a similar problem may stumble upon the solution.
|
2,377,443 | 2,377,451 | Can I make the following assumption when map key is not found? | std::map<std::string, int> m;
// Can I make assumption that m["NoSuchKey"] will return 0?
std::cout << m["NoSuchKey"] << std::endl;
| Yes. When an item is accessed through operator[] that does not exist, it is created with a default-constructed value, and returned.
For numeric types, default-constructed means 0.
|
2,377,515 | 2,381,142 | MSVC: Embedding Data in Program | I'm hoping someone has run into this sort of problem before, and can give me a hint to solve it.
With Microsoft Visual C++ 2005, I have this code in a program:
DWORD locator[FOURXFLAGCOUNT+1]={
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x58585858, 0x58585858,
0x58585858, 0x58585858, 0x58585858, 0x00000000
};
The idea is to make the locator discoverable (and fillable) from outside the program -- i.e. another program is filling it in, so that this program will have it built in when it starts up. This is for an anti-theft thing, so there's no conventional way to get the data, it has to be done something like this.
This worked just fine when I was compiling the program on its own, but when I added a static library to the program, the data vanished. The locator symbol is still there; the data it's supposed to be initialized with (and which is supposed to be visible outside it) isn't.
The linker switch /OPT:NOREF solves the problem, but at an unacceptable price: the program grows by several hundred K (doesn't seem like much, but it is in this case). Using the #pragma comment(linker, "/include:?locator@@BLAHBLAH") (don't remember what the "BLAHBLAH" part was) did nothing -- the locator symbol is already visible, it's just not initialized. Moving the locator definition into the library doesn't help either.
Ditching the static library is a last resort, I'd rather not do it if I can avoid it.
Any ideas?
| I haven't been able to find any acceptable solution to this problem. The linker is just too aggressive about what it trims... maybe a bug, maybe deliberate, though for the life of me, I can't imagine a case where you would want to eliminate the initialization of a variable while keeping the variable itself.
For now, I've turned on the /OPT:NOREF option. I'll just have to deal with the extra size, at least until I can find a way around it.
|
2,377,570 | 2,379,685 | A GUI which creates and uses a database and installes easily | I want to create a GUI with C++ (QT4). The GUI should work on Windows and should be able to
create a database
use the database created by it (I should use an existing DBMS, in order not to worry for queries)
database should be specific to the GUI, other software should not be able to use that database (the database may be for example encoded)
the gui with its ability of working with database should be easily installed on the other computers, that is I don't won't to ask user to change some options on his computer manually
So my questions are:
What kind of database can help me to do this, what I should learn connected with database to be able to perform this task?
Should I encode the database by my GUI, or databases have such command to save them on disk already encoded?
Thanks!
| You could try looking into SQLite. The library can be used with C++. It will not need an external DBMS. SQLite is embedded into your application, and you can access you database through it. Also, the database files it produces can be encoded, so it will be accessible to your application only.
|
2,377,617 | 2,377,649 | How to use COM dll in my C++ program | I wish to use a COM dll in my C++ library.
The way I figured going about it, is to #import the dll's .tlb file, which I did :
#import "mycom.tlb" no_namespace
The problem is , I don't quite know where to place this declaration. should it be inside the H file or the CPP file? or maybe the stdafx.h file?
I tried placing it in the .cpp file , just for testing.
in the H file I have this member declared :
ILogicSecuredPtr m_pbLogic;
(where ILogicSecured is the interface I want to work with in my COM dll)
Then I added this in the constructor to instantiate the interface :
CoInitialize(NULL);
m_pbLogic(__uuidof(LogicSecured));
(where LogicSecured is the name of the object that implements the interface)
In the destructor I added :
CoUninitialize();
This won't compile however, no matter where I try to place the #import declaration.
it just doesn't recognize the ILogicSecured object.
I get this error in the H file :
Error 2 error C2146: syntax error : missing ';' before identifier 'm_pbLogic'
I should also mention that when I F12 (in Visual Studio) on the ILogicSecuredPtr declaration, it takes me to the tlh file just fine. So I know it recognizes it.
What am I doing wrong here?
Thanks alot.
Roey
| The problem is that when the compiler parses the .h file it has not seen the #import yet. Since your project is small your best bet is to put #import into stdafx.h.
When you press F12 Visual Studio uses Intellisence database information that is formed parsing all the sources in order that might be different from the compilation order. So it's quite typical to have Intellisence know where something is declared and the compiler to not compile it at the same time.
|
2,377,619 | 2,378,090 | Fast way to determine right most nth bit set in a 64 bit | I try to determine the right most nth bit set
if (value & (1 << 0)) { return 0; }
if (value & (1 << 1)) { return 1; }
if (value & (1 << 2)) { return 2; }
...
if (value & (1 << 63)) { return 63; }
if comparison needs to be done 64 times. Is there any faster way?
| Works for Visual C++ 6
int toErrorCodeBit(__int64 value) {
const int low_double_word = value;
int result = 0;
__asm
{
bsf eax, low_double_word
jz low_double_value_0
mov result, eax
}
return result;
low_double_value_0:
const int upper_double_word = value >> 32;
__asm
{
bsf eax, upper_double_word
mov result, eax
}
result += 32;
return result;
}
|
2,377,733 | 2,377,772 | How does this program work? | #include <stdio.h>
int main() {
float a = 1234.5f;
printf("%d\n", a);
return 0;
}
It displays a 0!! How is that possible? What is the reasoning?
I have deliberately put a %d in the printf statement to study the behaviour of printf.
| That's because %d expects an int but you've provided a float.
Use %e/%f/%g to print the float.
On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is
00 00 00 00 00 4A 93 40
A %d consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f); You could get on output 0, 1083394560.)
As for why the float is converted to double, as the prototype of printf is int printf(const char*, ...), from 6.5.2.2/7,
The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.
and from 6.5.2.2/6,
If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions.
(Thanks Alok for finding this out.)
|
2,377,985 | 2,453,626 | Doxygen C++ comment string parser in python? | Does anybody know of a python module to parse a doxygen style C++ comment string? I mean a string like this (simple example):
/**
* A constructor.
* A more elaborate description of the constructor.
* @param param1 test1
* @param param2 test2
*/
and I would like to extract the brief, the long description, the parameters, the return value etc. I'm currently doing this using string methods and regular expressions but my solution is not very robust.
Alternatively can anybody recommend an easy to use python parser lib that I can set up quickly?
Thanks in advance
| You might be able to set something up using the SimpleParse module, but this does require creating an EBNF grammar which might be more investment than you are interested in.
The Sphinx/Doxygen bridge (Breathe) uses the xml output of Doxygen and acts on that instead. Perhaps a similar approach could work here - run Doxygen to extract xml formatted docs and then leverage some of the code from Breathe to get at the data you require.
|
2,378,072 | 2,378,105 | How to disable that an MFC application exits on pressing ESC or ALTF+F4? | I have an MFC application, which i don't want to be closed during the running. I have disabled the "X" icon in the right upper corner, but now if i press the ESC key, or ALT+F4 it still closes.
How can i disable this, so it won't close, if someone press those keys? After the program has finished running i want to reenable them.
Thanks,
kampi
| If you handle the WM_CLOSE message and throw it away. (i.e. Don't call DefWindowProc), then the window won't close.
You could also register the window class with the CS_NOCLOSE style, to disable all of the normal ways of closing the window.
|
2,378,080 | 2,378,154 | asm/atomic.h compile error | I have an old C++ project and I'm having problem building it. For a certain file I receive the following kind of errors:
error: ‘atomic_t’ was not declared in this scope
And others for other identifiers like atomic_read, atomic_inc, etc. The file has an include for asm/atomic.h, but I cannot find the header file on my system. I'm using SUSE Linux Enterprise Desktop 11 and gcc 4.3.2.
Could there be some package that needs to be installed, or an alternative header to be included for those identifiers?
| These are meant to be kernel headers, not really for applications to use. They are the prototypes for some atomic test and set, increment, decrement etc that are implemented in assembler.
so even if you find the header files, you will still need the .o from the asm or the .asm sources.
These are not the files you are looking for, but they are very likely to be the same or similar.
http://github.com/github/linux-2.6/blob/3067e02f8f3ae2f3f02ba76400d03b8bcb4942b0/arch/sh/include/asm/atomic.h
http://github.com/apache/stdcxx/blob/7b51a66e3db202b7d317c74a5666aaeef7b4ebd0/src/atomic.asm
|
2,378,106 | 2,378,131 | Pointer to pointer memory allocation, why is this wrong? | I am just trying to get my head around various pointer concepts and I have the following code:
char** a = new char*; // assign first pointer to point to a char pointer
char b[10] = "bla bla";
*a = new char; //assign second pointer a block of memory. -> This looks wrong to me!!
(**a) = b[2];
So what is wrong with the second 'pointer' memory allocation? It runs and stuff, but it just feels wrong.
EDIT:
Thanks for clarifying this! I learnt something!
| *a = new char; means that you create a single char variable using its default constructor.
It's equivalent to *a = new char(); And you assign the address of the just created variable to the pointer a
|
2,378,150 | 2,378,207 | C++ scope of inline functions | i am getting the compile error:
Error 7 error C2084: function 'Boolean
IsPointInRect(...)' already has a body
on my inline function, which is declared like this in a cpp file:
inline Boolean IsPointInRect(...)
{
...
}
i have exactly the same function in another cpp file. might this be causing the problem? how can i solve it?
| As litb and AndreyT point out, this answer doesn't address the actual problem - see litbs answer for details.
While static, as Ofir said, gives you internal linkage, the "C++ way" is to use unnamed namespaces:
namespace
{
inline Boolean IsPointInRect(/*...*/) { /*...*/ }
}
§7.3.1.1/1:
An unnamed-namespace-definition behaves as if it were replaced by
namespace unique { /* empty body */ }
using namespace unique;
namespace unique { namespace-body }
where all occurrences of unique in a translation unit are replaced by the same identifier and this identifier differs from all other identifiers in the entire program.
§7.3.1.1/2 adds:
The use of the static keyword is deprecated when declaring objects in a namespace scope (see annex D); the unnamed-namespace provides a superior alternative.
|
2,378,179 | 2,379,960 | Does std::vector call the swap function when growing? Always or only for some types? | As far as I know I can use a vector of vectors (std::vector< std::vector<int> >) and this will be quite efficient, because internally the elements will not be copied, but swapped, which is much faster, because does not include copying of the memory buffers. Am I right?
When does std::vector exactly make use of the swap function? I can't find anything about it in the C++ standard. Does it happen during buffer reallocation?
I did some tests to find it out, but I failed. The swap function for my custom data type isn't called at all.
EDIT: Here is my test program.
| I have no links to back up this claims, but as far as I know, the STL implementation distributed with Microsoft C++ uses some internal non-standard magic annotations to mark vector (and other STL collections) as having-performant-swap so vector<vector<>> won't copy the inner vectors but swap them. Up to VC9 that is, in VC10 they'll switch to rvalue-references. I think you are not supposed to be able to mark your own classes the same way as there's no cross-compiler way to do it and your code will work only on the specific compiler version.
Edit: I had a quick look at the <vector> header in VC9 and found this:
// vector implements a performant swap
template <class _Ty, class _Ax>
class _Move_operation_category<vector<_Ty, _Ax> >
{
public:
typedef _Swap_move_tag _Move_cat;
};
Just for experiment, you could try to specialize this class for you own type, but as I said, this is STL version specific and it's going away in VC10
|
2,378,416 | 2,378,433 | How do I link a static library in a cpp source file? | There's a #pragma command to link in a library from the source file rather than from the project settings. I just can't seem to remember it.
Can anyone here remind me?
Thanks
| #pragma comment(lib, "library")
http://msdn.microsoft.com/en-us/library/7f0aews7(VS.80).aspx
|
2,378,492 | 2,380,367 | Date/time conversion problem if moment is exactly at end of wintertime (non-DST) | In my application I need to calculate shifts using a pattern described in a file.
Recently, at one of my customers the application was hanging because of the following reason:
If you fill in a 'struct tm' with the exact moment at the end of the wintertime (non-DST) _mktime seems to return an incorrect result.
The code looks like this:
struct tm tm_start;
tm_start.tm_mday = startday;
tm_start.tm_mon = startmonth-1;
tm_start.tm_year = startyear-1900;
tm_start.tm_hour = starthour;
tm_start.tm_min = startmin;
tm_start.tm_sec = startsec;
tm_start.tm_isdst = -1; // Don't know if DST is active at this moment
_int64 contTime = _mktime64(&tm_start);
Suppose that there is a switch from winter- to summer-time on the 5th of April at 2:00.
In practice, this means we have the following time-moments:
5 April, 1:58
5 April, 1:59
5 April, 3:00
Since I don't know in the application when DST starts or ends (do I really want to know this?) I pass the date "5 april, 2:00" to _mktime64 using the code shown above.
I would expect _mktime64 to give me the time_t value that corresponds to 5 April, 3:00 (which is exactly the same moment as 5 April, 2:00).
However, this isn't what's happening. _mktime64 changes tm_start to 5 April, 1:00 and returns the corresponding time_t value. Which means that I get a totally different moment.
(in fact: every moment between 2:00 and 3:00 causes _mktime64 to return a moment between 1:00 and 2:00)
I thought this was a bug in Visual Studio 2005, but apparently Visual Studio 2010 (Release Candidate) has the same behavior.
The problem appears on both XP and Windows7 (didn't check Vista).
Is this a known bug?
Or are there other tips to tackle this problem?
| I guess it simply doesn't know how to correctly handle the invalid time you pass in. And it is certainly invalid for your time zone - you're thinking of it as '1 minute after 1:59 in the winter' implying that you wanted it to return '3:00' with DST back in operation, which sounds reasonable. However it could equally well treat it as 'an hour before 3:00 in the summer' meaning it must have been from the winter period and thus returns '1:00'. Thus I don't think it's a bug - it's more likely to be undefined behaviour about how to handle a non-existent time.
I expect the safest way to approach this is to use UTC throughout as then there are no ambiguities. Obviously this may not map cleanly to your application domain, but such is the murky world of pushing time backwards and forwards!
|
2,379,129 | 2,379,297 | How to order my objects in a C++ class correctly | I have been coding regurlarly in C++ in the past months. I am getting used to it step by step... but there are things that confuse me about formatting.
I know there is a lot of legacy from C that I supousee mixes with C++. This time I have doubts about how to order properly my members and functions within in a class. Also considering their access modifiers.
How is the convention in this? Until know I am doing everything "public" and writing first constructor of class, then destructor, next members and finally functions. It this correct? What happens when introducing "private" and "protected" access modifiers or "virtual" functions?
From the documents I have look in the Internet there is different ways of doing things. But my questions aims to get the knowledge from a community that develops in C++ that I want to blend into. ;-)
Thanks a lot!!!
| My humble opinion, after having read many style guides all over the 'net:
Public first, because that is the interface of your class, which people want to see first.
From the same reasoning, private goes last.
If you have any private functions, place them before private members. (Again, same reasoning. Your members are of the least interest to anyone.)
Constructor first in the public section, because people have to call that before they have an object on which to invoke any functions.
Destructor right after the constructor, just to have them in one place.
Within the public / protected / private sections, find some grouping logical to any users of the library, and write a one-line comment in front of each group. (Doesn't matter that much what's the logic, as long as it's documented.)
Don't make any rules more complicated than this, because the more complicated, the easier to get it wrong (or just ignore it as inconvenient).
Remember that members should be initialized in the order they are declared, and destroyed in the reverse order.
|
2,379,208 | 2,380,167 | How can I display a bitmap/icon on an XP style button | I have a small (6x9) graphic that I want to draw on a CButton. I have managed to get this to work using ::LoadImage and CButton::SetBitmap.
The problem is that when I put the bitmap on the button it is no-longer drawn as an 'XP style' button. I.e. it does not have rounded corners.
How can I draw a bitmap (or an icon) on a button without the button losing the XP style?
| Don't do it with owner draw. Use CMFCButton which has much better support for bitmapped buttons, even with transparency.
|
2,379,401 | 2,379,955 | Pointer to a class member | I am using Boost Spirit parser, and as the parser is parsing, semantic actions are reflected to an instance of the class ParserActions.
Here is the code for the parser (the relevant part)
struct urdf_grammar : public grammar<urdf_grammar> {
template <typename ScannerT>
struct definition {
definition(urdf_grammar const& self) {
prog = (alpha_p >> *alnum_p)[&(self.actions.do_prog)];
}
rule<ScannerT> prog;
rule<ScannerT> const&
start() const {
return prog;
}
};
const ParserActions & actions;
explicit urdf_grammar(const ParserActions & actions = ParserActions()) : actions(actions) {
}
};
| In order to call a member function of an object you need to provide two things:
the address of the member function, as said before you can get that by writing &my_class::my_member
the pointer (or a reference) to the instance of the object you want the member function be invoked for
Spirit semantic actions expect you to provide a function or function object exposing a certain interface. In your case the expected interface is:
void func(Iterator first, Iterator Last);
where Iterator is the iterator type used to call the parse function (accessible through typename ScannerT::iterator_t). What you need to do is to create a function object exposing the mentioned interface while still calling your member function. While this can be done manually, doing so is tedious at best. The simplest way to create a function object is by using Boost.Bind:
prog = (alpha_p >> *alnum_p)
[
boost::bind(&ParserActions::do_prog, self.action)
];
which will create the required function object for you, binding and wrapping your member function.
All this assumes your member function does not take any arguments. If you need to pass the pair of iterators the semantic action will be invoked with to your function the construct needs to be written as:
prog = (alpha_p >> *alnum_p)
[
boost::bind(&ParserActions::do_prog, self.action, _1, _2)
];
instructing the function object to forward its first and second parameter to the bound function.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.