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
6,454,426
6,454,444
C++ _inline is being ignored in a singleton and showing up in my profiler. How come?
I have a lot of classes in my project accessed by a singleton like so: _inline GUI_BS_Map* GUI_GetBS_Map() { static GUI_BS_Map obj; return &obj; }; As I understand it, this code should be inlined. I have the Visual Studio (2005) options set to inline anything suitable, and my profiler (AQTime) is definitely no...
The compiler is free to ignore inline and _inline. In Visual C++ you can try __forceinline that makes the compiler inline functions unless there're serious reasons not to do so (such reasons are listed in the linked MSDN article).
6,455,144
6,455,227
is < vector > threadsafe for read/write at different locations?
this is a beginner question i guess but i couldn't find the answer to this particular question: i have a standard (c++) vector v of size 10 and type int. is it safe to have a thread alter all the even positions (v.at(0) = x; v.at(2) = y; etc.) and another thread alter all the values for the odd positions (v.at(1) = a;...
vector does not provide any thread-safety guarantees, so technically the answer would be no. In practice, you should be able to get away with it... until the day that someone (possibly you) makes a small change in one corner of the program and all hell breaks loose. I wouldn't feel comfortable doing this in any non-tri...
6,455,220
6,498,338
Using MVP, how to create a view from another view, linked with the same model object
Background We use the Model-View-Presenter design pattern along with the abstract factory pattern and the "signal/slot" pattern in our application, to fullfill 2 main requirements Enhance testability (very lightweight GUI, every action can be simulated in unit tests) Make the "view" totally independant from the rest,...
Ok the technique I found is actually coming from Cocoa, so it's objective-C but you can definitely do the same in C++. The solution is simply to use a PasteBoard (developer.apple.com documentation). In the hope it helps someone ...
6,455,232
6,571,251
how I can use back-reference in boost::regex
I am tring to use back-reference in boost version 1.44 but this don't work for me. this is my code: boost::regex_constants::syntax_option_type flags = boost::regex::extended; std::string regx="(aaa)bb\1"; std::cout << "Expression: \"" << regx << "\"\n"; std::string str ="aaabbaaa"; boost::regex e(regx,flags); if...
I fix this problem by chaning this row boost::regex_constants::syntax_option_type flags = boost::regex::extended; to boost::regex_constants::syntax_option_type flags = boost::regex::bk_vbar; and ofcourse use \\ and this work for me. thanks
6,455,541
6,455,647
Does binary search have logarithmic performance of deque C++ data structure?
The standard says that std::binary_search(...) and the two related functions std::lower_bound(...) and std::upper_bound(...) are O(log n) if the data structure has random access. So, given that, I presume that these algorithms have O(log n) performance on std::deque (assuming its contents are kept sorted by the user). ...
Yes it still holds for deque because the container is required to provide access to any element in constant time (just a slightly higher constant than vector). That doesn't relieve you of the obligation for the deque to be sorted though.
6,455,715
6,456,132
How to find characters that cannot be part of a word in a Unicode string?
I have some text in a string, I need to check whether that particular string contains any characters which are not allowed to make a word. Suppose I have text like "(hello}" Here it contains to symbols '(' and '}'. How could I do it in C++. And a string may contains any unicode character.
If the string really contains Unicode (UTF-8), the problem is decidedly non-trivial; you'll probably want to use some external library, like ICU. Or you can convert to wchar_t (wstring), and use the single byte encoding solution below: If the characters are single byte encoded, std::find_if with a suitable predicate s...
6,455,783
6,455,851
How to properly return a large vector
vector<Foo*>& getVectorOfFoo(); I want to provide a list of my Foo objects to others. Is this the best way to do it? I am returning a reference here and not copying correct? The caller could (accidentally) modify this list right? Is there a way to avoid this possibility? Could I return const vector ? But ...
First don't return a list of pointers. That makes it doubly unclear about the allowed actions. Boost has a solution (as usual). Return a pointer container. This exposes the pointers as normal members. boost::ptr_vector<Foo> const& getVectorOfFoo(); Now the user can not alter the returned vector. Example: #include <bo...
6,455,904
6,455,989
Return vector from function
I have two classes, the first that contains a vector and a get-method like this: std::vector<mytype> const& MyClassA::getvector(std::vector<mytype>::iterator &it) { it = this->myiterator; return this->myvector; } std::vector<mytype> myvector; std::vector<mytype>::iterator myiterator; and I have another class...
You have made a copy of the vector in the calling code, and the iterator isn't valid because it's still pointing to the original vector. You probably intended something like this: const std::vector<mytype> & vector = MyClassA->getvector(it);
6,456,229
6,456,327
Process interaction(c# and pure c++)
I've got c# dispatcher and fast c++ program for data processing.I need pass data(initializtion) to c++ program from c# dispatcher. Passing data is primitive type: config strings, decimals. I don't want use file or command line arguments for interaction. I think it should be smarter way. Now interaction is one-way, but ...
you could make use of C++/CLI DLL as the middle layer.
6,456,253
6,456,428
Why is "reference to array" defined in such confusing way in C++?
The following code is based on a snippet from here. I want a templated function that accepts a reference to an array of size that is deduced when the function is instantiated: template<int size> void myFunction( SomeType(&param)[size] ) { //use param and size here } //called like this: SomeType array[SomeConstant]...
The problem with your second declaration becomes what value should be used as the identifier? Should it be param, or should it be SomeType? Because of the parenthesis, the first part of the declaration would be parsed first, but if that's the case, and SomeType was not the identifier, then at what point in the parsin...
6,456,271
6,457,910
Is it possible to filter out the data examined by STL multiset lower_bound using a comparator function?
We are using a std::multiset ranges_type member variable to store our Range data. When we call std::multiset<Range>::const_iterator iter = ranges_type.lower_bound(Range(n)); if (iter == ranges_type.end() || iter->low() > n){ found = false; } else{ curr = *(iter); } There are multiple candidate Range ele...
From std::lower_bound's documentation, the comparison function you pass as the third argument is a: Comparison function object that, taking two values of the same type than those contained in the range, returns true if the first argument goes before the second argument in the specific strict weak ordering it...
6,456,359
6,456,408
What is the lifetime of the result of std::string::c_str()?
In one of my programs, I have to interface with some legacy code that works with const char*. Lets say I have a structure which looks like: struct Foo { const char* server; const char* name; }; My higher-level application only deals with std::string, so I thought of using std::string::c_str() to get back const cha...
The c_str() result becomes invalid if the std::string is destroyed or if a non-const member function of the string is called. So, usually you will want to make a copy of it if you need to keep it around. In the case of your example, it appears that the results of c_str() are used safely, because the strings are not mo...
6,456,389
6,456,483
Using an object method as a function callback
I am using a C library which has callback functions such as: int DownloadStream(LPCTSTR host,DWORD channelNumber,NewImage pNewImage); typedef int (*NewImage)(BYTE *pData, int nLen,void *returnHandle); In C i can make call like this: int CallDownloadStream(LPCTSTR host,DWORD channelNumber) { int hr = DownloadStr...
Cannot be done. If the C function does not provide for a user-supplied argument pointer, which is idiomatic in C, then you cannot do this. Edit: This isn't strictly true. You can use a static variable, you can use thread-local storage, or you can JIT a function. However, those are not general-case solutions.
6,456,577
6,456,894
Nonconstant parameter for a template class
I have a template class from an API that is instantiated with something like this. BitField< length > object; The problem is that length variable is only known at runtime. error: 'length' cannot appear in a constant-expression -> this is the error message Any suggestions ?
Templates are strictly a compile-time concept. After compilation, they're baked in and cannot be changed. You cannot use information only known at runtime as a template parameter. One way around this is if you known an upper-bound for the size of your bitset, and use that constant for your templated bitset structure....
6,456,636
6,456,886
Disambiguator template keyword for a template member of a template: when exactly?
A question regarding template disambiguator was given here: template disambiguator and in the answer we can read: ISO C++03 14.2/4 When the name of a member template specialization appears after . or -> in a postfix-expression, or after nested-name-specifier in a qualified-id, and the postfix-expression or qualified-i...
They implement the C++0x specification, where Base is the current instantiation. And C++0x allows to omit template keyword in such a case. Since BaseType is a typedef for Base, when you say BaseType, that names the current instantiation too. To quote the spec, since you seem to be interested in spec refs A name is a ...
6,456,833
6,457,251
C++ DX11 application only runs in Visual Studio IDE
Alright, I presented this question on the MSDN forums but have yet to receive any kind of response so I figured I'd give StackOverflow a try. I'm currently developing a DirectX application using VS2008 on Win7. I recently experienced a nasty memory corruption bug with a memory allocation class that grabbed byte aligned...
Shoot, sorry I meant to post this as a comment... I can only suggest more diagnostic attempts. One would be to profile the app from within Depends, this will also show dynamic DLL loads and might show something new. Also it captures the debug output. It may behave differently than launching in the debugger itself and...
6,456,870
6,456,967
STL remove doesn't work as expected?
int main() { const int SIZE = 10; int a[SIZE] = {10, 2, 35, 5, 10, 26, 67, 2, 5, 10}; std::ostream_iterator< int > output(cout, " "); std::vector< int > v(a, a + SIZE); std::vector< int >::iterator newLastElement; cout << "contents of the vector: "; std::copy(v....
Actually std::remove doesn't remove the item from the container. Quoted from here Remove removes from the range [first, last) all elements that are equal to value. That is, remove returns an iterator new_last such that the range [first, new_last) contains no elements equal to value. The iterators in the range [new_las...
6,457,130
6,457,306
Pre & post increment operator behavior in C, C++, Java, & C#
DISCLAIMER: This is not a real-world example. It is just a theoretical question of how these languages work. What exactly are the differences between C/C++, C#, and Java when it comes to post & pre increment operators? This is what I get with VC++10, Java 1.6, and C# 4 int a = 2; int b = a++ + a++; int c = ++a + ...
Java and C# evaluate expressions from left to right, and the side-effects are visible immediately. In C++, the order of evaluation of subexpressions is unspecified, and modifying the same object twice without an intervening sequence point is undefined behavior.
6,457,207
6,718,927
programming ftp: how to abort file transfer?
i am doing small ftp client for recieving some big files from ftp. I have read in RFC that ABOR command is very problematic for servers. Almost all servers i see just continue to send data even after ABOR sent through control connection. Closing the data transfer can result (in 70% of tests) in closing control connecti...
The "ABOR\r\n" command should be sent as out-of-band data. In case of send() - send(control_socket, "ABOR\r\n", 6, MSG_OOB); Some time after you recv() code 426 Transfer aborted. Data connection closed. The following link is more helpful if you can't achieve success aborint transfer: http://www.developer.nokia.com/Co...
6,457,273
6,532,142
Adobe Eve ASL: how to render eve file into gui window?
So We have simple .eve and .adam files, compiled ASL, and all includes required for boost and adobe. We need a crossplatform function to make our layout rendered, and movable as real window on our platform (we need it for Mac OS X, Windows, Linux). How to do such thing? We have started trying to move in direction of si...
We have done it here!) it is really simple. Source: #include <boost/thread/tss.hpp> #include <adobe/future/modal_dialog_interface.hpp> #include <boost/filesystem/path.hpp> using namespace std; inline bool always_break(adobe::name_t, const adobe::any_regular_t&) { return true; } void dialog() { stringstream ...
6,457,418
6,457,480
How do you make python recognize read a precompiled shared file?
I have a package I've created in C++ and, have already compiled it into a shared library. When I link against it with my own main function, I can initialize the package by calling the initialization function directly, initfoo, and everything works fine. How do I get python to recognize my shared library as a package, s...
If you have a shared library with initfoo symbol exported (note: since you've tagged the question c++ — make sure it's an extern "C" symbol, otherwise name mangling will prevent the interpreter from finding it), then it's already a Python module, and can be loaded directly, with no further work. You only need to make s...
6,457,497
6,457,525
What is the data type of vptr?
Any class having a virtual function would get an extra hidden pointer which would point to the most derived class. What is the type of this vptr?
It has no type. It's an implementation detail unspecified by the standard; it is not part of the language. Note that C++ doesn't say that there has to be a virtual table or a virtual "pointer" at all (though this is the most common implementation of RTTI in C++ toolchains). Also, your analysis is wrong. In, say, GCC, u...
6,457,551
6,457,661
Hex character to int in C++
How can I change a hex character, not string, into a numerical value? While typing this question, I found many answers on how to convert hex strings to values. However, none work for chars. I remember reading somewhere that this works for strings: std::string mystr = "12345"; unsigned int myval; std::stringstream(myst...
You already have a solution that works with strings. Use it for chars too: #include <string> #include <sstream> #include <iostream> #include <iomanip> using namespace std; int main() { char val = 'A'; unsigned int myval; std::stringstream ss; ss << val; ss >> std::hex >> myval; cout << myval << endl; } C...
6,457,591
6,457,609
Problem with ostream/ofstream inheritance
I'm writing a C++ program and I need some help understanding an error. By default, my program prints to the terminal (STDOUT). However, if the user provides a filename, the program will print to that file. If I'm writing to the terminal, I will use the std::cout object, whereas if I'm writing to a file I'll create and ...
Streams are not copyable, so you cannot pass them to a function by value. Use a reference instead. void print_something(std::ostream& outstream);
6,457,646
6,458,388
Member method consting in Java?
In C++, a member method can be const if it does not modify the class. For example: class Foo { public: float getValue() const; }; Is there something similar I must do in Java classes? How exactly does consting work in Java? (Aside from adding the final keyword before a member variable declaration and initializing it...
Although Java lacks a const qualifier, you can achieve some of the same ends with read-only interfaces and immutable types. So, instead of qualifying a reference as const, you could specify its type to be a read-only interface type. For example, given these two interfaces: public interface A { int getValue(...
6,457,682
6,945,542
How to programatically get uid from pid in osx using c++?
Given a pid, I want to find the owner of the process (as uid). Is there a way to get this in osx (or any unix) using C++? Google didn't help. 'ps' is able to do it; so I assume there should be a way to get it programatically.
Finally found a way to programatically do this without parsing the output of 'ps' uint getUidUsingSysctl(uint pid) { struct kinfo_proc *sProcesses = NULL, *sNewProcesses; int aiNames[4]; size_t iNamesLength; int i, iRetCode, iNumProcs; size_t iSize; iSize = 0; aiNames[0] = CTL_KERN; ...
6,457,744
6,457,883
Confusing C++ compiler error, "cannot convert 'X' to 'double' in return
I am relatively new to C++ programming and building a small program in Dev C++ which is producing the following compiler output: Compiler: Default compiler Building Makefile: "C:\Documents and Settings\s0237326\My Documents\Postgrad_Research_Sync_Folder\C_Projects\mfemm2\Makefile.win" Executing make... make.exe -f "C:...
The problem is that you are getting the wrong sqrt function. You appear to have included the <complex> header but not the <cmath> header. The double parameter is being promoted to a complex parameter because the version of sqrt that takes a double is not known to the compiler at that point.
6,457,810
6,458,182
Guidance for when to explicitly enable/disable copying in C++ classes?
A colleague is cleaning up a couple of libraries. In doing so he's been reading API design for C++ and it talks about explicitly enabling or disabling copying in C++ classes. This is the same thing that Sutter and Alexandrescu say in their C++ Coding Standards. He agrees that one should follow this advice, but what nei...
It depends on the role the classes play in the application. Unless the class represents a value, where identity isn't significant, you should ban copy and assignment. Similarly if the class is polymorphic. As a generally rule, if you're allocating objects of the class type dynamically, it shouldn't be copiable. And...
6,457,830
6,457,878
Truly compile-time string hashing in C++
Basically I need a truly compile-time string hashing in C++. I don't care about technique specifics, can be templates, macros, anything. All other hashing techniques I've seen so far can only generate hashtable (like 256 CRC32 hashes) in compile time, not a real hash. In other words, I need to have this printf("%d", SO...
The trouble is that in C++03 the result of subscripting a string literal (i.e. access a single character) is not a compile-time constant suitable for use as a template parameter. It is therefore not possible to do this. I would recommend you to write a script to compute the hashes and insert them directly into the sour...
6,457,856
6,458,616
What's the difference between gtest.lib and gtest_main.lib?
Google's C++ Test Framework has two output libraries: one is gtest.lib and the other one is gtest_main.lib. According to Nik Reiman's answer on how to setup gtest with Visual Studio, we should link to gtest_main.lib but I'm linking to gtest.lib and the sample test cases that I have are running fine. What's the differen...
the only reasonable difference is that gtest_main.lib provides a default implementation of a test application entry point (i.e. main function): Citation from Getting started with Google C++ Testing Framework: "[...] maybe you think that writing all those main() functions is too much work? We agree with you compl...
6,457,935
6,459,087
Confusion about returning the address of an object
I have the following code (some code removed to strip it to the essentials; the couple methods/attributes used should be self explanatory): void testApp::togglePalette(){ GraphicalEntity* palette= this->getEntityByName("palette-picker"); cerr << palette << endl; } GraphicalEntity* testApp::getEntityByName(stri...
Following on my comment, here's a more complete answer. There is a path in your testApp::getEntityByName() method where control exits the method without returning a value. Depending on your compiler, architecture and calling convention, this could result in machine code that doesn't work even if your flow never goes th...
6,458,318
6,458,383
How to generate graphs from .heap files created by google HEAPPROFILER
Like the question says I created some .heap files using awesome google perftools and now I cant view them(ofc i can open them in the vim, but I want graphical representation )... I tried using the (like in the documentation) pprof --gv name-of-my-program /my_heap_file.0100.heap but I get pprof: invalid option -- '-...
The pprof is provided by installing tau. Use the absolute path to (perftools)pprof to use it, something like /usr/local/bin/pprof
6,458,612
6,458,689
Proper way to receive a lambda as parameter by reference
What is the right way to define a function that receives a int->int lambda parameter by reference? void f(std::function< int(int) >& lambda); or void f(auto& lambda); I'm not sure the last form is even legal syntax. Are there other ways to define a lambda parameter?
You cannot have an auto parameter. You basically have two options: Option #1: Use std::function as you have shown. Option #2: Use a template parameter: template<typename F> void f(F && lambda) { /* ... */} Option #2 may, in some cases, be more efficient, as it can avoid a potential heap allocation for the embedded lam...
6,458,719
6,458,818
QT display image obtained from network access manager
I am trying to display the image obtained from the get request made using networkaccess manager. I am able to compile and even able to run it. but I am unable to show the image in a Qlabel. QNetworkAccessManager* nam; void MainWindow::on_pushButton_clicked() { nam = new QNetworkAccessManager(this); QUrl url("h...
The data in QNetworkReply is not ready immediately after the call to QNetworkAccessManager::get(). The call is asynchronous, and you need to connect to either the finished() signal of QNetworkAccessManager, or readyRead() signal of QNetworkReply before you attempt to retrieve any data.
6,458,827
6,458,865
Why methods can not return multiple values
Just curious is there any technical limitation in having multiple return values for methods in languages like java, c, c++ or limitation is just by spec? In assembly language I understand callee can pop one value to register.
Because in the days of C there is/was a single register used to hold the return value. Because if you need more values, you can just return a struct, reference (in Java/C#), or pointer. Because you can use an out parameter. Allowing multiple return values would add complexity, and it's simply worked around. There's n...
6,458,889
6,458,989
Easy way to run command line programs C++ - Windows 7
I am trying to find an easier way to test my command line application. It has arguments so I run it from a command prompt. My process is this: Build Go to the output Open command prompt Change directory Run it There has to be an easier way not only to debug but to open a command prompt in the current folder. Thank y...
If you go to the project properties, Debugging settings, you can set the working directory and parameters. If you use the same parameters all of the time, you can enter those in on that screen as well. Then just F5 or Ctrl+F5 to run. Set a breakpoint at the end of the code to keep it from going away after it is done.
6,459,040
6,459,168
C/C++ Library for Extracting Icons from Binaries
I'm planning on building a hotkey-activated application launcher for Windows. I intend for it to be a pop-up grid of icons in which you can then click and launch what you need. I'd like for it to automatically scan the Start Menu and Desktop for program shortcuts and catalog them. However, I'm not sure of how to go abo...
I think you want to use ExtractAssociatedIcon See http://msdn.microsoft.com/en-us/library/ms648067%28v=VS.85%29.aspx
6,459,273
6,459,282
Overloading operator< for priority queue
I am trying to make a priority queue of a class I made like this - std::priority_queue<Position> nodes; I overloaded the < operator in Position like this - bool Position::operator<(Position& right) { return (fvalue < right.getFValue()); } However, whenever I try to compile I get this error message saying the < ...
Relational operators shouldn't change the operands. Try: bool Position::operator<(const Position& right) const { My guess is that either __x or __y (or both) are const. You can't call a non-const member function on __x if it's const, also you can't pass __y as the right parameter if __y is const and right is not.
6,459,619
6,459,723
Mac (or c++) connection to binary WCF
I've got a WCF service being hosted using TCP/IP (netTcpBinding): var baseWcfAddress = getWcfBaseUri(); host = new ServiceHost(wcfSingleton, baseWcfAddress); var throttlingBehavior = new System.ServiceModel.Description.ServiceThrottlingBehavior(); throttlingBehavior.MaxConcurrentCalls = Int32.MaxValue; throttlingBehav...
Every binding starting with net is considered as not interoperable. Even pure .NET client without WCF is not able to communicate with the service without enormous effort by reimplementing whole binary protocol and encoding. You should probably start with: .NET Message Framing protocol .NET Binary Format: XML Data Stru...
6,459,887
6,460,115
Windows service terminates unexpectedly in windows 7
I have written a windows service that catches a UDP message, creates a process as user, sends the message to the process via named pipes, and repeats. Service works great in XP but terminates unexpectedly in windows 7 after one iteration. Event Viewer shows that after I pass my message to the service there is an applic...
My guess would be tighter security in Win7 is getting you. There's missing code here, what's in pSecAttrib for example? Beef up your error handling so (for example) you don't execute the rest of the loop body if pipe creation fails, and you know exactly which API failed and why. CreateProcessAsUser - what user are...
6,460,043
6,460,103
C++ typedefs (from MATLAB)
I'm looking through some c++ code that MATLAB generated and I came across this: typedef char char_T typedef char_T byte_T What exactly is this code doing and what is its purpose?
What I think you're asking is for the reason why MATLAB's code generator is spitting out these seemingly superfluous typedefs. The probable reason being that MATLAB wants a type that represents bytes for its code, but it's unsure of what that type is on your specific system and architecture. It then probably has a syst...
6,460,054
6,460,112
Can I export a C++ interface with C-Style methods to a C# dll
I'm trying to avoid COM. I'm designing a mixture C# and C++ controls on a C++ exe. One method I came up with is PInvoking my C++ exe from C#, and sending windows messages to the C# windows. However the amount of methods I call on the controls base class is too long to justify windows messages. So, if it's possible to e...
I use C++/CLI with VS 2010 to do this. You can expose a DLL C interface that can be consumed in the usual way, the implementation would just marshal data from that interface to your C# assembly. Related question I think Calling C# from C++, Reverse P/Invoke, Mixed Mode DLLs and C++/CLI
6,460,094
6,487,769
stack traces stop at the leaf register (lr)
Often I see ARM stack traces (read: Android NDK stack traces) that terminate with an lr pointer, like so: #00 pc 001c6c20 /data/data/com.audia.dev.qt/lib/libQtGui.so #01 lr 80a356cc /data/data/com.audia.dev.rta/lib/librta.so I know that lr stands for link register on ARM and other architectures, and th...
Stumbled on the answer finally. I just had to be more observant. Look at the following short stack trace and the information that comes after it: #00 pc 000099d6 /system/lib/libandroid.so #01 lr 80b6c17c /data/data/com.audia.dev.rta/lib/librta.so code around pc: a9d899b4 bf00bd0e 2102b507 aa016d4...
6,460,148
6,460,286
c++ detect if the client closed the connection (multi sockets)
In my program I have several sockets on the server. Each socket has its own port. I tried to detect if the client closed the connection with: signal(SIGPIPE, sig_pipe); But I have the problem that I don't know on which socket the connection was closed. Is there some method to get it to know? More about code: In main p...
You should setup SIGPIPE to be ignored (see sigaction(2)) and handle EPIPE error code from write(2) and the likes. Note, that reading zero bytes from TCP socket is the real indication of the other side closing the connection.
6,460,169
6,570,217
Getting a runtime error "procedure entry not found in vssapi.dll" when trying to run Volume Shadow Copy
The code compiles fine and I have included the vssapi.lib in the additional dependencies for the linker. I get this error saying "CreatevssbackupcomponentsInternal procedure entry point could not be found in vssapi.dll" And I get this error only when I try to run it on Windows server 2003 or Windows XP. It runs fine o...
You have to use the Windows Shadow Copy SDK for Windows versions prior to Windows Vista: http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=23490
6,460,322
6,460,395
Writing 16 bits from matrix to a text file, reading them back in differently in C++
I have a matrix of unsigned 16's which I am writing out to a text file using void output() { ofstream myfile; myfile.open("output.raw", ios::out | ios::binary); for(int i=0; i< 100; i++) { for(int j=0; j < 100; j++) { myfile.write((char*)&r2[i][j], sizeof(uint16_t)); } } } As this is a ".raw" image fi...
You cannot write floating point data bitwise and read it back as int. You have to convert the float to an integer data type before you write it. Floating point numbers have a totally different binary representation as integer: IEEE_754 for(int i=0; i< 100; i++) { for(int j=0; j < 100; j++) { uint16_t val = ...
6,460,342
6,460,468
C++ Generated Code (from MATLAB)
So I generated some code from MATLAB, but I don't know how to use it. What I mean is if I wanted this to generate 15 (num2Gen) random numbers and perform the sum/avg calculation, how should I declare *a and *avg and then call the fxn? void randAvg(uint16_T num2Gen, emxArray_uint16_T *a, uint16_T *avg) { int...
I don't know MATLAB, but to answer your question on how to pass in a reference to a function: emxArray_uint16_T a = <put something here> uint16_T avg = <put something here> ... randAvg(num2Gen, &a, &avg);
6,460,542
6,460,585
Performance of pthread_mutex_lock/unlock
I've noticed that I take a pretty big performance hit when I have an algorithm that locks and unlocks a thread ALOT. Is there any way to help this overhead? Would using a semaphore be more/less efficient? Thanks typedef struct _treenode{ struct _treenode *leftNode; struct _treenode *rightNode; int32_t data; ...
Instead of worrying about the blades of grass, step back and observe the whole forest. Any algorithm which depends on two threads potentially closely stepping on each each other's toes is inherently inefficient. Try to find a way to drastically reduce the need for interaction. For example, if one thread produces data ...
6,460,729
6,460,812
Platform independent way of dumping vars onto screen
Is there any platform independent way of dumping the variables created by your program onto a screen? say i write the program #include <iostream> void f(){ std::string interal_data = "hello world"; } int main(){ f(); } is there any way to get internal_data out without adding a std::cout/std::stream to f()? i...
Ehm... "without adding a std::cout/std::stream" is nonsense, if you want to output something, just do it. Debuggers work with magic, namely inspect your process and stuff, and have debugging symbols for your process which you do not have. Edit: Of course, this may only be true for C++, as Python is a somewhat interpret...
6,460,833
6,460,896
Function pointer and Template
Why does the following code work? class foo { public: template <typename F> int Map(F function) const { return function(2); } }; int Double(int n) { return 2*n; } int main(){ foo f; int n = f.Map(Double); } My understanding is that the function accepting the function pointer must h...
Template are a compile-time concept, so of course it will be resolved during compile time (if what you mean is the template parameter substitution). Try passing something which you can't call like function(2), e.g., some int. This will yield a compile-time error. After substitution, your function will look like int Map...
6,460,907
6,462,058
Program structure for bi-directional TCP communication using Boost::Asio
First off, I hope my question makes sense and is even possible! From what I've read about TCP sockets and Boost::ASIO, I think it should be. What I'm trying to do is to set up two machines and have a working bi-directional read/write link over TCP between them. Either party should be able to send some data to be used ...
My concern is how to avoid situations in which both enter into some synchronous write() operation at the same time. They both have data to send, and then sit there waiting to send it on both sides. Does that problem just imply that I should only do asynchronous write() and read()? In that case, will th...
6,460,932
6,462,329
Change entire console background color (Win32 C++)
How can I change the entire console's background color? I've tried SetConsoleTextAttribute and it only changes the background color of new text. I effectively want the entire console to turn red when a serious error arises. Thanks to everyone who attempts to help.
Try something like: system("color c2");
6,461,007
6,461,066
C++ What version of directx?
Possible Duplicate: DirectX 9 or DirectX 10 for starters ?? I'm started to get into a little game programming and I have some learning materials for C++/Directx 9 and 10, and im wondering which I should learn first/use. I read somewhere windows XP doesn't have directx 10, so if i wanted to support XP, id have to use...
DirectX 10 is not supported on Windows XP so in order to run on such systems a DirectX 9 or earlier engine is required. However unless you are developing on a Windows XP system you should not worry about this and use the easier version. IMO DirectX 10 is the better platform to work with, so you should use that to learn...
6,461,072
6,461,372
read from file to array C++
i wanna read from file to array of unsigned char in RAD studio 2010, i have an example,but i need to read to array size of file. Sorry my english void __fastcall TForm1::ChooseFileClick(TObject *Sender) { TOpenDialog *od = new TOpenDialog(this); if (od->Execute()) { TFileStream *fs = new TFileStream(od->File...
While I'm not sure of your exact intent, I can tell you this: don't use a raw array! In C++, we have the vector type. A vector is very similar to an array, but you can keep adding elements to it. If it gets full, it makes itself bigger. (In actual fact, a vector is simply a wrapper for an array. When it is filled up, i...
6,461,200
6,461,220
If statement not seeming to check other && in statement
I have an if statement that looks as follows: int count=0; string Check; if ((count==4 && Check!="-s")||(count==4 && Check!="-S")) If count equals 4 and Check equals "-s" or "-S" it still enters this if statement because of the count == 4. It totally seems to ignore the second part. Is there something I'm doing wrong...
Well, if Check is "-S", then it will not even check the second pair of conditions, because you check with ||. The same holds true for the opposite case. If one is false, the other is true. Replace that with a &&. int count = 4; string Check = "-S"; if( (count == 4 && // count is 4, alright. Check != "-s") || // C...
6,461,236
6,461,384
Memory management in a lock free queue
We've been looking to use a lock-free queue in our code to reduce lock contention between a single producer and consumer in our current implementation. There are plenty of queue implementations out there, but I haven't been too clear on how to best manage memory management of nodes. For example, the producer looks like...
Only producer shall be able to create objects and destroy them when they aren't needed anymore. Consumer is only able to use objects and mark them as used. That's the point. You don't need to share memory in this case. This is the only way I know of efficient lock free queue implementation. Read this great article that...
6,461,309
6,461,338
How std:: tr1:: function gets the parameters of the signature features and specializes the class*
I wish to know how std::function determines the argument and parameters from the function type that you pass in.
It's a partial template specialization. template<typename T> class function; template<typename Ret> class function<Ret()> { ... }; template<typename Ret, typename Arg1> class function<Ret(Arg1)> { ... }; As you can see, this will get old quickly, but variadic templates will handle it in C++0x.
6,461,784
6,461,805
Understanding virtual base classes and constructor calls
I'm a bit confused about how virtual base classes work. In particular, I was wondering how the constructor of the base class gets called. I wrote an example to understand it: #include <cstdio> #include <string> using std::string; struct A{ string s; A() {} A(string t): s(t) {} }; struct B: virtual publi...
There is always just one constructor call, and always of the actual, concrete class that you instantiate. It is your responsibility to endow each derived class with a constructor which calls the base classes' constructors if and as necessary, as you did in B's constructor. Update: Sorry for missing your main point! Tha...
6,461,904
6,461,939
Exctracting Parameter Types from Mangled C++ Name
I'm trying to figure out the type of the parameters passed to a function. I want to do this using the mangled name of the function. For example the following function has the parameters _ZN7MyClass3funEP14AnAwesomeClass MyClass* this, AnAwesomeClass* p1 I now want to generate a function call to the toString member fun...
a few ways: c++filt nm -C objdump -t -C
6,462,014
6,465,660
Is this the best way to utilise tail call recursion traversing a linked list?
Basically I am creating a base class that will be used for classes stored as a linked list, which are traversed and deleted as dictated by a virtual update() function which returns a bool. I am wondering if this is the most efficient case (I like the fact that it can be a singley linked list in particular): class Trave...
You're deliberately obfuscating the code in order to "tempt" the compiler into creating a specific result; whether this happens or not is quite probably more dependent on the compiler used, the optimization flags in effect, or even the code compiled that's using the above. The following is more compact code: void Trave...
6,462,093
6,462,317
Reinitialize timeval struct
How can I reinitialize a timeval struct from time.h? I recognize that I can reset both of the members of the struct to zero, but is there some other method I am overlooking?
The completely correct and portable (albeit C99) way to zero-initialize arbitrary (possibly aggregate) types: myTime = (struct timeval){0}; This works even for structures that contain pointers and floating point members, even if the implementation does not use all-zero-bits as the representations for null pointers and...
6,462,141
6,462,199
Difference between interlocked variable access AND critical sections interlocked increment
can someone help explain the different between interlocked variable access AND critical sections interlocked increment in c++? thanks, much appreciated, in advance.
Basically, all those InterlockedXXX functions are more or less intrinsics that map to relatively few (typically one) assembly instructions. Such an operation cannot be interrupted and is thus said to be atomic (the atomicity is achieved at CPU level, at least if this is possible on the target platform). A CRITICAL_SEC...
6,462,251
6,462,294
C++ FILE to fstream?
I'm not an expert on this but I have this code: FILE *OUTPUT_FILE; OUTPUT_FILE = fopen(file, "a+"); fprintf(OUTPUT_FILE, "%s", &keys ); fclose(OUTPUT_FILE); And I would like to pass it to a fstream syntax like ofstream fs; ???? They are included on this function: int Store(int keys, char *file) I know this is a ...
First of all, ALL_CAPS should generally be reserved for macros -- using it for a normal variable holding a FILE * is generally a poor idea. As far as the rest goes, it would look something like this: std::fstream output_file(file, std::fstream::in | std::fstream::out | std::fstream::app); output_file << keys; That cou...
6,462,382
6,462,431
Is there a way to flag the use of non-reentrant C library calls?
I'm working on a project that's heavily multi-threaded, and was wondering if there's a way to have the compiler flag the use of non-reentrant calls to the C library (e.g. strtok intsead of strtok_r)? If not, is there a list of calls that are non-reentrant so I can grep through my code base periodically? A related ques...
For source, you could possibly insist that every source file contains the line: #include <beware.h> after the C headers, and then the beware.h header file contains: #define strtok unsafe_function_call_detected_strtok #define getenv unsafe_function_call_detected_getenv or some other suitable set of names that are ...
6,462,439
6,462,474
What's the difference between long long and long
What's the difference between long long and long? And they both don't work with 12 digit numbers (600851475143), am I forgetting something? #include <iostream> using namespace std; int main(){ long long a = 600851475143; }
Going by the standard, all that's guaranteed is: int must be at least 16 bits long must be at least 32 bits long long must be at least 64 bits On major 32-bit platforms: int is 32 bits long is 32 bits as well long long is 64 bits On major 64-bit platforms: int is 32 bits long is either 32 or 64 bits long long is 6...
6,462,509
6,462,560
How to make boost::serialization deserialization faster?
I use boost::serialization to save an object that contains this data : struct Container { struct SmallObject { struct CustomData { unsigned first; float second; }; std::vector<CustomData> customData; // <- i can have 1 to 4 of these in the std::vector ...
If I had to pick the single biggest drawback of Boost.Serialization, it would be poor performance. If 400ms is truly too slow, either get faster hardware or switch to a different serialization library. That said, just in case you're doing something blatantly "wrong", you should post the serialization code for Container...
6,462,623
6,462,655
C++ list/vector help
I'm new to C++ so this is probably a very simple question, but I haven't been able to find any examples online that have helped. I've defined my own Bubble class and I need to create a vector/list (I'm used to C# and Java, so I'm not sure which is correct) to dynamically store Bubble objects in. Here's my code so far: ...
The functions vector.add() and list.add() do not exist. #include "Bubble.h" #include <vector> #include <list> int backgroundImages[10]; std::list<Bubble> bubbles(); // use the std namespace and instantiate it std::vector<Bubble> bubbles_two(); // same here Bubble b; void AppMain() { loadImages(); ViewAdd(bac...
6,462,790
6,474,447
How to convert HBITMAP to BYTE array for JNI
first of all sorry by my bad english, Hello i am new in this kind of forum, the question i have is a headache, well i still looking for everywere in this page and other, i can't no find the solution, first i need to create a screen capture and save it in a jpeg byte array, my code is simple and create the HBITMAP but t...
Are you looking for GetDIBits? Convert a dependent bitmap into a DIB and then stream it into an array or file or whatever you want. There are several image libraries that can help give ideas as well. CxImage, FreeImage, all have functions to convert HBITMAP (both DDB and DIB) into a stream-o-bytes.
6,462,849
6,462,958
Retrieving image data from memory
I'm using the FreeImage Library to handle loading images and passing them to OpenGL. Currently, I have support for reading an image from a file. However, I'd like to extend this to being able to read from a variable for the purpose of game content packages. Basically, in short, I have the entire file, header and all...
It sounds like you want to use FreeImage_ConvertToRawBits. Here is an example from the documentation: // this code assumes there is a bitmap loaded and // present in a variable called ‘dib’ // convert a bitmap to a 32-bit raw buffer (top-left pixel first) // ------------------------------------------------...
6,462,985
6,464,658
C++ std::vector vs array in the real world
I'm new to C++. I'm reading "Beginning C++ Through Game Programming" by Michael Dawson. However, I'm not new to programming in general. I just finished a chapter that dealt with vectors, so I've got a question about their use in the real world (I'm a computer science student, so I don't have much real-world experien...
A: Almost always [use a vector instead of an array]. Vectors are efficient and flexible. They do require a little more memory than arrays, but this tradeoff is almost always worth the benefits. That's an over-simplification. It's fairly common to use arrays, and can be attractive when: the elements are specified at...
6,463,122
6,463,145
Sprite Sheet With OpenGL and SDL
I been working in a new game, and finally reached the point where I started to code the motion of my main character but I have a doubt about how do that. Previously, I make two games in Allegro, so the spritesheets are kind of easy to implement, because I establish the frame and position on the image, and save every fr...
You're on the right track. Things to consider: leave enough dead space around each sprite so that the video card does not blend in texels from adjacent sprites at small scales. set texture min/mag filtering appropriately. GL_NEAREST is OK if you're going for the blocky look. if you want to be fancy and save some textu...
6,463,181
6,565,958
Automake Variables to tidy up Makefile.am
I have a directory /src containing all of my source files, and /bin to store all binary after running make command. The directory is something like below: /BuildDirectory - - /src - - /bin - - configure - - Makefile.am - - configure.ac - - ... Now in Makefile.am, I have to specified: bin_PROGRAMS = bin/x bin/y bin/z...
You could take advantage of remote building. Place this makefile in the bin dir: VPATH = ../src bin_PROGRAMS = x y z k ... x_SOURCES = x.cpp y_SOURCES = y.cpp z_SOURCES = z.cpp Now replace the current Makefile.am with this one: SUBDIRS = bin Now tweak your configure.ac to also generate bin/Makefile AC_CONFIG_FILES(...
6,463,784
6,469,504
what values can I pass to message_flags attribute in stream_socket_service::receive
I am trying to use socket::receive in boost asio to receive data over network. I want it to block until certain size of data is available. For that it seems that I will have to set message_flag argument to the receive function, but I cannot find the information on what value can I pass so that the receive will be block...
For that it seems that I will have to set message_flag argument to the receive function This is incorrect. There are overloads to the async_read or read free function. They will read as many bytes as you request based on the buffer size: Remarks This overload is equivalent to calling: boost::asio::read( ...
6,464,113
6,476,546
Any suggestion about writing a chat room C program in Linux using Pipes and Daemon Processes?
The requirement is to make a C/C++ program that is a chat room. 1, Both the client and server program need no GUI, use command line only. And they only need to run in the same machine, connected with pipes. 2, Use a FIFO queue in a Daemon Process, and users can chat using the Daemon Process at the same time. 3, T...
Sounds like you are being asked to both design and write this program. Your question sounds rather like you need to have a client-server architecture (which makes sense) and talks over a pipe (you could equally do the same thing with a socket so you might want to make this layer easy to swap out later) So, you need one...
6,464,237
6,464,280
C++, Namespaces, Templates, and No Matching Function Call
I've checked similar tags but I can't seem to find out what I'm doing wrong. I'm trying to use the CImg library and it's my first time working with templates in C++. I'm in the process of porting some of my image processing stuff to work with this library and I've run into a bit of trouble. Hopefully someone here can ...
The compiler can't deduce template parameters solely from the return type. You have the supply the template parameter explicitly in this case: CImg<unsigned char> fromCN = cn_cimg_get_CNtoCImg<CImg<unsigned char> >(cn);
6,464,369
6,464,394
How do I set 4 bytes bit pattern for magic number in Java?
I am working on a network programming on linux machine using C++ and I was wondering how I can set 4 bytes bit pattern for magic number in Java (client). Also how do I set the same bit pattern in c++ co I can compare the one from client with the one on the server side. Thank in advance.. Edit So now I have this by...
Java has bitwise operators, for example bitwise OR |, bitwise AND & and bit shift operators >>>, >> and <<, very similar to what C++ has. You can use those to manipulate bits exactly as you want. Since you don't explain in more detail what you want to do, I cannot give you a more detailed answer.
6,464,404
6,464,551
virtual function default arguments behaviour
I have a strange situation over the following code. Please help me to get it clarified. class B { public: B(); virtual void print(int data=10) { cout << endl << "B--data=" << data; } }; class D:public B { public: D(); ...
Default arguments are entirely compile-time feature. I.e. the substitution of default arguments in place of missing arguments is performed at compile time. For this reason, obviously, there's no way default argument selection for member functions can depend on the dynamic (i.e. run-time) type of the object. It always d...
6,464,436
6,466,219
What is the semicolon in C++?
Roughly speaking in C++ there are: operators (+, -, *, [], new, ...) identifiers (names of classes, variables, functions,...) const literals (10, 2.5, "100", ...) some keywords (int, class, typename, mutable, ...) brackets ({, }, <, >) preprocessor (#, ## ...). But what is the semicolon?
The semicolon is a punctuator, see 2.13 §1 The lexical representation of C++ programs includes a number of preprocessing tokens which are used in the syntax of the preprocessor or are converted into tokens for operators and punctuators
6,464,665
11,600,334
Reporting library for Qt and C++
I'm looking for a reporting library for C++. What I need to do in my project is to present some statistical reports (pdf files including some grids and charts) based on the historical data stored in the database. We are using Qt and C++. I've done some research about it and found some libraries. Especially NCReports an...
It is late to say this but for the ones who are looking for this kind of library I can say that Chart Director is very simple, cheap and good.
6,464,670
6,468,379
Heap corruption when trimming delayed free queue
I'm currently attempting to track down the source of heap corruption in our code base, which doesn't present itself when full page heap tracking is turned on (so only normal page tracking). I'm using Application Verifier to break on the corruption, and get a not-so-helpful stop code of 00000008: APPLICATION_VERIFIER_H...
This suggests that you have modified the block after you freed it - perhaps from a different thread, or because something still has a pointer to it. (When you free it the runtime sets it to all F0, holds on to it for a while, then checks that it is still all F0; it isn't, so it must have been modified after the free.) ...
6,465,133
6,466,201
std::vector and contiguous memory of multidimensional arrays
I know that the standard does not force std::vector to allocate contiguous memory blocks, but all implementations obey this nevertheless. Suppose I wish to create a vector of a multidimensional, static array. Consider 2 dimensions for simplicity, and a vector of length N. That is I wish to create a vector with N elemen...
For reference the way I currently create a 2D array in a contiguous memory block is by first making a (dynamic) array of float* of length N, allocating all N*5 floats in one array and then copying the address of every 5th element into the first array of float*. That's not a 2D array, that's an array of pointers. If y...
6,465,290
6,465,315
After playing wav file, do I need to delete the buffer?
I am trying to implement classes implementing the wav playing, as explained in this example. The relevant code part is here : /* Setup for conversion */ wav_cvt.buf = malloc(wav_len * wav_cvt.len_mult); wav_cvt.len = wav_len; memcpy(wav_cvt.buf, wav_buf, wav_len); /* We can delete to original WAV data now */ SDL_Fre...
No, nothing is done automatically. You must free it.
6,465,325
6,465,394
Do classes have external linkage?
I have 2 files A.cpp and B.cpp which look something like A.cpp ---------- class w { public: w(); }; B.cpp ----------- class w { public: w(); }; Now I read somewhere (https://en.cppreference.com/w/cpp/language/static) that classes have external linkage. So while building I was expecting a multiple definition ...
External linkage means the symbol (function or global variable) is accessible throughout your program and Internal linkage means that it's only accessible in one translation unit. you explicitly control the linkage of a symbol by using the extern and static keywords and the default linkage is extern for non-const symbo...
6,465,557
6,465,762
Where is DEBUG defined in the code?
I looked at a sample code to create a log system on my server... And I found this #if DEBUG printf("something here"); #endif I know what it does. It prtins something only if DEBUG has been defiend. But where is DEBUG defined? I looked at the all the header files but I could't find DEBUG.. Also, Could you please provi...
Compilers, at least those I know of, have an option to define preprossessor macros from "the outside" of compiled files. For example, to define DEBUG with a microsoft compiler, you'd go with something like cl -DDEBUG file.cpp ...
6,465,597
6,465,638
2D Pointer initialization
How to initialize a 2D array with pointer. int *mapTable[] = { {1,10} , {2,20} , {3,30} , {4,40} }; // It's giving error Here int *mapTable is giving an error. How can I declare them properly?
int *mapTable[] is not a 2D array: it is a 1D array of pointers. But then you go and use a 2D array initialiser { {1,10} , {2,20} , {3,30} , {4,40} }. That's why it's "giving error". The 2D array way Try: int mapTable[][2] = { {1,10} , {2,20} , {3,30} , {4,40} }; And, yes, you do need to specify the size of that seco...
6,465,759
6,465,776
empty vector allows push back first element of itself
One friend of mine showed very simple example: #include <vector> int main() { vector<int> v; v.push_back( v[0] ); return 0; } It compiles, without any warnings. Problems with templates should be detected at compile time. What is your explanation of this strange behavior?
this seems like a runtime issue not a compile time issue to me. how is the compiler supposed to know how vector runs?
6,466,010
6,466,062
Operator Overloading in C++
I have doubt whether we can do the following or not. Suppose I have created two instance of class A i.e. obj1 and obj2 and class A has member function show(). Can I use the following? (obj1+obj2).show() If yes, how? If no, why it is not possible?
Yes it is possible, just implement operator+ for A and have it return a class of type A: #include <iostream> class A { public: explicit A(int v) : value(v) {} void show() const { std::cout << value << '\n'; } int value; }; A operator+(const A& lhs, const A& rhs) { A result( lhs.value + rhs.value ); ...
6,466,253
6,466,276
If temporaries are implicitly non-modifiable, how does this work?
I'm told that, in C++03, temporaries are implicitly non-modifiable. However, the following compiles for me on GCC 4.3.4 (in C++03 mode): cout << static_cast<stringstream&>(stringstream() << 3).str(); How is this compiling? (I am not talking about the rules regarding temporaries binding to references.)
I'm told that, in C++03, temporaries are implicitly non-modifiable. That is not correct. Temporaries are created, among other circumstances, by evaluating rvalues, and there are both non-const rvalues and const rvalues. The value category of an expression and the constness of the object it denotes are mostly orthogon...
6,466,265
6,466,795
The best way to provide a JSON InputStream
In different languages I need to provide users with a stream of JSON objects with an interface similar to the following: JSONObject json = stream.nextJSON(); Since it is a stream, each call will block until a full object has been retrieved. This means it makes no sense to try and encapsulate each JSON object inside a ...
Well Google already thought about it apparently: http://sites.google.com/site/gson/streaming
6,466,352
6,466,445
Pimpl idiom and internal object collaboration without friend declaration
I'm implementing several classes using the pimpl idiom and am coming across some design issues. Firstly, I've always seen pimpl done like this class Object { public: Visible(); ~Visible(); .. etc .. private: class ObjectImpl *_pimpl; }; I have several classes which use this approach and my problem is that...
I doubt there is a good reason to make the implementation public: you can always expose the implementation's functionality using public methods: class Object { public: Object(); ~Object(); int GetImplementationDetail(); private: std::unique_ptr< ObjectImpl > _pimpl; }; int Object::GetImplementationDetail() ...
6,466,653
6,466,679
.net components in unmanaged code - performance?
I need to write some dll that will be loaded into some existing system via COM. How much performance do I lose if I write using c#.net instead of plain c++?
In general, none. Things to watch out for: Creating lots of strings by performing lots of string concats; but that in itself won't necessarily be a problem Excessive Boxing/Unboxing Performance (C# and Visual Basic)
6,466,694
6,470,323
Scheduling Task Based on Date time
I am working for private video network where I have to schedule the task based on following parameter.There is client Portal, Server and Gateway. Through portal a user can request Streaming the video. User can also Schedule Streaming for some future time.Each each task is having a task ID. Task is scheduled based on ...
There are dozens of ways to design this. It all depends on what you want to do and what the specific requirements are. In a basic design I'd create an additional field called "next run time" which will be calculated by using start time, frequency and previous (if any) end time. Then I'd dump all the tasks in a queue s...
6,466,816
6,467,562
Are virtual method not "delete"able in C++0x?
The error message seems to be little mis-leading with the scenario, when we try to delete a virtual method. prog.cpp:4:16: error: deleted function 'virtual void Test::foo()' prog.cpp:8:2: error: used here Code struct Test : public Base { Test() {} virtual void foo () = delete; // error }; Are virtual method not ...
The term use has a concrete definition in the standard, and in particular for virtual functions the definition of odr-used is: §3.2/2 (C++0x FDIS) [...]A virtual member function is odr-used if it is not pure.[...] Where odr-used is a new term in the upcoming standard that refers to what the previous standard called p...
6,466,817
6,507,251
DBus Glib, send a signal with a struct nested
I'm developing an application on c++ language on linux. I want to send a signal as this: <signal name="EmitSignal"> <arg type="(u(i)uussssu)" name="t_struct_of_signal" direction="out" /> </signal> The second parameter in type="(u(i)uussssu)" is an enum type. I'm trying to register a struct #define STRUCT_OF_SIGN...
I resolved it: I changed G_TYPE_VALUE_ARRAY to dbus_g_type_get_struct ("GValueArray", G_TYPE_UINT, G_TYPE_INVALID) Then, this was: g_value_init(g_value_array_get_nth(ret, 0), G_TYPE_VALUE_ARRAY); Now, it is: g_value_init(g_value_array_get_nth(ret, 0), dbus_g_type_get_struct ("GValueArray", G_TYPE_UINT, G_TYPE_INVALID)...
6,466,882
6,467,575
Can jconsole be used to identify memory leaks in JNI C++ objects?
Is it possible to identify the C++ allocations that are unfreed? The C++ calls are made using JNI from my Java application to which I'm planning to attach jconsole. If that is possible please tell how (whether in an exported dump file or otherwise) you have been able to see the heap objects that were left unfreed.
No. C++ code doesn't allocate memory from anywhere that the JVM can see. (Unless you're talking about Java objects allocated from C++.)
6,467,166
6,467,493
bison/flex: print erroneous line
I am using bison+flex to parse file. On error yyerror() is invoked. How can I get the line number or string that is violating the rules, to print it with the error message?
Line number is easy: yylineno is the line number. Specify %option yylineno at the top of your .l file. Well, almost easy. Lookahead can sometimes make the line number be off by one. Instead of saying something like "Error occurred at line #xxx" you might want to say that the error occurred near line #xxx. As far as the...
6,467,585
6,467,655
Deterministic random number generator tied to instance (thread independent)
Random numbers have been well covered here, so I'll keep it brief. I use srand and rand to generate some deterministic random numbers in a simulation. However, when running multiple simulations at once on separate threads, the individual sequence gets muddled up and becomes non deterministic, because all threads draw f...
Your compiler most likely already has something very like Boost.Random. C++0x includes a <random> header which is based on Boost.Random (with a few tweaks here and there). Before then, TR1, a set of "semi-standard" libraries was available for most compilers as well, which contains nearly the same <random> header.
6,468,046
6,468,064
C++ Program won't enter for loop
Alright, so here's the portion of my code that is giving me a problem. What I want it ot do is to take in a grade, decide if it is a valid grade, and then keep asking for a valid number if it is not. However, it won't even enter the loop, so.... any advice? Ive been programming for a little bit but Im still pretty new,...
Your condition is an assignment: b_valid=false. It will evaluate to false and the loop will never execute. You meant for(bool b_valid = false; b_valid == false; ) ^^^^ There is a coding style which mandates that the constant in comparison be the first argument, like if(false == b_val...
6,468,113
6,468,138
binding a port number to a TCP socket (outgoin) to send packets
I know that it is not easy to bind a port number to TCP socket that you would use to send data (because systems usually bind a random port to sockets). But I read on one article that by using some low level networking methods you can bind a port number to a TCP socket then use it to send data ? Does anyone has an idea...
Bind it before connecting. s = socket(AF_INET, SOCK_STREAM, 0); /* ... */ memset(&client_addr, 0, sizeof(client_addr)); client_addr.sin_family = AF_INET; client_addr.sin_port = htons(22222); if (bind(s, (struct sockaddr *) &client_addr, sizeof(client_addr)) < 0) { perror("bind"); exit(1); } connect(s, (struc...
6,468,425
6,468,482
Why isn't this polymorphic?
#include <cstdio> #include <cstring> class A { public: virtual void foo() { puts("A"); } }; class B : public A { public: void foo() { puts("B"); } }; int main() { A a; B b; memcpy(&a, &b, sizeof (b)); (&a)->foo(); }
You are not supposed to mess with non-POD types like that. In particular, the C++ standard says that memcpying non-PODs results in undefined behavior, which, in your case, shows as continuing to see a as being of type A. In your particular case, the compiler "knows" that the both the "static type" and the "dynamic type...