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 |
|---|---|---|---|---|
4,632,290 | 4,632,375 | Why don't any of the integer methods work for OpenGL? | I'm developing C++ OpenGL code in Windows using Visual Studio 2008. I can't for the life of me understand why none of the integer functions work. I'll try using glVertex2i(2,2) but all I get is a black screen, I've also tried this with glrecti but I have had the same result.
When I use the floating point functions, th... | Your code doesn't set any projection matrices, so passing values outside [-1, 1] is drawing outside of the viewport. That's why integer functions "don't work".
|
4,632,314 | 4,632,425 | conditional operator usage | Consider the following statement. What will be the value stored in b?
int a=1;
int b = a+=1 ? a+=1 : 10;
I get the answer as 4. Can anyone explain how that works please.
| It has to do with precedence. If you examine the following code (with the rightmost a+=1 changed for simplicity):
#include <iostream>
int main (void) {
int a=1;
int b = a+=1 ? 7 : 10;
std::cout << b << std::endl;
return 0;
}
you will see that the output is 8, not 7 or 10.
That's because the statement:... |
4,632,453 | 4,632,479 | Undefined reference while including header in C++ | I was working on my project while I decided that I should split it into files. However I got stucked with problem like this and all advice I found via google were about forgetting to link both object files which I am doing right (at least I think so).
Makefile:
test : class.o main.o
g++ class.o main.o -o test.exe
mai... | So here's what you did wrong. In class.cpp you recreate a new Trida class rather than implement the one you've created in class.h. Your class.cpp should look more like this:
#include <iostream>
#include "class.h"
using namespace std;
Trida::Trida(int n)
{
this->a = n;
}
void Trida::fce() { cout << this->a << end... |
4,632,465 | 4,635,885 | Do the functions in libpcap and winpcap have identical names? | Do the functions in libpcap and winpcap have identical names? If not, what names are different, or are the majority of them different?
Also, can libpcap++ be used for winpcap?
| The WinPcap website says:
This library also contains the Windows
version of the well known libpcap Unix
API.
So it looks like the answer should be they are about the same. As for whether libpcap++ can be used with WinPcap, why don't you give it a quick try and let us know? If it doesn't work, you might look at ... |
4,632,502 | 4,633,590 | waveInProc / Windows audio question | I'm using the Windows API to get audio input. I've followed all the steps on MSDN and managed to record audio to a WAV file. No problem. I'm using multiple buffers and all that. I'd like to do more with the buffers than simply write to a file, so now I've got a callback set up. It works great and I'm getting the d... | typedef struct {
LPSTR lpData;
// etc..
} WAVEHDR;
Hmya, awkward type there. It isn't a STR of course, should have been a PVOID. Just cast it to whatever type you need:
short* data = (short*)(mBuffer->lpData);
unsigned samples = mBuffer->dwBytesRecorded / sizeof(short);
// etc..
|
4,632,521 | 4,632,673 | Problem with square root of (2147483647) in c++ | I am calculating square root of 2147483647 by sqrt function.and the result must be a float value 46340.95 but my code returns the value 46341.
Can anyone tell me where is the problem?
i am using code :
double x=2147483647.0;
double y=sqrt(x);
cout<< y;
| I get that same result. But, if I inject a setprecision, I get the right value:
#include <iostream>
#include <iomanip>
#include <cmath>
int main (void) {
double x=2147483647.0;
double y=sqrt(x);
std::cout << std::setprecision(10) << y << std::endl;
return 0;
}
gives me:
46340.95
In fact, if you use t... |
4,632,528 | 4,632,601 | What does "Class* &cls" mean in C++'s function definition? | I know Class *cls is a pointer, and Class &cls takes the address, but what is
void fucction1( Class *&cls)
If I have Class c, what should I pass to function1()?
Thanks!
| Besides, what James explained in his response, let me add one more important point to it.
While you can write Class* & (reference to pointer) which is perfectly valid in C++ only, you cannot write Class& * (pointer to reference), as you cannot have a pointer to a reference to any type. In C++, pointer to reference is ... |
4,632,652 | 4,632,720 | C++ Instantiate class and add name to array/vector then cycle through update functions from the array | I have a bunch of classes in a basic (and badly coded!) game engine that are currently instantiated in the code and have to have their individual update functions called. What I want to do is be able to create an instance of a class, pass the name to an array, and then subsequently cycle through the array to call the u... | //vector initialization
std::vector<Enemy> enemies;
enemies.push_back(enem1);
enemies.push_back(enem2);
enemies.push_back(enem3);
enemies.push_back(enem4);
//update code
for(std::vector<Enemy>::iterator e = enemies.begin() ; e != enemies.end() ; e++ )
{
//treat 'e' as if it's a pointer to Enemy!
e->update(); /... |
4,632,762 | 4,632,768 | Why are pointers to a reference illegal in C++? | As the title itself mentions - why are pointer to a reference illegal, while the reverse is legal in C++?
| A pointer needs to point to an object. A reference is not an object.
If you have a reference r, once it is initialized, any time you use r you are actually using the object to which the reference refers.
Because of this, you can't take the address of a reference to be able to get a pointer to it in the first place. ... |
4,632,844 | 4,632,941 | How to access the element of a list/vector that passed by reference in C++ | The problem is passing lists/vectors by reference
int main(){
list<int> arr;
//Adding few ints here to arr
func1(&arr);
return 0;
}
void func1(list<int> * arr){
// How Can I print the values here ?
//I tried all the below , but it is erroring out.
cout<<a... | You aren't passing the list by reference, but by a pointer. In "C talk" the two are equal, but since there is a reference type in C++, the distinction is clear.
To pass by reference, use & instead of * - and access "normally", i.e.
void func(list<int>& a) {
std::cout << a.size() << "\n";
}
To pass by pointer, you ... |
4,633,000 | 4,633,071 | Better way to refer to structure size( #pragma pack VS defined size ) | Assume I have the struct Foo
struct Foo{
int a;
short b;
char c;
};
And I has to write this struct in to n/w buffer. I need to know the size of this struct.
In my environment, sizeof(Foo) returns 8, That's ok, I understand.
These are two way to refer to the exact size that I want to write to the buffer
1.... | If you need to write out such a structure to a network, please use a protocol framework or marshal the data explicitly using a protocol you define independent of the structure layout.
Depending on the binary layout details of a structure will likely cause pain down the road.
I've heard good things about Google Protocol... |
4,633,128 | 4,633,148 | SVN or Git for repository with hierarchial access control | Which one do you recommend for a commercial project with developers that need to have access to a particular part of repository only?
Development IDE is Eclipse
and Programming language is C/C++
Key features of the requirement is: Authoritative and ACL hierarchical access to repository
| Git, combined with a "central" server managed with Gitolite, can provide all the fine-grained control you need (per user/per group, with access to all or only some part of the repo, even to only some branches).
That being said, if your developers are more familiar with a CVCS like SVN, it might be wiser to use that kno... |
4,633,143 | 4,633,150 | How can I assign the positive value? | I declared an int variable like this,
int temp1 = -3;
How can I assign the int value 3 to temp2?
I can only find the method as this,
If (temp1 < 0){
temp2 = 0 - temp1;
}
Is there a good method to approach this?
| Try using abs:
temp2 = abs(temp1);
ideone
|
4,633,222 | 4,633,237 | static thread function access non-static class member in C++ | Class Test{
int value;
static void* thread_func(void* args){
value++;
}
void newthread(){
pthread_create(&thread_func,...);
}
}
I'm trying to create a thread in Class Test. Therefore compiler forces me to make thread_func static. However I cannot access the non-static member "value"... |
However I cannot access the non-static
member "value" anymore.
That is because static function in your class doesn't have (and cannot have ) this pointer. All you need to pass the pointer to your Test object to pthread_create() function as fourth argument, and then do this:
static void* thread_func(void* args)
{
... |
4,633,252 | 4,633,342 | how to cast an array of char into a single integer number? | i'm trying to read contents of PNG file.
As you may know, all data is written in a 4-byte manner in png files, both text and numbers. so if we have number 35234 it is save in this way:
[1000][1001][1010][0010].
but sometimes numbers are shorter, so the first bytes are zero, and when I read the array and cast it from c... | You cast (char*) to (int). What you should do is cast to pointer to integer, i.e.
t_num = *((int*) s_num));
But really you should extract your code into it's own function and make sure that:
endianness is correct
sizeof(int) == 4
Use C++ casts (i.e. static, dynamic, const, reinterpret)
|
4,633,295 | 4,633,308 | XML validator library | I'm using XML in my application with some own XML-parser (from ClanLib library).
The problem : that parser can't validate XML and it fails if any mistakes are presented. I need some validator which will say if the XML is valid and (preferable) show the error.
| Xerces-C++ can validate XML using DTD and XSD. Syntax is also validated.
|
4,633,317 | 4,633,411 | How to draw a part of a window into a memory device context? | I'm using simple statements to keep it, er, simple:
The screen goes from 0, 0 to 1000, 1000 (screen coordinates).
A window goes from 100, 100 to 900, 900 (screen coordinates).
I have a memory device context that goes from 0, 0 to 200, 200 (logical coordinates).
I need to send a WM_PRINT message to the window. I can p... | You can call SetViewportOrgEx() to specify the device context coordinates that will be mapped to the window's origin:
SetViewportOrgEx(yourDC, -600, -600, NULL);
Since your window's size is 800x800, offsetting the DC's coordinate system by -600x-600 will result in the 200x200 bottom right area of the window being draw... |
4,633,383 | 4,634,298 | How to make checkboxes in a list view control tri-state? | Is it possible to make the checkboxes in a list view control with LVS_EX_CHECKBOXES style tri-state (having BS_3STATE button style)? I'm using WTL but I'm OK manually sending messages around.
| Yes, you need an ImageList with 3 images of a unchecked, checked and indeterminate checkbox. Call ListView_SetImageList() to assign the LVSIL_STATE image list. Manipulate LVITEM.state to display the kind of checkbox you want.
|
4,633,410 | 4,633,527 | Get formatted message for WSA error codes | i'm using winsock2 in a win32 c++ application. I would display with MessageBox the network errors that i can retrieve by calling WSAGetLastError(). How can i do this? I saw FormatMessage but i didn't understand how to use it
| Here's how for example, The following searches error code in the system's message table and places the formatted message in LPTSTR Error buffer.
// Create a reliable, stream socket using TCP.
if ((sockClient = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
{
DWORD err = GetLastError();
LPTSTR Error = 0;
if(FormatM... |
4,633,458 | 4,633,504 | What is "Extending move semantics to *this" all about? | Please, could someone explain in plain English what is "Extending move semantics to *this"? I am referring to this proposal. All what am looking for is what is that & why do we need that. Note that I do understand what an rvalue reference is in general, upon which move semantics is built. I am not able to grasp what su... | The ref-qualifier feature (indicating the type of *this) would allow you to distinguish whether a member function can be called on rvalues or lvalues (or both), and to overload functions based on that. The first version gives some rationale in the informal part:
Prevent surprises:
struct S {
S* operator &() &; ... |
4,633,584 | 4,633,612 | Algorithm to generate all possible arrays of ones and zeros of a given length | How can I generate all possible bit combinations in an array of bits of length n. If I start with all zeros in my array then there are n possibilities to place the first bit and for these n possibilities there are n-1 possibilities to place the second bit.. unit all n bits are set to one. But so far I didn't manage to ... | How would you count manually on paper? You would check the last digit. If it is 0, you set it to 1. If it is already 1, you set it back to 0 and continue with the next digit. So it's a recursive process.
The following program generates all possible combinations by mutating a sequence:
#include <iostream>
template <typ... |
4,633,826 | 4,637,074 | QDockWidget is closed if main window is minimized | I'm using Qt 4.7 on Windows 7 Ultimate 32 bit.
The QMainWindow of my program has a QDockWidget. I've noticed that if I minimize the main window by the minimize button on the title bar, after restoring it the dock widget is closed. I didn't write any support for a feature like this!
How does this happen and how to preve... | I faced the same problem... I managed to get rid of it by using a method called StoreWindowsLayout and RestoreWindowsLayout.
StoreWindowsLayout will save the content of the ByteArray returned by the Method QMainwindow::saveState().
RestoreWindowsLayout will restore that bytearray, and therefore your windows layout, the... |
4,633,862 | 4,633,882 | C/C++ Memory Leak (Using PCRE) | // Returns a list of topic numbers found on the page
vector<string> findTopics(char* rData, int rDataLen) {
pcre *re;
const char *error;
int erroffset;
re = pcre_compile(
"topic/([0-9]+)", /* the pattern */
0, /* default options */
&error, /* for error message ... | You define regOf with 2 elements. You then pass sizeof(regOf) into the pcre_exec function, however the function asks how many items are in the array, not how many bytes in size it is. As such, the function thinks it has 8 slots to fill, it only has 2, so can run off the end of the array and corrupt memory.
|
4,633,864 | 4,633,903 | How do the stream manipulators work? | It is well known that the user can define stream manipulators like this:
ostream& tab(ostream & output)
{
return output<< '\t';
}
And this can be used in main() like this:
cout<<'a'<<tab<<'b'<<'c'<<endl;
Please explain me how does this all work? If operator<< assumes as a second parameter a pointer to the functi... | The standard defines the following operator<< overload in the basic_ostream class template:
basic_ostream<charT,traits>& operator<<(
basic_ostream<charT,traits>& (*pf) (basic_ostream<charT,traits>&) );
Effects: None. Does not behave as a formatted output function (as described in 27.6.2.5.1).
Returns: pf(*this).
... |
4,633,879 | 4,633,931 | Question about best practices and Macros from the book 'C++ Coding Standards' | From Herb Sutter and Andrei Alexandrescu's 'C++ Coding Standards', Item 16: Avoid Macros under Exceptions for this guideline they wrote:
For conditional compilation (e.g.,
system-dependent parts), avoid
littering your code with #ifdefs.
Instead, prefer to organize code such
that the use of macros drives
alte... | What they mean is that you should abstract your code from the system-dependent part through the use of abstract base classes and use condition compilation only at the point of instantiation.
class SystemAgnosticInterface
{
public:
virtual ~SystemAgnosticInterface() {}
virtual void doStuff() = 0;
};
You could t... |
4,634,074 | 4,634,086 | Modifying a makefile |
I have the following file from the PARSEC opensource benchmarks, and I want to be able to profile it using gcc. yet as u know i need to raise the -pg flags. yet i am having difficulties doing so. i tried to use a regular g++ -pg -o files.cpp yet it didnt work. i also tried to modify the makefile that infront of the -o... | Try adding this near the top of the file:
CXXFLAGS+= -pg
|
4,634,295 | 4,634,401 | How can I reuse a base class function in a derived class | Let's say we have these four classes:
BinaryTree,
SplayTree (which is a sub-class of BinaryTree),
BinaryNode and
SplayNode (which is a sub-class of BinaryNode).
In class BinaryTree I have these 2 functions, and in SplayTree I would like to reuse the first one, because it works in the same way as in SplayTree.
//Bi... | The CRTP idiom is used to solve problems like this. Basically, you derive from a template that gets the derived class as a template parameter, so you can use the type in return values etc.
In your instance, you need to create a common base-template for the two tree-types and implement your Find there, while implementin... |
4,634,415 | 4,634,440 | Interface-like inheritance in C++ | I have the following situation, pictured is the theoretical inheritance graph of my classes:
The idea is basically to
1) have two abstract base classes that can be implemented on different platforms (in my case two different operating systems)
2) allow BBase to be up-castable to ABase to be able to handle both equally... | You can directly use that type of hierarchy in C++ by using virtual inheritance:
class ABase{...};
class BBase : public virtual ABase {...};
class A : public virtual ABase {...};
class B : public A, public BBase {...};
Of course if you plan on having more levels, it might be a good idea to use virtual inherita... |
4,634,696 | 4,634,792 | Storing C++ templated objects as same type | I have a class that is a core component of a performance sensitive code path, so I am trying to optimize it as much as possible. The class used to be:
class Widget
{
Widget(int n) : N(n) {}
.... member functions that use the constant value N ....
const int N; // just initialized, will never ... | The issue here is that if you store the widgets as the same type, then the code that retrieves the widgets from that store (by calling GetWidget) doesn't know N at compile time[*]. The code that calls the constructor knows N, but the code that uses the object has to cope with multiple possibilities.
Since the performan... |
4,634,780 | 4,635,604 | c++ Hole punching UDP(RTP) | I am doing a client-server voice chat program(unmanaged C++,win32) in which clients connects to the server using TCP and textchat/chatroom functions are done in TCP while all audiotransmission is sent through a separate UDP/RTP socket (using the API from JRTPLIB).
So the IP is known from the TCP connection, and the por... | There are two possible definitions of "opening a port". One is opening a port with bind() for UDP or listen() for TCP, another one is opening a port in a firewall.
You need to open a port with an API call in order to receive something, there is no way around it, but you probably realize this, so I think you mean openin... |
4,634,930 | 4,634,998 | How to add event listners / signals to a simple superman class? | I can and would love to use boost or std for this. Sorry - I am new to C++. So I created a really simple program like:
#include <iostream>
#include <string>
using namespace std;
class superman
{
public:
void punch(){cout << "superman: I hit the bad guy!" << endl;};
};
int main()
{
superman clark;
clark.punch();... | you can use boost::signal for that
you have to declare one class and overload her operator ()
after uoi have to bind the class on the signal, by using connect() method, and finally, use operator () of the signal
struct HelloWorld
{
void operator()() const
{
std::cout << "Hello, World!" << std::endl;
}
};
... |
4,634,955 | 4,635,446 | glDrawElements with constant normal | I was just curious if you can specify constant normal when drawing with single call of DrawElements. I'm using VAOs and VBOs so it's not that problem because I load them once for all vertices and just store VBO ID, but I could free some memory in graphic card..
this is the way you need to load data into graphics:
glBi... | You can implementing the function using a vertex shader which specify always the same normal. So, it's only required to specify the normal as uniform, since it's the same for those vertices.
|
4,634,968 | 4,901,697 | Allowing developer-specific settings in VS2008 Native C++ projects | Is it possible to combine the following properties, and if so, how?
Store in our version control system some Visual Studio 2008 native C++ (VCPROJ) project files for the developers in our team that use this IDE.
Allow some of those developers to tweak their projects (e.g. using debug version of third-party libraries i... | You may not be able to do this but using a solution that generates the vcproj like CMake for example would let you do this. Scripts all your project with CMake and literally conditionally include a config file(if present for example) that developers can change on their setup.
|
4,635,046 | 4,635,539 | function to convert wstring to const char * for SQlite | as the question says, what would be a suitable template function to convert wstring to const char *? My program is written entirely in Unicode, however, SQlite requires const char * for most of their functions.
I found the method of doing this on msdn, here: http://msdn.microsoft.com/en-us/library/ms235631%28v=vs.80%29... | You should use the *16 sqlite functions (e.g. sqlite3_prepare16) where you4 can give UTF-16 (i.e. wstring) as parameters. Don_t forget to use 2*wcslen as length of the string. If you insist on the const char* functions, you have to convert to UTF-8 first.
|
4,635,154 | 4,635,218 | how can i move pointer of one class to another in c++ | I have class named CiF and I want to move in the constructor pointer of CiF to new class named Cmanager.
I tried something like this:
CiF::CiF() : Cmanager(new Cmanager(CiF THIS))
{
}
please help
thanks
| The following code shows how a pointer of one class is given to another in ctor. I think thats what you're trying to achieve.
I HIGHLY recommend you on not using code like this, but you did not give enough information about your usecase and so I'm not able to give you alternatives.
You probably should take a look into ... |
4,635,259 | 4,635,291 | converting array of bytes to UTF-8 unicode | I have a file saved as UTF-8, and i'm reading it like this:
ReadFile(hFile, pContents, pFile->nFileSize, &dwRead, NULL);
(pContents is a BYTE* of size nFileSize)
its just a small file with 100 bytes or so, contains text which i want to read into memory in wchar_t* format, so i can set the text of edit and static contr... |
MultiByteToWideChar to convert from UTF-8 to UTF-16 (wchar_t).
WideCharToMuliByte to convert from UTF-16 to UTF-8.
|
4,635,823 | 4,637,531 | Qt development lib and crossplatform screen capturing is it true? | Will it capture desctop for me on all platforms if I'll port my windows VS 2008 console app code into Qt app compatable code (I have a console app so I hope it will not be a big trobule to port it into Qt console app)?
| if you're asking if
QPixmap::grabWindow(QApplication::desktop()->winId())
would work on different platforms, then yes it does. I've tested it on my windows and x11 systems and it worked as expected.
hope this helps, regards
|
4,635,891 | 4,641,168 | depth-first search algorithm | the depth-first algorithm implemented in the boost library visits each vertex just one time.
Is there any work around to deactivate this option. I want that the vertexes can be visited whenever there is a branch in any vertex.
any suggestion...
EDIT: The graph is acyclic.
| If you want to enumerate all paths in an acyclic graph, then I don't think you can easily modify depth-first search to do that. There are algorithms specifically designed for this purpose, in particular: Rubin, F.; , "Enumerating all simple paths in a graph," Circuits and Systems, IEEE Transactions on , vol.25, no.8, p... |
4,636,020 | 4,636,085 | MSVC 2010 linker error 2005 with std::cout in static library | I have found other examples of people having this problem but have had no luck with their solutions. I am trying to use std::cout in a static library that also uses boost threads and bind. When I don't use and std::cout it compiles and links fine with the main program but when I do and I compile the library I have no... | Try checking -> Project + Properties, C/C++, Code Generation, Runtime library.
Your .lib and your main project must use the same setting here.
|
4,636,039 | 4,637,514 | What is the preferred way to write my linux daemons? | Hello to All
I have a PHP website that should use some cached data (stored in Memcache, for example).
The data should be stored in cache by daemons fetching it from web services and some of it should be stored in MySQL server too.
The daemons should do the following:
Fetch foreign exchange rates, parse them and store... | Perl and Python are default answers for writing such scripts. But it doesn't matter (much) what language you use if you write good code. The more importat thing is that how you handle your script on failure.
In the long run you may see your scripts are failing seldom for arbitrary reasons, and it may not worth for you... |
4,636,042 | 4,636,113 | Determining the location of staves in sheet music | I want to be able to determine the location of staves in sheet music. Example: http://imgur.com/XOAMr
The sheet music could be scanned and so could be skewed, have gaps etc. I've spent some time researching various methods (the Hough transform seems to crop up a lot) and looking at how staves are recognised in the Op... | Well my advise is to go with a blob extraction algorithm
See it in action here
|
4,636,144 | 4,636,163 | Declaring a function that return a 2D array in a header file? | I am trying to declare, within my header file, a function that returns a 2D array. How can this be accomplished, given that we already know the size of the array? Below is what I'm currently doing.
class Sample
{
public:
char[x][y] getArr();
void blah(int x, int y);
private:
const static int x = 8;
co... | It turns-out my original answer was totally incorrect, but I can't delete it since it's been accepted. From two separate answers below, I was able to compile this:
class Sample
{
const static int x = 8;
const static int y = 2;
public:
typedef char SampleArray[x][y];
SampleArray& getArr();
void blah... |
4,636,149 | 4,636,301 | Container needed for C++ | I need a container (like array)for integers in such a way that given x and y and z ,which has to be inserted between x and y it will be possible to insert z between them.And given x and y ,get if x is placed left to the y.
| Well you could use an std::set<int>. It will always keep your elements ordered.
|
4,636,182 | 4,636,230 | Problem with std::map::iterator after calling erase() | // erasing from map
#include <iostream>
#include <map>
using namespace std;
int main ()
{
map<char,int> mymap;
map<char,int>::iterator it(mymap.begin());
// insert some values:
mymap['a']=10;
mymap['b']=20;
mymap['c']=30;
mymap['d']=40;
mymap['e']=50;
mymap['f']=60;
it=mymap.find('a');
mymap.er... | Erasing an element of a map invalidates iterators pointing to that element (after all that element has been deleted). You shouldn't reuse that iterator.
Since C++11 erase() returns a new iterator pointing to the next element, which can be used to continue iterating:
it = mymap.begin();
while (it != mymap.end()) {
if... |
4,636,260 | 4,636,450 | c++: good name for argument argument conversion classes | In C++, I sometimes end up with utility classes like this:
struct time_ref
{
time_ref(FILETIME & ft) : ftval(&ft), ttval(0) {}
time_ref(time_t & tt) : ttval(&tt), ftval(0) {}
FILETIME * ftval;
time_t * ttval;
}
They rely on implcit conversions e.g. to reduce the numner of overloads:
void Foo(int x, int... | A shim is often a good choice when you need to handle many different argument types, even after your interface is "done". It allows you to do the conversion in a modular, fairly reusable way. See this wikipedia entry and its referenced articles for more information.
|
4,636,378 | 4,636,423 | How to write this php code in c++ | $x = pack("N", $num1).pack("N", $num2).$data;
I am trying to do it with
union unionchal {
struct ast{
unsigned long a;
unsigned long b;
char c[8];
} chal;
unsigned char response[16];
};
ast being the input and response being the output
It is meant to output yp¶ ‚¬þÖHpö€ì_± but gives ¶pyßêÈ)ÖHpöì_
I ... | Try using htonl on your integers before placing them into the structure. It will convert them into big-endian order. If you need 64-bit longs, see the discussion about it on SE.
|
4,636,405 | 4,636,416 | Stack overflow when overloading << operator | #include<iostream>
using namespace std;
class aClass
{
public:
char *message;
aClass(const char *message);
~aClass(){delete[] message;}
};
aClass::aClass(const char* newmessage)
{
message = new char[strlen(newmessage) +1];
strcpy(message,newmessage);
}
const ostream& operator<<(const ostream& o,... | Because you have const where it shouldn't be:
///// /////
const ostream& operator<<(const ostream& o, const aClass &a)
The output stream is suppose to be non-const; after all, outputting data is changing something. So when you do this:
o << a.message;
It cannot use the normal overload for char*, b... |
4,636,406 | 4,636,540 | Up to date OpenGL tutorials or books for c++ | I'm new to OpenGL, I'm on Linux and have an NVIDIA card that supports OpenGL 3.2.
I'd like to learn from the most recent changes of OpenGL. I'm looking for C++ tutorials or books of OpenGL 3.0+.
I know this question has been asked frequently but all the sources seem to be old or the tutorials are in C. I couldn't find... | Get a copy of the fifth edition of the OpenGL Superbible. It comes with a C++ library for use with OpenGL, and only covers the modern programmable pipeline.
|
4,636,439 | 4,636,504 | compiling error on C++ | can somebody please explain why can't I compile this snippet of the code? I know that this design is very bad, but I just want to know why I can't compile it, thanks in advance
P.S. sorry for the format, can't find backquotes on the panel
//Deriving classes definition
class IntClass; class DoubleClass;
//The Virtual ... | Inside IntClass::addDouble, you use the class DoubleClass, but at that point DoubleClass has only a forward declaration, so you can't call methods on it.
This can be fixed by putting the body of IntClass::addDouble after the full declaration of class DoubleClass, or by separating your code into header and implementatio... |
4,636,456 | 4,674,531 | How to get a stack trace for C++ using gcc with line number information? | We use stack traces in proprietary assert like macro to catch developer mistakes - when error is caught, stack trace is printed.
I find gcc's pair backtrace()/backtrace_symbols() methods insufficient:
Names are mangled
No line information
1st problem can be resolved by abi::__cxa_demangle.
However 2nd problem s more ... | Not too long ago I answered a similar question. You should take a look at the source code available on method #4, which also prints line numbers and filenames.
Method #4:
A small improvement I've done on method #3 to print line numbers. This could be copied to work on method #2 also.
Basically, it uses addr2line to c... |
4,636,512 | 4,636,539 | C# generic with constant | Is there something similar to this C++ template?
template <int A>
class B
{
int f()
{
return A;
}
}
I want to make every instance of B<1>, B<2>, etc (eg tuple) a different type.
| The short answer is no.
It doesn't fit the way C# generics, as apposed to C++ templates, work.
The .net generics are not a language feature, they are a runtime feature. The runtime knows how to instantiate generics from special generic bytecode which is rather restricted compared to what C++ templates can describe.
Com... |
4,636,575 | 4,636,632 | Win conditions for a connect-4 like game | I have an 5x10 array that is populated with random values 1-5. I want to be able to check when 3 numbers, either horizontally, or vertically, match. I can't figure out a way to do this without writing a ton of if statements.
Here is the code for the randomly populated array
int i;
int rowincrement = 10;
int row = 0;
... | Suppose that you have some particular starting point (x, y) and you're curious if there's three equal numbers in a row that start at this point. Let's consider just the case where you're looking in the horizontal direction. Then one way to do this (ignoring bounds-checking) would be like this:
bool IsHorizontalMatch(... |
4,636,651 | 4,636,747 | Substituting Boost for C++0x Library Features | I'm working on a library that makes heavy use of the latest C++0x language and library features. I'm mainly developing in Linux with gcc4.6, but would like to test in OS X (because Apple makes excellent profiling tools). Unfortunately all versions of libstdc++ that ship with any gcc4.6 for OS X I've found have their <... | This is not a standard complaint code because you're not allowed to change the inside of namespace std, but it should work on most compilers:
#include <boost/your_headers.hpp>
namespace std {
using boost::thread;
using boost::mutex;
// ...
}
the remaining code is unchanged.
|
4,636,672 | 4,636,705 | Moving all {'s to the right of function name? | I'm merging some code and this code's functions are all like this:
void someFunction()
{
}
While all our code needs to be:
void someFunction() {
}
I was wondering if there was a way to find and replace in order to change everything at once. It would save me hours of work.
I'm using VS 2008.
Thanks
| You can use Visual Studio's Replace All on the Find and Replace window, with regular expressions. Going to be something like
Find: \):b*\n:b*\{
Replace: ) {
You'll want to try it out a bit first to make sure it doesn't change things you don't want changed, like if you want to keep your if() { on separate lines.
Another... |
4,636,802 | 4,636,998 | Why is there a prefix/postfix ++ but no prefix/postfix +=? | This may seem like a silly question, but why is it that in many languages there exists a prefix and postfix version of the ++ and -- operator, but no similar prefix/postfix versions of other operators like += or -=? For example, it seems like if I can write this code:
myArray[x++] = 137; // Write 137 to array index at... | I'd guess there are several reasons, I think among the more heavily weighted might be:
there probably weren't thought to be too many real use cases (it may not have even occurred to some language designers in the early days)
pre/post increment mapped directly to machine operations (at least on several machines), so th... |
4,636,805 | 4,636,820 | Does postfix increment perform increment not on returned value? | Again, a silly question.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
int i = 0;
i = i++;
cout<<i;
return 0;
}
I get 1 printed as a result of this program though I expected 0: first a temp object created eing equal 0, then i is incremented, then temp object is returned and assigned to... | The behavior of
i = i++;
is undefined. If a single expression assigns two different values to a variable, the C++ spec says that anything can happen - it could take on its old value, one of the two new values, or pretty much anything at all. The reason for this is that it allows the compiler to make much more aggres... |
4,636,815 | 4,637,203 | Unhandled exception after execute | I'm trying to make a gray image more bright, the code did compile normaly but no change in the seconde picture, and an error message Unhandled exception ... showed up after that the execute is done. Here is a piece of my code:
int main(int argc, _TCHAR* argv[])
{
IplImage *img = cvLoadImage("mra.jpg");
if (!img... |
You say you use C++ in your tags, but use the C interface of opencv. Why? The C++ interface is far friendlier.
There are opencv functions for what your functions are doing. http://opencv.willowgarage.com/documentation/cpp/core_operations_on_arrays.html#cv-minmaxloc for min and max and http://opencv.willowgarage.com/do... |
4,637,095 | 4,637,106 | Python equivalent for C++ STL vector/list containers | Is there something similar in Python that I would use for a container that's like a vector and a list?
Any links would be helpful too.
| You can use the inbuilt list - underlying implementation is similar to C++ vector. Although some things differ - for example, you can put objects of different type in one and the same list.
http://effbot.org/zone/python-list.htm
N.B.: Please keep in mind that vector and list are two very different data structures. List... |
4,637,139 | 4,637,159 | could anyone suggest me a simple way of splitting names in C++ | I've been trying to split a name into first and last name, but I'm sure my implementation is not the best one as far as simplicity.
string name = "John Smith";
string first;
string last (name, name.find(" "));//getting lastname
for(int i=0; i<name.find(" "); i++)
{
first += name[i];//getting fir... | How about using the substr method from string to split things up combined with find:
std::string name = "John Smith"
std::size_t pos = name.find(" ");
std::cout << "First: " << name.substr(0, pos) << " Last: " << name.substr(pos, std::string::npos) << std::endl;
where I've also used the std::string::npos to indicate t... |
4,637,140 | 4,637,178 | How to Release jstring that is sent from Native Code back to Java? | I have the following native routine:
void sendMessage(const char* text)
{
JNIEnv* env;
if(!_jvm)
return;
_jvm->AttachCurrentThread(&env, NULL);
if(!_nativesCls)
_nativesCls = env->FindClass("com/foo/BaseLib");
if(_nativesCls == 0)
return;
jstring message = env->Ne... | DeleteLocalRef(). Just like any other Java object that was allocated within JNI. However, it will be automatically garbage-collected once the JNI method returns. Details here: http://download.oracle.com/javase/1.3/docs/guide/jni/spec/design.doc.html#1242
|
4,637,277 | 4,637,524 | Debug external console program using Eclipse | How can I use Eclipse to debug a (C/C++) console program running external from Eclipse? I'd like to click the Debug button to launch the external console (Cygwin shell in Windows; or Terminal in OS X) and break in main().
| You can attach your debug session to an external application:
Is it possible to attach a debugging session to a running program in eclipse CDT
Greetings
|
4,637,348 | 4,637,373 | Windows GUI applications in VisualStudio | What are the valid ways to write (hopefully native) C++ applications with GUI in VS 2010?
I remember some 10 years ago I was using MFC, any big changes today?
| If you want to stay with Native API then MFC is still a good choice or plain Win32 API.
There are new controls like the ribbon control introduced in VS2010. There's a tutorial on native development with VS2010 on MSDN. There are also a lot of C++0x features available to your native program if you're using VS2010.
Qt... |
4,637,406 | 4,637,469 | problem with inheritance | class OGraph {
public:
OGraph() { }
virtual ~OGraph();
virtual bool is_directed()=0;
};
class OUGraph : public OGraph {
public:
OUGraph() { }
bool is_directed() { return false; }
~OUGraph() {}
};
but when I do this
OUGraph myGraph();
cout << myGraph.is_directed();
I get the following error:... | You have no implementation provided for virtual ~OGraph();. Either provide an implementation, specify it as pure virtual with = 0;, or just get rid of it.
The compiler is expecting to attach type info for the class to the implementation of its first virtual method. Your first virtual method is undefined, so the imple... |
4,637,442 | 4,637,452 | Using std::unique_ptr with standard containers | I've been looking for a way to do safe vectors and maps of dynamic pointers, when I realized C++11 adds unique_ptrs. I looked into how to use them on Google, but have been unsuccessful in looking for details. What I need to know are the following:
What, exactly, is different between pointers and unique_ptrs besides au... |
Nothing. A unique_ptr is just a wrapper around a pointer, which deletes the pointer when the unique_ptr is destroyed. It has no overhead (just like the auto_ptr template it replaces).
Nope -- it will just work. The difficulty actually comes from inserting the pointer into the vector or map -- whereas you must move the... |
4,637,580 | 4,637,636 | Getting Clipboard data in raw format in c++ | I've been playing around with the windows clipboard. I noticed that you can only view the clipboard if you supply a format. I've seen programs that can dump the raw contents of the clipboard. Look at http://www.autohotkey.com/docs/misc/Clipboard.htm#ClipboardAll for an example of what I mean.
Is there a way to do some... | There's no "raw" data involved. Just enumerate all the formats currently on the clipboard, and fetch and save the contents of each format. But be careful of automatic format conversions.
If you carefully read the autohotkey documentation you linked, it even tells you that it's retrieving each format separately, and t... |
4,637,648 | 4,637,678 | Optimizing the finding of the widest string in an array of strings? | Right now I have an array of std::strings, and have a function in my font to find how wide it is.
for(std::vector<std::pair<std::string,bool>>::const_iterator it = items.begin();
it != items.end(); ++it)
{
cSz = getFont().getTextWidth(it->first);
if( cSz > h)
{
h = cSz;
}
}
widestItem = h;
I was wonde... | If I were optimizing this I'd:
Make sure to use a profiler to find out that this is where significant time is going.
Maybe have a cache of (font, string) tuples. If you're repeatedly computing the width of the same strings, this will help. But it depends on your exact use case.
You can make your getTextWidth method ve... |
4,637,662 | 4,637,669 | Self-imposed try/catch for unwanted integers | Try and catch statements are easy for actual exceptions, but how might I write a try/catch for a self-imposed restriction?
For example, if I am getting an integer from cin that I want to be either 2,4, or 7, and anything else to print "That number is not valid" and try again, how would this get written in c++?
| @Adam Rosenfield is right: exceptions should be reserved for exceptional situations -- i.e., things you don't expect to happen (or at least not very often). A user entering bad data is expected to happen -- frequently.
Since you always want to read the input at least once, this is a situation where a do/while loop make... |
4,637,774 | 4,637,788 | Is the size of a struct required to be an exact multiple of the alignment of that struct? | Once again, I'm questioning a longstanding belief.
Until today, I believed that the alignment of the following struct would normally be 4 and the size would normally be 5...
struct example
{
int m_Assume_32_Bits;
char m_Assume_8_Bit_Bytes;
};
Because of this assumption, I have data structure code that uses offs... | One definition of alignment size:
The alignment size of a struct is the offset from one element to the next element when you have an array of that struct.
By its nature, if you have an array of a struct with two elements, then both need to have aligned members, so that means that yes, the size has to be a multiple of... |
4,637,811 | 4,637,816 | How to use namespace across several files | I notice that C++'s std namespace is spread across several files (like in vector, string, iostream, etc.). How can I accomplish the same thing in my programs? Do I simply declare the same namespace in each individual header file, so that it's something like:
a.h
namespace something
{
class A {};
}
b.h
#include "a.h"
... | Yes, that is exactly how to do it.
|
4,637,951 | 4,637,973 | What is implicit sharing? | I am building a game engine library in C++. A little while back I was using Qt to build an application and was rather fascinated with its use of Implicit Sharing. I am wondering if anybody could explain this technique in greater detail or could offer a simple example of this in action.
| The key idea behind implicit sharing seems to go around using the more common term copy-on-write. The idea behind copy-on-write is to have each object serve as a wrapper around a pointer to the actual implementation. Each implementation object keeps track of the number of pointers into it. Whenever an operation is p... |
4,638,279 | 4,638,290 | Access GCC Compiler Switches From Inside C/C++ Program | It is possible to access the gcc compiler switches a c/c++ program was compiled with from inside the program?
In my application as part of the logging information I would like to write which switches the program was compiled with, such as optimizations and pre-processor variable input by the compiler.
| Not in any standard way.
It is usually the build system that will generate such things in a version string that is built into the application (but none of it is automatic).
|
4,638,364 | 4,638,386 | Undefined behavior and sequence points reloaded | Consider this topic a sequel of the following topic:
Previous installment
Undefined behavior and sequence points
Let's revisit this funny and convoluted expression (the italicized phrases are taken from the above topic *smile* ):
i += ++i;
We say this invokes undefined-behavior. I presume that when say this, we imp... | It looks like the code
i.operator+=(i.operator ++());
Works perfectly fine with regards to sequence points. Section 1.9.17 of the C++ ISO standard says this about sequence points and function evaluation:
When calling a function (whether or not the function is inline), there is a sequence point after the evaluation o... |
4,638,429 | 4,638,499 | c++ placement new vs. overloading new | Many questions on SO ask about placement new feature of C++ (example 1, example 2) why it is used for. Many answers saying - custom allocating of objects like in pre-allocated spaces.
But question is - why need placement new for this? Won't just overload of operator new for class enough? By overload operator new for cl... | You are correct in thinking that both can be used to solve a same category of problems, but what you are missing is that operator new overloading is intrusive (allocation strategy is in the object), while placement new isn't (allocation strategy is completely independent).
Martin York's answer provides a great example ... |
4,638,553 | 4,664,334 | Is there a library available which easily can record and replay results of API calls? | I'm working on writing various things that call relatively complicated Win32 API functions. Here's an example:
//Encapsulates calling NtQuerySystemInformation buffer management.
WindowsApi::AutoArray NtDll::NtQuerySystemInformation(
SystemInformationClass toGet ) const
{
AutoArray result;
ULONG allocationS... | Is it really that hard to implement by hand?
#include <stddef.h>
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
typedef char BYTE;
//Note: Buffer is MODIFIED after this call (hence why it's not const)! Don't re-use it!
void saveBuffer(FILE* stream, BYTE* buffer, size_t bufferSize)
{
assert(bufferSize ... |
4,638,714 | 4,638,727 | type casting template | I am try to make a template that type casts and I got error on compiling following program.
#include<iostream.h>
#include<conio.h>
template<typename T,typename U>
T mycast(U u)
{
return (T)u;
}
int main()
{
double d= 10.6577;
int j= mycast<int>(d) ;
return 0;
}
please tell me where is problem and how to overcome?
... | If I remove the #include <iostream.h> (because it should be #include <iostream>, but it's not needed anyway), then it compiles fine (in VS 2010).
|
4,638,824 | 4,638,870 | Is there a setting in the Windows headers that disables definition of TCHAR-neutral function name macros? | Let's say I'm implementing a simple wrapper around ExpandEnvironmentStringsW:
//ExpandNStuff.hpp:
#include <string>
namespace WindowsApi
{
std::wstring ExpandEnvironmentStrings(const std::wstring& source);
}
//ExpandNStuff.cpp:
#include <windows.h>
#include "ExpandNStuff.hpp"
#include "Win32Exception.hpp"
namespac... | Their definitions aren't wrapped in any macro.
WINBASEAPI
BOOL
WINAPI
GetVolumeInformationA(
__in_opt LPCSTR lpRootPathName,
__out_ecount_opt(nVolumeNameSize) LPSTR lpVolumeNameBuffer,
__in DWORD nVolumeNameSize,
__out_opt LPDWORD lpVolumeSerialNumber,
__out_opt LPDWORD lpMaximumComponentLengt... |
4,638,852 | 4,639,329 | Default arguments in function and polymorphism |
Why can default arguments in C++ functions be considered polymorphism?
Why is it consider ad-hoc polymorphism and universal polymorphism?
I think that it can be considered as an ad-hoc polymorphism as its like overloading functions(?), but in what way is it universal polymorphism?
| If something is polymorphic, it has many shapes.
In computer science, polymorphism is a
programming language feature that
allows values of different data types
to be handled using a uniform
interface.
As this link explains, there are different types of polymorphism. Ad-hoc polymorphism is what we call it whe... |
4,638,903 | 4,638,926 | Google Mock: Mocked overloaded functions create warning C4373 | I'm mocking a C++ class which has 2 overloaded functions using Google Mock and VS2010:
#include "stdafx.h"
#include "gmock/gmock.h"
#include "A.h"
class MockA : public A
{
public:
// ...
MOCK_METHOD3(myFunc, void(const int id, const int errorCode, const CString errorMsg));
MOCK_METHOD1(myFunc, void(const ... | If this is new code, you should be fine. The C4373 warning is saying that old versions of Visual Studio violated the standard. From the linked documentation:
Versions of the compiler prior to
Visual C++ 2008 bind the function to
the method in the base class, then
issue a warning message. Subsequent
versions o... |
4,638,934 | 4,639,953 | C++ Linux getpeername and getsockname return only port | In my Linux C++ application I'm using getpeername and getsockname.
when IPv6 enabled on the OS, both getpeername and getsockname return only port!
code:
int GetSockAndPeer(int sock)
{
struct sockaddr_storage ss;
socklen_t salen = sizeof(ss);
struct sockaddr *sa;
struct addrinfo hints, *padd... | Related to RFC2553 you have to use the IN6_IS_ADDR_V4MAPPED and IN6_IS_ADDR_V4COMPAT macros to identify if there is any usable IPv4 information available within yours socket_storage, or to be exact the sockaddr_in6 structure:
struct sockaddr_in6 {
sa_family_t sin6_family; /* AF_INET6 */
in_port_t s... |
4,638,935 | 4,639,612 | Examples of practical usage of Boost::MPL? | Can you share any real-world examples of Boost::MPL usage (except lambdas), just to let me better understand its purposes and field of practical usage? The MPL documentation tutorial has a dimensional analysis example, but maybe because it's such an academic example it hasn't given me a feeling of Boost::MPL and when i... | I've used Boost.Mpl to generate variant-like classes.
For example, given a MPL type list such as this:
typedef boost::mpl::set<Foo, Bar, Baz> type_set;
I then use boost::mpl::fold to build a chain of classes derived from each others which each adds an std::unordered_set of one of the types in the type set. The end res... |
4,638,956 | 4,638,975 | Why is this default template parameter not allowed? | I have the following class:
template <typename Type = void>
class AlignedMemory {
public:
AlignedMemory(size_t alignment, size_t size)
: memptr_(0) {
int iret(posix_memalign((void **)&memptr_, alignment, size));
if (iret) throw system_error("posix_memalign");
}
virtual ~AlignedMemo... | I think that you need to write:
AlignedMemory<> blah(512, 512);
See 14.3 [temp.arg] / 4:
When default template-arguments are used, a template-argument list can be empty. In that case the empty <> brackets shall still be used as the template-argument-list.
|
4,638,988 | 4,639,464 | How can we compute N choose K modulus a prime number without overflow? | How can we computer (N choose K)% M in C or C++ without invoking overflow ?
For the particular case when N (4<=N<=1000) and K (1<=K<=N) and M = 1000003.
| To compute (n choose k) % M, you can separately compute the nominator (n!) modulus M and the denominator (k!*(n - k)!) modulus M and then multiply the nominator by the denominator's modular multiplicative inverse (in M). Since M is prime, you can use Fermat's Little Theorem to calculate the multiplicative inverse.
Ther... |
4,639,232 | 4,639,353 | Finding all perfect squares of the form XXYY | I have to find 4 digits number of the form XXYY that are perfect squares of any integer. I have written this code, but it gives the square root of all numbers when I have to filter only perfect integer numbers.
I want to show sqrt(z) only when it is an integer.
#include<math.h>
#include<iostream.h>
#include<conio.h>
vo... | I'd probably check it like this, because my policy is to be paranoid about the accuracy of math functions:
double root = sqrt(z);
int introot = floor(root + 0.5); // round to nearby integer
if ((introot * introot) == z) { // integer arithmetic, so precise
cout << introot << " == sqrt(" << z << ")\n";
}
double can... |
4,639,360 | 4,639,390 | Unnecessary linked libraries in linker | I have a project which I can exclude some of libraries from linker and still builds ?
Is it any better to exclude them in terms of the performance and memory of final product ?
| Excluding some unused libraries from the final executable might make startup a bit faster and save a tiny amount of memory - chances are only the header and library startup code will actually end up being loaded, and these can be paged out after startup.
However, don't do it manually. If you were told to add the librar... |
4,639,576 | 4,639,839 | Copy constructor is not called for copy-initialization or optimized? | If copy constructor is made private then in
Case 1: No error, the compiler doesn't care if the copy constructor was defined in class.
Case 2: Error, copy constructor is private and when it is made public, it is elided.
Does it directly optimizes the copy without being noticing that if the constructor was made private?
... | Case 2 comes under 12.8/31 in N3225:
A program is ill-formed if the
copy/move constructor or the copy/move
assignment operator for an object is
implicitly odr-used and the special
member function is not accessible.
Just because the copy ctor is elided doesn't mean it isn't odr-used. 3.2/2:
A member of a set... |
4,639,600 | 4,639,654 | Reading different data types in shared memory | I want to share some memory between different processes running a DLL. Therefore i create a memory-mapped-file by HANDLE hSharedFile = CreateFileMapping(...) then LPBYTE hSharedView = MapViewOfFile(...) and LPBYTE aux = hSharedView
Now I want to read a bool, a int, a float and a char from the aux array. Reading a bool ... | If you know, for instance, that array elements aux[13..16] contain a float, then you can access this float in several ways:
float f = *(float*)&aux[13] ; // Makes a copy. The simplest solution.
float* pf = (float*)&aux[13] ; // Here you have to use *pf to access the float.
float& rf = *(float*)&aux[13] ; // Doesn't ... |
4,639,657 | 4,639,919 | Scale Bitmapfont clearly with openGL (interpolation)? | I load an bitmapfont (as png image) in my openGL Application to render characters from there at a fixed size. That's working. But: If I want to scale some glyphs at a smaller size it doesnt look great. Is there a way - without using pregenerated mipmaps (I have a big bunch of several characters and need stepless sizes)... | Did you try using Linear filtering on your textures?:
glTexParameteri(GL_TEXTURE_2D, GL_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_MAG_FILTER, GL_LINEAR);
This after binding textures.
|
4,639,703 | 4,639,757 | why the polymorphic types error and cleanup question? | #include <iostream>
#include <string>
#include <map>
#include <vector>
class base {};
class derived1 : public base
{
public:
unsigned short n;
derived1()
{
n = 2;
}
};
class derived2 : public base {};
void main()
{
// way 1
{
std::vector<derived1> a1;
... | To make Base a polymorphic type, you need to give it at least one virtual function. The easiest in this case would be the destructor:
class Base {
public:
virtual ~Base() { }
};
Regarding your question about cleanup:
Technically, there is some undefined behaviour in both ways, because the objects that the map refer... |
4,639,873 | 4,639,880 | C++ Call base constructor with enum | Is it possible to pass a value and a constant enum to the base constructor of a class?
For example:
enum CarBrand
{
Volkswagen,
Ferrari,
Bugatti
};
class Car
{
public:
Car(int horsePower, CarBrand brand)
{
this->horsePower = horsePower;
this->brand = brand;
}
... | In C++, you do not prefix the enum value with the enum type name. Just say Ferrari.
|
4,639,909 | 6,364,939 | standard way to perform a clean shutdown with Boost.Asio | I'm writing a cross-platform server program in C++ using Boost.Asio. Following the HTTP Server example on this page, I'd like to handle a user termination request without using implementation-specific APIs. I've initially attempted to use the standard C signal library, but have been unable to find a design pattern su... | Version 1.5.3 of Boost.Asio (to be integrated in upcoming boost 1.47 release?) has the signal_set class:
#include <boost/asio/signal_set.hpp>
// Register signal handlers so that the daemon may be shut down. You may
// also want to register for other signals, such as SIGHUP to trigger a
// re-read of a configuration fi... |
4,640,058 | 4,640,113 | C++ Multithreaded server help | I'm working on a multithreaded server in c++ using boost-asio. Currently a design problem I'm running into deals with erasing a connection.
I have a single server instance which holds a vector of connection objects. These connections receive commands which I parse. One command in particular deals with sending data to A... | Whatever class maintains this vector of connections needs a strand. Use strand::post or strand::dispatch when accessing, adding to, or removing from the vector. The strand concept is explained in detail in the documentation.
A strand is defined as a strictly
sequential invocation of event
handlers (i.e. no concurr... |
4,640,141 | 4,640,175 | returning filename from file save dialog (windows32) | I have a simple save file dialog that I wish to use as a tool to return the file path, name, and extension. This function produces a runtime error, saying that the stack around filename is corrupted. I wish to use it like so:
wchar_t filename[] = L"";
newGradebookDialog( hwnd, filename );
And here is my function. It m... | wchar_t filename[] = L"";
That's an array with one element. You are copying a much bigger string into it, that corrupts the stack frame. Fix:
wchar_t filename[MAX_PATH] = {0};
|
4,640,162 | 4,640,186 | does ifstream accept variable file name? | does ifstream accept variable file name?
I am trying to give a fine as an argument and then will try to read it. What should be the best way?
| Yes, of course it does.
const char * filename = "abc.txt";
std::ifstream fin(filename);
Or using std::string
std::string filename = "abc.txt";
std::ifstream fin(filename.c_str());
With C++11, you can just use the string directly.
std::ifstream fin(filename);
|
4,640,281 | 4,640,356 | Design of std::ifstream class | Those of us who have seen the beauty of STL try to use it as much as possible, and also encourage others to use it wherever we see them using raw pointers and arrays. Scott Meyers have written a whole book on STL, with title Effective STL. Yet what happened to the developers of ifstream that they preferred char* over s... | My copy of the standard disagrees with you. It says both these are overloads:
void open(const char* s, ios_base::openmode mode = ios_base::in);
void open(const string& s, ios_base::openmode mode = ios_base::in);
However, that copy of the standard is a draft of the next version of the standard, C++0x.
The reason for th... |
4,640,315 | 4,640,323 | How to make OpenSSL use http instead of https? | So what I want is simple -I love openSSL api. I found some simple code to begin with for learning it. I am quite new to server creation stuff. I wonder - how to make OpenSSL work with simple http instead of https? I mean I want to provide same service, be capable to jump into https when I need to but have no protection... | HTTPS is simple HTTP with SSL (the implementations of which is the point of OpenSSL). The S in HTTPS stands for secure.
Don't use the OpenSSL API when you don't want SSL.
|
4,640,362 | 4,640,377 | Understanding C++ struct size | Consider the following code:
struct CExample {
int a;
}
int main(int argc, char* argv[]) {
CExample ce1;
CExample ce2;
cout << "Size:" << sizeof(ce1) << " Address: " << &ce1 << endl;
cout << "Size:" << sizeof(ce2) << " Address: " << &ce2 << endl;
CExample ceArr[2];
... | Because objects in an array are required to be contiguous. Objects declared consecutively on the stack(in source code, not machine) are not[required to be contiguous], although they can be.
|
4,640,509 | 4,640,521 | Linking a DLL in Visual Studio | I'm using Visual Studio C++ 2005 on Windows XP.
I have created a DLL shared library using Visual Studio C++ 2005.
However, I am not sure how to link it. Normally I have just created the static libraries (*.lib).
Do I link the same way I would when linking a library. By using the properties C/C++ and linker general prop... | When you create the DLL there should be a .lib file created for the purpose of dynamic linking. You can use these just as you would static .lib files.
|
4,640,514 | 4,640,541 | Changing visual style of controls based on windows version | I'm looking to have vista/win7 use Aero-style windows while XP users use normal window style (how does one get windows XP stlye and not win95 styles btw?)
The idea is something like this:
OSVERSIONINFOEX osvi;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
GetVersionEx((OSVERSIONINFO*)&osvi);
if (osvi.dwMajorVersi... | You are mixing compile-time evaluation of pragma with run-time execution of code. Obviously this won't work.
It's possible to keep a manifest for the application in "PutYourProgramNameHere.exe.manifest" file. So if you need different manifests for XP and Vista/Win7, then you can install different manifest files when yo... |
4,640,543 | 4,640,680 | What's the difference between integer promotions and integer conversions in C++ | Section 4.5 of the C++ standard (integer promotion) talks about specific cases of converting integral types to types with a higher rank.
Section 4.7 of the C++ standard (integral conversions) begins with (bullet 4.7.1):
An rvalue of an integer type can be converted to an rvalue of another integer type. An rvalue of... | I think that the distinction is important because both do not fall in the same conversion category and have different rank (see 13.3.3.1.1, Standard conversion sequences). The rank makes a difference when it comes to overload resolution :
Standard conversion sequences are ordered by their ranks: an Exact Match is a be... |
4,640,617 | 4,640,635 | When to use the for loop over the while loop? | We can use for loop and while loop for same purpose.
in what means they effect our code if I use for instead of while? same question arises between if-else and switch-case? how to decide what to use?
for example which one you would prefer?
This code:
int main()
{
int n = 10;
for(int i=0;i<n;i++)
{
do... | If you know the number of iterations the loop should run beforehand, I would recommend the for construct. While loops are good for when the loop's terminating condition happens at some yet-to-be determined time.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.