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
7,337,646
7,338,333
Concurrent receiveing/sending from/to one sender/receiver
I wonder if it is possible to concurrent receive the message from one sender, and other way round to concurrent sent to one receiver. And if yes how it will behave? To make the question more clarified let imagine we have 4 threads, each of them is listening on message from the same source MPI_Recv(buf, count, type, THE...
Receives are processed in the order they are registered. There is never an "at the same time" situation, since they are synchronised. Description of Point-To-Point Communication Semantics So, in your first circumstance, this means that the one send that happens when four threads are waiting to receive will be sent to ...
7,337,697
7,337,739
for(int i=0;i<myVector.size();++i) How many times is size() called?
If i have a myVector which is a STL vector and execute a loop like this: for(int i=0;i<myVector.size();++i) { ... } Does the C++ compiler play some trick to call size() only once, or it will be called size()+1 times? I am little confused, can anyone help?
Logically, myVector.size() will be called each time the loop is iterated - or at least the compiler must produce code as if it's called each time. If the optimizer can determine that the size of the vector will not change in the body of the loop, it could hoist the call to size() outside the loop. Note that usually, v...
7,337,832
7,337,962
NULL passed directly to a function expecting a const reference parameter (VC++ 4.2)
I am looking at something that I discovered in an old code base, and I am pretty confused. Here is a function definition: void vUpdateSequenceDetailsAndIncrement( const CallEvent& roCPEvent, const CallInfo& roCallInfo, BOOL bCreationEvent); Here it is being called: vUpdateSequenceDe...
Depends on how NULL is defined in VC 4.2 If it is just #define NULL 0 then you are actually getting this under the hood: vUpdateSequenceDetailsAndIncrement(roCPEvent, CallInfo(0), FALSE); and reference of temp var of type CallInfo is passed to the function (if CallInfo has compatible ctor)
7,337,837
7,337,884
Segmentation fault, can you help me?
Im getting a segmentation fault when trying to display an element of type (int) template <class T> void Lista<T>::imprimir() { NodoL *ptr = new NodoL; ptr->sig = pri->sig; cout << *ptr->sig->elem; //THIS DISPLAYS CORRECTLY cout << *ptr->sig->sig->elem; //SEGMENTATION FAULT }
Are you sure sig is not NULL ? template <class T> void Lista<T>::imprimir() { NodoL *ptr = new NodoL; ptr->sig = pri->sig; cout << *ptr->sig->elem; //THIS DISPLAYS CORRECTLY if(ptr->sig == NULL || ptr->sig->sig == NULL) return; cout << *ptr->sig->sig->elem; //SEGMENTATION FAULT }
7,337,903
7,337,920
OpenMP - Running parallel code inside parallel code
I have a function compute() that has parallelized matrix multiplication inside of it using OpenMP #pragma omp parallel for This function is called many times in a loop - which I would like to run in parallel. Will there be any issues in running parallel code inside other parallel code? This is c++ compiled on Ubuntu.
It will work fine, but you'll need to enable OpenMP nesting for it to work. Call omp_set_nested(1); at the start of the program and it will allow you to have nested parallel regions. However: Be aware, that you could end up running many more threads than what you want. So you will want to limit the # of threads of bot...
7,337,922
7,337,974
Why isn't my program displaying the integer I'm outputting?
#include<iostream> #include<string> using namespace std; int main() { int i; cout<<"enter ur no. plz"; cin>>i; cout<<"ur no. is:"<<i; cin.get(); return 0; } This code is not displaying the integer I entered. It returns back after entering an integer and hitting enter. I...
After the user enters the integer, there is still a newline character left in the input buffer. cin.get() reads that character, then the program immediately ends. You could put an additional call to get if you want the program to stay open. Or, before the call to get, you could have a call to ignore: std::cin.ignore...
7,337,966
7,338,875
How to create a generic network proxy using Python or C++?
I have an application which communicates over the local area network. However, I want to instead make it communicate over the internet. To do this I propose making an intermediate program which will read the network traffic generated from the application on one computer and send it to the application on another compute...
The term you are missing in your original question is proxy. You specifically need a transparent forwarding proxy. Here is a link to some source code in Python that will get you started with writing a proxy. That said, if you search around you should be able to find a transparent forwarding proxy that you don't have to...
7,338,028
7,338,079
How to debug template arguments at compile-time?
I have a piece of code that pretty much reduces down to: template<class T> struct MyStruct; // No definition by default template<class T> struct MyStruct<T *> { ... }; // Specialization for pointers Now somewhere in my code, I'm getting an instantiation of MyStruct<T> that happens to be undefined (no C++0x/011, no B...
I believe you're using MSVC++, if so, then see the output window, it might have more info printed, especially the line number along with the filename. Once you know the file and line number, you can start from there. Output window usually prints everything, like how and with what template argument(s), a template is ins...
7,338,045
7,444,379
Why istream::getline() returns so many times (with nothing)
I am trying to read a poorly formatted text file, and maybe I'm going about this the wrong way, but based on the getline documentation it sounded like it would pull values until the values weren't a delimiter value (' ', in my case): "If the delimiter is found, it is extracted and discarded, i.e. it is not stored an...
I think the output text file I was reading from had trailing spaces and they were just being put into the stream so I was really confused about what was going on. I simply used .str("") at the end of each line to reset my current stream and things worked out marvelously. Thanks for all the help guys.
7,338,071
7,338,237
istream_iterator ignoring EOF (Ctrl+D) when reading chars
I'm trying to use istream_iterator for reading characters from cin. I've read that pressing Ctrl+D sends an EOF character which ends the input stream. Unfortunately, something is going wrong with it. Here's my code: #include <iterator> int main() { using namespace std; istream_iterator<char> it(cin), eos; while ...
Input iterators require special care. Rewrite your loop this way and the behavior will become similar to any other character input loop: while (it != eos) { clog << *it; it++; } That will take care of "Why it doesn't print the last character" PS: as for EOF in the middle of the line, it is the POSIX-mandated b...
7,338,170
9,338,574
"Retroactive Union" - can it be done?
I've got two classes: a template class, and a regular class that inherits from it: template <int N> class Vector { float data[N]; //etc. (math, mostly) }; class Vector3 : public Vector<3> { //Vector3-specific stuff, like the cross product }; Now, I'd like to have x/y/z member variables in the child class ...
To finish off an old question: No. It makes me sad, but you can't do it. You can get close. Things like: Vector3.x() = 42; or Vector3.x(42); or Vector3.n.x = 42; or even Vector3.x = 42; //At the expense of almost quadrupling the size of Vector3! are within reach (see the other answers - they're all very good). ...
7,338,338
7,340,373
C++ mq_receive EMSGSIZE problem
I'm trying to send message "test" with mqueue, but message receiving fails with EMSGSIZE. Code: #include <iostream> #include <cstdio> #include <cstdlib> #include <ctime> #include <cstring> #include <sys/types.h> #include <sys/wait.h> #include <mqueue.h> #include <errno.h> using namespace std; int main() { mqd_t mqdes...
From The mq_receive page [EMSGSIZE] The specified message buffer size, msg_len, is less than the message size attribute of the message queue. Most likely the message buffer is too small to contain the complete message. char* buf; cout << mq_receive(mqdes, buf, 8, NULL) << endl; should be something like char buf[1024]...
7,338,340
12,938,049
is GCC STL thread-safe?
I found contradictory information on the web: http://www.sgi.com/tech/stl/thread_safety.html The SGI implementation of STL is thread-safe only in the sense that simultaneous accesses to distinct containers are safe, and simultaneous read accesses to to shared containers are safe. If multiple threads access a sin...
FWIW I updated the libstdc++ docs a while ago, it now says (emphasis mine): The user code must guard against concurrent function calls which access any particular library object's state when one or more of those accesses modifies the state.
7,338,506
7,338,522
Member function returning a static variable
Should a member function that returns a static member variable also be static? For instance: struct T { static int i; static int getNumber() { return i; } }; Should getNumber be static or not?
Usually, yes. If the variable doesn't have any per-instance state, then what possible per-instance logic could the function perform on it before returning it?
7,338,573
7,340,881
Scale values from a smaller array into a bigger array
I have an array, whose size is 256. This array has elements which are in 0 to 1 range. Now, i need an array whose size should be 65536, where each element should be interpolated or scaled from the original array of 256 values. I asked in another thread, but i wasnt clear enough :( Some kind of mapping where, lets say, ...
Disclaimer: My C++ isn't so great these days. This will look something more like Java. I'm assuming you weren't planning on copying and pasting anyway: knowing the algorithm is much more important then the implementation language. The following algorithm does NOT make 65536 entries for a 256 entry input. Instead, it ma...
7,338,633
7,338,686
Namespace 'cmb1' causes C++ compilation error
When I try to compile this code: #include <windows.h> namespace cmb1 { } void main() {} I get this: Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.762 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. a.cc a.cc(3) : error C2059: syntax error : 'constant' a.cc(3) : error C2143: ...
from windows.h: #define cmb1 0x470 #define cmb2 0x471 #define cmb3 0x472 #define cmb4 0x473 #define cmb5 0x474 #define cmb6 0x475 #define cmb7 0x476 #define cmb8 0x477 #define cmb9 0x478 #define cmb10 0x479 #define cmb11 0x47A #define cmb12 0x47B #define cmb13 0x47C #define cmb14 0x47D #define cmb15 0x47E #define cmb16...
7,338,886
7,339,007
Function that polymorphically handles vector and hash_set
I have function in C++ that takes a vector and pushes some items onto it. For example: void MyFunction(vector<int>* output); I want to modify it to be able to now take a vector or a hash_set. In Java, this would be easy, simply change the function to take a Collection (the common interface). All MyFunction does is p...
He'd have a small issue doing a straight-up template. Vector typically uses push_back while hash_set would use insert. Use a template, but use the insert function and insert at the .end() element so that the vector maintains fast operations - its your best bet. You'll still slow down your hash-set a little though if i...
7,339,105
7,339,204
Appropriate image file format for losslessly compressing series of screenshots
I am building an application which takes a great many number of screenshots during the process of "recording" operations performed by the user on the windows desktop. For obvious reasons I'd like to store this data in as efficient a manner as possible. At first I thought about using the PNG format to get this done. B...
If you have access to a PNG compression implementation, you could easily optimize the compression without having to use the MNG format by just preprocessing the "next" image as a difference with the previous one. This is naive but effective if the screenshots don't change much, and compression of "almost empty" PNGs wi...
7,339,183
7,340,020
Can't open text file resource in Xcode 4 c++ tool?
I am working on figuring out how to use Xcode 4 to debug c++ projects. I have basically copy pasted a working c++ executable that when compiled from the terminal ran fine. However, i was thinking it might be nice to use Xcode for debugging. So I am trying to migrate the single .cpp file into Xcode as a command line to...
The executable built by Xcode is in a different folder than the project. Passing in the name of the file without an absolute path before it will cause the executable to look for it in the wrong place, which is why it can't be found. Some of the possible solutions are to include the file as part of the build process (so...
7,339,229
7,341,665
Android std and stl support
I am playing with android ndk. I am using Window Vista with cygwin (latest version). I compiled and launched the hello world jni sample on my phone. It is working. The code is (is a .cpp file): #include <string.h> #include <jni.h> extern "C" { JNIEXPORT jstring JNICALL Java_org_android_helloworld_HelloworldActivit...
From NDK r5's docs/CPLUSPLUS-SUPPORT.html: By default, the headers and libraries for the minimal C++ runtime system library (/system/lib/libstdc++.so) are used when building C++ sources. You can however select a different implementation by setting the variable APP_STL to something else in your Application.mk, for ...
7,339,345
7,339,562
Nested if drop to parent else
Maybe I'm just being stupid but how could something like this "goto parentelse" be accomplished (I'm using c++): if (Something) { if (AnotherThingDependentOnSomething) { certain stuff } else { <goto parentelse> } } else { other stuff } AnotherThingDependentOnSomething canno...
If I understand your needs right, then maybe having a little success flag makes the code more readable: bool complicated_condition_holds = false; if (Something) { // laborious stuff... if (SomethingElse) { // tedious stuff... complicated_condition_holds = true; } } if (!complicated_condition_holds) ...
7,339,390
7,339,819
Microsoft PPL parallel_for_each with boost filesystem directory_iterator
using Visual Studio 2010 SP1 so i have a std::for_each iterating on lots of files using the boost::filesystem library. since those iterations dont mess with each other i was trying to get multi threading working on it, so im trying to use VS 2010 library PPL. old: for_each(directory_iterator(path), directory_iterator()...
If most of your time is spent loading files, you're only slowing yourself down by trying to load multiple files. That said, if your work is processing-bound, you could do something like this: for each file // serial { load file into memory spawn task to process file // concurrent } wait until tasks to complete...
7,339,408
7,339,602
How to decode mp3 into wav using lame in C/C++?
I learned how to encode wav into an mp3 using lame_encode_buffer_interleaved from this question: Is there any LAME c++ wraper\simplifier (working on Linux Mac and Win from pure code)? Now I want to decode the mp3 back into wav. I know there's lame_decode but I don't know how to use it since it requires two pcm buffers ...
Take a look into the lame frontend source code. Start at the lame_decoder() function in the .../frontend/lame_main.c file, it decodes an MP3 file and writes the wave header.
7,339,489
7,339,563
How to map PC (ARMv5) address to source code?
I'm developing on an ARM9E processor running Linux. Sometimes my application crashes with the following message : [ 142.410000] Alignment trap: rtspserverd (996) PC=0x4034f61c Instr=0xe591300c Address=0x0000000d FSR 0x001 How can I translate the PC address to actual source code? In other words, how can I make sen...
With objdump. Dump your executable, then search for 4034f61c:. The -x, --disassemble, and -l options are particularly useful.
7,340,058
7,340,084
Different values when ANDING and assigned uints to a char array in C++ and C#
I have a very simple problem that is giving me a really big headache in that I am port a bit of code from C++ into C# and for a very simple operation I am getting totally different results:- C++ char OutBuff[25]; int i; unsigned int SumCheck = 46840; OutBuff[i++] = SumCheck & 0xFF; //these 2 ANDED make 248 The...
Maybe you should be using byte or sbyte instead of char. (char is only to store text chars and the actual binary serialization for char is not the same as in c++. char allows us to store characters without worrying about character byte width.)
7,340,079
7,340,481
Compilation error on Eclipse CDT
I have MinGW installed on my computer (I just use the one shipped with Strawberry perl). I can compile things just fine from the command line. Using Eclipse CDT, however, results in weird errors. Using the c++ hello world default project which comes with Eclipse, compilation in CDT fails with these errors: \**** Intern...
I experienced this only a few days ago, the problem turned out to be that I had both g++4.3 and g++4.4 installed and Eclipse was getting confused. I uninstalled 4.3 and the problem went away.
7,340,182
7,340,224
Is there any way to trick the compiler into allowing template specializations in the header file?
Normally when you write a template class and have a specialization of a function in that class, you need to put the specialization in the .cpp file since it is a concrete definition (rather than a template definition). If you only have one tiny function to specialize though this is a little annoying and sometimes you ...
Use the inline keyword: template <unsigned N> unsigned get_const() { return N; } template <> inline unsigned get_const<42>() { throw "meaning of life"; } The keyword indicates that multiple definitions should assumed to be the same, and therefore not an error. (This is orthogonal to static, which keeps repeat...
7,340,434
7,340,455
How to update an existing element of std::set?
I have a std::set<Foo>, and I'd like to update some value of an existing element therein. Note that the value I'm updating does not change the order in the set: #include <iostream> #include <set> #include <utility> struct Foo { Foo(int i, int j) : id(i), val(j) {} int id; int val; bool operator<(const Foo& oth...
Since val is not involved in comparison, it could be declared mutable struct Foo { Foo(int i, int j) : id(i), val(j) {} int id; mutable int val; bool operator<(const Foo& other) const { return id < other.id; } }; This implies that the value of val may change in a logically-const Foo, which means that it ...
7,340,720
7,340,743
C++ Object Oriented Design
class Allegro {}; class Input { private: Allegro allegro1 }; class Graphics { private: Allegro allegro2 }; class Game { private: Input keyBoardinput; Graphics Gamegraphics; }; In the input I need access to Allegro functions related to the user keyboard input. In the Graphics class,I want only functi...
Obviously, Graphics and Input should be talking to the same Allegro class. So you should do that: create the Allegro class instance, then use that instance in the constructors for Graphics and Input.
7,340,722
7,340,851
Compile error in 'winbase.h'
I get the following error with a Windows file when compiling winbase.h. Not sure why I get a syntax error and the compiler shows many more: 1> c:\program files\microsoft sdks\windows\v6.0a\include\winbase.h(238) : error C2146: syntax error : missing ';' before identifier 'Internal' Here a simple code to reproduce ...
Are you including <winbase.h> directly? You shouldn't - it expects to have some things defined/declared before it's processed. Specifically in this case the identifier ULONG_PTR which is declared as a typedef in intsafe.h. Include <windows.h>.
7,340,830
7,365,337
boost::bind, boost::shared_ptr and inheritance
I'm new with the Boost library, and I got a problam a bit complex for me. I tried to reformulate it with an example found in previous question that might fit well my problem. (The previous question is here) #include <boost/bind.hpp> #include <iostream> #include <map> #include <set> #include <algorithm> #include <boost/...
It works with this workaround, but I'm not satisfied with it, so if someone find a better solution, go ahead. #include <boost/bind.hpp> #include <iostream> #include <map> #include <set> #include <algorithm> #include <boost/noncopyable.hpp> #include <boost/shared_ptr.hpp> #include <boost/enable_shared_from_this.hpp> cl...
7,340,850
7,341,978
Debugging c++ .cpp file using Xcode
I have a solitary .cpp file, and I would very much like to debug it. Without creating an Xcode project, is there anyway I can debug this using the Xcode debugger? When I open the file in Xcode to edit and set breakpoints, the program doesn't stop at the break points.
You can't debug via Xcode without a project because without a project, Xcode works only as a file editor with color highlight and so one. For debugging you need an executable compiled with debug option, which is produced via a compiler. The easy way (but in my opinion the worse) is to make a Xcode project and put the ....
7,340,909
7,342,744
Variadic templates and dynamic cast
I have a piece of C++ code as follows: template <typename ...A> struct CastAll{ template <typename ...B> void cast_all(void(*fun)(B...), A...as){ //... } }; What I'd like to do is to implement cast_all in such a way that it dynamic-casts each one of its arguments to its respective type in B and then calls t...
Simply template <typename ...A> struct CastAll{ template <typename ...B> void cast_all(void(*fun)(B...), A...as){ fun(dynamic_cast<B>(as)...); } }; should work, and it does with my copy of GCC. Some changes in your example code are needed though: A should be polymorphic (which will make B polymorp...
7,340,925
7,340,943
return by value assigned to const reference
I was fixing another bug in some code and came across some code that I would have thought was a bug; however, this code compiles under gcc 4.4, 4.5, and 4.6 and appears to function as "expected". Can anyone tell me if this is valid c++? struct foo { int bar; }; foo myfunction(foo const &orig) { foo fooOnStac...
Yes, this is legal C++. Forming a reference-to-const to a temporary extends the lifetime of the temporary to the lifetime of the reference.
7,340,927
7,340,950
C++: overloading the += operator for a matrix template
I've been implementing a custom template matrix class and I have a function I need some help with. I'm trying to overload the operator+= for which I use the overloaded operator[] that I have already implemented and is working. The problem is, I don't know how to incorporate the 'this' pointer with the operator[]. Here'...
You can write (*this)[i][j] or, if you want to be extremely perverted about it this->operator[](i)[j]; or worse: this->operator[](i).operator[](j); // :) happy debugging And don't use the word irregardless. Stewie Griffin said everyone who uses that term along with "all of the sudden" must be sent to a work camp :)...
7,340,936
7,340,965
Comparison in string literal results in inspecified behavior - C++
I'm using eclipse. I declared #define OUTPUT_FLAG "-o" and then, I have the main : int main(int argc, char **argv) after that I write: for (int i = 1; i < argc; i+=2) { if(argv[i]==INPUT_FLAG) { cout<<"input flag\n"; input_file=argv[i+1]; } } and there I get ...
You cannot compare strings with == in C++. You either have to use strcmp or convert them to std::strings and then use the == operator. That is, either: if (!strcmp(argv[i], INPUT_FLAG)) or if (std::string(argv[i]) == INPUT_FLAG)
7,340,946
7,341,139
std::istream extraction sets failbit for no apparent reason
I'm creating a primitive type wrapper, which can use boost::lexical_cast for setting its value from a string. It works fine, but for some reason std::istream extraction operator sets the failbit. The following program prints: 123.45 EXCEPTION: ios_base::failbit set But if you comment out the line "inStream.exceptions( ...
One reason for this might be that the implementation of lexical_cast might deliberately try to cause some stream to fail in order to check that all of the input text was consumed. For example, a naive implementation might look like this: template <typename Target> Target lexical_cast(const string& s) { /* Inse...
7,340,986
7,342,989
weekdays' duration using boost date
Is there a way to get only the no. of weekdays between 2 boost dates. In the following, I'm only getting calendar days. date begin_dt(2011,Aug,3); date end_dt(day_clock::local_day()); days duration=end_dt-begin_dt; std::cout<<"calendar days between begin & end date are: "<<duration<<std::endl;
Perhaps the simplest way is to run a day_iterator from start to finish: #include <iostream> #include <boost/date_time.hpp> int main() { using namespace boost::gregorian; date begin_dt(2011,Aug,3); date end_dt(day_clock::local_day()); days duration=end_dt-begin_dt; std::cout<<"calendar days between...
7,341,046
7,341,515
POSIX equivalent of boost::thread::hardware_concurrency
Possible Duplicate: Programmatically find the number of cores on a machine What is the POSIX or x86, x86-64 specific system call to determine the max number of threads the system can run without over-subscription? Thank you.
It uses C-compatible constructs, so why not just use the actual code? [libs/thread/src/*/thread.cpp] using pthread library: unsigned thread::hardware_concurrency() { #if defined(PTW32_VERSION) || defined(__hpux) return pthread_num_processors_np(); #elif defined(__APPLE__) || defined(__FreeBSD__) int count; ...
7,341,084
7,731,927
Getting Matrix (CGAffineTransform) Info from iPhone Movies in C#/C++
When the iPhone records a video it puts the data from the camera directly onto the disk. What tells the player how to reorient the video is the Transform Matrix. Its a Mathematics structure that is used to change the position of the pixels in X,Y space. In the iPhone and in the Macintosh I can ask the Video what its Tr...
It appears that the CGAffineTransform is something that will need to be pulled right out of the file itself. I used the Quicktime File Format Specification pdf to gain an understanding of the file and where to get the CGAffineMatrix Here is a link to the page with the Matrix data on it Quicktime File Format Specificati...
7,341,125
7,341,148
ifstream arguments - C++
I Declared: std::string input_file="1.txt"; then I tried to do this command: static ifstream myfile (input_file); and I get the error: no matching function for call to : std::basic_ifstream<char>::basic_ifstream(std::string&)
Try: static ifstream myfile(input_file.c_str()); For some reason, the ifstream constructor doesn't accept an std::string.
7,341,202
7,341,262
Module concept for C++
C++ is still an evolving language and new features are being added to it over the years. One feature that I miss badly in C++ is a proper module concept: the current approach using header files (where you use a conditional #define to make sure that the header is not included twice) seems definitely unsatisfactorily to ...
C++ is still an evolving language and new features are being added to it as part of the C++0x development. The C++11 standard has already been approved and published, so no more features are being added to it. Not for at least another few years. One feature that I miss badly in C++ is a proper module concept: the ...
7,341,607
7,341,631
so what is the type of "this" ? Why is "this" not a lvalue?
Say the object is class A { public : void Silly(){ this = 0x12341234; } I know I will get compiler error ' "this" is not a lvalue.' But then it is not a temporary either. So what is the hypothetical declaration of "this" ? Compiler : GCC 4.2 compiler on mac.
For some class X, this has the type X* this;, but you're not allowed to assign to it, so even though it doesn't actually have the type X *const this, it acts almost like it was as far as preventing assignment goes. Officially, it's a prvalue, which is the same category as something like an integer literal, so trying to...
7,341,791
7,341,815
Why my implicit conversion function doesn't work?
I have a wrapper class and I want to modify the data and convert it back to its original type. class A { public: A ( unsigned __int64 _a ) : a (_a) { } operator unsigned __int64 () const { return a; } unsigned __int64 a; }; I want the object of this class to implicitly convert back...
It doesn't work because you haven't created an operator>> overload for your class that takes an integer and does something with it. I'm guessing you're trying to do a right shift on your int, but I'm not sure that overloading your operator>> is a good idea for that, as these operators in a context like that, are normal...
7,341,909
7,342,489
How to prevent Texture_2D bigger than viewport from being scaled to viewport in openGL
Total noob here learning openGL and I don't have any code to post because this is a question about a concept, not my current implementation. If code is absolutely required let me know and to my nooby shame I will post some. Basically I have a VBO that is displaying a 2D image in GL. However, since my viewport is 800x60...
The best way to do that is to scale the vertices you are drawing to the current viewport size. For example, to draw a 10px by 10px box(Ignore obsolete api). glBegin( GL_QUADS ); glVertex2d(0.0 ,0.0); glVertex2d(10.0/viewportWidth * 2,0.0); glVertex2d(10.0/viewportWidth * 2,10.0/viewportHeight * 2); g...
7,342,045
7,342,666
Are boost mapped files RAII?
From what I can tell from documentation they aren't, on the other hand RAII is the one of the features of modern cpp. http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/classes/mapped_file.html EDIT: It turns out that the answer is yes, but please please dont forget to use .is_open().
Looking at the implementation, the mapped_source/mapped_sink both contain a shared pointer to the underlying mapped_file_impl (See here for the mapped_file_impl source) As you can see, once the last reference is destroyed, it calls the destructor which detaches from the mapped file. However, it does not destroy the ma...
7,342,086
7,342,215
help on code improvement and time effiency
I wrote a program that reverses each word in a string. For example hello and goodbye is turned into olleh dna eybdoog. My program works, however the time efficiency is o(n^2) and I probably could of written less code. I am trying not to use any of the string.functions() ( I used string.length() once). Any tips or s...
Isn't far simple something like #include <iostream> using namespace std; int main () { string me=("hello and goodbye"); int i,j, index=0; char tmp; for (i=0; i<me.length()+1; i++) if (me[i] == ' ' || me[i] == '\0') { for(j=i-1;j>index;j--,index++) { tmp = me[index]; me[index] = m...
7,342,383
7,342,407
C++ templates and structs problem
I have this... template <typename Key, typename Value> class A { public: //... private: struct MyStruct{ Key key; Value value; }; }; And it gives me the following errors: Error 1 error C2146: syntax error : missing ';' before identifier 'value' Error 2 error C4430: missing type spe...
You forgot a semicolon after the class definition, at the very end of your code. In some cases you need to write typename Key key; instead of a simple Key key; in templates, since the compiler may not know that Key is really a typename. So try this: template <typename Key, typename Value> class A { public: //... pr...
7,342,488
7,342,511
Is there a standard naming convention in C++ for variable and function names?
I am new to C++ but not to programming. Normally, a language has one set of naming conventions that it abides by but with C++ there seems to be no standard on how to write variable and function names. I have seen some people use camel case (i.e. myVariable, myFunction()), some use all lower case (i.e. myvariable, myfun...
Normally, a language has one set of naming conventions that it abides by While the standard library for most languages has a consistent convention, I know of very few languages that enforce a convention on the programmer. And no, there is no common C++ naming convention.
7,342,524
7,342,573
assignment by index or field doesn't work in C++
static struct inet_protosw inetsw_array[] = { [0] = { /* assignment by index */ .type = SOCK_STREAM, /* assignment by field */ .protocol = IPPROTO_TCP, .prot = &tcp_prot, .ops = &inet_stream_ops, .no_check = 0, .flags = INET_PROTOSW_PERMANENT | ...
If I remember correctly the [0] and .type initialization designators have been introduced by ISO C99, and since the C++ standard came out in 1998, it didn't incorporate these features. And also in C++11 it is not possible. The relevant section in the standard is 8.5.1 Aggregates, and all the examples in that section ar...
7,342,527
7,405,841
Byte swap during copy
I need to efficiently swap the byte order of an array during copying into another array. The source array is of a certain type; char, short or int so the byte swapping required is unambiguous and will be according to that type. My plan is to do this very simply with a multi-pass byte-wise copy (2 for short, 4 for int, ...
Yes there are existing functions like the one linked in the question but its not worth the effort because the size of the data (in this case) means the set up overhead is too high. So instead, it's better to just read out 2, 4, and 8 bytes at a time and do the swap using intrinsics and write back.
7,342,571
7,342,701
Detect if process memory being manipulated?
I was wondering how one could monitor the process memory of another application and see if it is being manipulated by a third party. Such as when ReadProcessMemory, WriteProcessMemory are called on a specific process. For example, nProtect GameGuard can detect when a games process memory is being manipulated.
The real answer could be very lenghthy so here are a few short tips for you. First, you need some system-wide hooks to these functions, and their lower-level building blocks (Zw..., Nt..., and even system call). This should be done by a kernel driver. Second, you need a way to install this driver, and remove it at will...
7,342,574
21,517,019
How to run gtests without logging from google log?
I'm running unit tests with gtest. However I'm also using google glog in the code I'm testing. Unfortunately this output gets in the way of the test results and looks messy. How do I do I get rid of the glog output?
This seems to work, suppressing all log messages. int main(int argc, char * argv[]) { FLAGS_logtostderr = true; FLAGS_minloglevel = 5; google::InitGoogleLogging(argv[0]); // Start running unit tests here }
7,342,677
7,342,857
How does Windows 7 show the thumbnails of application in taskbar?
How does Windows 7 show the thumbnails of application in taskbar? I can even see the movies in these thumbnails playing. Is it possible to do this with VC++?
The live thumbnail previews are created by the Desktop Window Manager. Your application can get access to them by using the DwmRegisterThumbnail and DwmUpdateThumbnailProperties functions. For more information, see the DWM Thumbnail Overview at MSDN.
7,342,703
8,935,954
GCC 4.4/4.5 unique_ptr not work for unordered_set/unordered_map
Is there any place I can confirm this? I am not sure if it is the problem of GCC or my code. For example, the following code doesn't compile: #include <unordered_set> #include <memory> using namespace std; int main() { unordered_set<unique_ptr<int> > s; unique_ptr<int> p(new int(0)); s.insert(move(p)); ...
Your code is correct. This is a known issue in GCC 4.5. It has been fixed in 4.6. See http://gcc.gnu.org/bugzilla/show_bug.cgi?id=44436 . It affects ordered containers too (std::map, std::set etc). Probably the easiest workaround (at a slight performance penalty) would be to use std::shared_ptr instead of std::uni...
7,342,733
7,342,757
get the return value of command run in the terminal in c++
for now this is my code. This command will execute a script and supposed to return Safari browser version on Mac if its run in the Terminal. int versionResult = system("osascript /Library/Application\\ Support/Version.scpt"); In C++, this wil return 1 or 0. How can I make it return the result of the command in C++?
You can't do it with system; there's no platform-independent way to do it without using a cross-platform framework like Qt. That looks like a Mac command; to do this on the Mac, which is Unix-like, you could use popen(), something like char buffer[100]; FILE * f = popen("osascript /Library/Application\\ Support/Version...
7,342,775
7,342,834
C++ passing 2D array to function only loads one char
I have a program I am working on that is basically like this: bool isUnique(char**,int,char[]); int main() { char** uniqueWords = new char *[MAXWORDSIZE]; uniqueWords[posofUnique] = new char[MAXWORDSIZE]; //assign value to uniqueWords[0]="value" isUnique(uniqueWords,posofUnique,currentWord); } boo...
Your uniqueWords array has MAXWORDSIZE elements and all of them contain garbage pointer values immediately after allocation. Then you set uniqueWords[posofUnique] pointer to some newly allocated memory. So, that single entry now holds some more-or-less meaningful value. The other entries of uniqueWords array still con...
7,342,889
7,342,938
Hex value in string conversion
I have a C++ script which involves string representations of would-be hexadecimal numbers. In a later portion of the script, I would like to convert these would-be hexadecimal numbers into doubles for some arithmetic in base 10. To try to make this conversion, I use a function. double MyFunction(string input) { double ...
The hex manipulator only works for integral types like int. First input the hexadecimal string into an integer and then convert that to a double: double MyFunction(string input) { int Number; // Notice now Number is an integer stringstream ss(input); ss >> hex >> Number; return Number; // This should c...
7,342,937
7,342,962
Structs and Classes in C++
In c++ if you create a struct or class like this struct foo { } Must you use the struct or class qualifier to create another one as you do in c, if not why is that? When would it be appropriate to use it in C++ Example struct foo a; Thanks :-)
The struct is not required. In C++, the only difference between a struct and a class is that in a struct, members are public by default, while in a class, they're private by default.
7,343,045
7,343,140
tree.hh - C++ Leaf Traversal
The output from the following code is incorrect. It should only output the leaves in the tree: tree<Node> gameTree; tree<Node>::iterator root = gameTree.insert(gameTree.begin(),Node(14)); tree<Node>::iterator first = gameTree.append_child(root,Node(32.0)); tree<Node>::iterator second = gameTree.append_child(root,Node(...
From the docs you should be using a leaf_iterator rather than an iterator, the output you're seeing is from an in order traversal, you want to do a leaf traversal I'm guessing. btw, thanks for posting this I was just starting in a search for a tree container hth
7,343,127
7,343,161
ASSEMBLY Offset to C++ Code question
I've been trying to convert this code to C++ without any inlining and I cannot figure it out.. Say you got this line sub edx, (offset loc_42C1F5+5) My hex-rays gives me edx -= (uint)((char*)loc_42C1F5 + 5)) But how would it really look like without the loc_42C1F5. I would think it would be edx -= 0x42C1FA; But i...
loc_42C1F5 is a symbol. Given the information you've provided, I cannot say what its offset is. It may be 0x42C1F5 or it may be something else entirely. If it is 0x42C1F5, then your translation should be correct.
7,343,171
7,343,200
C++ helper function for copy constructor
I haven't been able to find a good answer to this question. I'm working on a C++ program and I'm trying to implement a function named copy which takes a reference to another object as an argument. Then, it returns a deep copy of this object. Some background on my project: the Scene class contains a dynamic array (call...
Scene const & Scene::operator=(Scene const & source); overloaded assignment operator copies the content of this to the argument received source. For copy there is no need to return any thing or to create a local object. Just make a member wise copy from this to source. void Scene::copy(Scene const & source){ //...
7,343,184
7,343,214
C++ swap() for deque indexes
I have two questions, the second being optional. First, in the program below (a prototype of a simple card program), I am getting the following error: (29): error C2660: 'shuffle' : function does not take 1 arguments with the following code: #include "stdafx.h" #include <iostream> #include <sstream> #include <deque...
The reason you get that error is because you declare shuffle as a function not taking any arguments. void shuffle(); Another note is that you probably want to take a reference to the deque in that function, otherwise you'll shuffle a local copy and won't have the desired side effect. You probably want it to lok like t...
7,343,460
7,344,082
const casting an int in a class vs outside a class
I read on the wikipedia page for Null_pointer that Bjarne Stroustrup suggested defining NULL as const int NULL = 0; if "you feel you must define NULL." I instantly thought, hey.. wait a minute, what about const_cast? After some experimenting, I found that int main() { const int MyNull = 0; const int* ToNull =...
Your code is modifying a variable declared constant so anything can happen. Discussing why a certain thing happens instead of another one is completely pointless unless you are discussing about unportable compiler internals issues... from a C++ point of view that code simply doesn't have any sense. About const_cast one...
7,343,473
7,343,505
Variable declared as Node *&ptr = root->mRight
I am trying to understand what that means I know that declares a variable to an address of type node and that & gets the address of a variable. I also know that in a function parameter it is a call by reference pointer. But I have never seen it in a variable declaration before... What does it mean exactly Node *&ptr ...
On the right, root is a pointer to a node. root->mRight is a member of that node, namely its mright, which is another pointer to a node. On the left, we declare something (before assigning a value to it with =). If it were Node *ptr, it would be a pointer to a node, but because of that &, it is not such a thing in its ...
7,343,531
7,343,555
Are some design patterns language dependent?
If yes, then are there any patterns that are specific to C++, and some that are not? Which are they, if any? Well I am referring to these design patterns: http://en.wikipedia.org/wiki/Design_pattern_%28computer_science%29
RAII is a powerful pattern that relies on C++'s scope cleanup mechanism. In garbage-collected environments this language feature is usually missing. Other languages (e.g. Ruby) have other ways of using user-provided control flow constructions.
7,344,054
7,344,222
Why are private members/methods defined in the interface?
I've always been confused by the fact that most OOP languages (or rather, C++) make you define private methods/members in the interface (by interface I mean the class declaration - seems like I was confused). Isn't this showing the implementation details of the class and going against the idea of encapsulation? Is the...
For C++ it's an implementation issue. The C++ compiler must be able to generate code that uses a class by only seeing the class declaration and not the implementation. One very important thing that is needed by the compiler is the size of an instance of the class because among other things C++ handles sub-objects in ob...
7,344,127
7,344,165
Operator '.' vs '->' in C++
Possible Duplicate: What is the difference between the dot (.) operator and -> in C++? What is the difference between the two? When do you use one instead of the other? There was once I tried to use '->' instead of '.' and I got "left operand has 'class' type, use '.'" error, what does it mean?
The . allows you to access members of a class. thingy.member, for example. If you have a pointer to your class, say pThingy, you need to dereference it in order to access the members. Like (*pthingy).member. A shortcut to the dereference/access combination is ->: pThingy->member.
7,344,640
7,344,802
Getting garbage chars when reading GLSL files
I run into the following problem.I load my shaders from files.The shader program ,when trying to compile, throws these errors for the vertex and fragment shaders: Vertex info 0(12) : error C0000: syntax error, unexpected $undefined at token "" Fragment info 0(10) : error C0000: syntax error, unexpected $undefined at to...
It looks like all you have to do is allocate one more byte of memory in which you can place a null ('\0'): ... memblock = new char[1 + fSize]; file.seekg (0, ios::beg); file.read (memblock, size); file.close(); memblock[size] = '\0'; ... edit I changed my code to use fSize in the array rather than size, since i...
7,344,739
7,344,861
Reference to Abstract Class assign problem
In relation to question "reference to abstract class" I wrote the following example: #include <iostream> #include <vector> class data { public: virtual int get_value() = 0; }; class data_impl : public data { public: data_impl( int value_ ) : value( value_ ) {} virtual int get_value() { return value; }...
In data& d = db.get( 0 ); std::cout << d.get_value() << std::endl; d = db.get( 1 ); std::cout << d.get_value() << std::endl; the first statement is a reference initialization, while the third statement is a slicing assignment. You can not re-seat a reference. Cheers & hth.,
7,344,810
7,344,966
C++ Inheritance Issue
I am using code::blocks, with, I believe gcc. Given the example code (this is pseudo code and may not replicate the problem): //Assume this is in a separate header file to B class TestA { protected: int A; public: void Function1(){A = 0;} }; class TestB : public TestA { public: voi...
The problem that you're having about accessing base class stuff in a class template, is a FAQ item. Rather then quoting the whole FAQ item here, I just link to it: that's your answer. The code that you presented to illustrate the problem was unrelated, sorry. It is always a good idea to give an actual example rather th...
7,345,117
7,349,426
Efficiently expand set of graph edges
I have a set of edges from a graph, and would like to expand it with all edges that share a vertex with any edge. How could I do this efficiently with boost::graphs? The only way I've been able to come up with is the naive solution of extracting all the source and target vertices, using boost::adjacent_vertices to get...
Instead of considering all adjacent vertices in each step to generate the new edges, use a property map to mark edges already encounterd. Thus, you need to consider unmarked edges in each step only. A vertex is marked after adding all edges incident to it to your set. Given the fact that the internal data structure use...
7,345,326
7,345,416
Implementation for EVP_CipherInit_ex / EVP_CipherUpdate / EVP_CipherFinal_ex
I am using OpenSSL and libcrypto for encryption. I would like to ask where can I find these methods. I need them because i would like to add these methods in my code. I just want the .h and .cc or .c files. appreciate
Here is detailed information on how to compile the openssl library yourself: http://www.ski-epic.com/2007_notes_on_openssl/index.html You can download the source code from here: http://www.openssl.org/ Simply search the code for implementations of the functions you are referring to, and copy/paste. Make sure the librar...
7,345,614
7,345,767
is there aes 256 with cbc encryption in ubuntu/linux/unix?
I would like to create an IV encryption with aes 256 and cbc pkcs7 padding. I would like to ask if there is a library in linux that implements this type of encryption. I don't want to add dependency files/ libraries. THX! APPRECIATE If there is nothing like this includes in Linux(I am working on Ubuntu) could you plea...
See http://www.openssl.org/docs/crypto/crypto.html
7,345,649
7,346,122
How to change delimiter's position?
This example : #include <iostream> #include <iterator> #include <algorithm> int main() { int v[] = { 1, 2, 3 }; std::copy( &v[0], &v[3], std::ostream_iterator< int >( std::cout, "\n " ) ); } produces next output : 1 2 3   Is there a way to change the example to make it produce next output? 1 2 3 P...
There is no way to do this with std::ostream_iterator. (IMHO, there should be, but it's not there.) If you don't mind writing an extra small function or class, you can use std::transform, e.g.: struct FormatString { std::string operator()( std::string const& original ) const { return ' ' + original +...
7,345,825
7,347,882
Portable Directory/File watch library in C / C++
Is there a portable library to watch for filesystem changes without polling? I know there is inotify for Linux solution for osx FindFirstChangeNotificationfor Windows NIO.2 for Java System.IO.FileSystemWatcher for .NET but i have not found any portable wrapper for those. Is there a portable wrapper for Linux, Windo...
QFileSystemWatcher -- Qt is very cross-platform.
7,345,956
7,346,083
Advantages of classes with only static methods in C++
Even though there are no static classes in C++, coming from a Java background I use to create a helper class like Util containing only static methods. Is this considered bad style or usual practice? One alternative I see is to use C functions (no class context at all). What other alternatives are there? What are there ...
If you want to create a collection of utility functions without clobbering the global namespace, you should just create regular functions in their own namespace: namespace utility { int helper1(); void helper2(); }; You probably don't want to make them static functions either. Within the context of a non-membe...
7,345,981
7,348,843
Does QVector::replace() create a deep copy?
I have a memory leak in my application which I have been writing with Qt (C++) . And I suspect problem is with that line. for(int i=0; i<DATA_LENGTH;i++){ cdata1->replace(i,data->at(i)); } cdata1 is a QVector, data is a QList . The reason I'm using replace(), I have constant length of data. And I didn't ...
Deep copy means the whole container, not the elements. As linked just after the sentence you quoted, QVector uses implicit sharing, also known as copy-on-write. read-only copies of the container are cheap, as the internals are shared, until one of the copy is modified: QVector<A> vec1; ... QVector<A> vec2 = vec1; //che...
7,346,088
7,346,246
Multi-site execution : Getting rid of virtual table with inheritance (legacy code)
I've been stuck for some time on this problem, and I need your help. My C++ application is running on multiple exec sites. My problem is that I cannot pass objects holding a virtual table, because sites do not share memory (thus a virtual method from a given object will lead to an undefined behaviour). By "I cannot pas...
If you just want to get rid of virtual tables, you don't have to get rid of inheritance. You have to get rid of virtual functions. Looking at the code you post, maybe you can make a few changes so that getSize and getBuffer are in GenericList, so you can make them non-virtual, but that really depends on the rest of you...
7,346,163
7,346,327
Efficient Memory Barriers
I have a multithreaded application, where each thread has a variable of integer type. These variables are incremented during execution of the program. At certain points in the code, a thread compares its counting variable with those of the other threads. Now since, we know that threads running on multicore might execu...
The C++11 standard library includes support for fences in <atomic> with std::atomic_thread_fence. Calling this invokes a full fence: std::atomic_thread_fence(std::memory_order_seq_cst); If you want to emit only an acquire or only a release fence, you can use std:memory_order_acquire and std::memory_order_release inste...
7,346,179
7,346,249
A vector or multimap dilemma
I have a dilemma of whether to have a multimap <int key, int value> or maintain a vector containing a vector of all values corresponding to int key. I'm interested in which performs faster when looking up the values for a certain int key.
If you want a multimap and not just a map, the alternative will probably be a vector< list<int> > or something like that (a multimap, being generally implemented as an RB tree that allows multiple equivalent keys, is somewhat akin to a map with a list element type). In general, a vector lookup is faster: it's O(1) for ...
7,346,634
7,928,897
Dereferencing an invalid pointer, then taking the address of the result
Consider: int* ptr = (int*)0xDEADBEEF; cout << (void*)&*ptr; How illegal is the *, given that it's used in conjunction with an immediate & and given that there are no overloaded op&/op* in play? (This has particular ramifications for addressing a past-the-end array element &myArray[n], an expression which is explicit...
Assuming the variable `ptr' does not contain a pointer to a valid object, the undefined behavior occurs if the program necessitates the lvalue-to-rvalue conversion of the expression `*ptr', as specified in [conv.lval] (ISO/IEC 14882:2011, page 82, 4.1 [#1]). During the evaluation of `&*ptr' the program does not necessi...
7,346,906
7,347,001
How to read in a bunch of strings in C++?
I need to read in a bunch of strings without knowing in advance how many are there and print them as they are read. So I decided to use while(!feof(stdin)) as an EOF indicator.Here is my code: #include<stdio.h> #include<stdlib.h> #include<iostream> using namespace std; int main(void) { char* str; std::cout...
You need to allocate some memory for the string you are reading to go into. All you have currently is a pointer on the stack to some random memory area, which means that as you read characters they will stomp all over other data, or even memory you aren't allowed to write to - which then causes a segfault. The proble...
7,346,970
7,347,147
How to delete a file such that the delete is irreversable?
I want to delete a sensitive file (using C++), in a way that the file will not be recoverable. I was thinking of simply rewriting over the file and then delete it, Is it enough or do I have to perform more actions ?
Here is an interesting paper: http://www.filesystems.org/docs/secdel/secdel.html It adresses some issues with overwriting of files. Especially you can't be sure that the newly written data was written to the same location and that it's impossible to recover data that was overwritten just a very few times or even once (...
7,347,033
7,347,115
Including headers inside class declaration / definition
I know you can do something like: def.h: A(); int x; A.h class A { public: #include "def.h" } A.cpp A::A() { x = 0; } int main() { A a; return 0; } My questions is: why would you do this? Are there any advantages? I can see how it would be helpful if you have some classes with the same members but not t...
The preprocessor (which runs before anything), when it stumbles upon an include, almost literally copies the content of that header and pastes it in the place of the #include directive. The advantages of using it like you describe are few, the main one being that you don't have to duplicate code. However, in 9999/10000...
7,347,713
7,348,190
mcrypt linux how to use rijndael 256 cbc
I am working on linux/ubuntu. I found out that mcrypt is automatically included as a library in this platform. I want to create an encryption with aes 256 and cbc padding 7 (iv). Could someone please give me an example of how to encrypt a string with aes 256 and cbc iv, padding 7? Rijndael is the same with aes.! this i...
Are you asking how to use mcrypt? Here's a basic skeleton: #include <mcrypt.h> int main() { char algo[] = "rijndael-256"; char mode[] = "cbc"; char key[] = ... char iv[] = ... MCRYPT td = mcrypt_module_open(algo, NULL, mode, NULL); if (td == MCRYPT_FAILED) { /* error */ } int r = mcrypt_generic_init...
7,347,880
7,347,948
How to get 2 ints from cin in C++?
I'am trying to get three pairs of int from user. But if i enter letters my code ran into infinitive cycle. What am I doing wrong? struct Point { int x; int y; }; istream& operator>> (istream& is, Point& pt) { int x, y; is >> x >> y; if (!is) return is; pt.x = x; pt.y = y; retur...
The while (true) ... loop never stops. The break never executes because cin >> pt keeps failing. You can't fix this with simple istream operations, since cin >> pt will never succeed once you've supplied bad input. Either expect correct input, and fail outright if it isn't: while (points.size() < 3 && (cin >> pt)) { ...
7,348,051
7,348,075
Convert uint64_t to std::string
How can I transfer uint64_t value to std::string? I need to construct the std::string containing this value For example something like this: void genString(uint64_t val) { std::string str; //.....some code for str str+=(unsigned int)val;//???? } Thank you
use either boost::lexical_cast or std::ostringstream e.g.: str += boost::lexical_cast<std::string>(val); or std::ostringstream o; o << val; str += o.str();
7,348,206
7,348,348
boost::shared_ptr parent <-> child communication
I am using boost::shared_ptr to organize my pointer data in my game engine. I tried to make a very short example to show my problem: class CSceneNode { public: CSceneNode(CScene *p) : parent(p) {} void foo() { parent->notifyThatFooWasCalledOnMe(my_shared_ptr_version_of_this???); }; CScene *par...
Now the child needs to notify the parent of a change. Remove this requirement, and the whole problem collapses... as well as your cyclic dependency. You might consider an event-based system instead, or state polling.
7,348,229
7,348,327
How do I reinitialize a singleton that I don't have full control over in the middle of an app?
I have a compiled external library that I'm using in my (Objective-C++) code. This library has a singleton class to store some information throughout the duration of the application being used. I really need a way to be able to remove the loaded information and reload it in the middle of the application. Or to reload t...
Unless the API is providing you a way to do it, it's probably impossible. But I would have try to rerun the "load" function after I call the delete...
7,348,673
7,352,048
std::move realisation
I got next snippet from microsoft template <typename T> struct RemoveReference { typedef T type; }; template <typename T> struct RemoveReference<T&> { typedef T type; }; template <typename T> struct RemoveReference<T&&> { typedef T type; }; template <typename T> typename RemoveReference<T>::type&& Mov...
The reason your Move doesn't work, is because t is always lvalue (even when T&& resolves to, say, int&&). Even though it might seem weird, named rvalue references are indeed lvalues. When returning from your Move, you attempt to implicitly bind lvalue to rvalue reference, which is forbidden by standard (§8.5.3). As not...
7,348,707
7,348,780
Wrong reading of text file in c++
I just want to read a text file and store the data into a vector. Thereby the value weight should be sum till the limit is reached. The first four lines will be read correctly but the following will not read. What is the mistake? #include <iostream> #include <fstream> #include <string> #include <vector> #include <li...
These two lines, std::getline(stream_in, passenger.group_code); stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); should be in the opposite order: stream_in.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); std::getline(stream_in, passenger.group_code); Think about what the...
7,348,735
7,348,788
Name a good guide for the implementation of an STL compatible sequence container)
I'd like to implement a sequence container with the bells and whistles required for an STL class - for example, my own deque class that can use all of the STL algorithms and utilities that the normal deque class could use. I'm aware all the STL components and how they work, but I'd definitely miss alot trying to do th...
A container must implement a series of Concepts. A comprehensive list can be found here: http://www.sgi.com/tech/stl/Container.html Simply implement the requirements there, and you got yourself a container.
7,348,776
7,348,831
obj1 *= obj2 VS. obj1 = obj1 * obj2 in C++
Assuming that i've implemented *=, = and * operators overloading, which will you prefer to use complexity wise? Thanks.
Given that I’d usually implement operator * in terms of operator *= and a copy, there is no reason ever to prefer operator *. The normal implementation of operator * (and +, -, / etc.) should usually look as follows: T operator *(T const& left, T const& right) { T result = left; return result *= right; }
7,348,796
7,348,896
exception while thread is throwing error in scoket c++ windows
i am creating client sever application in windows using socket and i want to throw exception at run time from thread if any problem occur but i am getting error for throw statement. //create thread in cpp file CreateThread(NULL,0,startServer,this,0,NULL); //thread in header file static uns...
The code that throws the exception is not the problem; it's the lack of any code to catch the exception that's the problem. The application is terminating because nothing is catching the exception you're throwing; you must ensure that something is going to catch it. Your startServer method -- the thread procedure -- mu...
7,348,914
7,348,987
Specifying struct in function signature
Say I have struct mystruct { }; Is there a difference between: void foo(struct mystruct x){} and void foo(mystruct x){} ?
Not in the code you've written. The only difference I know of between using a defined class name with and without struct is the following: struct mystruct { }; void mystruct() {} void foo(struct mystruct x){} // compiles void foo(mystruct x){} // doesn't - for compatibility with C "mystruct" means the function So, d...
7,349,023
7,349,092
accessing C++ static class member variables in multiple source files
I've got a pair of classes. One of them has a set of static const uint32_t's (the following code is a trimmed down example): class Foo { public: static const uint32_t BAZ; void RunMe(void); }; class Bar { public: void RunMeAlso(void); }; I'm doing the usual thing of one class per cpp file, since the actual...
Case labels must be compiler constants. A static member variable is not a compiler constant, unless it is constant and initialized in the declaration with a constant expression. So: Declare it static const uint32_t BAZ = 1; in the header; or Use if instead of switch. BTW, it is usually helpful to read the actual erro...
7,349,129
7,349,605
Compile header-only template library into a shared library?
We are in the process of designing a new C++ library and decided to go with a template-based approach along with some specific partial template specialisations for corner cases. In particular, this will be a header-only template library. Now, there is some concern that this will lead to a lot of code duplication in the...
Yes. What you can do is explicitly instantiate the templates in CPP files using the compiler's explicit template instantiation syntax. Here is how to use explicit instantiation in VC++: http://msdn.microsoft.com/en-us/library/by56e477(v=VS.100).aspx. G++ has a similar feature: http://gcc.gnu.org/onlinedocs/gcc/Template...
7,349,183
7,349,281
Constructor chaining in C++
My understanding of constructor chaining is that , when there are more than one constructors in a class (overloaded constructors) , if one of them tries to call another constructor,then this process is called CONSTRUCTOR CHAINING , which is not supported in C++ . Recently I came across this paragraph while reading onl...
The paragraph basically says this: class X { void Init(params) {/*common initing code here*/ } X(params1) { Init(someParams); /*custom code*/ } X(params2) { Init(someOtherParams); /*custom code*/ } }; You cannot call a constructor from a member function either. It may seem to you that you've done it, but th...
7,349,257
7,349,634
Default constructor in C++
I was just curious about the question, but couldn't find the answer in the Internet. Let's suppose we have simple header: // SimpleHeader.h class SimpleClass { int i; } As we know, the default constructor is automatically generated for this class. Now I have 2 more files: // First.cpp #include <SimpleHeader.h> /...
From the standard: If you do not write any constructors, a default constructor will be provided for you, and this default constructor is defined inline and equivalent to an empty constructor T::T() {}. I'm pretty sure that [edit]your thus inlined constructor will not actually result in any machine code at all.