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,843,722 | 6,843,742 | G++ compiler: Segfault handling | I'm working on a project where I call a function which triggers a segfault. I fixed this, but during the process I noticed the following.
When my code is of the format;
main(){
...
std::cout << "Looking for segfault\n"; // this does not print
buggyFunction(); // crashes in here
...
}
buggyFunction(){
...
t... | The reason for this is that cout has a buffer and it will only pass to the system function and write to the console when the buffer is full. Your second use of cout happens to overflow the buffer and so it calls the operating system and empties the buffer. If you want to guarantee that the output has left the buffer, y... |
6,843,831 | 6,844,002 | Receiving JPEG images via http GET request | I want to receive images from an IP camera over HTTP via GET request. I have written a program that creates TCP socket connection with the camera and sends the following GET request to the camera:
GET /mjpeg?res=full HTTP/1.1\r\nHost: 143.205.116.14\r\n\r\n
After that, I receive images with the following function in a... | Why reinvent the wheel (for the umpteenth time)? Use a ready-made HTTP client library, such as libcurl.
For that matter, perhaps you can even just write your entire solution as a shell script using the curl command line program:
#!/bin/sh
curl -O "http://143.205.116.14/mjpeg?res=full" || echo "Error."
curl -o myfile.j... |
6,844,232 | 6,858,761 | C++/CLI XMLSerialization Layout | Got a problem in C++:
I have written a program which generates an XML file using XMLSerialization (XmlWriter, XmlReader). Now everything is done, excluding the layout. In my generated XML file tabs and the standard XML layout are missing! Is it possible to automatically format this text using a C++ function...?
XmlSeri... | This was the right code in my case:
XmlWriterSettings ^settings = gcnew XmlWriterSettings();
settings->Indent = true;
settings->IndentChars = (" ");
settings->NewLineOnAttributes = false;
writer = XmlWriter::Create( filename, settings );
|
6,844,257 | 6,844,374 | qt 4.7 removeChild() and memory | Im writing a c++ qt application. In one part I'm creating a QTreeWidget. The user has all possibilities to create and delete entries in that tree.
So when the user creates a item he will call a function which then itself calls:
QTreeWidgetItem* newItem = new QTreeWidgetItem();
When the user later decides to delete the... | How about
delete curItem;
?
According to the documentation, the destructor will remove the item from the tree in which it is included, so I think you don't even need to perform the removeChild beforehand.
|
6,844,569 | 6,844,625 | How to ensure uniqe seeds for the RNG on subsequent process launches? | Summary: I need a simple self-contained way to seed my RNG so that the seed is different every time the program is launched.
Details:
I often need to run the same program (which does calculations with random numbers, e.g. Monte Carlo simulation etc.) many times to have good statistics on the result. In this case it i... | "Cross-platform" is a subjective term. Do you mean "any platform" (you might encounter in the future) or "every platform" (on your list of supported platforms)? Here's a pragmatic approach that I usually take:
Check if you have /dev/urandom; if yes, seed from there.
On Windows, use CryptGenRandom().
If all else fails,... |
6,844,601 | 6,845,118 | Java vs native coding in Android Application development | I plan to create an SDK (involving huge data manipulations), which can used to create applications on Android.
I plan to develop the complete SDK, including the libraries in Java, for the reason that if I implement my libraries in the native language(C++) the data movement between the Java and the native layer will inv... | Windows Mobile supports native code (Visual C++, see Getting Started in Developing Applications for Windows Mobile) so using the Android NDK would be a good option. At least you wouldn't have to write the whole thing from scratch. You could have the common code base written in C/C++ and only write the Java wrappers for... |
6,844,605 | 6,844,768 | C++ macro/metaprogram to determine number of members at compile time | I am working on an application with a message based / asynchronous agent-like architecture.
There will be a few dozen distinct message types, each represented by C++ types.
class message_a
{
long long identifier;
double some_value;
class something_else;
...//many more data members
}
Is it possible to write a m... | No, there is no way in C++ to know the names of all members or how many members are actually there.
You could store all types in a mpl::vector along in your classes but then you face the problem of how to turn them into members with appropriate names (which you cannot achieve without some macro hackery).
Using std::tu... |
6,844,701 | 6,844,728 | how to convert Qstring to Long? | I am new to Qt Creator. I would like to convert a QString value into a long number. How would I do this?
long s;
QString x = "6458621237";
EDIT
As a result I'll have long s = 6458621237;
| Use the toLong function.
For example,
QString str = "FF";
bool ok;
long hex = str.toLong(&ok, 16); // hex == 255, ok == true
long dec = str.toLong(&ok, 10); // dec == 0, ok == false
|
6,844,712 | 6,844,815 | how to use quickfix c++ isSessionTime() | Anyone knows how to use the function bool isSessionTime(const DateTime& time) of quickfix/c++? What I mean is that what should be passed in as the parameter? In the quickfix/J, there is no parameter required, and the function of this method is to predict whether the current time is for a stock session time. But in quic... | You have to create a DateTime object to pass it as a parameter. Have a look at the link and check out your API library files to get a better idea.
Default constructor - initializes to zero.
DateTime ()
Construct from a Julian day number and time in millis.
DateTime (int date, int time)
Construct from the specified c... |
6,844,738 | 6,845,298 | Help with a regular expression | I am fairly new to regular expressions and have been having difficulty using one to extract the data I am after. Specifically, I am looking to extract the date touched and the the counter from the following:
<span style="color:blue;"><query></span>
<span style="color:blue;"><pages></span>
<span style=... | That's because cmatch::operator[](int i) returns a sub_match, whose sub_match::operator basic_string() (used in the context of cout) returns a string starting at the beginning of the match and ending at the end of the source string.
Use sub_match::str(), i.e. match[1].str() and match[2].str().
Moreover, you'll need you... |
6,844,782 | 6,844,924 | Very Strange Constructor behaviour | I have the following situation
Class A
{
public:
A(/* x number of arguments */);
};
A::A(/*.....*/)
{
std::set<__int64> tmpSet;
tmpSet.insert( /*<num>*/ ); // repeat statement for some 30 K or more
tmpSet.insert( /*<num>*/ );
//-----repeat statement for some 30K or more times
}
main()
{
... | std::set.insert() returns a std::pair<iterator, bool>. The compiler has to allocate stack memory to store the return value, as it is too large to fit into registers.
A good optimisation would be to reuse this stack memory for the next call. It looks like your compiler does not do so.
Hence, your constructor requires a ... |
6,844,956 | 6,845,012 | MSVC 2008 16 Bytes structure members alignment weirdness | Can anybody please explain what's going on?
My MSVC 2008 project's structure member alignment setting is set to 16 bytes (/Zp16) alignment, however one of the following structures is being aligned by 16 bytes and another is aligned only by 8 bytes... WHY?!!!
struct HashData
{
void *pData;
const char* pName;
... | I think you misunderstood the /Zp16 option.
MSDN says,
When you specify this option, each structure member after the first is
stored on either the size of the member type or n-byte boundaries
(where n is 1, 2, 4, 8, or 16), whichever is smaller.
Please read the "whichever is smaller". It doesn't say that the st... |
6,845,372 | 6,845,819 | call a pointer function in class | I've a pointer function in a class that is defined outside the class and used as a callback.
The class goes like this
class A
{
void CreateGrid(OWindow *win,int x,int y);
Otkobject *GetIcon(void *data,Otkobject *obj,int x)
}
I've defined the GetIcon function like this
Otkobject *A::GetIcon(oid *data,Otkobject ... | That's a function returning a pointer, not a function pointer. The error might be the missing semicolon after the class declaration:
class A
{
void CreateGrid(OWindow *win,int x,int y);
Otkobject *GetIcon(void *data,Otkobject *obj,int x); // <- also here
}; // <- notice semicolon
|
6,845,695 | 6,845,752 | static_cast - what does conversion between compatible types mean? | I understand that static_cast can convert between base and derived and between derived and base. dynamic_cast will check resulting object is a 'complete' object.
dynamic_cast uses RTTI feature. But how does static_cast work? What does 'compatible types' mean?
My question was really about what compatible types meant.... | The main cases are they have a parent-child relationship or are both builtin numeric types. It's also valid if one object can be constructed from the other, integral types can be converted to enumerated types, and void pointers can be cast to pointer-to-object.
EDIT for the main cases (I omitted some more obscure cases... |
6,845,722 | 6,845,832 | question about pointers and overloading (.append() doesn't work in one line) | In my program I would like to manipulate boost::filesystem::path elements of a vector in a for loop.
typedef vector<fs::path> path_vec;
path_vec pv;
for (auto it = pv.cbegin(), end = pv.cend(); it != end; ++it)
What I would like to do is to add a string to the end of the path.
If I do it like this, it works fine:
str... | fs::path.string() returns const& so you cannot append anything to it, first you need to make a copy
but why do you do this at all? there's a obvious way to append nested path:
path / nested_path
EDIT:
typedef vector<fs::path> path_vec;
path_vec pv;
for (auto it = pv.begin(), end = pv.end(); it != end; ++it)
*it /=... |
6,845,779 | 6,855,977 | Explicit destructor in templated context | I want to explicitly destroy a vector in a templated context. The following works for me (GNU C++ 4.3, 4.4 and Clang++ 1.1):
template <typename T>
void destroy_vector_owner(VectorOwner<T> *obj)
{
obj->v.~vector();
// further cleanup by Python API functions omitted
}
while it fails on Mac OS X v10.5's g++ (i686... | My first answer was wrong actually, litb pointed me into the right direction. The right answer is
that both syntaxes are correct:
Destructor call syntax.
The syntax for an explicit destructor call is described in 12.4 Destructors:
12 In an explicit destructor call, the destructor name appears
as a ˜ followed by a... |
6,845,853 | 8,548,850 | .NET Property Sheet for Qt? Any suggestions? | I have some variables I want to change via GUI. The variables are of four types: bool, long long, double, char *. Different widgets for different types are wanted:
QCheckBox for bool
QSpinBox for long long
QDoubleSpinBox for double
QLineEdit for char*
Or change char* to std::string - doesn't matter.
So I need a widg... | create your own sub-class of QWidget to make your own "property widget" which will have a QLabel and the corresponding Widget for the variable type. then add your custom "property widget" to your application.
for example, if you need to add a line for the bool type, it's class would look something like this:
class Bool... |
6,845,854 | 6,845,874 | C++ multiple inheritance function call ambiguity | I have a basic question related to multiple inheritance in C++. If I have a code as shown below:
struct base1 {
void start() { cout << "Inside base1"; }
};
struct base2 {
void start() { cout << "Inside base2"; }
};
struct derived : base1, base2 { };
int main() {
derived a;
a.start();
}
which gives the fol... | a.base1::start();
a.base2::start();
or if you want to use one specifically
class derived:public base1,public base2
{
public:
using base1::start;
};
|
6,845,949 | 6,846,180 | design issues in producer-consumer problem | I am working on a little multi-threading project.The system could be divided into 2 sub parts, A and B. the data flows from A to B.
A part keeps fetching raw data from outside world, do some transformation and and then generate thousands of new data, let's call it A_OUTPUT.
B part do some calculations based on each A_O... | It's rather classical problem that is well described in wikipedia
I can recommend following approach:
Synchronize access to the queue by mutex. keep two condition variables, one to signal that queue is not full (you need to handle cases when Producer produces more data than Consumer can consume) and another one to sign... |
6,846,307 | 6,846,410 | Operator precedence in `copy` implementation example | I read a few lines of code here where it looks to me like there should be some parentheses.
template<class InputIterator, class OutputIterator>
OutputIterator copy ( InputIterator first, InputIterator last, OutputIterator result )
{
while (first!=last)
*result++ = *first++; // <--- this line
return result;
... | The postfix increment does execute first, but the return value from postfix increment is the original value of the pointer. That's why it works.
|
6,846,321 | 6,868,558 | No cout from wxWidget application, but with Eclipse it works fine | my wxWidget Application does not make any std::cout << "xyz" ... on a windows console (Windows XP) when it is startet from a console by e.g.: "call MyApplication.exe". It will produce no output at all. The Application instead rises correctly and works fine. All Buttons and Widgets on the Frame have their functions work... | I've always been curious about this, so I followed the links provided in Bo Persson's answer and pieced together some code. To use it, just define a UseConsole object in main.
UseConsole.h:
class UseConsole
{
public:
UseConsole();
~UseConsole();
private:
bool m_good;
};
UseConsole.cpp:
#include <windows... |
6,846,641 | 6,846,781 | Dynamic array width id? | I need some sort of dynamic array in C++ where each element have their own id represented by an int.
The datatype needs these functions:
int Insert() - return ID
Delete(int ID)
Get(ID) - return Element
What datatype should I use? I'we looked at Vector and List, but can't seem to find any sort of ID. Also I'we looked ... | A std::map could work for you, which allows to associate a key to a value. The key would be your ID, but you should provide it yourself when adding an element to the map.
An hash table is a sort of basic mechanism that can be used to implement an unordered map. It corresponds to std::unordered_map.
|
6,846,657 | 6,846,850 | Calling the function pointed by a Pointer-to-Member-Function from within a struct | I have a class Test with a peculiar data structure.
A member of class Test is a std::map where the key is a std::string and the mapped value is a struct defined as follows:
typedef struct {
void (Test::*f) (void) const;
} pmf_t;
Initialization of the map is OK. The problem is when I am trying to call the function po... | The name of the pmf_t type is f, so the first change is to remove the * to get second.f. That gives you a pointer-to-member value. To use a pointer-to-member, you need an instance. The only one you have available of the correct type is this, so use it with the ->* operator:
(this->*it->second.f)();
You need parenthese... |
6,846,708 | 6,846,811 | My vectors are disappearing | So I am having an issue within the two methods posted below. Aside from terrible naming of variables, I only have one problem. Somehow between getData and cutRamping, my vector TwoDee disappears. I have traced it using gdb, and at the end of getData it is filled with values, but when I try to trace it manually or th... | The vector in getData is "shadowing" (hiding) the vector in your class, and then when getData exits, all the contents of the vector are freed. You should probably just not redeclare it in the method.
|
6,846,924 | 6,994,962 | Payload split over two TCP packets when using Boost ASIO, when it fits within the MTU | I have a problem with a boost::asio::ip::tcp::iostream. I am trying to send about 20 raw bytes. The problem is that this 20 byte payload is split into two TCP packets with 1 byte, then 19 bytes. Simple problem, why it is happening I have no idea. I am writing this for a legacy binary protocol that very much requires th... | Your code:
out << (char) 0x1 << (char) 0x2 << (char) 0x3;
Will make 3 calls of operator<< function.
Because of Nagle's algorithm of TCP, TCP stack will send available data ((char)0x1) to peer immediately after/during the first operator<< call.
So the rest of the data (0x2 and 0x3) will go to the next packet.
Solution ... |
6,846,971 | 6,847,553 | C++ memcpy and happy access violation | For some reason i can't figure i am getting access violation.
memcpy_s (buffer, bytes_per_line * height, image, bytes_per_line * height);
This is whole function:
int Flip_Bitmap(UCHAR *image, int bytes_per_line, int height)
{
// this function is used to flip bottom-up .BMP images
UCHAR *buffer; // us... | You're getting an access violation because a lot of image programs don't set biSizeImage properly. The image you're using probably has biSizeImage set to 0, so you're not allocating any memory for the image data (in reality, you're probably allocating 4-16 bytes, since most malloc implementations will return a non-NUL... |
6,847,098 | 6,847,177 | How to use a typedef function pointer to register a callback | I'm trying to implement an observer pattern (of sorts) with C++ and I want to use function pointer to do so, but I keep getting an error when trying to cast a function pointer from class B to a typedef function pointer:
#include <map>
typedef int (*OutputEvent)(const char*, const char*, int);
class A
{
private:
i... | The function you are trying to cast to OutputEvent is a member function. This is represented clearly in the error message by this:
'int (B::*)(const char*, const char*, int)'
which is a different type than
int (*OutputEvent)(const char*, const char*, int)
because of the B:: part (that means that the function has an... |
6,847,116 | 6,847,180 | Visual Studio 2008 says "the specified file is an unrecognized or unsupported binary format" when I try to debug | I have a VS2008 solution containing two C++ projects. One is a Win32/console .dll and the other is a tester program to test that dll, also a Win32 console app.
When I build the solution, even with a clean build and with the Debug Command set to the hardcoded path to the executable, trying to debug presents a messagebo... | Please make sure that your test application (it should be an executable: .exe) is the one you're running and not the DLL. Set it as the "startup project" for example.
You can do so from within your Solution Explorer by right-clicking the appropriate project and selecting "Set as startup project".
|
6,847,227 | 6,847,277 | can the compiler optimize the memory management allocating a static array on the heap? | I wanted to allocate a big char array in the data segment so I used some code like this one:
const int size = 1000000000 ;
static char chr [ size ] ;
int main ( )
{
chr [ size - 1 ] = 1 ; // line 1
string s ;
cin >> s ; // line 2
}
line 1 : I put this line so that the array is used at le... | The operating system allocates memory only after it has been accessed. Read about demand paging.
|
6,847,360 | 6,847,847 | error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup, but this time it's NOT a Windows/Console problem! | So, the infamous error is back. The project is complaining that it can't find the main() method (that's what the error means, right).
However I do have a main, and my project is a Console project, as it should be. It worked before, so I know it's not that.
Also, the project has too many classes and files for me to post... | SDL_main.h is included automatically from SDL.h, so you always get the nasty #define.
Just write:
#include <SDL.h>
#undef main
And it should work fine
|
6,847,457 | 6,847,573 | Advice on Copy Constructor of a Class containing a non-copyable member reference | I have a class A which has an reference to an object of class B as a member. The copy constructor (and assignment operator) of class B is private. Do you think it is a valid and good idea to use
the default copy constructor for A. (I actually want a functionality where I can store a lots of object for type A in some s... | As a general guideline, I never store references inside objects because I cannot get copy semantics for free.
I store pointers instead. Here, storing a dumb pointer and letting the compiler implement copy semantics for you seems fine:
class A
{
B* b; // or a smart pointer, depending on what semantics you want.
pub... |
6,847,538 | 6,847,606 | C++ pointer arithmetic weirdness | I found my bug (after a few hours) and isolated it in the following program. The problem is with the way in which the pst2 variable's value is calculated when using pointers to a struct. When using pointers to char, all works fine. Why is this? (Using gcc/g++ version: (Debian 4.4.5-8) 4.4.5) (For those who are wonderin... | That looks fine to me. The line:
(pst1 + np1)
adds np1 instances of st_one to what pst1 points at, which means that pst1s value is incremented by np1 * sizeof (st_one) bytes, which is 25 (sizeof = 5), which corresponds to the values you've outputted. Instead of the above, I think you wanted:
(pst1 + 1)
The pc1 valu... |
6,847,891 | 6,847,969 | Binary Search Tree - to Make a dictionary | I wanted to make a dictionary using BST but I did not have any Idea how to store them in the tree
struct node
{
char word[50];
char meaning[256];
struct node *left, *right;
};
I started like that but I dont know which words to put in the left and which on the right...
| Instead of a binary tree, you should use something like a suffix tree. BSTs are really more for "greater/less-than" relationships, which would be hard to map with words. With suffix trees your nodes are characters and branches eventually lead to leaves representing an actual word.
|
6,848,128 | 6,849,134 | Peek stdin using pthreads | I'm trying to peek stdin to see if anything is there using pthreads. I (think I) need to do this because if there is nothing in std in, stream access functions will block for input.
I feel the way to do this is to fire off a pthread that checks stdin, and sleep(1) and see if the thread found anything.
Here's what I ... | You don't need pthreads for that and you can use select(2) or poll(2) to known if you can peek the stdin without blocking your application. For that I coded the my_peek() function which you just need to pass the number of seconds you want to wait for the input (you can even pass 0 if you don't want to wait):
/* Accordi... |
6,848,230 | 6,849,083 | Maintaining a container of objects sorted by the difference between that object's member and its neighbor's member | I'm working on implementing a histogram, and one of the key points is the quick merging of histogram bins. Because I don't have a priori knowledge of the data set being approximated by the histogram, I need to come up with a way that quickly merges neighboring bins, after I've exceeded the maximum number of bins.
So, a... | Posting this as an answer:
Take a look at the answer to this question: Online k-means clustering. If I understand your problem correctly, that's pretty much what your looking for, where the initial k guesses are your first k values.
If you keep your bin centers ordered, you can binary search into the list and the close... |
6,848,462 | 6,848,655 | Macro to log error and return false | Most of the statements in the project I work with is of the form
if(!someObject->someFunction(arg1,arg2))
{
cerr << "Something bad happened. Args are: " << arg1.print() << " " << arg2 << endl;
return false;
}
This makes my code not readable as error logging triples the actual code. Hence I wrote the following... | I think that it would better be a function:
bool fnAssert(bool cond, char * strCond, char *msg, char *file, int line)
{
if (!cond)
{
cerr << "@File: " << file << ":" << line << " " << strCond << " failed."
<< msg << endl;
}
return cond;
}
#define Assert(cond, a) fnAssert(cond, #co... |
6,848,559 | 6,861,963 | Problems having CMake access SWIG and link a java library to an existing C++ project | I am modifying a CMake file of an existing open source project written in C++ to try to link it to a SWIG Java interface file. The code I have pieced together from other forums and tinkering around is this :
FIND_PACKAGE(SWIG REQUIRED)
INCLUDE(${SWIG_USE_FILE})
INCLUDE_DIRECTORIES(${JAVA_INCLUDE_PATH})
... | I fixed my particular problem by adding the full path to the wrapper and interface files in the set source properties commands. To point it towards jni.h, I added FIND_PACKAGE(JNI REQUIRED) at the beginning.
|
6,848,628 | 6,848,677 | Can a base class implementation stand in for a pure virtual method of an interface? | Say I have CFooer and it implements method void foo().
I then have ISomething that has virtual void foo() = 0.
I now create a class:
class CSuperFoo : public CBase, public CFooer, public ISomething
{
};
When I instance CSuperFoo, will I get a cannot instance abstract class error, or would this use CFooer's implementat... | You will have to provide an implementation in the Derived class CSuperFoo to be able to create objects of it, otherwise it will be an Abstract class.
The method foo() from the Base class ISomething needs to be overridden in the deriving class CSuperFoo explicitly because compiler cannot see any relation between method ... |
6,848,792 | 6,848,831 | Application not running on a PC with VS 2008 not installed | I have been working on a project using OpenCV and have made a face detection project.
I would like to know why does an executable created using Visual Studio 2008 not run on another pc and give the following error:
"This application has failed to start because the application configuration is incorrect"
| Perhaps you need the Visual C++ Runtime package installed.
Available for download .... here
|
6,848,848 | 6,848,878 | finding a key in a map | I have a map which I have declared as follows:
map<int, bool> index;
and I insert values into the map as:
int x; cin>>x;
index[x]=true;
However,
cout<<index[y]; // for any number y not inindexgives me 0
As I get the value 0 when I check for a key which is not present in the map, how can I reliably find out if a key ... | You can use if (index.find(key) == index.end()) to determine if a key is present. Using index[key] you default-construct a new value (in this case, you call bool(), and it gets printed as 0.) The newly constructed value also gets inserted into the map (i.e. index[key] is equal in this case to index.insert(std::make_pai... |
6,848,866 | 6,849,066 | Multiple compiler errors while trying to implement the observer pattern | I posted a question earlier on how to cast a member function to a typedef function pointer ( How to use a typedef function pointer to register a callback ) and it prompted me to consider a slightly modified solution by implementing the "classic" observer pattern.
I want to allow class A to notify observers who get a ca... | The only thing that you might not be able to fix easily just by reading the error messages is:
std::set<IObserver> observers;
This needs to be a collection of pointers. Making copies of the observer objects is almost certainly the wrong thing to do. Use
std::set<IObserver*> observers;
This will also fix the problem... |
6,848,955 | 6,849,687 | Can a GL_FLOAT texture be assigned to a FBO as a COLOR attachment? | For offscreen rendering to a texture, I'm attaching at the attachment GL_COLOR_ATTACHMENT0 a texture defined by
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_FLOAT,NULL);
I then render to the FBO using a fragment shader that outputs a vec4, so normally, that should be ok. To check that I display the ... | I know this question was self-answered, but a discussion need to be had about this:
glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,width,height,0,GL_RGBA,GL_FLOAT,NULL);
That does not create a floating-point texture. It creates a texture that contains normalized, unsigned integers.
The actual format of a texture is the third pa... |
6,848,959 | 6,848,981 | What is the scope of optimizations in a compiler? | When compiler optimizes code, what is the scope of the optimizations? Can an optimization
a) span more than a set of nested braces?
b) span more than a function?
c) span more than a file?
We are chasing an obscure bug that seems to derive from optimization. Code crashes in release mode but not debug mode. And of cour... | An optimization can do literally anything as long as it doesn't change the semantics of the behaviour defined by the language. That means the answers to your first questions (a), (b), and (c) are all yes. In practice, most compilers aren't that ambitious, but there are certainly some examples. Clang and LLVM have fla... |
6,849,092 | 6,849,104 | Error in Release mode but not in Build mode | I recently made a project using opencv and c++ in visual 2008
When i build the project in Debug mode - i don't face any issues - but when i build it in release mode i get the following errors:
1>test.obj : error LNK2001: unresolved external symbol _cvHaarDetectObjects
1>test.obj : error LNK2001: unresolved external sym... | Check Linker->Input->Additional Dependencies settings in the Release configuration ; you have undoubtedly forgotten to include the OpenCV libraries. Just copy-paste them from the Debug configuration, but don't forget to remove the d suffix.
E.g. cv210.lib : Release mode and cv210d.lib : Debug mode.
|
6,849,286 | 6,849,777 | C++: Confusion over function overloading and order of declaration | I realize that C++ inherited many requirements from C, and one of those is that the compiler won't recognize a global function unless it has previously encountered a prototype or definition for this function.
This also effects C++ function overloading. If there is more than one candidate for a function call, the "corr... | First, there's no need for the compiler to see a definition when it
practices overload resolution; a declaration suffices. Second, the
issue is a lot more complex than you seem to realize. In your function
template call_foo, foo is a dependent name, because it is used in a
context which depends on the instantiation t... |
6,849,287 | 6,849,456 | C++ Callback -- How to decouple the call back type | For example, in the following pseudo code, Class B need to call A::Action() through B::m_cb member.
The objective is, how to make a general, non-template Callback class, so "B" does not have to be a template, and the "CallBack" can hold any kind of function signature.
I ever use such code before, but now I can not find... | This doesn't really answer your question, because a callback has to be a template, unless you want to pass a parameter through void* (which is totally crazy idea in my opinion).
I asked a similar question : What is wrong with this variadic templates example?
One of answers gave a complete solution :
#include <memory... |
6,849,291 | 6,849,358 | Types of Declaring variables in C++ | If I have a structure called student
so what's the difference between these
Student& refFriend;
Student* ptrFriend;
Student valFriend;
|
First one is a reference type, you need to initialize it with an instance of Student. Once it refers to an instance, you cannot change it to refer to another instance. Its fixed.
Second one is a pointer to Student object. You can change the pointer to point to another Student object, and you can do this as many times ... |
6,849,426 | 6,849,703 | dialog context - how to save? | I'm wondering how to provide context for dialog procedures?
Up to now, I declare static or global variables to provide whatever context I need knowing that the dialog procedure can only be active one time. However, I find this pretty ugly and wonder if I can pass the context to the dialog procedure through the DialogB... | There are actually quite a few ways to store context for your window procedures, and dialogs are simply a special case of windows, so these techniques apply.
One way, as you mentioned, is to use GWLP_USERDATA/GetWindowLongPtr()/SetWindowLongPtr() to store a pointer to the dialog context. Note that the functions are pre... |
6,849,567 | 6,849,621 | Does copy constructor of the std::containers call contained copy constructors? | Does the copy constructor of any std::container (specifically std::queue) containing object pointers call the member's copy constructors to allow deep copies or does it perform a shallow copy on the pointer values?
Example:
/*******************************************************************************
* <summary>
*... | It performs a deep copy (on the contained object).
So all the contained elements are copied into the new container.
But since your container contains pointers,
std::queue<Event*> eventQueue;
it is only copying the pointer Event* (as this is the contained object). In this case the object that is pointed at by the con... |
6,849,685 | 6,849,704 | How can I store data in C++ and make the data searchable? | I'm working on an Address Book application in C++. I need to store the data and be able to retrieve it later. I know this requires serialization. I know how to serialize a simple map with a key and value.
I need to know how to store a lot of data, more than just one value. I will be storing: Name, Street Address, City,... | You might want to go with something like SQLite. It will allow you to store your data in an SQL database that you can query for whatever information you want out of it.
|
6,849,696 | 6,849,726 | using bigint class c++ | I am solving a problem where I need to deal with 120 digit binary numbers. there is no simple data type and I have understood I need to use bigint. I am using 64 bit win 7 HB and visual studio 2010 ultimate as my ide for c++.
Can any one explain how do I create variable of bigint and how do I perform functions of squa... | Use this library..
https://mattmccutchen.net/bigint/
and perform calculations as normal..
a = 12333333333333333333333333333333333;
cout << a * a;
|
6,849,921 | 6,849,979 | define assignment operator= that allows only zero rhs, otherwise won't compile | In short:
How do I define operator= for my class such that it compiles only if rhs is 0 (obj = 0)
but gives compilation error if rhs is non-0 value.
I know it is possible, forgot how.
Longer:
I have class C. I want to allow assignment obj = 0 for object of this class (which means, reset the object), but assignment from... | Use a pointer-to-member:
class foo
{
// Give it a meaningful name so that the error message is nice
struct rhs_must_be_zero {};
// The default operator= will still exist. If you want to
// disable it as well, make it private (and the copy constructor as well
// while we're at it).
foo(const fo... |
6,849,931 | 6,860,484 | Java JNIEnv Segmentation Fault | I'm in the process of doing some Java<->.NET interop code using a native library between them, so far things are going fairly well.
However for some reason I cannot run any methods under JNIEnv.
System::String^ JNIStringToNet(JNIEnv * env, jstring js)
{
const char *buf = env->GetStringUTFChars(js, 0); // segfault
... | Well I feel bad.
Native.loadLibrary == JNA.
System.loadLibrary == JNI.
The purpose of JNA is to not require any real knowledge of the JVM environment, so you can run native libraries as is, so instead of jstring you can use char*...
|
6,849,965 | 6,851,611 | C++ Simple Reflection without Macros: Print Variable Name and Its Value | Is there a non-macro way in C++ of printing a variable name with its value. Here is the macro way:
#define SHOW(a) std::cout << #a << ": " << (a) << std::endl
PS: I'm using Linux and do not need a cross-platform solution
| You can use dynamic symbols, but then it will only work in shared libraries or executables compiled with the -rdynamic flag. And it will recognize just global variables with default dynamic visibility.
#include <dlfcn.h>
#include <iostream>
int NameMe = 42;
const char *GetName(const void *ptr)
{
Dl_info info;
... |
6,850,009 | 6,850,131 | C++ Deleting Static Data | If I have a class that contains private static data allocated on the heap that never changes, when, if at all, should I delete it?
As I understand it, a class itself is never constructed (because classes aren't first class objects in C++) then there is no destructor to delete the static data in? Im new at C++ so sorry... | If the data is static, it isn't allocated on the heap, and it will be
destructed during the shutdown of the process.
If it is a pointer to the data which is static, e.g.:
Something* MyClass::aPointer = new Something;
then like all other dynamically allocated data, it will only be
destructed when you delete it. There ... |
6,850,148 | 6,850,517 | How to convert the string "0xAp-2" to double of 2.5, using a std library function | I have a string containing "0xAp-2". I want to convert that to a double value:
#include <iostream>
#include <cstdio>
int main()
{
char array[] = "0xAp-2";
double a;
sscanf(array, "%lf", &a);
std::cout << a << "\n";
}
I've tried both atof and sscanf, and can't get it to work. I apologize if the answ... | I believe the strtod function should be able to parse binary scientific notation.
|
6,850,149 | 6,850,188 | Substitution failure is not an error (SFINAE) question with static_cast | Given:
class Hokey
{
public:
explicit C(int i): i_(i) { }
template<typename T>
T& render(T& t) { t = static_cast<T>(i_); return t; }
private:
unsigned i_;
};
If I try:
Hokey h(1);
string s;
h.render(s);
Codepad gives me an error on the static cast:
t.cpp: In member function 'T& Hokey::render(T&) [wi... | It's only not an error during overload resolution. In other words, it puts off giving you an error until it's sure the call definitely isn't going to work. After that, it's an error.
struct example
{
template <typename T>
static void pass_test(typename T::inner_type); // A
template <typename T>
static ... |
6,850,246 | 6,850,298 | ifstream's operator>> to detect end of line? | I have an irregular list where the data look like this:
[Number] [Number]
[Number] [Number] [Number]
[Number] [Number] [Number]
[Number] [Number] [Number]
[Number] [Number] [Number]
[...]
Notice that some lines have 2 numbers, some have 3 numbers.
Currently I have my input code look like these
inputFile >> a >> ... | Use getline and then parse each line seprately:
#include <iostream>
#include <sstream>
#include <string>
int main()
{
std::string line;
while(std::getline(std::cin, line))
{
std::stringstream linestream(line);
int a;
int b;
int c;
if (linestream >> a >> b >> c)
... |
6,850,348 | 6,850,441 | How can I have the effect of default parameter with variadic template | I am hitting this problem for some time now and I can't figure out how to solve it. The context is a reflection system in c++. A slim down explication of the problem is this. I have those 2 structs. One is to represent multiple parents of the type ClassType and the other would represent and Orphan class (a class of Cla... | The GCC preprocessor allows for a special syntax that elides the final comma in a variadic macro argument list if the list is empty:
#define MACRO(arg, ...) foo(arg, ##__VA_ARGS__)
This exapands:
MACRO(a,b) -> foo(a, b)
MACRO(a) -> foo(a )
You can use this for your DEFINE_METACLASS macro to cover all cases at... |
6,850,543 | 6,850,596 | stdvector inserting and erasing problem | I need to control the amount to touch points in my application, for this I am using a vector container and my basic setup is this:
//--------------------------------------------------------------
void testApp::touchDown(ofTouchEventArgs &touch){
isTouching = true;
touchPoints.push_back( ofVec2f( touch.x, touch... | Many things: First off, you cannot modify (erase/insert) a container and expect iterators to remain valid!
Let's see. I want to modify touchMove as well:
void testApp::touchMoved(const ofTouchEventArgs & touch)
{
if (touch.id < touchPoints.size())
touchPoints[touch.id] = ofVec2f(touch.x, touch.y);
}
Next, the bi... |
6,850,751 | 6,854,379 | XAudio2 in Qt Creator | I'm currently working on an audio project with XAudio2 and I've been using MSVC++ Express 2010. I wrote some basic functionalities, and I thought I'd try making a UI with Qt, so I followed the steps to be able to use Qt in my version of MSVC:
Download the Qt source code
Compile everything in MSVC with the cmd prompt
C... | Well, I found my answer, but it was a hard one. So, 8 hours later, here it is. CoInitializeEx initializes a COM library for use by the calling thread, and some other stuff...
CoInitializeEx Function Reference
The following link explains how to use COM objects with Qt.
Using COM objects in Qt
Basically, you add
CONFIG +... |
6,850,807 | 6,851,008 | Why is valarray so slow? | I am trying to use valarray since it is much like MATLAB while operating vector and matrices. I first did some performance check and found that valarray cannot achieve the performance declared as in the book C++ programming language by Stroustrup.
The test program actually did 5 million multiplication of doubles. I tho... | I suspect that the reason c = a*b is so much slower than performing the operations an element at a time is that the
template<class T> valarray<T> operator*
(const valarray<T>&, const valarray<T>&);
operator must allocate memory to put the result into, then returns that by value.
Even if a "swaptimization" is used... |
6,850,998 | 6,851,084 | STL and TR1 on mobile devices | I'm newbie in developing apps for smartphones, but have lots of experience writing desktop applications using STL and TR1.
Is it possible to use these libraries when developing using:
Official iOS development tools
Android NDK
Marmalade (former Airplay SDK)
| The C++03 STL is available on both iOS and the Android NDK. Much of TR1 is also available for both, as they both use GCC 4.x.
I'm not familiar with Marmalade.
|
6,851,026 | 6,851,174 | Why can't auto be used as a template type parameter? | I've been playing around with C++0x's auto keyword and tried the following.
std::unique_ptr<auto> ptr(new int(0));
I tried compiling it with g++ 4.4.5 and got
error: invalid use of auto
Judging by eye, auto can easily be inferred to int.
My guess is the type inference and the template engine don't talk to each other.... | @dascandy has correctly identified what's wrong with your code. I'll try to provide some rationale:
You're expecting the compiler to infer unique_ptr<int> because the argument is an int*, and unique_ptr<int> has a constructor which accepts int*. For a moment let's ignore the fact that we're using std::unique_ptr, and... |
6,851,060 | 6,877,261 | Create SQLite Database in Qt (C++) | I'm trying to create a SQLite database in Qt. This is the code that I have:
#include <QtCore/QCoreApplication>
#include <QtSql/QSqlDatabase>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("C:\\Users\\Tanner\\Des... | After not getting it to work, I checked with the Qt Community Forum and it seems that all I was missing was
QT += sql
in the .pro file
Here is the forum post: http://developer.qt.nokia.com/forums/viewthread/8262/
|
6,851,275 | 6,859,363 | Unable to define a rule in Spirit:: Qi | I am trying to parse a Unix file path into pairs of folders(key/value pairs - as needed by my application). The problem is I am unable to define parsers using qi::rule correctly. I get pages of compiler errors which I am unable to understand completely (Sorry if the question sounds simple but I am really stuck and unab... | After adding these #include's your program above compiles fine for me (Boost V1.47):
#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix.hpp>
#include <boost/fusion/include/std_pair.hpp>
Please note that there have been quite some implementation changes to Spirit in this (newest) version, whi... |
6,851,339 | 6,852,049 | When calling ReadDirectoryChangesW, only the first call returns any changes (both sync and async) | The following is a minimal program which uses ReadDirectoryChangesW. The problem I am having is that only the first call to GetQueuedCompletionStatus returns. The second time through the loop it blocks forever no matter how many changes are made to the directory.
I have also attempted using the synchronous version and ... | A few problems.
First, you're trying to output multi-byte string literals to wcout. You should turn them into wide strings by prepending L.
Second, the FileNameLength variable represents the length of the name in bytes, not characters. You should divide it by 2 to get the number of characters.
|
6,851,436 | 6,851,455 | Difference between const char*, char const*, const char const* & string storage | First of all, what's the difference between:
(1) const char*
(2) char const*
(3) const char const*
I'm fairly certain I understand this fully, but I'd like someone to give me a sentence for each, specifically, so it sticks in my head. It's one of those things that I'm fine with until someone puts me on the spot and t... | 1 and 2 are equivalent, and specify the type of a pointer to a const char. The pointer itself is not const. 3 is invalid, because it repeats "const". It's like saying const const int. The order is not relevant, so it's also like saying int const int.
In C99 it is valid to repeat const like that. But in C++, you cannot... |
6,851,628 | 6,852,033 | Using Rotation and Translation Matrix in OpenCV | What I am trying to do is overlay the image from the right camera to the image from the left camera. To do this, I think have to fine the rotation and translation matrix for the right camera with respect to the left camera. Then I would apply the translation and rotation matrix to the image on the right camera?
Assumin... | What you are trying to do is called image rectification.
In a nut shell you need to find the Fundamental matrix relating the two cameras and then compute rectifying homographies to project the images into the same plane.
See this question and answer for an overview with a bit more detail.
|
6,851,738 | 6,851,802 | Specialize function template result | I'm pretty new to template metaprogramming and can't find my thinking error in this approach:
template <typename T>
typename T::ReturnType Query(const std::string& Str);
template <>
ResultTypeRowCount Query(const std::string& Str) { return this->queryRowCount(Str); }
ResultTypeRowCount implements a public typedef... | It should be:
template <>
ResultTypeRowCount::ReturnType Query<ResultTypeRowCount>(const std::string& Str) { return this->queryRowCount(Str); }
|
6,851,893 | 6,851,924 | Template function causes a compiler error when used with local lambda | My previous question concluded that a distasteful "double cast" might be necessary to use the POSIX makecontext with a C++ lambda function (i.e. function object). Moving on, I'm now faced with a compilation error relating to the following minimal code:
#include <iostream>
#include <ucontext.h>
using namespace std;
te... | If you use [=] to induce your lambda, you will not get a function pointer (or an object that is convertible to one). You will get a function object. And no amount of casting is going to allow you to pass that to makecontext. Not in any way that actually works.
According to N3291, the most recent working draft of C++0x:... |
6,852,462 | 6,852,540 | How to pass a method as parameter? | Having this class :
class Automat
{
private:
// some members ...
public:
Automat();
~Automat();
void addQ(string& newQ) ;
void addCharacter(char& newChar) ;
void addLamda(Lamda& newLamda) ;
void setStartSituation(string& startQ) ;
void addAccQ(string& newQ) ;
bool checkWord(stri... | What you try to do is usually known as closure, a concept strong in functional programming. Rather than reinventing the wheel, I suggest you look into Boost::Phoenix, which provides this in a nice, peer reviewed library.
http://www.boost.org/doc/libs/1_47_0/libs/phoenix/doc/html/index.html
However, since C++ is a stati... |
6,852,490 | 6,852,839 | What does RtlInitializeExceptionChain do, and how can I reduce its execution overhead? | I am trying to find bottlenecks in my program (currently in the "low-hanging fruit" stage), and using a profiler I get something like the following:
The thing I see in this is that RtlInitializeExceptionChain takes up the far majority of the time, and functions from my actual program don't even make it onto this top l... | RtlInitializeExceptionChain is an internal function in the Run-Time Library, a collection of kernel-mode support functions used by kernel-mode drivers and the OS itself. It's kind of the kernel-mode version of the C run-time library.
If your application is 32-bit and you're profiling it on a 64-bit machine, profiling ... |
6,852,522 | 6,852,643 | C/C++ Rarer keywords - register, volatile, extern, explicit | Can you give me a quick runthrough of what these 4 keywords are used for and why?
I understand the basics that google would tell you on register and volatile, but would like to know a little more (just a practical overview). Extern and explicit confuse me a little as I've never found a reason to have to use them mysel... | extern
extern is overloaded for several uses. For global variables, it means that it is declaring the variable, not defining it. This is useful for putting global variables in headers. If you put this in a header:
int someInteger;
Each .cpp file that includes that header would try to have its own someInteger. That wil... |
6,852,524 | 6,853,008 | How to do a "try_lock" with an "upgrade_to_unique_lock" | I want to perform an upgrade_to_unique_lock on an upgrade_lock without blocking but a cursory look at the Boost source code (v1.46.1) shows that this is impossible? Is my approach wrong?
I want to first obtain a read lock on a resource that can also potentially be held for reading by other threads. Then I want to s... | Straw man answer. I'm pretty sure this isn't a valid answer. But I can't put it in a comment because of formatting concerns.
To generate the center tile I would be tempted to do something like this:
tile::generate_center()
{
tile& north = ...;
tile& east = ...;
tile& south = ...;
tile& west = ...;
... |
6,852,670 | 6,852,924 | How to write fast (low level) code? | I would like to learn more about low level code optimization, and how to take advantage of the underlying machine architecture. I am looking for good pointers on where to read about this topic.
More details:
I am interested in optimization in the context of scientific computing (which is a lot of number crunching but ... | Drepper's What Every Programmer Should Know About Memory [pdf] is a good reference to one aspect of low-level optimisation.
|
6,852,678 | 6,854,738 | Template Friend for Superclass | I have a non-templatized class (Par_list_elem), and I would like to give access to its internals to the class Par_list (to build an intrusive list).
The catch: I need Par_list_elem and all of its subclasses to be accessible to Par_list. In detail, the only fields that need to be accessible are _next and _prev; explicit... | The problem is that you're inheriting privately from Par_list_elem. So, although Par_list can access private members of the base class, it cannot access the base class itself.
I need Par_list_elem and all of its subclasses to be accessible to Par_list.
This would solve the problem if it were possible, but it can't be... |
6,852,717 | 6,852,734 | What can a 'const' method change? | C++ methods allow a const qualifier to indicate that the object is not changed by the method. But what does that mean? Eg. if the instance variables are pointers, does it mean that the pointers are not changed, or also that the memory to which they point is not changed?
Concretely, here is a minimal example class
class... | Most succinctly, it means that the type of this is const T * inside const member functions, where T is your class, while in unqualified functions it is T *.
Your method set does not change data, so it can be qualified as const. In other words, myclass::data is accessed as this->data and is of type int * const.
|
6,852,794 | 6,852,854 | C++ communicate across processes | I have a dll that is loaded into multiple processes.
What would be a clean way to have communication across those processes/dlls.
Sending simple strings is the goal.
I would prefer to avoid sendmessage, file io, and sending the address of the string command.
| I would look into shared memory. There's a nice example on MSDN.
Keep in mind that just like when using threads in the same process, access to shared memory is not serialized. You'll need some form of synchronization (e.g. a named mutex) to serialize access to the memory block.
|
6,852,920 | 6,852,934 | How do I turn a macro into a string using cpp? | GNU's cpp allows you to turn macro parameters into strings like so
#define STR(x) #x
Then, STR(hi) is substituted with "hi"
But how do you turn a macro (not a macro parameter) into a string?
Say I have a macro CONSTANT with some value e.g.
#define CONSTANT 42
This doesn't work: STR(CONSTANT). This yields "CONSTANT" w... | The trick is to define a new macro which calls STR.
#define STR(str) #str
#define STRING(str) STR(str)
Then STRING(CONSTANT) yields "42" as desired.
|
6,853,592 | 7,227,165 | Error compiling testOnDemandRTSPServer.cpp (From the Live555 libraries) | I'm trying to figure out how to compile testOnDemandRTSPServer.cpp as found in the testProgs directory from the live555 media server source. I am using Ubuntu 11.04 and have installed the liblivemedia-dev libraries.
I have modified the header includes (within testOnDemandRTSPServer.cpp), to:
#include <liveMedia/liveMed... | The Answer
By not using the Ubuntu Packaged libraries at all... But by just compiling the source code from the Live555 website.
In a custom Makefile, this is the structure I used to compile my own program and the testOnDemandRTSPServer:
LIVE_INCLUDES=-I../UsageEnvironment/include -I../groupsock/include -I../liveMedia/i... |
6,853,691 | 6,853,732 | What does #ifdef 1 in C++ | in C++, I know that programmers use #ifdef 0 to block out code from running, but in this same project I see a lot of #ifdef 1. Does this mean that the code always runs? Unfortunately the code does not compile so I can't just run and test!
| #ifdef 1 is ill-formed. The #ifdef directive requires a single identifier; 1 is not an identifier.
#ifdef x is equivalent to #if defined(x). The defined preprocessing operator yields true if the identifier names a defined macro (i.e., a macro that has been defined with #define and not yet undefined via #undef) and fa... |
6,853,704 | 6,854,419 | Stop bell sound on keypress in dialog box | win32 api:
So when one of my dialog boxes has focus, I press 'a' and then do some stuff in the WM_KEYDOWN message, and then it gives the bell/warning sound. Is there someway to suppress this?
| It seems I needed to add a:
HANDLE_MSG(hWnd, WM_GETDLGCODE, Dlg_YOURPROC_OnGetDlgCode);
to the dialog and then in the Dlg_YOURPROC_OnGetDlgCode you need to return DLGC_WANTCHARS:
UINT Dlg_YOURPROC_OnGetDlgCode(HWND hwnd, LPMSG lpmsg)
{
return DLGC_WANTCHARS;
}
Not sure why I was downvoted for my question, I seem... |
6,853,751 | 6,853,772 | What's wrong with my macro function? | I defined a multi-line macro function using line continuation character "\" like the following:
#define SHOWMSG( msg ) \
{ \
std::ostringstream os; \
os << msg; \
throw CMyException( os.str(), __LINE__, __FILE__ ); \
}
But it could not pass compilation. BTW, I'm using VS2008 compiler. Woul... | The usual method for a multi-statement macro is something like:
#define SHOWMSG(msg) \
do { \
std::ostringstream os; \
os << msg; \
throw CMyException(os.str(),... |
6,853,825 | 6,854,435 | Is there a random access container type that accepts a prefilled & preallocated buffer? | I'm about to write something myself since I didn't find what I was looking for, but figured I should ask the crowd before diving in.
Is there a boost or stl random access container type that allows passing in of prefilled buffer?
The imaginary(?) container type would operate something like this:
const int blobSize ... | Going from Dennis Zickenfoose's comment, I looked up Boost.range seems to offer the perfect solution:
#include <boost/range.hpp>
#include <boost/foreach.hpp>
#include <iostream>
int main()
{
const int blobSize = 100;
int blob[blobSize];
for( int i = 0; i < blobSize; ++i )
blob[i] = i;
... |
6,854,039 | 6,854,105 | Correct Way to Define a Predicate Function in C++ | I'm trying to write predicate function for use with STL algorithms. I see that they are two ways to define a predicate:
(1) Use a simple function as below:
bool isEven(unsigned int i)
{ return (i%2 == 0); }
std::find_if(itBegin, itEnd, isEven);
(2) Use the operator() function as below:
class checker {
publ... | I guess it's because the type of c.isEven() is,
bool (checker::*)(unsigned int) // member function of class
which may not be expected by find_if(). std::find_if should be expecting either a function pointer (bool (*)(unsigned int)) or a function object.
Edit: Another constraint: A non-static member function pointer mu... |
6,854,765 | 6,854,884 | Refactoring legacy C code into MVC design | I am working on some OLD (as in older than me) C code that needs to be cleaned up and brought up to date so that (amongst other things), it is easier to maintain and integrates more cleanly with current code.
The existing code is quite messy, and freely intersperses GUI logic with business logic and data access logic. ... | I'm not convinced that there can be a definitive set of steps, what we do will vary with the structure of the existing code.
I agree with @Jesus Ramos that figuring out a test strategy is key here. The problem for you is likely to be that the code is currently not unit-testable, because there are effectively no "units"... |
6,854,799 | 6,858,199 | Error in linking files into a kernel | I have problem. I have compiled file boot.o:
[BITS 16]
[ORG 0x7C00]
[global start]
[extern _main]
start:
call _main
cli
hlt
and compiled C++ file main.o:
int main(){
//processes
}
Im using this LD file linker.ld for linking:
OUTPUT_FORMAT("binary")
ENTRY(start)
SECTIONS
{
. = 0x100000;
.text ALIGN(4096) :
{
... | Maybe -oformat bin?
And I doubt you will be able to boot it, anyway... Go read some bootloader tutorials (on osdev.org and brokenthorn.com) and you will get an answer why.
|
6,854,805 | 6,854,999 | Search in vector<std::pair<int, vector<int> > > | I would like to search within a vector<std::pair<int, vector<int> > >. This won't work due to the vector parameters:
std::vector<std::pair<int, std::vector<int> > > myVec;
iterator = find(myVec.begin(), myVec.end(), i);
Search would be on the first std::pair template parameter (int), in order to get the vector associa... | You could make do with the following (pretty ugly) functoid:
struct FindFirst {
FindFirst(int i) : toFind(i) { }
int toFind;
bool operator()
( const std::pair<int, std::vector<int> > &p ) {
return p.first==toFind;
}
};
using it like this ( I couldn't get bind2nd to work - that's wh... |
6,855,101 | 6,873,472 | Apple GCC 4.2.1 passing a pointer to constructor | Let's say I have a class and there are no visible problems with it or its members, however if I try to pass the addresses of several class members to another class in the same module, the first argument is being passed correctly, but the second one is always NULL! How can this be? Could there be some kind of hidden sta... | Blasted GCC... :doubleFacePalm I wasn't able to solve this problem normally, but I found a workaround by passing all class constructor data in a structure aligned by 16 bytes boundary.
|
6,855,115 | 6,855,151 | Byte array to int in C++ | Would the following be the most efficient way to get an int16 (short) value from a byte array?
inline __int16* ReadINT16(unsigned char* ByteArray,__int32 Offset){
return (__int16*)&ByteArray[Offset];
};
If the byte array contains a dump of the bytes in the same endian format as the machine, this code is being call... | It depends on what you mean by "efficient", but note that in some architectures this method will fail if Offset is odd, since the resulting 16 bit int will be misaligned and you will get an exception when you subsequently try to access it. You should only use this method if you can guarantee that Offset is even, e.g.
i... |
6,855,149 | 9,651,803 | Are trigraph substitutions reverted when a raw string is created through concatenation? | It's pretty common to use macros and token concatenation to switch between wide and narrow strings at compile time.
#define _T(x) L##x
const wchar_t *wide1 = _T("hello");
const wchar_t *wide2 = L"hello";
And in C++11 it should be valid to concoct a similar thing with raw strings:
#define RAW(x) R##x
const char *raw1 =... | No, the trigraph is not reverted in your example.
[lex.phases]p1 identifies three phases of translation relevant to your question:
1. Trigraph sequences are replaced by corresponding single-character internal representations.
3. The source file is decomposed into preprocessing tokens.
4. Macro invocations are expa... |
6,855,409 | 6,855,471 | Argument dependant Name Lookup in C++ : point from n3290 Draft | A point from ISO C++ DRAFT n3290 :Argument dependant Name Lookup : section 3.4.2, para 2,
For each argument type T in the function call, there is a set of zero or more
associated namespaces and a set of zero or more associated classes to be
considered. The sets of namespaces and classes is determined entirely... | The fundamental types, like int and char, are not defined in any namespace or class. That's why their list of associations will be empty.
If the function parameters are types created from a template, not only the namespace of this template is considered, but also the namespaces of its template parameters. For example i... |
6,855,465 | 6,855,543 | Weak reference to a scoped_ptr? | Generally I follow the Google style guide, which I feel aligns nicely with the way I see things. I also, almost exclusively, use boost::scoped_ptr so that only a single manager has ownership of a particular object. I then pass around naked pointers, the idea being that my projects are structured such that the manager... |
2. Is there a better way, that still meets my single ownership goal?
Do use a shared_ptr, but as a class member so that it's part of the invariant of that class and the public interface only exposes a way to obtain a weak_ptr.
Of course, pathological code can then retain their own shared_ptr from that weak_ptr for a... |
6,855,686 | 6,855,742 | What is the difference between static_cast and reinterpret_cast? |
Possible Duplicate:
When should static_cast, dynamic_cast and reinterpret_cast be used?
I'm using c function in c++, where a structure passed as a void type argument in c is directly stored that same structure type.
eg in C.
void getdata(void *data){
Testitem *ti=data;//Testitem is of struct type.
}
to do the s... | A static_cast is a cast from one type to another that (intuitively) is a cast that could under some circumstance succeed and be meaningful in the absence of a dangerous cast. For example, you can static_cast a void* to an int*, since the void* might actually point at an int*, or an int to a char, since such a conversi... |
6,855,688 | 6,855,958 | Detecting IP addresses of network cards and ethernet devices with Windows API | I am using the Microsoft code here to learn how to detect IP addresses of cards and devices:
http://msdn.microsoft.com/en-us/library/aa365949%28v=VS.85%29.aspx
I notice some strange behavior.
I have a system with two ethernet cards; one is connected to the internet and one is connected to an ethernet device. When I ru... | That address of 127.0.0.1 is not the address of the other card. It is the address of the loopback adapter - a virtual IP address that can only send and receive data with itself. The other NIC (that isn't plugged into a network) is simply not in the address table.
You may just want to call GetAdapterAddresses and fil... |
6,855,701 | 6,855,733 | Problem in understanding pointer to an Object set to NULL | Can any one explain what does it mean by making an pointer to an object to NULL?
When we assign ptr to an object to NULL, how can we still access the member function?
class A
{
public:
void print()
{
cout<<"Hello";
}
}
int main()
{
A * a;
A* b = NULL;
a->print();
b->print();
}
EDI... | The pointer is used for accessing the members of that object. If your function(s) don't need to access any members and are not virtual, they actually don't use the object. The code is still strictly speaking invalid, but it won't crash.
If you replace the contents with printing the "this" pointer, it'll still work as y... |
6,855,825 | 6,856,049 | Embedded Linux for Mobile Development and Set top Box Application | I am exploring on Embedded Linux for Mobile Development and Set top Box Application.
I need to do some R/D on Embedded Linux.
I found BusyBox is good for Set Top Box and Maemo for Mobile Development.
I wanted to know is there any Embedded Linux Distribution (open Source/free) which can be used for both Mobile Develop... | I'm not sure you understand the words you wrote. Set top box is a type of hardware, there are many of those being manufactured, each needs its own stack of software (at least the hardware porting layer, the drivers and the bootstrap). On top of the hardware-dependent stack you can put the BusyBox utilities or Maemo, or... |
6,855,888 | 7,144,037 | How to print a CStringList in c++ using cout | I am new to C++. I was just going through some code and got this doubt.
The code had some CStringList defined somewhere. I wanted to print that to a file. So I wrote the below code
CStringList *stringListDev;
.....
.....
.....
.....
ofstream myfile("example.txt");
for(int i=0; i<stringListDev->Count; i++)
{
... | I got it myself. The code was very simple
CStringList *stringListDev;
.....
.....
.....
.....
ofstream myfile("example.txt");
for(int i=0; i<stringListDev->Count; i++)
{
myfile << stringListDev->Strings[i];
}
Thanks for all your responses!! You people rock !!
|
6,855,913 | 6,856,471 | Texture Array, creating the texture | I'm working on a section of someone else's code and hence have been limited to the amount of modification I can do. Anyway, I'm currently trying to create a texture array and have become stuck with a problem:
What I need to support is n textures being individually loaded and stored as GLubytes in a vector. I then need ... | If I understand your problem correctly you need to use std::copy. Something along the lines of std::copy(*vecPixelData[i], *vecPixelData[i] + imageSize, puData + offstet) (leaving the calculations of imageSize and offset to you) inside your last for loop.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.