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
5,257,317
5,257,504
decltype not working properly in gcc 4.3.2?
#include <iostream> #include <map> using namespace std; int main() { int x = 5; decltype(x) y = 10; map<int, int> m; decltype(m) n; decltype(m)::iterator it; } g++ -std=c++0x main.cpp main.cpp: In function `int main()': main.cpp:11: error: expected initializer before `it' The first 2 decltypes w...
The ability to use a decltype-expression to form a qualified-id (type::type) was only recently (well, a year ago), added to the C++0x working paper, but it will be part of the finished standard. So the code you have written is actually well-formed C++0x. Eventually gcc will catch up. In the meantime, you can use someth...
5,257,388
5,257,450
C++ should all member variable use accessors and mutator
I have about 15~20 member variables which needs to be accessed, I was wondering if it would be good just to let them be public instead of giving every one of them get/set functions. The code would be something like class A { // a singleton class public: static A* get(); B x, y, z; // ... a lot of other o...
The C++ world isn't quite as hung up on "everything must be hidden behind accessors/mutators/whatever-they-decide-to-call-them-todays" as some OO-supporting languages. With that said, it's a bit hard to say what the best approach is, given your limited description. If your class is simply a 'bag of data' for some other...
5,257,509
5,257,664
freopen() equivalent for c++ streams
When programming with c-style i/o I sometimes use freopen() to reopen stdin for testing purposes so that I don't have to retype the input over and over. I was wondering if there is an equivalent for c++ i/o streams. Also, I know that I can use pipes to redirect it on the command line/terminal/whateveritis but I was won...
freopen also works with cin and cout. No need to search for something new. freopen("input.txt", "r", stdin); // redirects standard input freopen("output.txt", "w", stdout); // redirects standard output int x; cin >> x; // reads from input.txt cout << x << endl; // writes to output.txt Edit: From C++ standard 27.3.1: ...
5,257,768
5,257,950
Local variables construction and destruction with optimizer involved
If I have this code: class A { ... }; class B { ... }; void dummy() { A a(...); B b(...); ... } I know that variables a and b will be destroyed in reverse allocation order (b will be destroyed first, then a); but can I be sure that the optimizer will never swap the allocation and construction of a and b? ...
The only guarantees are that any observable side effects (that is, reads and writes to volatile objects and calls to I/O functions) of the construction of a will happen before any observable side effects of the construction of b, and any side effects of a required by b will happen before they are needed. It's hard to i...
5,257,801
5,258,059
Implementing a Deck of Cards in C++
So I am trying to create a deck of cards and I am still kind of new to C++ and pointers so I have a few question So I have Card class with getRank, getSuit, and comparison of two Card objects. They way I'm setting the deck is number 1-13 for the rank and 1-4 for the suit. So it's a simple compare by comparing one Card'...
Here is some draft for you to consider and probably build your class upon it: class Card { public: // TODO: provide suitable constructor... enum Suit {Hearts, Diamonds, Clubs, Spades}; enum Rank {A, K, Q, J, _10, _9, _8, _7, _6, _5, _4, _3, _2}; Suit getSuit() { return suit; } Rank getRank() { return r...
5,257,914
5,258,589
Using a constructor in a function call?
I've been searching awhile for a good explanation of why/why not the following use of the struct constructor as a function argument is legal. Can someone provide one? // Begin simple illustrative example C++ program #include<vector.h> struct Item { Item(double data, const int lead) : m_grid(data), m_lead(l...
It is legal. You never call the constructor yourself; you're actually just declaring an unnamed or "temporary" object of type Item. See how the syntax evolves when you make the object unnamed: Item a(img,i); // normal Item(img,i); // temporary Even though it looks as if you're calling the constructor like a function...
5,257,977
5,260,551
How to bring other app window to front without activating it?
I want to bring to front a window(from other application). Currently I'm using: ::SetWindowPos(hwnd, GetForegroundWindow(), 0, 0, 0, 0, SWP_ASYNCWINDOWPOS | SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE); It works fine, but in some (unknown to me) cases, it makes the window always on top. According to MSDN, I should use HW...
The other application's window can be made temporarily 'top-most' to bring it to front without activating it, first by specifying HWND_TOPMOST as 'hWndInsertAfter' in a SetWindowPos call and then by specifying HWND_NOTOPMOST in a second call (both calls with SWP_NOACTIVATE in 'uFlags'). If there's a risk of removing th...
5,257,984
5,258,094
C++ equivalent to Python's cmp or Haskell's compare
Question: Is there a C++ equivalent for Python's cmp or Haskell's compare? compare is like operator== and operator< in one. It returns LT, EQ, or GT. But it's twice as fast as calling both operator== and operator< because it does it in one pass. More details: At work, I often have structs that are used as keys for maps...
You can easily implement it yourself, as a free function. #include <string> #include <vector> enum order { order_lt = -1, order_eq, order_gt }; // General case, templated version. template < typename T > order compare(T left, T right) { if (left < right) return order_lt; if (left == right) ...
5,258,006
5,258,051
#define mockable virtual in C++
I found this code: #define mockable virtual Do you have any idea why somebody will define virtual like this? I'm just curios what's the point of doing this
So that you could do: class ClassIdLikeToTest{ mockable void mymethod(){ //Behavior I would like to be different in my tests } } And then define mockable as virtual for the test build so that you can override that method inheriting from the class. You write your test and use a class that inherits from...
5,258,081
5,258,548
What's the point of issuing a compiler warning for "while(true)" and not issuing one for "for(;;)"?
When I compile C++ code with Visual C++ 9 with "warning level 4" the following: while( true ) { //loop body with break on certain condition } and the following: for( ; true; ) { //same loop body } both trigger C4127: conditional expression is constant warning but the following: for( ; ; ) { //same loop body ...
The reason is simple, though stupid. It is important to diagnose infinite loop, but such might not be evident: while(i >= 0) { --i; } // infinite if i unsigned while(SOME_MACRO(i)) // err, depends on the expansion of macros It is a great feature of a compiler to produce a warning for a tautological test, that is a te...
5,258,321
7,221,393
Windows Debug Api - Detaching not working
I'm running my event loop in a thread that is created on attaching to target process. What I did before to detach was simply calling a function that would clear the debug and call DebugSetProcessKillOnExit etc. but getting bad return values I figured they must be called from the thread that I created. So I did, no erro...
I found out the error: I was exiting my program before the thread had done its part (detaching).
5,258,521
5,258,861
Allow Low-Privileged Users to Start Windows Services
I want to deploy a C++ application that will run in enterprises where users have low privileges on their machines, so they can't run as admin or do tasks that require admin privileges. The service I want can be run as Local Service, which is a low privilege account in Windows, so how can I , programmaticaly, let my app...
This is simply not possible; standard users don't have the necessary privileges to do this. By default, only members of the Administrators and Power Users group can start, stop, and pause services. This is a problem best solved by group policies, rather than by software. Ask about that on Server Fault.
5,258,607
5,258,662
How to Get array of string from Native Code(C++) in Managed Code(C#)
is there any way through which we can get the collection of string from c++ to c# C# Code [DllImport("MyDLL.dll")] private static extern List<string> GetCollection(); public static List<string> ReturnCollection() { return GetCollection(); } C++ Code std::vector<string> GetCollection() { std::vector<string> collect...
There are a multitude of ways to tackle this, but they are all rather more complex than what you currently have. Probably the easiest way to pass a string allocated in C++ to C# is as a BSTR. That allows you to allocate the string down in your C++ and let the C# code deallocate it. This is the biggest challenge you fac...
5,258,627
5,258,904
Atomic 64 bit writes with GCC
I've gotten myself into a confused mess regarding multithreaded programming and was hoping someone could come and slap some understanding in me. After doing quite a bit of reading, I've come to the understanding that I should be able to set the value of a 64 bit int atomically on a 64 bit system1. I found a lot of this...
Disassembling the loop, I get the following code with gcc: .globl _switcher _switcher: LFB2: pushq %rbp LCFI0: movq %rsp, %rbp LCFI1: movl $0, -4(%rbp) L2: cmpl $0, -4(%rbp) je L3 movq _foo@GOTPCREL(%rip), %rax movl $-1717986919, (%rax) movl $429496729, 4(%rax) j...
5,258,665
5,260,751
How to set number of lines for an QTextEdit?
I use a QTextEdit for some inputs. But I want to adjust the height of the box. Can I set the height based on the number of lines I want to have visible at a time?
If you use QPlainTextEdit, something like this should do the trick: void SetHeight (QPlainTextEdit* edit, int nRows) { QFontMetrics m (edit -> font()) ; int RowHeight = m.lineSpacing() ; edit -> setFixedHeight (nRows * RowHeight) ; } You might want to add two or three pixels as margin; experiment will tell....
5,258,793
5,258,996
boost::asio::async_read texutal stop condition?
I'm writing a server with Boost, something pretty simple - accept an XML message, process, reply. But I'm running into trouble at telling it when to stop reading. This is what I have right now: (_index is the buffer into which the data is read) std::size_t tcp_connection::completion_condition(const boost::system::error...
You can pass pointers to member functions. The syntax for doing it with C++ is tricky, but boost::bind hides it and makes it fairly easy to do. An example would be making completion_condition non-static and passing it to async_read as such:boost::bind(&tcp_connection::completion_condition, this, _1, _2) &tcp_connection...
5,258,826
5,258,938
How to see the actual order of include files after preprocessing?
I have one .cpp file that includes a few header files. These header files may include other header files as well. Include guards are in place to prevent including the same file twice. Knowing that each file is only included once. Is there a way to figure out the eventual order in which all headers will be included? I t...
Use cpp -H. This prints the headers used to standard error. Example: $ cpp -H -I../../include base64.cpp 2>&1 >/dev/null | head . /usr/include/c++/4.4/cstring .. /usr/include/c++/4.4/i486-linux-gnu/bits/c++config.h ... /usr/include/c++/4.4/i486-linux-gnu/bits/os_defines.h .... /usr/include/features.h ..... /usr/include...
5,258,835
6,067,648
Running out of file descriptors for mmaped files despite high limits in multithreaded web-app
I have an application that mmaps a large number of files. 3000+ or so. It also uses about 75 worker threads. The application is written in a mix of Java and C++, with the Java server code calling out to C++ via JNI. It frequently, though not predictably, runs out of file descriptors. I have upped the limits in /etc...
So, from all I can tell, this appears to have been an issue specific to Ubuntu 8.04. After upgrading to 10.04, after one month, there hasn't been a single instance of this problem. The configuration didn't change, so I'm lead to believe that this must have been a kernel bug.
5,259,170
5,259,198
Explain GCC error after using an object accidentally declared as a function
The following is a common typo with language newcomers, who think that they are defining an object but are actually declaring a function: struct T { void foo() {} }; int main() { T obj(); obj.foo(); } GCC 4.1.2's error is: In function 'int main()': Line 9: error: request for member 'foo' in 'obj', which is o...
IIRC this is just a compiler bug. GCC 4.4 says T() while 4.2 says T()() for me.
5,259,215
5,260,045
Can I lock the width or height of an MFC dialog during resizing?
Is there a way to lock a dialog box's size in one direction (restrict only width or only height) in MFC?
You need to override OnGetMinMaxInfo. In OnInitDialog you can capture the current height, and then use it for both minimum and maximum height. Call __super::OnGetMinMaxInfo first and then only change the height members. Note that the window may not exist the first couple times OnGetMinMaxInfo are called. Here's a detai...
5,259,273
5,259,509
cURL in c++ using STL
the cURL example given here http://curl.haxx.se/libcurl/c/getinmemory.html shows how to get a url to memory. i would like to change the above code to use in c++ without much change. I would like to replace the malloc and realloc with something else. Is there a way to get the above code to work by using an STL like lis...
as nick has pointed out, luckyspin.org/?p=28 gave me the answer. static int writer(char *data, size_t size, size_t nmemb, std::string *buffer) { int result = 0; if (buffer != NULL){ buffer->append(data, size * nmemb); result = size * nmemb; } return result; }
5,259,320
5,259,370
STATUS_STACK_BUFFER_OVERRUN with LoadLibrary
When I load iphlpapi.dll with LoadLibrary my stack buffer overrun! How can I solve this problem?! typedef DWORD (*GetExtendedTcpTable)(PVOID, PDWORD, BOOL, ULONG, TCP_TABLE_CLASS, ULONG); GetExtendedTcpTable _GetExtendedTcpTable; // load function at runtime HINSTANCE hstLibrary = LoadLibrary("C:\\Windows\\System32...
You need to specify calling convention: typedef DWORD (WINAPI * GetExtendedTcpTable)(PVOID, PDWORD, BOOL, ULONG, TCP_TABLE_CLASS, ULONG); The default calling convention in VS is __cdecl, Windows API requires __stdcall. These differ in how the stack for arguments is handled, most notably __cdecl requires the caller ...
5,259,757
5,259,821
Thread Argument Problem
I have working on multithreaded application I am passing IMAGETHREADINFO structure in thread here nSock is showing garbage value. What is the problem here.pointer to IMAGETHREADINFO is declared as member variable of CServerConnectionMgr class. typedef struct { int nScok; CServerConnectionMgr* pConMgr; }IMAGETH...
(void*)&stThreadInfo is a pointer to the stThreadInfo pointer. You likely want to remove the & And then, also change IMAGETHREADINFO *pImageThreadInfo = (IMAGETHREADINFO*)&args;, remove the &
5,259,874
5,259,994
How can I perform conversion from float -> double -> float when processing an audio buffer in c++
I am currently developing an application where frames of audio samples are processed in the following callback. void Eav07AudioProcessor::processBlock (AudioSampleBuffer& buffer) { for (int channel = 0; channel < getNumInputChannels(); ++channel) { float* channelData = buffer.getSampleData (channel); ...
No, casting the float to double and back will not do what the gain()-function expects. The gain-function expects a pointer to an array of doubles and no amount of casting will do that. The best thing you can do is replace the gain()-function. I would just use the "demo-code" you included (the inner for-loop). If you h...
5,259,929
5,261,359
Comparison operators for directory_entry are missing
Consider the following program: #include <iostream> #include "boost/filesystem.hpp" int main() { boost::filesystem::directory_entry d("test.txt"); boost::filesystem::directory_entry e("test.txt"); if (d == e) { // <---- error C2784 std::cout << "equal" << std::endl; } return 0; } This fa...
Ok, apparently this is only supported in the new Version of the library. Defining BOOST_FILESYSTEM_VERSION as 3 at the start of the program fixed the problem.
5,260,099
5,260,399
passing information to multiple thread
I am working on MultiThreaded TCP Server(c++) which will serve multiple client to stream Video. I have decided to go with "thread per client" approach. There're no more than 100 simultaneous clients. I am multiplexing the client using select system call and accepting the (accept) and then creating thread to stream vide...
usually starting a thread, ether using standard approach of void function or functor class: class StreamInfo { public: int _id; std::string _ip; int _port; int status; StreamInfo(int id, string ip, int p):_id(id), _ip(ip), _port(p){}; }; void myThread(void* datastruct) { StreamIn...
5,260,188
5,260,572
Good resources on using a QT backend with a C# Gui
I am interested in creating a WPF user interface for a QT project. I am wondering if anyone has any recommendations for articles / books which might cover this or similar topics. I am aware that I would need to wrap the QT dll but am unsure of the logistics of this. Cheers Mike.
http://doc.qt.nokia.com/4.7-snapshot/activeqt-dotnet.html http://developer.qt.nokia.com/faq/answer/is_qt_compatible_with_.net http://doc.qt.nokia.com/latest/activeqt.html
5,260,211
5,260,308
execve from a Mac OS X launchd daemon
Is it possible to use execve from a launchd daemon? My process that I would like to make into a daemon launches several child processes using fork() followed by execve, but the documentation for creating launchd daemons states that "calling fork followed by exec" is not ok. Does this mean that I cannot create child pro...
AFAIK, you can fork and exec just fine. The critical point is this one: "You must not fork your process and have the parent process exit." Thing is, launchd "watches over" your service. If your service exits, it gets restarted. That means it may not daemonize, either (with daemonize I mean the classical spawn a new pro...
5,260,621
5,260,726
What are some interesting C/C++ libraries to play around with?
I'm looking for a few new libraries and for C and C++. In the past most of the time I "accidently" stumbled across a few - and most of them found good use in projects I worked on. Libraries should run on Mac OS X and Linux/POSIX and possibly on Windows. Lua - A minimal and fast scripting engine for configuration files...
STL and Boost are musts. SQLite provides a completely embedded, full-featured relational database in a few 100k that you can include right into your project. It's also a highly marketable skill because of its high presence (it's included in Mozilla Firefox as well as Android and iOS). If you're interested in creating u...
5,260,862
5,261,134
Vector of object pointers does not seem to perform as intended in C++
I have been a follower for a long time but this is the first time I ask a question. In a nutshell, the issue is; vector<Student*> studentvector that is a vector of object pointers seems to push the student info back as student ; but when I print to see the first one in vector whether it performs as intended, I see it a...
Doh! Here's your problem - all objects from type Student use the same global pointers: string *Alias; string *Name; Make these two as members in you class class Student { private: string *Alias; string *Name; //.. }; EDIT: Also, I don't think, that it's a good idea to use pointer to std::string, I'd sugges...
5,260,907
5,262,122
What's the way to access argc and argv inside of a test case in Google Test framework?
I’m using Google Test to test my C++ project. Some cases, however, require access to argc and argv to load the required data. In the main() method, when initializing, argc and argv are passed to the constructor of testing. testing::InitGoogleTest(&argc, argv); How can I access them later in a test? TEST(SomeClass, myT...
I don't know google's test framework, so there might be a better way to do this, but this should do: //--------------------------------------------- // some_header.h extern int my_argc; extern char** my_argv; // eof //--------------------------------------------- //--------------------------------------------- // mai...
5,261,027
5,261,183
How to write cache friendly polymorphic code in C++?
I am writing a piece of code with high demands on performance where I need to handle a large number of objects in a polymorphic way. Let's say I have a class A and a class B which is derived from A. I could now create a vector of B:s like this vector<A*> a(n); for(int i = 0; i < n; i++) a[i] = new B(); but if n is l...
You can use placement new to construct an object at a particular memory location: vector<A*> a(n); for(int i = 0; i < n; i++) a[i] = new(storage + i*object_size) B(); // and invoke the destructor manually to release the object (assuming A has a virtual destructor!) a[i]->~A(); But you cannot solve the 'real' pr...
5,261,279
5,261,301
Is it possible to throw two values at the same time?
I have 4-line and two throw statements ; Pseudocode ; In function f () if a == 2 throw SMT_0 if b == 3 throw SMT_1 For a != 2 and b != 3, I want to throw both throw statements, simultaneously. How can I do ? ex : if a!= 2 && b != 3 throw SMT_0 and SMT_1
You cannot. But you can throw any object, so you can use OO techniques to have the one object you throw contain the relevant information from both SMT_0 and SMT_1. What are the thrown values, and what does your catch block look like? Update: OK, so it looks like you want to throw the reason(s) that your input was not c...
5,261,283
5,261,320
Boost random numbers - weird compilation error
In a simulation I'm writing I have a class that represents an Agent that must take some actions and I want this agent to have access to a random number generator. I heard boost rng's where good ones, so I wanted to learn how to use them. So, here's the problem. This code compiles and runs perfectly: //Random.cpp #inclu...
I think you need to initialise you member variables uni and uniRng in the constructor initialisation list rather than inline where they are declared.
5,261,299
5,261,457
Static keyword in function declaration can be missing in function definition?
I want to have a static function which I declare in my .c file before defining it: //file a.c version 1 static int foo(); ... static int foo() { ... } However, it seems that I can leave the static keyword out of the function definition and I get no compiler warnings... e.g. //file a.c version 2 static int foo(); ... i...
Yes 7.1.1/6 A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. See also the examples of 7.1.1/7
5,261,409
5,261,453
Process text file by C++ -- extract a certain string from text file
I am a new learner to C++. I have a text file, its contents like following: Systemname localtesthost SystemIp X.X.X.X Systemowner root ... Now I want to extract the value of "Systemname", that is "localtesthost". And I can extract the line containing "Systemname localtesthost", but I don't know how to ext...
Here is an approach: create a std::istringstream using the line you just read in. read from the stream two std::string objects, key and value if the key matches what you are looking for, value should contain what you require.
5,261,515
5,261,584
Can you cast a LPTSTR to a BSTR?
Is it legal to cast a LPTSTR directly to a BSTR? Based on my understanding of BSTR, casting a LPTSTR to a BSTR directly will leave you with a corrupted length prefix. The example code explicitly states that a string literal cannot be stored to a BSTR. Can anyone confirm for me that a LPTSTR/LPCTSTR cannot be cast direc...
If your program is unicode and your LPTSTR therefore is a LPWSTR, you can use SysAllocString to convert from a pointer to a wide character string to BSTR. A direct cast is not possible because the two have different memory representations. If you use C++, you can use the _bstr_t class to simplify the usage of BSTR stri...
5,261,658
5,265,251
How to seek in FFmpeg C/C++
Does anyone know how to implement seeking by seconds (or milliseconds) in FFmpeg. I currently have a loop running through the frames of a video using av_read_frame() and I want to determine what time this frame should be at in seconds. If it gets to a certain point then I want to seek to a later point in the video. By ...
NOTE: This is out of date, it should still work but there is now av_seek_frame() to do it officially. I didn't write this but here is some code from a sample I have bool seekMs(int tsms) { //printf("**** SEEK TO ms %d. LLT: %d. LT: %d. LLF: %d. LF: %d. LastFrameOk: %d\n",tsms,LastLastFrameTime,LastFrameTime,LastLast...
5,262,027
5,262,073
How do all the different size types relate to each other?
Currently I have a scenario where I want to check whether writing a given string to a filestream will grow the file beyond a given size (this is used for logfile rotation). Now, std::ofstream::tellp() returns a streampos, but std::string::size() returns a size_t. The effect is, that this does not work: out_stream.tellp...
You should be able to convert the result from tellp to a std::string::size_type by casting. static_cast<std::string::size_type>(out_stream.tellp()) + string.size() < limit EDIT: This is safe because your stream offset will never be negative and will safely convert to an unsigned value.
5,262,091
5,512,885
HTTP connection through DMZ / proxy in C++
I want to connect from webserver via dedicated proxy to the intranet. I am not sure if it matters I want to send and receive XML. It would be great if I could use HTTP. I know of one open port 78xx which I successfully used with a TCP socket as described in this excellent tutorial Is it possible? Or does the answer dep...
The answer is.... in progress.- I need to practice more with c++ tcp libs etc. My post was unfortunately hard too understand, Had some confusion about that all.
5,262,161
5,262,723
Can cuda be used combining with activeX technology?
every one. i am a newbie to cuda. i am wondering that can cuda be used combining with ActiveX technology, the presented ocx or dll file can be used in webpage, for example, using cuda can we simulate a fluid particle easily. if combine cuda and activeX technology , we can see fluid particle in a webpage, am i right? wh...
I think that if ActiveX could access your GPU on such low level as running your arbitrary CUDA code, it would be a big security risk. If on the other hand, ActiveX could perform some of its computations on the GPU though some higher-level interface, that would be safer, but it is Microsoft who would have to implement i...
5,262,301
5,263,894
how can I corrupt the data segment of a linux process?
I am coding in C/C++. What are the possible ways to corrupt a static variable that is stored in the data segment? Is this considered a memory leak? #include <stdio.h> int aaa[5]; int bbb; int main() { int i; bbb=41; for (i = 0; i < 6; ++i) aaa[i] = 42; printf("%d...
Yes, there is more than one method to destroy the contents of global variables (your variables are not static in the example you posted). Pointers are a good tool to corrupt memory and write where your program should not. Casting can also add some excitement: #include <iostream> using namespace std; int aaa[5]; int...
5,262,404
5,322,471
Portably generate XML document without using a DOM
I have a need to generate XML documents from C++. For reasons of performance I don't want to use an XML parser such as Xerces, or TinyXML and generate a DOM which I then serialize, ideally I want a kind of "reverse SAX" interface. I also need the code to be really portable, across Windows, UNIX, MacOSX etc. The only re...
Looks like libxml2 has a streaming API. See answer to question create and stream large XML document in C++
5,262,405
5,262,468
0 initialization of C++ built-in types
suppose I have this struct (or class, my question applies to both): struct builtin { int a; int b; builtin() : a(), b(0) { } }; I know that both a and b will be initialized to 0 by the constructor of builtin. My question is: Is one method faster than the other?
Answer: no. The compiled code is identical.
5,262,497
5,262,540
How to implement a reference constructor?
I am looking for a way to have my constructor make a reference to another object in this way: Foo object1("File1"); Foo object2("File1"); The first object is created normally. The second object sees that there is already an object that is using the "File1" parameter and makes itself a reference to the first object. ...
Try to use static map<string, object*> as variable where object is the rest of the class you need.
5,262,667
5,262,704
infinite loop while counting dates
I'm trying to solve problem that asks to find how many times 13th day occurs at each weekday in period of 1990+N-1 years. int weekDay = 1; int week[] = {0,0,0,0,0,0,0}; N = 20; for (int year = 1990; year <= 1990+N-1; year++){ for (int month = 1; month <= 12; month++){ int days = numberOfDays(year,month); ...
You are using weekdays in the range 1..7 but your histogram array week[] is indexed 0..6. One possible solution - change: week[weekDay] += 1; to: week[weekDay - 1] += 1; Another solution - make week[] one element bigger and don't use element 0, i.e. change: int week[] = {0,0,0,0,0,0,0}; to:...
5,262,889
5,262,934
Float subtraction returns incorrect value
So I have a calculation whereby two floats that are components of vector objects are subtracted and then seem to return an incorrect result. The code I'm attempting to use is: cout << xresult.x << " " << vec1.x << endl; float xpart1 = xresult.x - vec1.x; cout << xpart1 << endl; Where running this code will return 16 1...
This is called floating point arithmetic. It is why numerical code is so "tricky" and filled with pitfalls. That result is expected. And what is more, it can depend on the processor that you're working with as to what and to what extent you'll see it. I'd like to add that each type of variable of the floating point ...
5,263,100
5,264,639
Anybody there succeeded debugging C++ in Eclipse?
I wanted to shift from Visual Studio 2008 to Eclipse Helios for C++ dev. I tried in mac and found a lot of unstabilities while debugging. Then I tried on Linux and similar. This is the last problem I found: http://www.eclipse.org/forums/index.php?t=msg&th=205832&start=0&S=0b23d01871ba30eea27e36afdf03712d At the moment ...
I use Eclipse Helios as my C++ IDE. Os is Ubuntu 10.04. I use it regularly for debugging and can't remember to have ever had any serious problems. I had never problems with "unstabilities" while working with projects of significant size including Qt applications. I would suspect you are an isolated case. If you are mor...
5,263,143
5,263,211
What is the difference between a blocking and non-blocking read?
Add to the above question the concept of a wait/no wait indicator as a parameter to a ReadMessage function in a TCP/IP or UDP environment. A third party function description states that: This function is used to read a message from a queue which was defined by a previous registerforinput call. The input wait/no wait...
Blocking means that execution of your code (in that thread) will stop for the duration of the call. Essentially, the function call will not return until the blocking operation is complete. A blocking read will wait until there is data available (or a timeout, if any, expires), and then returns from the function call. A...
5,263,194
5,263,922
Examples of small and middle opensource projects on GTK+
Can you tell me where i can see a source of examples GTK+ projects (non gtkmm). It is desirable that be used Glade for design UI. I want to see how to organize program and get experience.
You've got plenty of projects in GTK+ in many languages on the GNOME development servers.
5,263,404
5,263,605
Read/write data then separate data
I am a newbie in C++. I am doing a C++ sign up form where I keep all the user datas in a text file named user.txt with formats like name|password|address|postal|phone Each user record will occupy one line. So my first question how can I do this nicely in C++ As for the reading part, my main problem is how to separate ...
Check out this answer. In your case, the fields will be appended to the vector<string> in order, so you can access them directly from it. First position would correspond to the name, second to the password and so on. Here's an example: // The elements should be in this order: name, password, address, postal, phone vect...
5,263,487
5,263,521
Deciding which standard header files to #include
Suppose i am editing some large C++ source file, and i add a few lines of code that happen to use auto_ptr, like in the following example. #include <string> // ... (much code here) void do_stuff() { std::string str("hello world"); // ... (much code here too) std::auto_ptr<int> dummy; // MY NEW CODE //...
If you use something in the standard library, you should include the header in which it is defined. That is the only portable option. That way you avoid the instance you cite where one header happens to include another in one version or compiler, but not another. auto_ptr is defined in <memory>, so if you use it, in...
5,263,524
5,263,531
C++ -- why should we define the pure virtual destructor outside the class definition?
class Object { public: ... virtual ~Object() = 0; ... }; Object::~Object() {} // Should we always define the pure virtual destructor outside? Question: Should we always define the pure virtual destructor outside the class definition? In other words, it is the reason that we should not define any virtual functio...
You can define virtual functions inline. You cannot define pure virtual functions inline. The following syntax variants are simply not permitted: virtual ~Foo() = 0 { } virtual ~Foo() { } = 0; But this is fully valid: virtual ~Foo() { } You must define a pure virtual destructor if you intend to instantiate it or subc...
5,263,619
5,263,637
What is the purpose of adding a defininition for a pure-virtual destructor?
Inspired by: C++ -- why should we define the pure virtual destructor outside the class definition? What does the following code actually do? class Object { public: virtual ~Object() = 0; }; Object::~Object() { /*...*/ } I thought that the point of a pure virtual function was to force subclasses to implement t...
This code prevents you from creating an instance of Object, while at the same time allowing you to create subclasses. When destroying an object, the destructor of the parent class will be called, so it must exist. This applies whether the destructor is pure virtual or not. A pure virtual member function only needs to b...
5,263,898
5,263,962
stdafx.h cross platform without issues?
Hey i've been following learncpp.com tuts for the last couple days, they say to comment out "#include "stdafx.h" from .cpp files for Code::Blocks. Is that a must, to remove the include line? What happens if you had hundreds of files and changed from Visual Studio on Win7 to Code::Blocks on Linux or hand it off to someo...
stdafx.h is the idiomatic name used for precompiled headers in the Visual Studio ecosystem. In a nutshell, it's a regular header, but the contents of this file will be compiled once and reused for all cpp files in the project. That is useful since in most projects, a large number of headers (standard library, system he...
5,264,046
5,264,223
Dynamically allocated list in C++
I made a cute generic (i.e. template) List class to handle lists in C++. The reason for that is that I found the std::list class terribly ugly for everyday use and since I constantly use lists, I needed a new one. The major improvement is that with my class, I can use [] to get items from it. Also, still to be implemen...
The best answer is that you must think on the lifetime of each one of the objects, and the responsibility of managing that lifetime. In particular, in a relation from people and the sites they have visited, most probably neither of them should be naturally made responsible for the lifetime of the others: people can li...
5,264,597
5,264,624
What exactly happens when a character is appended to a string literal with the '+' operator in C++?
Based on my reading, the following code: string aggregate = "give" + 'n'; Should produce a resulting string with the value: "given". It instead produces garbage. Why doesn't the following happen? "give" is converted to a std::string via the constructor that takes a pointer to a character array. The '+' overload that...
The expression "give" + 'n' is evaluated first, adding (int)'n' to the address of the string constant "give". The result of this pointer arithmatic is assigned to the string object. No error is raised because the result is of type const char*. You should get used to thinking of everything on the right of the = as happe...
5,264,709
5,264,759
What STL container to perform removal of elements in between?
I need to pick a container to hold pointers to a type I defined (Particle). I'm using a pre-allocated Particle Object Pool ( which contain objects pre-allocated on an std::vector ). My Particle emitters ask the Particle Pool for particles when they need to emit, ( in order to avoid in-game Particle allocation ). When a...
I don't entirely follow your algorithm, but std::vector is required to provide amortized constant time push_back. It may also have better locality of reference when iterating. If order doesn't matter, removal of any item is also a constant time operation: template <typename T> void remove(std::vector<T> &v, size_t i) {...
5,264,803
5,264,900
Is there any way to connect to oracle db using simple c++ not vc++ or proc
I am struggling to connect to oracle db using GNU C++.Is there any library which I have to install to connect to oracle db using simple c++ (oops). Please provide me some sample code as well, this is new for me. Appreciate your help. I asked a similar question before but forgot to mention that I am not using vc++ and p...
You would need the oracle C++ libraries (OCCI) from oracle. You can find them here: http://www.oracle.com/technetwork/database/features/instant-client/index-097480.html Google "Oracle OCCI tutorial" and you should find pretty much everything you need.
5,264,950
5,267,518
openmp randomly uses only one core
I'm on Ubuntu 10.04, gcc version 4.4.3. I'm compiling c++ code with omp.h and a g++ parameter -fopenmp. Most of the time everything works as expected. I have quad-core with hyper-threading, so virtually 8 cores. Randomly, when I run my software (and watch system monitor) all 8 cores woof up to 100%, fans kick in, all t...
From the omp_set_dynamic(n) maual page: n ... A value that indicates if the number of threads available in subsequent parallel region can be adjusted by the runtime. If nonzero, the runtime can adjust the number of threads, if zero, the runtime will not dynamically adjust the number of threads Try to set the number of ...
5,264,969
5,369,395
A Cross-Platform Localization Resource Format
I want to keep my replacement strings (German, French, etc) in a file format that is standard-ish and useable across Windows and Linux platforms. Thus VC++ resource files are ruled out right away. What file format do others prefer to use for keeping these l10n resources? Two more features I'd like the format to suppo...
For a standard format, use gettext and msgfmt to make binary .mo files. The format comes from Unix, but is usable cross platform. Audacity, which is Linux/Mac/Windows, uses it. 1) The key is the English string. 2) The standard format doesn't come with an anti-tamper approach, so you will need to cook up your own. T...
5,265,160
5,265,547
Using getline to extract information and store them in a datatype in c++
Here's a code that I wrote which isn't complete. string line; ifstream fp ("foo.txt"); if (fp.fail()){ printf("Error opening file %s\n", "foo.txt"); return EXIT_FAILURE; } unsigned int lineCounter(1); while(getline(fp, line)){ if(lineCounter == 1){ lineCounter++; } // to skip first line ...
Building on @Martin's answer: std::string line; std::getline(file, line); std::stringstream linestream(line); int a,b,c,d; char sep; // For the comma // This should work even if there are spaces in the file. // The operator >> will drop leading white space // Then read the next type // For int object will read...
5,265,255
5,265,306
C++ not finding class method definition
I'm likely just doing something dumb, but I can't figure it out. I have a class called VariableList thats defined in a .h and a .cc file as follows: (some of the .cc file ommitted) Header: #pragma once #ifndef _VARIABLELIST_H_ #define _VARIABLELIST_H_ #include "Variable.h" #include <algorithm> #include <vec...
Are you adding all your .cc files when compiling? g++ -o myExecuatable file1.cc file2.cc file3.cc ...
5,265,291
5,265,352
Sorting a vector of objects in C++
struct Keyword { std::string keyword; int numUses; }; bool sortingVector(const Keyword& key1, const Keyword& key2) { return key1.numUses < key2.numUses; } sort(topKeywords.begin(), topKeywords.end(), sortingVector); : no matching function for call to 'sort(std::vector<Keyword>::iterator, std::vector<...
Is sortingVector a non-static member of some class? The error message suggests that it is, in which case you will need to wrap it (using boost::bind, for example) into a binary operation that doesn't take a this parameter. You might want to make sortingVector a static member or a free function instead.
5,265,309
5,266,763
Anyone knows some small library for downloading web pages?
I need something that will allow my C++ program to download a HTML source of some page. Can someone recommend me a library to do that? I'd prefer as simple thing as it can be. Thanks in advance.
For Windows use URLDownloadToFile function.
5,265,510
5,265,524
C++ std::list: Erasing / removing elements while iterating
Possible Duplicate: Can you remove elements from a std::list while iterating through it? I have a loop in a function, that iterates over an std::list from begin to end. In each cycle, I perform some checks and maybe do a few manipulations on the current list entry, and in some cases I want to remove it from the list...
Use postfix increment. list.erase(it++); it is increased, so it no longer refers to the erased element, then the previous value of it is given to list.erase. Make sure that you either do list.erase(it++) or ++it in your loop - doing both will skip elements and potentially increment past end of the list.
5,265,516
5,265,950
Writing a server-side language program to render web sites (HTML, etc..)
Similar to technologies like ASP.NET, PHP, JSP and some other web languages which run on the server side are often called within a web pages code. For instance a web server may parse through a file hit I don't have any difficulty writing server / client programs, only I am unsure where to tie in to web servers such t...
To implement your own simple custom language you would need to do the following under Apache and something very similar under IIS. For example for an Apache server to process PHP the following configuration is required. LoadModule php5_module modules/libphp5.so ScriptAlias /php/ "/usr/local/php/bin/" AddType applicatio...
5,265,552
5,265,725
What could cause the ResetEvent API to fail?
I'm writing a VC++ application. Just for the sake of argument, what could cause the ResetEvent API to fail? The Microsoft documentation is not clear on this. Thanks.
Most commonly an invalid handle will cause this to fail. An invalid handle, in turn, could result from: the handle being closed by another process or thread prematurely passing gobbledy-gook to ResetEvent() Passing a handle to a thing that isn't an even Number 1 can often be avoided by creating a duplicate of the ha...
5,265,637
5,306,209
SWIG wrapped vector of vectors (C++ to python) - how to recognise the inner vector as a proxy object?
I'm facing a similar issue to Wrap std::vector of std::vectors, C++ SWIG Python - but it's not just simple C++ parsing. I have the following in my C++ code namespace ns { typedef unsigned long long uint64_t; typedef std::vector<uint64_t> Vector; typedef std::vector<Vector> VectorOfVectors; class MyClas...
I worked on this with a colleague of mine, and we have managed to come up with some solutions. First of all, in the SWIG .i file, it's important to define this preprocessor variable: %{ # define SWIG_PYTHON_EXTRA_NATIVE_CONTAINERS %} And then, to ensure that the references returned from methods such as front(), bac...
5,266,197
5,271,542
String comparison with changed character ordering
How would you compare strings when the characters ( and ) should come after the alphanumeric characters. Do I have to write a function or is there any library function available? Thank you for your answers!
You can use std::lexicographical_compare with a custom predicate. That predicate should take 2 chars, and return false if the first should come before the second.
5,266,228
5,266,253
Is the order of method return types and modifiers in C++ important?
I have come across a situation that conflicts with my current understanding of methods in C++. I am working through Ivor Horton's "Beginning Visual C++ 2010" (Wrox Press). On page 449, Example 8_03, a method is defined as: double Volume() const { return m_Length * m_Width * m_Height; } I had rearranged the modifi...
When const is placed after the name of a member method, that is stating that the this pointer is what is constant. That is to say, the original declaration states that the method CBox::Volume() does not change the CBox object on which it is called. The most likely source of error is that the CBox::Volume() function i...
5,266,260
5,266,599
How is the stack initialized?
When a process requests for memory and an operating system is giving some new pages to the process, the kernel should initialize the pages (with zeros for instance) in order to avoid showing potentially confident data that another process used. The same when a process is starting and receives some memory, for example t...
I am pretty sure that when the OS starts your process, the stack is only zeros. What you observe is another phenomenon, I think. You seem to have compiled your program as C++. C++ does a lot of code (constructors and stuff like that) before your main starts. So what you see are the left over values of your own executio...
5,266,345
5,266,385
Named Constructor Idiom and Templates?
Is there a way to use the Named Constructor Idiom with templates in a "pretty" fashion? For instance: #include <vector> using namespace std; template< typename T > class Foo { public: static Foo Copy(const T& arg) { Foo ret; ret.t_copy = arg; return ret; } static Foo CopyClear(...
Updated answer If I understand your intent correctly, this will do the trick: template< typename T > class Foo { private: friend class FooHelper; size_t sz; }; class FooHelper { public: template< typename T > static Foo<T> Size(const T& arg) { Foo<T> ret; ret.sz = arg.size(); ...
5,266,630
5,266,660
Am i filling this array wrong or outputting it wrong?
I am working on a program that fills an array with data from a text file. When I output the array its contents are not in the order I thought I read them in. I'm thinking the problem is either in one of the for loops that inputs data into the array or outputs the array to the iostream. Can anyone spot my mistake? The d...
You're filling it wrong. for (a = 0; a < 100; a++) for (b = 0; b < 6; b++) The above loop doesn't match up very well with the first lines of your file, where you don't have 6 elements per row. In the first inner loop, you will read 2, 1, 1, 1, 3, 0 into airplane[0]. EDIT: The fix. for (a = 0; a < FC_Row; a++...
5,266,783
5,267,706
Classes, Rvalues and Rvalue References
An lvalue is a value bound to a definitive region of memory whereas an rvalue is an expression value whose existence is temporary and who does not necessarily refer to a definitive region of memory. Whenever an lvalue is used in a position in which an rvalue is expected, the compiler performs an lvalue-to-rvalue conver...
For me: int main(void) { ret_a(A(5)); } Yields: int conversion ctor rvalue copy ctor (i.e. rvalue, not lvalue). This is a bug in your compiler. However it is understandable as the rules for this behavior changed only a few months ago (Nov. 2010). More on this below. When the function completes execution, it...
5,266,806
5,266,842
generating a hash for data larger than memory (without getting arrested)
Good afternoon Overflowers! ;) What I want to do: I'm interested in verifying transferred file integrity. How I approached it: I was considering using a hash code for this but there's one problem. The files can be extremely large so I need to be able to iteratively generate the hash. I can't load the entire file into m...
Most hash algorithms operate on fixed-size blocks of data - you can e.g. look up SHA1 or MD5 reference implementations, they use an "init/loop { update }/finalize" construct allowing you to pass as much or little data as you wish in every update. Looking at e.g. Skein, they use the same concept in their reference imple...
5,268,091
5,268,111
How do I include everything
I've been fighting with my compiler for too long. Problems with circular includes, redefinitions, "missing ';' before *" and so on. This seems like the place to get a good answer. How do I include everything into everything else, and never have to worry about the subtleties of includes ever, ever again? What combinatio...
Forward deceleration in the headers and inclusions in the implementation (.c, .cpp, etc).
5,268,095
5,268,131
How does C/C++ know how long a dynamic allocated array is
This question has been bothering me for a while. If I do int* a = new int[n], for example, I only have an pointer that points to the beginning of array a, but how does C/C++ know about n? I know if I want to pass this array to another function, then I have to pass the length of the array with it, so I guess C/C++ does...
C/C++ doesn't; it's the allocator (the little piece of code that implements malloc(), free(), etc.) that knows how long it is. C/C++ is welcome to wee all over itself, free of the constraints of having to worry about the length. Also, PyString_AsStringAndSize().
5,268,264
5,268,320
structures and pointers
I'm not sure what I'm doing... Let say I have a structure struct Inner{ exampleType a; int b; } struct Outer{ int current; int total; Inner records[MAXNUMBER]; } struct Outer2{ Outer outer; } And I have the following functions: void try3( Outer2& outer, type var, type2 var2 ){ } void try2( O...
From try3, you would need to use ++outer.outer.current since outer is the name of the variable at the point. To answer the actual question though, look at the two functions. try2 takes a pointer to an Outer2, so no copy is made. try2 passes this to try3 which take a reference to an Outer2, so again no copy is made. Th...
5,268,342
5,268,697
Double free errors when using shallow copies of objects... how to fix?
How do I remove double (delete) errors from shallow copied object vs original object. A simple example: class INT { int *p; //dynamic. //define here fancy constructors etc. set(int i){ p=new int; p=i;} ~INT(); } INT::~INT() { if(p) delete p; } void somefunction(INT a) { //done some stuff ,e.g. call...
For all objects with dynamic members, it is usually best to define your own copy and copy-assignment operations for just this reason. Regarding 'big' objects and expensive copying, reference counting is a technique employed by many languages and patterns to circumvent this problem of pointer ownership. Note that all co...
5,268,395
5,268,938
boost::filesystem3::path::codecvt() undefined reference
Trying to use boost filesystem 3, but when I link I get the following undefined reference: ../myfile-g.o: In function `boost::filesystem3::path::codecvt()': ../boost/filesystem/v3/path.hpp:377: undefined reference to `boost::filesystem3::path::wchar_t_codecvt_facet()' I grep'd everywhere in boost and there is no wchar...
Perhaps you are missing a linked library? When I grep for it I get: filesystem/v3/path.hpp:371 return *wchat_t_codecvt_facet(); filesystem/v3/path.hpp:462 static const codecvt_type *& wchar_t_codecvt_facet(); This is with boost 1.44 on macosx. Since the function is defined in the header file it should be part of l...
5,268,507
5,268,528
structs within classes?
I have a class. I have made two seperate files, the header, and the c++ file. I am using it to create a more-or-less Light 'object' for an opengl game I am working on. Here are the files: Light.h #ifndef LIGHT_H #define LIGHT_H class Light { public: Light(float ix, float iy, float iz, float ir, float ig, ...
This should read so: #ifndef LIGHT_H #define LIGHT_H class Light { public: Light(float ix, float iy, float iz, float ir, float ig, float ib , float ia, int itype, int iindex); virtual ~Light(); float x,y,z; int index; int type; struct { float r, ...
5,268,521
5,268,591
about "int const *p" and "const int *p "
#include <iostream> using namespace std; int main(int argc, char* argv[]) { int i1 = 0; int i2 = 10; const int *p = &i1; int const *p2 = &i1; const int const *p3 = &i1; p = &i2; p2 = &i2; p3 = &i2; cout << *p << endl << *p2 <<endl << *p3 <<endl; return 0; } T...
With the help of pointer, you can actually do two things. You can change the data it is pointing to but cannot point to a different memory location. You can point it to a different memory location but cannot change the data it is pointing to. Now, when you say, int const* ptr or int const* ptr, it falls under first...
5,268,801
5,268,844
expected specifier-qualifier-list before std
typedef struct _stResult { std::string x; int y; struct _stResult *next; } strResult; In this structure i am getting the following error expected specifier-qualifier-list before std. What does this error mean?
std::string is not declared. If you #include <string> at the top, the code compiles.
5,268,817
5,268,838
How can I find the intersection of two arrays using Hash functions in C++?
I am new to hash and not sure how to do this in C++. In java, we have functions like ContainsKey, put, get etc for Hash. Is there anything similar in C++? Thanks.
You could start with std::set<>, which is a balanced binary tree. Most recent compilers also provide unordered_set<>, which is a hash table but not part of C++03: it will be part of C++0x. The boost library also has a hash set implementation. For std::set<>, see http://www.cplusplus.com/reference/stl/set/ e.g. std::s...
5,268,868
5,445,458
Exporting *.png sequence from *.fla with C++
I need an animation in my program. My designer draws animation in Flash and provides me with *.fla file. All I need is to grab 30-40 PNGs from this file and store them within my internal storage. Is it possible grab resources from *.fla with C++ ? Probably, some Adobe OLE objects can help? Please, advice. Thanks in adv...
Assuming You are using CS5 The assets used internally in the FLA are already PNG's as you want them to be. Then simply get the FLA saved as a XFL file, and you will be able to grab them from the library folder ( but then why not just get them to mail you the pngs ? ) So if for some reason you can only get access t...
5,268,940
5,268,952
C++ GUI Toolkit with OpenGL Support
I've been looking for a good C/C++ GUI Toolkit for some time now, and have found these to be the general requirements: I need it to be: Good looking cross-platform C++ or C that will compile w/C++, either is fine OpenGL support can be used in commercial applications without royalties (no licensing s...
You may want to reconsider Qt as your answer, and you are a few years behind on the license changes since Nokia acquired them -- that is no longer a concern as it is LGPL these days. And support for OpenGL is just one of many strong points in favor.
5,269,102
5,270,561
Best practices to manage versions with scons?
I would like my Qt/C++ application to know which version it is. It should know that not from some configuration files, but with version number compiled into application binary. A version itself is string like "X.Y.Z", where X is a major version number, Y is a minor version number and Z is a revision under SVN (or a rev...
SCons has Substfile and Textfile builders for generating files. So create a function to calculate the version (using pysvn or by calling svn command) and write it's output to a file using Substfile (takes template from a file) or Textfile (just writes provided content). Than compile and link that file with the rest of ...
5,269,277
5,269,458
glibc detected (memory error) on inserting into std::map
I have the following code: struct VRfile{ char sessionID[10]; char file[20]; int first; }; std::map (int ,struct VRfile *) maps; struct VRfile *vrinfo = (struct VRfile*)malloc (sizeof(struct VRfile*)); strcpy(vrinfo->sessionID, sessionId.c_str()); strcpy(vrinfo->file, filename.c_st...
You're not allocating enough space for your structure—you're only allocating a pointer's worth (4 or 8 bytes, depending on your pointer size), when in fact you should be allocating somewhere on the order of 36 bytes (specifically, sizeof(VRfile). So, you're stomping on the heap by writing random values into it (a so-c...
5,269,436
5,270,115
RegDeleteKey fails with ERROR_ACCESS_DENIED
Windows Mobile: As the final step of unloading a driver, I am trying to delete the registry subkey (HKLM\Drivers\BuiltIn\XYZ) using RegDeleteKey API and it fails returning ERROR_ACCESS_DENIED code. Below are the steps I followed: 1. FindFirstDevice 2. Stored the key and needed values for later use in case I need to re...
The reasons could be Make sure you deleted each of the contained value pairs You maybe trying to delete key that are not permitted to be deleted by anyone. Try changing to another key which you are able to delete for sure, and then test the code again. You might forget to close the handle to this key (HKLM\szSubKey) ...
5,269,646
5,270,159
socket Recv api return unexpected Value
this the client code.server send data continuously.Here I am peeking the 13 (Header Length)byte message getting the size of the data which is encoded in the message itself and creating the buffer size of MESSAGE_HEADER_LENGTH + DATA-LENGTH. after getting total message size I am using second recv to read data from the s...
Your code has a few problems: Do you know that delete[] is a NOP when passed a null pointer? Why in the first check about pRecvBuffer being the null pointer you end up with a return 0 and in the (terrible) catch(...) you don't? Do you know that catching everything with catch(...) is a terrible idea in general and espe...
5,269,745
5,274,297
Problem with QLabel opacity when the underlying QMainwindow has a background image
I'm using Qt 4.6 with a simple apps that only has a QMainwindow with a background image (set via the stylesheet property to an image in a ressource file). If a add a QLabel on the this window and set it's background-color (also via stylesheet), the resulting label is not opaque. The background color of the label is not...
This works for me on Win7 + Qt 4.7.1 setStyleSheet("QMainWindow { background-image: url(:/bg.jpg); } \ QLabel { background-color: rgba(0, 255, 0, 90); } ");
5,269,982
5,270,034
Is there a way to call a .jar file inside C++ code?
I need to execute a jar file from inside of some C++ code. The jar file reads in some data from a text file, and then writes out some information into a different text file. I thought (void)system("filename.jar"); would do it, but it doesn't seem to.
If you want to simply call the jar, you should invoke java with proper command line java -jar "filename.jar" A better way, if you need real integration between c++ and java, is to use the java native interface (jni), but for that you must be able to modify the sources in the jar file.
5,270,083
5,270,207
Forking a new process in C++ and executing a .jar file
I am attempting to write a program that will read the output from a java .jar file and also give it input from time to time. Basically I am hoping to make a program that will execute certain functions when certain output is encountered. The .jar file wasn't created by me, and I don't have the source code, so I have to...
For finding the java executable: if you want to find it in PATH you can use execlp instead of execl. Otherwise you can make it configurable (configuration file or env. variable). For the jar file you can look for it in the current directory or again a configurable location. E.g., for java in PATH and myprog.jar in the ...
5,270,119
5,270,281
Sync video play over network
I have made a media player that plays basically anything that's scheduled to it via a text file. The player can also play the exact same clip on multiple machines(PC's). The problem is the syncing. The same video starts playing on each of the machines, but they are out by about 400ms, which looks crap and if there's so...
You can use the known streaming protocols, such as RTP (or others) to do the job. Reading a file over the network (which is what it seems that you're doing) is prone to network delays, and if the precision required is in milliseconds - you've got real time constraints there.
5,270,191
5,271,101
C++ incrementals builds for continuous integration
We have a fairly large C++ project built in VS2005 that can take up to 40 minutes to compile and build from scratch, and a further 10 minutes for the installers as the software is being built in both 32-bit and 64-bit configurations. I would like to reduce this time to somewhere around 10 minutes at least as I feel it...
Good question. When I was putting together a CI system for a large C++ project for Microsoft Visual Studio 2003/2005/2008 I enounteded problems as well with incremental builds. Especially when using pre-compiled headers it seems to not work under all circumstances to do an incremental build. I would be interested hear ...
5,270,277
5,270,311
character pointers in C++
I have a doubt regarding character pointers in c++. Whenever we create a character pointer in c++: char *p="How are you doing", p should contain the address of memory location which holds the value "how are you doing". However, I am perplexed at a sample code and the output. Why cout<<p gives back the entire string? It...
This is due to Operator overloading. the << operator is overloaded to output the string pointed to by the character pointer. Similarly, with *p, you will get the first character, hence you get the first character as output.
5,270,401
5,270,582
C++ iterators, default initialization and what to use as an uninitialized sentinel
The Context I have a custom template container class put together from a map and vector. The map resolves a string to an ordinal, and the vector resolves an ordinal (only an initial string to ordinal lookup is done, future references are to the vector) to the entry. The entries are modified intrusively to contain a a b...
You basically got the idea right. A map iterator is only invalidated if the element it points to is removed. map.end() doesn't point to an element, and therefore is never invalidated. It is NOT the default value of a map iterator, though. Each map object has its own end(), and they are not comparable. This shouldn't be...
5,270,514
5,270,596
Overloading postfix ++ operator
Is it some kind of enforced rule that the overload ++ function must take an int as argument to distinguish itself from prefix operators? Also, In case of prefix overload ++ function, how does the right hand operand is implicit argument? E.g ++ClassObj //ClassObj is rhs, but usualy lhs is made implicit
On the second issue. Both prefix and postfix ++ are unary operators, they do not have a left-hand-side and right-hand-side operand, but a single operand on which they are applied. That is, in x++ and ++x, x is the operand, not the right hand/left hand, but the operand. Then on why the int that is required in the signat...
5,270,540
5,270,563
Calling derived class functions from within a vector (c++)
I have two classes: class Object { public: Object(); virtual void update(); virtual void draw(); private: protected: int x, y, tick; } and class Unit : public Object { public: Unit(); void update(); private: protected: } I then define the constructors and functions in sepparate .cpp files. Here's th...
Yes, it calls methods of class Object, because you have a vector of class Object objects: vector<Object> objects; // stores instances of class Object The possible solution is to use a vector of pointers: vector<Object*> objects; objects.push_back( new Unit() ); and then call though pointers: for (int i = 0; i < objec...