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
3,646,699
3,646,768
How to make function local to main only?
Let us say i have File1.c: #include<stdio.h> #include"File2.c" void test(void) { sum(1,2); } int main(void) { int sum(int a,int b); test(); sum(10,20); return 0; } File2.c: int sum(int x,int y) { printf("\nThe Sum is %d",x+y); } Now as far as my understanding goes test() calling sum() should give a Compile-Time Err...
Prototypes are helpful when compiling as they tell the compiler what a function's signature is. They are not a means of access control, though. What you want to do is put sum() into the same source file as main() and give it static linkage. Declaring it static means it will only be available in that one .c file, so fun...
3,646,715
3,646,729
virtual functions are determine during the compilation?
i tried to look up whether virtual function determine during compilation or while running. while looking i found something as dynamic linking/late binding but i didn't understand if it means that the function itself determine during compilation before the executable or during the executable. can someone please explain?...
For virtual functions resolution is done at runtime. When you have an instance of an object the resolution of which method to call is known only when the program is running because only at runtime you know the exact type of this instance. For non-virtual functions this resolution can be done at compile time because it ...
3,646,779
3,646,782
unrecognized type in a function call
I am trying to print into a file in C++ and for some reason I keep getting this weird error: error C2061: syntax error : identifier 'ofstream' I included the following: #include <fstream> #include <iostream> This is my function: void Date::PrintDate(ofstream& resultFile) const { resultFile << m_day << "/" << m...
Use std::ofstream This is because we have to explicitly specify which ofstream we are talking about. Since the standard namespace std contains the name ofstream, it has to be explicitly told to the compiler There are essentially two ways: Just before all the include files in the .cpp file, have a using directive 1: usi...
3,646,785
3,646,896
Automatic library selection
I noticed that when linking boost libraries in VS2010, I only need to specify the linking directory, and the compiler automatically selects the right libary to link. How can I do the same with my libraries?
Visual C/C++ has a #pragma that allows you to 'insert' linker options, e.g. #pragma comment(linker,"/DEFAULTLIB:myveryownlibrary.lib") See http://msdn.microsoft.com/en-us/library/7f0aews7%28v=vs.71%29.aspx for more information (look for /DEFAULTLIB).
3,646,802
3,647,184
C preprocessor macros: check if token was declared
This is for the C preprocessor experts: How can I declare an enum with a list of some identifiers and later during the switch-statement check if an identifier was included in the list? Example of what I need: typedef enum { e1, e2, e3, e4, e5, e6 } e; e x; switch (x) { #if DECLARED_IN_ENUM (e1) case e1 : ... #endif ...
I don't think BOOST_PP_SEQ_CONTAINS can be implemented. It would require you to be able to compare two sequences of preprocessing tokens, which you can't do. However, if you rearrange your logic a bit, you can get something closer to what you want. First, we need a couple of helper macros for use with BOOST_PP_SEQ_FO...
3,646,967
3,647,427
Rendering Cubes as quickly as possible? (OpenGL)
I'm making a 3D game with OpenGL that basically has a world made entirely of AABB cubes. I created this to make 24 verticie cubes: void CBox::UpdateDimensions( float w, float h, float d, Vertex3f c ) { width = w; height = h; depth = d; center = c; Vertex3f verticies[24]; GLfloat vboverticies[72...
What I'm wondering is if there is a way to do this by only uploaading 8 verticies to the graphics card instead of 24? Take a look at glDrawElements. I see you use VBO, EBO would be useful as well. If most of your elements have the same geometry (and it seems that they have) you can use glDrawElementsInstanced.
3,647,144
3,647,625
How can I call Nant scripts from Maven?
I'm working on a mainly Java based project, that also has a couple of components written in C++. The project is currently built using Ant scripts which invoke Nant to build the C++ components. We are in the process of moving to Maven and I was wondering if anyone could recommend the best way to build Nant scripts using...
I think you can either roll your own, this tutorial is probably a good place to start (can be adapted to call nant rather than msbuild easily enough). Otherwise you may want to look at Mojo, will depend which takes longer to setup I guess.
3,647,428
3,647,458
recursive inline function
i have this files: //Q2a.h #ifndef Q2A_H #define Q2A_H inline int MyFactorial(int a) { if (a < 2) return 1; return a*MyFactorial(a-1); } int NumPermutations(int b); #endif //Q2a.cpp #include "Q2a.h" int NumPermutations(int b) { return MyFactorial(b); } and file with the main- Q2b.cpp i notice that the co...
Because when you #include "Q2a.h", you're essentially doing a text substitution of the contents, so both Q2a.cpp and Q2b.cpp end up defining a function called MyFactorial(). You either need to use inline, or define the function in one of the source files. Note that using inline won't help very much with a recursive fu...
3,647,438
3,649,082
Conventions for accessor methods (getters and setters) in C++
Several questions about accessor methods in C++ have been asked on SO, but none was able satisfy my curiosity on the issue. I try to avoid accessors whenever possible, because, like Stroustrup and other famous programmers, I consider a class with many of them a sign of bad OO. In C++, I can in most cases add more respo...
From my perspective as sitting with 4 million lines of C++ code (and that's just one project) from a maintenance perspective I would say: It's ok to not use getters/setters if members are immutable (i.e. const) or simple with no dependencies (like a point class with members X and Y). If member is private only it's als...
3,647,462
3,647,474
Handmade auto template (without using C++0x)
How can be realized the auto keyword functionality without using c++0x standard? for(std::deque<std::pair<int, int> >::iterator it = points.begin(); it != points.end(); ++it) { ... } Maybe such class: class AUTO { public: template <typename T1> AUTO(T1); template <typename T2> operator T2(); }; Wi...
If a library extension was easily implementable there would have been no need for a language extension. See N1607 for details on the auto proposal. However, the article on the Boost.Foreach (which sort of does what you want) macro may help understand the issues related to such an implementation. What is BOOST_FOREACH?...
3,647,562
3,647,567
Is there a guarantee as to the size of a class that contains an array?
Given: template <int N> struct val2size { char placeholder[N]; }; Is there any guarantee that sizeof(val2size<N>) == N?
The only guarantee is that sizeof(val2size<N>) >= N There may be unnamed padding at the end of the struct. I don't think it's likely that there will be unnamed padding, but it's possible.
3,647,580
3,647,916
Set a class instance's function after it has already been defined
I am trying to give a class event functions such as .onShow() and .onHide(), so when the object is shown, the .onShow() function will run. How can I allow the function to be change like so: MyClass myInst = MyClass(); myInst.onShow = OnShowFunction; Is it possible to allow this?
This is how you do it (and impress/horrify your cow-orkers at the same time): #include <iostream> class MyClass { public: void (MyClass::*OnShow)() ; void OnShowFunction() ; } ; int main (int argc, char** argv) { MyClass C ; C.OnShow = MyClass::OnShowFunction ; (C.*C.OnShow)() ; } void MyClass::OnS...
3,647,696
3,647,701
Do you know a regular expression based parser in C++ that can be used to parse streams?
I would like to specify the regular expression during run-time, not compile-time. So that is why pcre falls out. Do you know C/c++ regular expression library that can parse streams and can recognise relatively complex regular expression such as .+? Thanks.
AFAIK boost::regex should know how to work with streams and it supports perl regular expressions
3,647,775
3,647,793
Error : C2143:syntax error : missing ';' before '.'
//// header file #ifndef _SECTION_ #define _SECTION_ #include <map> #include "Employee.h" using namespace std; class Section { private: char* m_sectionName; Employee* m_director; Employee* m_viceDirector; typedef multimap<string,Employee*> m_employees; public: Section (char* name); Section(const Sec...
typedef multimap<string,Employee*> m_employees; Makes m_employees an alias for the specialized map type. You need to define a member. Use instead: typedef multimap<string,Employee*> EmpMap; EmpMap m_employees;
3,647,960
3,647,978
Objective C syntax inside .cpp file?
I'm trying to copy over some example code into my own project. The example project is iPhoneExtAudioFileConvertTest from the sdk. The example project contains a file called ExtAudioFileConvert.cpp. This file contains what looks like Objective-C code: assert([NSThread isMainThread]); The example project runs fine, but ...
Change the file extension to .mm for Objective-C++ instead of just .cpp for C++.
3,648,097
3,648,114
memory layout of multithreaded process in C++
Am a bit confused on how stack and heap are arranged in multithreaded processes: Each thread has its own private stack. All threads share the heap When the program dynamically creates thread (ex: new Thread() in Java), the object is allocated on heap. so does the heap contain memory for thread object, which means doe...
Its delibrately vague as we don;t want to constrain the implementers of the threading software. Each thread has its own private stack. As each thread executes a set of function independ from each other they need to store return addresses etc thus each needs its own stack. All threads share the heap That's the easie...
3,648,285
3,648,365
Collision detection between two general hexahedrons
I have 2 six faced solids. The only guarantee is that they each have 8 vertex3f's (verticies with x,y and z components). Given this, how can I find out if these are colliding?
It seems I'm too dumb to quit. Consider this. If any edge of solid 1 intersects any face of solid 2, you have a collision. That's not quite comprehensive because there are case when one is is fully contained in the other, which you can test by determining if the center of either is contained in the other. Checking edg...
3,648,604
3,648,639
mixing fstream streams issue even when closed streams
I am having problems with the code bellow. It can write fine if i kill the read section. It can read fine if i kill the write section and the file has already been written. The 2 don't like each other. It is like the write stream is not closed... though it should be. What is wrong? #include "stdafx.h" #include <iost...
You have a memory overwrite. You have six strings, but dimension only for five strings string a[5]; a[0]= "this is a sentence."; a[1]= "that"; a[2]= "here"; a[3]= "there"; a[4]= "why"; a[5]= "who"; this can cause the rest of your program have unexpected behavior.
3,648,620
3,648,633
C++ command line argument comparison
I am doing some validation of the arguments passed by command line in C++ and am having some difficulties. I am doing like so ./a.exe inputfile.txt outputfile.txt 16 flush_left And I am trying to do the validation like so if(argv[4] == "flush_left" || argv[4] == "flush_justify" || argv[4] == "flush_right"){ And its n...
try: std::string argv4 = argv[4]; if(argv4 == "flush_left" || argv4 == "flush_justify" || argv4 == "flush_right"){ //... } or (untested): if( argc >=4 && (!strcmp(argv[4],"flush_left") || !strcmp(argv[4],"flush_justify") || !strcmp(argv[4],"flush_right")) ) { //... } argv[4] has type char*, and string literals h...
3,648,621
3,648,665
Calculating total return with compound interest
So, I'm trying to figure out the total amount of return from an investment of £5 with a daily interest rate of 1.01%. Obviously, I am wanting the compound interest rate, so I have this so far: int main() { double i = 500; int loop; int loopa; double lowInterest; double highInterest; lowInteres...
The figure is about right - if you really were lucky enough to invest $5 at a daily interest rate of 1.01%, you'd end up with close to half a billion dollars after 5 years (a daily interest rate of 1.01% is an annual interest rate of ~ 3800%). Are you sure you don't mean a daily interest rate of (1.01 / 365) % ?
3,648,638
3,690,776
void return value from a function used as input to a templated function is seen as a parameter
Say you have some target class with some methods on it: class Subject { public: void voidReturn() { std::cout<<__FUNCTION__<<std::endl; } int intReturn() { std::cout<<__FUNCTION__<<std::endl; return 137; } }; And a Value class (similar in concept to Boost.Any): struct Value { Value() {} Value( Value const & ...
You could use Return and just specialize operator() handling. No need to duplicate the whole template. // I think it's a shame if c++0x really gets rid of std::identity. It's soo useful! template<typename> struct t2t { }; // Specialization for signatures with no parameters template< typename Host, typename Return > cl...
3,648,674
3,649,067
Existing C++ *nix system library?
There are several good cross-platform libraries, by which we usually mean something that wraps the commonalities of Windows and *nix. Is there anything for developers that don't really care about Windows but want the benefits of C++ wrapping *nix system calls? I am thinking of a library that reduces the tedium of stru...
Sounds like Boost Filesystem and Boost Threads cover a lot of that ground. Threading is also included in C++0x. Don't know of any for managing process information a la getpid, though. What other kinds of info and interfaces would be bundled into a process object?
3,648,797
3,648,916
Why would a copy constructor have more than one parameter?
$12.8/2 - 'A non-template constructor for class X is a copy constructor if its first parameter is of type X&, const X&, volatile X& or const volatile X&, and either there are no other parameters or else all other parameters have default arguments (8.3.6).106)' So far, I have not come across any example ...
The old std::basic_string does have one too: basic_string(const basic_string& s, size_type pos = 0, size_type n = npos)
3,648,848
3,648,906
Convert BSTR to char*
Anyone know how to convert BSTR to char* ? Update: I tried to do this, but don't know if it is right or wrong. char *p= _com_util::ConvertBSTRToString(URL->bstrVal); strcpy(testDest,p );
Your code is okay. ConvertBSTRToString does just that. As for the strcpy, testDest needs to be large enough to hold the string pointed to by p. Note that since ConvertBSTRToString allocates a new string you will need to free it somewhere down the line. Once you are done make sure you do: delete[] p; A couple of cavea...
3,649,278
3,649,351
How can I get the class name from a C++ object?
Is it possible to get the object name too? #include<cstdio> class one { public: int no_of_students; one() { no_of_students = 0; } void new_admission() { no_of_students++; } }; int main() { one A; for(int i = 0; i < 99; i++) { A.new_admission(); } cout<<"class"<<[classname]<<" "<<[o...
You can display the name of a variable by using the preprocessor. For instance #include <iostream> #define quote(x) #x class one {}; int main(){ one A; std::cout<<typeid(A).name()<<"\t"<< quote(A) <<"\n"; return 0; } outputs 3one A on my machine. The # changes a token into a string, after preprocessin...
3,649,281
3,663,250
How to increase thread priority in pthreads?
I am using pthread in Linux. I would like to increase the thread priority by setting the parameters sched_param.priority. However, I could not find much info from the net regarding the range of the thread priority I could set, or about the description of the thread priority. Also, I would like to know about the relativ...
The default Linux scheduling policy is SCHED_OTHER, which have no priority choice but a nice level to tweak inside the policy. You'll have to change to another scheduling policy using function pthread_setschedparam (see also man sched_setscheduler) 'Normal' scheduling policies: (from sched_setscheduler(2)) SCHED_OTH...
3,649,356
3,649,721
How to go about a platform independent E-Book Reader in C/C++?
I'm trying to develop an ebook reader(for mobile devices) which is platform independent. Currently my focus is epub only. As a proof of concept, we were able to make a basic epub reader for android platform, using the functionalities provided by the platform itself(using webview, Xml Parser, Unzipper etc). But now we ...
Most likely you will have to split your application into the cross-platform backend and a platform specific front-end. If you want to implement indexing and searching of all e-pubs in your app, this could be part of the cross-platform part. If the epub reader contains a catalogue of downloaded/transferred epubs, the d...
3,649,364
3,649,381
drawing outside client area, winAPI
How would I draw outside the client area of a window, and on the title bar. I know it can be done, but I am unsure of how to implement this effectively. Think google chrome, where the tabs are on the title bar.
When Windows asks you to draw the portion of the window that is outside your client area, it will send you an WM_NCPAINT message. Handle that message and draw whatever you want the non-client portion of your window to be. See the page I linked for an example of how to get a device context you can draw upon.
3,649,377
3,649,384
Tridiagonal matrix class in Boost c++
Does boost provide any classes to implement a tridiagonal matrix?
http://www.boost.org/doc/libs/1_44_0/libs/numeric/ublas/doc/banded.htm
3,649,468
3,649,507
How to set a breakpoint in GDB where the function returns?
I have a C++ function which has many return statements at various places. How to set a breakpoint at the return statement where the function actually returns ? And what does "break" command without argument means?
break without arguments stops execution at the next instruction in the currently selected stack frame. You select strack frames via the frame or up and down commands. If you want to debug the point where you are actually leaving the current function, select the next outer frame and break there.
3,649,599
3,649,644
How to load a DLL as a local server
I really need help... I have implemented a COM component (i.e A.dll) with IDL, also coded a wrapper DLL (B.dll) for that component. I have implemented required export functions for DLL "A" and registered it with "regsvr32.exe". Problem is that I have 3 EXE files that uses B.dll to access methods of A.dll. But, I could ...
A DLL mediated by COM is known as an in-process server. Which suggests your problem: it will always be mapped into the memory space of its clients, just like any other DLL. Similarly any DLLs it loads will be mapped into the original process. It is not clear from your question why you don't want to use a DLL. If it...
3,649,639
3,649,663
limit on string size in c++?
I have like a million records each of about 30 characters coming in over a socket. Can I read all of it into a single string? Is there a limit on the string size I can allocate? If so, is there someway I can send data over the socket records by record and receive it record by record. I dont know the size of each record...
To answer your first question: The maximum size of a C++ string is given by string::max_size
3,649,789
3,649,812
How to condense multiple for loops with different initial values
In a function, I have several consecutive for loops with the same code but different initial values for the control variable. The initial values are obtained from inputs to the function. Ie, void thisFunction( class A a){ //some other code for (int i = a.x; i != 0; --i){ code } for (int i = a.y; i != 0; -...
EDIT: In most cases you should avoid doing this, and rather follow MSalter's answer. Just because you can, doesn't mean you should. I am not sure how good an idea this is, but without any more context, a simple solution could be: int starts[3] = { a.x, a.y, a.z }; for ( int var = 0; var < 3; ++var ) { for ( int i = ...
3,649,919
3,649,933
Theory on C++ convention regarding cleanup of the heap, a suggested build, is it good practice?
I have another theory question , as the title suggested it's to evaluate a build of code. Basically I'm considering using this template everywhere. I am using VC++ VS2008 (all included) Stapel.h class Stapel { public: //local vars int x; private: public: Stapel(); Stapel(int value); ~Stapel(){} ...
Boost provides several utilities for RAII-style heap-managment: Smart pointer (there are several implementations here for different scenarios) Pointer Containers Drawbacks of your proposal: In your implementation, you still have to remember to place a delete in the CleanUp-method for every heap-allocation you do. Tr...
3,649,940
3,653,022
eclipse sfml library issues
I pulled out an application that I wrote in C++ using the sfml library, but I'm having trouble setting up the library in Eclipse. I specified the include path, the lib path and included all the necessary .so libraries to link to. the application compiles fine but it complains at runtime about missing libraries. Why is ...
There is only the name of the shared lib stored in the executable. At program startup the dynamic linker then searches for the specified libs in its search paths. You can add/specify search paths by placing them colon separated in the environment variable LD_LIBRARY_PATH or by specifying them in /etc/ld.so.conf (at lea...
3,650,074
3,650,092
std::string append too slow?
I have a situation where I read data from a struct and keep appending it to a string so that it can be sent over a socket. When the data is fairly large, this operation is taking a lot of time. Can someone suggest any alternatives? I have a structure struct fileInfo { int file_id; char filename[16]; ...
std::ostringstream from <sstream> is designed for exactly that mode of operation. ostringstream my_text; my_text << "hello " << 2 << foo << endl; // efficiently catenate socket.send( my_text.str() ); // get a std::string to handle data
3,650,161
3,650,261
Derived class from a templated base class
I am quite new to real use of templates, so I have the following design question. I am designing classes Bunch2d and Bunch4d that derive from a abstract base class Bunch: class Bunch {virtual void create()=0;}; class Bunch2d : public Bunch {void create();}; class Bunch4d : public Bunch {void create();}; The class Bunc...
There is one single note: different template instances (ie template classes with different types in the parameters) are of different types, and therefore are NOT a single base class. If you need polymorphism, you will need to add a layer in your design: class Bunch { public: virtual void create() = 0; virtual ~Bunc...
3,650,263
3,650,287
What does it mean if a method call starts with two colons?
A coworker routinely writes something like this: ::someObject->someMethod(anAttribute, anotherAttribute); someObject is a global variable. Those two colons seem strange to me. The code compiles and runs just fine without them. The coworker claims that those colons make someObject explicitly global and thus prevent con...
Your coworker is right. You can indeed define a local someObject which would hide the global someObject within that scope: SomeClass* someObject = ...; // here the global object is visible someObject->someMethod(anAttribute, anotherAttribute); // calls the global object void someMethod() { SomeClass* someObject = ....
3,650,372
3,650,415
Array shifting to the next element
How can I move elements in an array to the next element eg: x[5] = { 5, 4, 3, 2, 1 }; // initial values x[0] = 6; // new values to be shifted x[5] = { 6, 5, 4, 3, 2 }; // shifted array, it need to be shifted, // not just increment the values. This what I've done so far. It's wron...
#include <iostream> int main () { int x[5] = { 5, 4, 3, 2, 1 }; int array_size = sizeof (x) / sizeof (x[0]); for (int j = array_size - 1; j > 0; j--) { x[j] = x[j - 1]; } x[0] = 6; for (int j = 0; j < array_size; j++) { std::cout << x[j]; } return 0; }
3,650,411
3,650,436
C++ WinAPI save and open dialogues
How do I implement a save and load dialogue box into my current project? I only need to know how change the basics, like the filename mask and default path. Any help appreciated, or even a link to a helpful website. Thanks.
TheForger's WinAPI tutorial is the best IMHO and the part I linked also answers your question. In WinAPI, the save and open dialogs are created by the functions GetSaveFileName() and GetOpenFileName(). The parameters of the dialog, such as the file name filter is stored in an OPENFILENAME struct. GetOpenFileName GetSa...
3,650,426
3,650,568
Can template definitions of abstract (pure virtual) classes be put in source files c++
According to Storing C++ template function definitions in a .CPP file it is easy to seprate the interface and the implementation of a template class, .h file template<typename T> class foo { public: foo(); ~foo(); void do(const T& t); }; .cpp file template <typename T> void foo::foo() { ...
You can explicitly instantiate a type without needing to instantiate a variable. Also, your existing code is hideously bugged and doesn't even come close to compiling. template<typename T> class foo { public: foo(); ~foo(); void something(const T& t); }; template <typename T> foo<T>::foo() { ...
3,650,450
3,650,512
Big->little (little->big) endian conversion of std::vector of structs
How can I perform endian conversion on vector of structs? For example: struct TestStruct { int nSomeNumber; char sSomeString[512]; }; std::vector<TestStruct> vTestVector; I know how to swap int values, but how to swap a whole vector of custom structs?
As said in the comments. Endian swap each element in the vector: auto iter = vTestVector.begin(); while( iter != vTestVector.end() ) { EndianSwap( iter->nSomeNumber ); iter++; }
3,650,691
3,650,773
Taking the address of a pointer
If I declare the following variables: int array[10] = { 34, 43,12, 67, 34, 43,26, 98, 423,1 }; int * p = array; Then, this loop: for ( int i = 0; i < 10; i++ ) { std::cout << &*p++ << " "; } gives me different output ( a different set of addresses ), to this code: for ( int i = 0; i < 10; i++ ) { std::cout <<...
int array[10] = { 34, 43,12, 67, 34, 43,26, 98, 423,1 }; int * p = array; for ( int i = 0; i < 10; i++ ) { std::cout << p++ << " "; } p = array; std::cout << '\n'; for ( int i = 0; i < 10; i++ ) { std::cout << &*p++ << " "; } std::cout << '\n'; Gives me the same addresses. Did you accidentally forget p = arra...
3,650,812
3,655,473
Core dump not in sync with gdb stack trace
I have a program which crashes due to a segmentation fault. The core file is produced. running the core in gdb gives me the following: HP gdb 6.1 for HP Itanium (32 or 64 bit) and target HP-UX 11iv2 and 11iv3. Core was generated by `gcpf1fwcApp'. Program terminated with signal 6, Aborted. I used the command thread a...
It is possible that you are simply looking at the wrong thread. Try thread apply all where, and see if one of the threads is in fact abort()ing. When debugging a live process, GDB will stop when a thread receives SIGABRT, and so will likely show you the relevant thread. When debugging a core (post-mortem), GDB doesn't ...
3,650,876
3,650,991
Not getting any Response from Named Pipe Server
I have created a NamedPipe inside a Windows Service and starting the Service Manually or as the System Starts up. EDIT: lpszPipename = TEXT("\\\\.\\pipe\\1stPipe"); OVERLAPPED m_OverLaped; HANDLE hEvent; hPipe=CreateNamedPipe (lpszPipename, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, ...
m_OverLaped.hEvent = CreateEvent(NULL,TRUE,FALSE,NULL); ... ConnectNamedPipe(hPipe, &m_OverLaped); Since the pipe is created with FILE_FLAG_OVERLAPPED flag, you must pass LPOVERLAPPED parameter to every pipe I/O call (including TransactNamedPipe). If function returns FALSE and GetLastError returns ERROR_IO_PENDING, w...
3,650,901
3,651,062
Are Static Library Machine Independent?
Well, I am Developing a program in C++ in an Ubuntu 10.04.1 (Intel Core2Quad) LTS, but the releases are running in a Debian 5.0.5 (Intel(R) Xeon(R) CPU). Some libraries such as crypto++ or mysqlclient have different versions in both OS. So I decided to compile the binary statically with all the libraries statically com...
They're architecture dependant. Usually though, library gets compiled to a common architecture on x86 machines, such as i686 which will run fine on both an Intel Xeon and a Intel Core2Quad (But not on e.g. an old Intel Pentium processor)
3,650,949
3,651,100
Assigning boost::iterator_range to singular range
I'm using Boost.Range to pass around some data and a container class for this data. The data is loaded in a different thread and may in some cases not be ready yet. In this case the container is initialized with the default iterator_range, hence containing singular iterators. I'm doing assignments and copying of the da...
If by "works", you mean "it does not blow up with my current compiler version and invocation options", then yes, assigning a singular iterator might "work". Actually, the code typedef std::vector<int>::iterator iterator; iterator it; // Singular iterator it2 = it; // Works results in undefined behaviour, so you are up...
3,651,390
3,651,543
Arguments for and against supporting std::wstring exclusively in cross-platform library
I'm currently developing a cross-platform C++ library which I intend to be Unicode aware. I currently have compile-time support for either std::string or std::wstring via typedefs and macros. The disadvantage with this approach is that it forces you to use macros like L("string") and to make heavy use of templates base...
A lot of people would want to use unicode with UTF-8 (std::string) and not UCS-2 (std::wstring). UTF-8 is the standard encoding on a lot of linux distributions and databases - so not supporting it would be a huge disadvantage. On Linux every call to a function in your library with a string as argument would require the...
3,651,499
3,651,872
read arguments from variadic template
I am a little confused about how can I read each argument from the tuple by using variadic templates. Consider this function: template<class...A> int func(A...args){ int size = sizeof...(A); .... } I call it from the main file like: func(1,10,100,1000); Now, I don't know how I have to extend the body of func to be ab...
You have to provide overrides for the functions for consuming the first N (usually one) arguments. void foo() { // end condition argument pack is empty } template <class First, class... Rest> void foo(First first, Rest... rest) { // Do something with first cout << first << endl; foo(rest...); // Unpa...
3,651,539
3,651,569
Interesting problem on pointers..Please help
#include<iostream> #include<conio.h> using namespace std; int main() { int x = 65; int *ptr = &x; char * a= (char *)ptr; cout<<(int)*(a); getch();return 0; } Sixeof(ptr) and Sizeof(a) display 4 Sizeof(int) displays 4 and sizeof(char) displays 1 So 65 i...
Your machine is little-endian, and least significant bytes go first.
3,651,613
3,651,783
Collision detection between 2 rotated cubes
Possible Duplicate: Collision detection between two general hexahedrons Right now I do collision detection by finding the min and max and doing bounding box check. Unfortunately, my player cube rotates with the camera and this makes for some annoying results when the player is at a 45 degree angle. The constraints a...
If one of the cubes is not rotated then its easy to check if a single point is within the cube (with bounds checks). So take each of the 8-nodes of the rotated cube and check to see if it falls within the unrotated cube.
3,651,847
3,651,940
Prettier syntax for "pointer to last element", std::vector?
I'm wondering if there is prettier syntax for this to get a normal pointer (not an iterator) to the last element in a C++ vector std::vector<int> vec; int* ptrToLastOne = &(*(vec.end() - 1)) ; // the other way I could see was int* ptrToLastOne2 = &vec[ vec.size()-1 ] ; But these are both not very nice looking!
int* ptrToLastOne = &vec.back(); // precondition: !vec.empty()
3,651,862
13,923,245
Better variable exploring when debugging C++ code with Eclipse/CDT
Using Eclipse and CDT to debug C++ code the variable windows is cumbersome and not very informative for types defined in the standard template library or in boost (e.g. shared_ptr). Just an example how this may look like for an std::vector: bar {…} std::_Vector_base<TSample<MyTraits>, std::allocator<TSample<MyTrait...
You need a version of GDB capable of using python to pretty print structures. I know at least on windows using mingw that this is not provided in the default install. Pretty Printers are python modules which tell gdb how to display a given structure. You can write your own, but there are already printers for STL avai...
3,651,888
3,651,910
C++ STL containers, 'under the bonnet'?
what would be the best way to learn what actually happens with the STL containers? I presume just programming wouldnt be enough. Are there any books specifically aimed at this?
This book is quite good, even if maybe it does not go deep enough in the details as you would like: The C++ Standard Library: A Tutorial and Reference
3,651,996
3,652,201
Berkeley DB and C++ benchmark example?
I'm trying to run benchmarks with a little berkeley db and c++ code, just for research purposes. Currently I'm testing with the following code. I'm filling the recors only with incrementing integers (I omitted things like error handling for better readability) (db is my own berkeley db class) // Open the database db.op...
Basically performance figures can be compared with another benchmarking results only when all the other variables are constant. These variables can be exhaustive i will try to put some of them The Processor. Memory Disk throughput Load on the system. Operating system. Compilation parameters. Tuning parameters of the r...
3,652,103
3,652,138
Implementing the copy constructor in terms of operator=
If the operator= is properly defined, is it OK to use the following as copy constructor? MyClass::MyClass(MyClass const &_copy) { *this = _copy; }
If all members of MyClass have a default constructor, yes. Note that usually it is the other way around: class MyClass { public: MyClass(MyClass const&); // Implemented void swap(MyClass&) throw(); // Implemented MyClass& operator=(MyClass rhs) { rhs.swap(*this); return *this; } }; We pass by value in ...
3,652,182
3,652,206
C++ void return type of main()
Some C++ compilers allow the main function to have return type void. But doesn't the Operating System require int type value returned to specify whether the program ended well or not?
C++ does not allow main to have a void return type. The published C++ standard requires it to be int. Some C++ compilers allow you to use void, but that's not recommended. In general, the OS doesn't care one way or the other. A specific OS might require a program to give a return value, but it doesn't necessarily have ...
3,652,240
3,652,320
Packing or making executables in C++
I am new to C++. Before, when working with Java, I could make an executable as either a jar or exe file. Is it is possible in C++ for any other format? I need an format that works on Linux. I am using Eclipse as development IDE - is there any built in way to export as an executable file?
Linux uses ELF format for executables. Just setup Eclipse CDT IDE and creator will ask you if you want executable, static or shared library. Although it can be directly set in Project Properties (C/C++ Settings -> Build -> Build Artifacts) On Java you are running class files, which can be packed into jar archives, beca...
3,652,327
3,652,478
choice between win32 APIs and .NET framework
I have to develop an application for windows that will enable controlling the mouse through web cam by recognizing hand gestures. I will be using vc++ 2008 for development. But I am confused whether to go with .NET framework or core win32 APIs. Performance is very important for my application. As per the book "Beginnin...
If you are acquainted with Win32 API, then go Win32 API. It is the natural choice in your case since most of your source code will be video capturing, image processing, algorithms, and interfaces to mouse in Windows. When you are interested in performance, be closer to the hardware avoiding thick layers like .NET. I be...
3,652,329
3,652,367
redirecting input in c++
i was told that to redirect from standard input to file i need to do the following: static std::ifstream inF("inpur.txt"); std::cin.rdbuf(inF.rdbuf()); and every call to std::cin will be redirected to input.txt. but my question is: do i need to open inF? and if i do, where do i need to do this?
That's the beauty. You already did so while declaring the object and passing the string to the explicit constructor of ifstream. The file is opened in TEXT mode. Refer this
3,652,429
3,654,031
c++ frameworks yes or no
I am familiar with QT/gtk+ libs under linux. I've just roughly had a look at available c++ frameworks like Reason and Platinum. Does anyone have any experience working with any of them? Are they any good, should I consider learning them? I am not a big fan of frameworks though.
I worked on a project that had to run on multiple platforms (Linux, Windows, Windows CE). We used WxWidgets for the UI. The libraries and the tools weren't perfect. But it compiled and ran on all the platforms without any issues. The platform is completely open source, so you have the benefits therein. In the end, I w...
3,652,476
3,653,739
Using boost::bind and boost::lambda::new_ptr to return a shared_ptr constructor
Given a class A, class A { public: A(B&) {} }; I need a boost::function<boost::shared_ptr<A>(B&)> object. I prefer not to create an ad-hoc function boost::shared_ptr<A> foo(B& b) { return boost::shared_ptr<A>(new A(b)); } to solve my problem, and I'm trying to solve it binding lambda::new_ptr. boost::function<bo...
Use boost::lambda::bind instead of boost::bind. #include <boost/shared_ptr.hpp> #include <boost/lambda/bind.hpp> // ! #include <boost/lambda/construct.hpp> #include <boost/function.hpp> void test() { using namespace boost::lambda; boost::function<boost::shared_ptr<A>(B&)> func = bind( constructor< boost::shar...
3,652,621
3,653,058
Drawing areas and expose events
I have a dialogue which contains a drawing area. I wish to redraw the contents of the drawing area if the dialogue is enlarged or shrunk or buried and exposed, as is normal and natural with drawing areas. To this end, I created a method bool on_expose_event (GdkEventExpose *event); in the class. But the presence of t...
You should really sub-class the Gtk::DrawingArea class and implement the on_expose_event() function from that class.
3,652,731
3,652,777
how to make sure that a file will be closed at the end of the run
Suppose someone wrote a method that opens a certain file and forgets to close it in some cases. Given this method, can I make sure that the file is closed without changing the code of the original method? The only option I see is to write a method that wraps the original method, but this is only possible if the file is...
Since this is C++, I would expect that the I/O streams library (std::ifstream and friends) would be used, not the legacy C I/O library. In that case, yes, the file will be closed because the stream is closed by the stream object's destructor. If you are using the legacy C API, then no, you're out of luck. In my opinio...
3,652,741
3,652,792
Timer Vs Event: which one is preferable for Asynchronous processing?
Ours is a huge project. I need to call certain functions in my code asynchronously to avoid some circular function calls. Upon receiving a specific input, I can call my function asynchronously either by using Event or Timer. Which way is preferable considering Performance ? Sending events to Event manager and handling ...
For pure performance, event-driven model will be better. Use timers only if you cannot rely on one or more of your events to get set in a timely way by the worker code, and so need a backup means by which to continue processing. This may be the case if your worker code makes external calls to a database or other remot...
3,652,790
3,666,795
How to implement template class with template-dependent signal member from boost?
I try to implement a template class which requires to have a signal member that depends on the template argument. My first idea was to realize it like the following: template<class T> class SignalClass { typedef boost::signals2::signal<void (T &)> OnReceive; public: SignalClass(const OnReceive::slot_type &_sl...
Here is the reason why adding typename (either directly in the constructor argument or in an additional typedef) works: First, the type OnReceive is a so-called "dependent type", because it depend on the type of the template parameter. Then, templates are processed in two stages in the compiler: The first stage is when...
3,652,963
3,653,001
Alternatives to including MS C runtime distro?
I use MSVS 2010 and MSVC++E 2010 to build my applications in C++ and I've notice a lot of my friends (who test my apps on their PCs) don't have the Microsoft C++ runtime library installed on their computers. I've started including the Microsoft C++ redistributable package with my apps, but this seems unnecessary. Would...
in your project options, for code generation, you can choose the STATICally linked libraries instead of the DLL versions. That eliminates the need for an external dependency like this, at the cost of a larger EXE.
3,653,071
3,653,242
interfaces, inheritance, and what between them
if i want to have 3 classes, which have common fields (and i want them to be static) and they have a common function (which needed to be overridden, i.e virtual) what the best design to do this? do i need to create an interface in a header file and then create it's .cpp file and get the 3 classes inheritance from it? ...
Declare the classes in header files. This is so that the declaration can be shared between multiple source files (with #include) and thus obey the (One definition rule). It is traditional (though not required) that each class has its own file. To make it consistent and easy to find things you should name the file after...
3,653,075
3,653,095
Is it bad form to provide only a move constructor?
I would like to return a noncopyable object of type Foo from a function. This is basically a helper object which the caller will use to perform a set of actions, with a destructor to perform some cleanup after the actions are complete. Before the advent of rvalue references, I would have returned a shared_ptr<Foo> or s...
This isn't bad form at all- consider objects like mutexes or scoped objects like unique_ptr. Unique_ptr is movable but not copyable and it's part of the STL.
3,653,216
3,653,237
Linking problems template with return
I'm having some problems on returning the parameter of a method as a template, look: // CTestClass.h template<class T> class CTestClass { public: T getNewValue(); }; // CTestClass.cpp template<class T> T CTestClass<T>::getNewValue() { return 10; // just for tests I'm returning hard coded 10 } // main.cpp i...
You'll want to read the C++ FAQ "Why can't I separate the definition of my templates class from its declaration and put it inside a .cpp file?" Effectively, you need to define CTestClass<T>::getNewValue() in the header file.
3,653,218
3,653,336
Linux tool to check spelling of comments in c/c++ source code
What software do you suggest to check spelling of comments contained in c/c++ source code (especially doxygen comments)? I'm looking something that will parse only comments so I can easily find mistakes and correct them. The question is general but to be more specific - I'm using CodeLite IDE.
Emacs has ispell-comments-and-strings which works pretty well from inside the editor. It relies on the syntax highlighting mechanism to identify comments and strings, so it works with any language for which you have good highlighting. No idea if how you make it work with your IDE.
3,653,267
3,653,400
Building legacy Turbo C++ Code
I am looking to revive some old C++ code, developed in Turbo C++ for DOS. It's a console-based text game. This app makes heavy use of conio.h - the Turbo C-specific functions (I think) gotoxy(), window() and the like. I find that Turbo C++ compiler is no longer available for download. Embarcardero/CodeGear/Borland see...
I was able to build the app using C++ Builder trial edition. It does not I had to make a new project file though. There is still support for conio.h in C++ Builder.
3,653,274
3,653,378
visual studio project dependency on another project LINKING failure
I have a solution with 2 projects cira_lib and md5_test. One project (cira_lib) is a central library that compiles to a DLL. The other project (md5_test) is an exe with a dependency on cira_lib. When I build md5_test it builds cira_lib first, so I know the project dependencies are being followed. However when VC++ ...
Only symbols that you specifically mark for export are available to executables linking against your DLL. You should check the MSDN documentation
3,653,412
3,653,421
include typedef inside a class header
This is my header: #ifndef TIMING_H #define TIMING_H #define MAX_MESSAGES 1000 typedef Message* MessageP; //inside the class? class Timing { public: Timing(); private: struct Message { Agent *_agent; double _val; }; MessageP* _msgArr; int _waitingMsgs; }; My question is: do I have to place the typede...
Outside of the class, that type must be referred as Timing::Message, so typedef Timing::Message* MessageP; But this is possible only after the declaration of Timing::Message, yet MessageP is used before the declaration of Timing is complete, so it's not possible. Moreover, the struct is a private: member, so you can'...
3,653,437
3,653,542
Cannot deallocate mem
Why in this code (this is just working code and not fully exception safe) I'm getting an assertion error: HEAP_CORRUPTION_DETECTED ... class Allocator { public: explicit Allocator() { std::cout << "Allocator()" << '\n'; } virtual ~Allocator() { std::cout << "~Allocator()" << '\...
You corrupted your heap because your allocation is incorrect. Namely, consider this: template<class T> T* Allocate(const std::size_t count) { return static_cast<T*>(::operator new(count)); } If count is one, you get one byte. (You then try to construct an object which has a size greater than one in that memory...b...
3,653,896
3,653,900
cannot convert int to int *
#include "stdio.h" #include "conio.h" void swap(int *x,int *y); void main() { int a=10,b=20; swap(a,b); printf("value of a=%d and b=%d"); getch(); } void swap(int *x,int *y) { if(x!=y) { *x ^= *y; *y ^= *x; *x ^= *y; } } // I'm getting .. cann't convert int to int * ... can any...
Your call to swap() should include ampersands: swap(&a,&b); swap is expecting pointers to int, so you need to take a and b's addresses when passing them in.
3,654,046
3,654,103
Mastering C++ to prepare for my second year: How?
I'm going to my second year of Computer Science at a local University, in which C++ is a large part of the education, but as they only give an introductory course in the first year (basics, pointers, creating a linked list and an implementation of a game like Mastermind), I'd like to program a bit in my free time to cr...
A really good resource is http://projecteuler.net/index.php?section=problems, it builds both programming language familiarity and your list of programming algorithms (not to mention keeping your math skills sharp). However I wouldn't worry too much about it, universities have this weird Java and Matlab fetish, I don't ...
3,654,047
3,654,112
Audio Recording and playback VC++
Hi folks I am planning on recording audio, and later play it back, for on of my projects. The requirement is that it should be c++ ( Visual studio 2008 ) compatible. Rest of our application is mostly in silverlight/ VC++. I have worked with NAudio before in C#, but nothing on vc++. I would like to know what is best su...
Probably the easiest way is using MCI. Basically, you can use mciSendCommand (or mciSendString) to send an MCI_RECORD command to do recording, or an MCI_PLAY to do playback.
3,654,264
3,654,273
i want to know if the ide we use contains linker or not
Is the Linker part of the Operating System or the Compiler/IDE?
It is part of the compiler/IDE. Or to be precise, the compiler and the linker are separate programs (invoked at separate phases of building an executable), but usually the whole bunch (which includes several other executables) is referred to as a compiler, e.g. gcc. The linker is not part of the OS, although some OSs (...
3,654,380
3,657,513
int transforms into int&?
code snippet: // some code SDL_Surface* t = Display->render_text(text); int z=100; Display->blit_image(t,z,100); // some more code does not compile because z magically changes to an int&, file.cpp:48: error: no matching function for call to ‘display::blit_image(SDL_Surface*&, int&, int) how can this happen? post scrip...
Having seen the code, the defaults should be given in the header and not in the implementation file. When you are compiling "monkeycard.cpp", the compiler has only the information in the headers to work with. The compiler has no idea that blit_image has default arguments, and therefore cannot match the function to call...
3,654,565
3,654,589
Algorithm to only draw what the camera sees?
I'm making a 3D FPS with OpenGL and here is the basics of how it works. The game is a 3D array of cubes. I know the location of the player's current cube, aswell as the camera x,y,z and I know the x, y, z rotation of the camera too. Right now I just make a square around the player and render this and then add distant f...
You are talking about frustum culling, if i get you right. I suggest that you take a look at this tutorial. They provide nice demos and explain everything in detail.
3,654,622
3,654,642
How can I tell if a const char* points to a valid string?
std::string str = "string": const char* cstr = str.c_str(); str.clear(); //here, check if cstr points to a string literal. How do i check if cstr still points to a string when running the program in debug or release mode? Would there be a way to determine this using exception handling in C++?
There is no portable way to do this. The implementation is perfectly free to hold onto the buffer, unmodified, after the call to clear(). If, OTOH, clear() frees the string's buffer, cstr is now pointing into unallocated memory, but even then it depends on how the memory allocator handles it. A debug allocator will fil...
3,654,770
3,654,782
Is there a structure in Python similar to C++ STL map?
Is there a structure in Python which supports similar operations to C++ STL map and complexity of operations correspond to C++ STL map?
dict is usually close enough - what do you want that it doesn't do? If the answer is "provide order", then what's actually wrong with for k in sorted(d.keys())? Uses too much memory, maybe? If you're doing lots of ordered traversals interspersed with inserts then OK, point taken, you really do want a tree. dict is actu...
3,654,828
3,654,838
How to return the last three values of a vector?
I'd like to place the last three values of vector v_2 in three variables (one value per variable). Is there a faster or simpler way to do this? struct Desempenho { double maximo; }; double ultimo, penultimo, antepenultimo; Desempenho d; int n (0); vector<Desempenho> v_2; d.maximo=1.1; v_2.push_back(d); d.m...
Well, you don't need a loop to use iterators: vector<Desempenho>::const_reverse_iterator rit = v_2.rbegin(); if (rit != v_2.rend()) { ultimo = rit->maximo; if (++rit != v_2.rend()) { penultimo = rit->maximo; if (++rit != v_2.rend()) antepenultimo = rit->maximo; } } If you want to be needles...
3,654,881
3,664,683
Mixing static and dynamic (shared) libraries?
I am working with three different libraries, a Core (can be compiled as static or DLL), Graphics (can be compiled as static or DLL - Dealing with Ogre), Physics (can be compiled as static only due to licensing - Havok). A project then uses a combination of the libraries depending on the needs. The Physics portion is de...
I found a solution but I don't know why it works. There would be an explanation if all the functions (instead of just the one) that were defined in the header gave the linking error, but no, there are only two. Anyway, the solution is to put the definitions of the functions in the source files. Why does that work? If ...
3,654,924
3,654,962
Where should I go after learning C++?
I'm in high school and taking a class where basically we design our own course and choose what we learn. I've chosen to learn about C++ and game programming. I'd like to learn as much about using C++ with OpenGL or DirectX or some other API as I can. After I finish learning C++ where should I go? Can you recommend a ...
Saying that you think you know most of C++ reminds me of when I said I thought I knew most of Java. When you find yourself saying things like that about languages you haven't used for 8+ years, you've slipped into a bad comfort zone. Stretch yourself. A lot. Read a book about the language. You'll be shocked about every...
3,654,926
3,654,950
64 bit floats compiled with 32 bit compiler on 64 bit OS
I hope this has not been covered before, but if i compile a 32 bit program in c++ that uses 64 bit floating point numbers (double), and run it on a 64 bit OS, will it still take as many clock cycles to move the 64 bit float to the cpu and back to ram as it would on a 32bit OS because its compiled for 32 bit. Or would i...
The 32 vs 64 bits you're hearing about is how many bits are in the address. It has little to do with how many bits are used to represent a double. In particular, 32-bit programs still represent a double in 64 bits, and modern processors have hardware that can process 64 bit floats natively (even if they can only proc...
3,654,968
3,654,985
Progress bar embedded in listview
Does anyone know how I can add a progress bar to a listview cell using "pure" api. The only examples I've found are either in c# or outdated mfc
You would need to overlay the progress bar onto the list view. You will need to handle column resize and scrolling messages to resize it properly. Alternatively, you can use DrawThemeBackground() to draw a scroll bar onto the listview, without needing an actual control. PAINTSTRUCT ps; HDC hDC = BeginPaint(hwnd,&ps); R...
3,655,043
3,655,081
How do I get resize handles in QT?
Is there a way to get a resize effect between two widgets? Like say I have two QTextEdit boxes next to eachother, I want to get a handle between them so I can move it back and forth. Sort of in the same way that the textarea I'm writing in now has a handle at the bottom for making it larger. I'm using QT Creator and I ...
What you need is a QSplitter.
3,655,060
3,655,113
Detect double free in C++ code
I have a code, class foo { public: foo(){}; ~foo(){}; }; class bar { public: bar(){}; ~bar(){}; foo& Foo() { return m_foo; } private: foo m_foo; }; int main() { bar *obj = new bar; if( /* true condition here */ ) { foo lcFoo; lcFoo...
There is no double free in the code you posted. I suspect that there is some pointer resource in foo, which is being copied as a pointer when foo is copied; yet is deleted in foo's destructor. You might also want to change the contents of your if block to foo& lcFoo = obj->Foo(); though the fact that you're getting ...
3,655,389
3,655,406
How to convince people that a single class with 11975 lines of code is bad? (isn't it?)
I have a dejavu feeling when reading [What to do about a 11000 lines C++ source file?] post, but I don't think I can start taking action on my own since I do not have the authority to take action. So I think the first step is to convince people in the organization that big lump of code is bad. I have a similar situatio...
You have my sympathies. Any class that is that huge is inevitably breaking the Single Responsibility Principle, making it difficult to maintain. My best advice is to lead by example: Keep your new code small. Refactor mercilessly when changing code to reduce the size of classes and functions. Your code will shin...
3,655,390
3,657,605
How To Make a clone method using shared_ptr and inheriting from enable_shared_from_this
I have seen that a useful way to write a clone method that returns a boost::shared_ptr is to do class A { public: shared_ptr<A> Clone() const { return(shared_ptr<A>(CloneImpl())); } protected: virtual A* CloneImpl() const { return(new A(*this)); } }; class B : public A { public: shared_ptr<B> Clo...
Since you are already implementing the public interface covariance yourself via the non-virtual Clone() functions, you may consider abandoning the covariance for the CloneImpl() functions. If you only need shared_ptr and never the raw pointer, so you could then do: class X { public: shared_ptr<X> Clone() const { ...
3,655,445
3,655,476
Object-oriented programming
I am developing a project in C++. I realised that my program is not OO. I have a main.cpp, and several headers for different purposes. Each header is basically a collection of related functions with some global variables to retain data. I also have a windowing.h for managing windows. This contains the winMain() and win...
No, I think if it ain't broke, don't fix it. Any windowing system is inherently OO to a degree. You have a handle to a window managed by the OS, and you can perform certain operations on it. Whether you use window->resize() or resize(window) is immaterial. There is clearly no value in such syntactic rearrangement. Howe...
3,655,598
3,655,622
c++ having strange problem
I have a function that creates and insert some numbers in a vector. if(Enemy2.dEnemy==true) { pt.y=4; pt.x=90; pt2.y=4; pt2.x=125; for(int i=0; i<6; i++) { Enemy2.vS1Enemy.push_back(pt); Enemy2.vS2Enemy.push_back(pt2); y-=70; ...
First things first: get rid of that abominable if (Enemy2.dEnemy == true) - it should be: if (Enemy2.dEnemy) (I also prefer to name my booleans as a readable sentence segments like Enemy2.isABerserker or Enemy3.hasHadLeftLegCutOffThreeInchesBelowTheKnee but that's just personal preference). Other than that, the only t...
3,655,778
3,655,799
synchronizing between send/recv in sockets
I have a server thats sending out data records as strings of varying length(for eg, 79,80,81,82) I want to be able to receive exactly one record at a time.I've delimited records with a (r) but because I dont know howmany bytes I have to receive, It sometimes merges records and makes it difficult for me to process.
I have two ideas for you: Use XML for the protocol. This way you know exactly when each message ends. Send in the header of each "packet" the packet size, this way you know how much to read from the socket for this specific packet. Edit: Look at this dummy code for (2) int buffer_size; char* buffer; read( socket, &...
3,655,888
3,655,896
Referencing a pointer in a C++ member function
I'm writing a member function that uses a member variable pointer as an iterator. However I want to reference the pointer within the function purely for readability's sake. Like so: /* getNext will return a pos object each time it is called for each node * in the tree. If all nodes have been returned it will return a ...
Your member function is const-qualified, so you cannot modify the member variable getNextIter. You need to use a const reference: BTreeNode * const & it = getNextIter; However, in your function, you modify it, so instead you probably need to remove the const-qualification from the member function or make the getNextI...
3,656,050
3,656,054
c++ " undefined reference to 'Foo::Foo(std::string)' "
I'm not too familiar with c++ and how instantiating objects work, so this is probably a very simple thing to solve. When I compile with g++ I get the error " undefined reference to 'Foo::Foo(std::string)' ". I want to create an instance of the class Foo that has a string parameter in its constructor. Here is the cod...
You're probably not including Foo.cpp in your compile line. It should look something like this: g++ main.cpp Foo.cpp -o testFoo
3,656,124
3,656,193
socket max number of sends?
Is there a maximum on the number of sends on a socket? My sends work upto about 480 sends after which it starts returning -1 I'm using visual studio 2008 vc++ and socket programming using ACE.
No, there's no upper limit on the number of send()s you can call. Check out the man page for send (or whichever page is suitable for your platform) and try using the perror() (example: 'perror("error sending. system said");') call to see which error is being generated. Note that -1 is a generic return code in this ca...
3,656,127
3,656,150
Customizing STL iterator class
which concept in c++ teaches you to extend and write your own iterator class? I know a little about writing templates.
The SGI Standard Template Library (STL) documentation explains all of the iterator concepts and their relationships. How you take those concepts and use them to implement an iterator for your own container depends entirely on what kind of container it is and what you want to do with it.
3,656,275
3,656,871
How to auto-collapse certain comments in Visual Studio 2010?
A colleague of mine uses a abomination text editor that routinely leaves comment blocks all over the code. Needless to say, this is driving me rather mad. The comment blocks look like this: /* EasyCODE ) */ /* EasyCODE ( 0 WndProc */ /* EasyCODE F */ i.e. they all start with EasyCODE and most of them span several lin...
Here is a macro that should do it. There are some weirder EasyCode comments that it doesn't catch but it mostly does the trick. Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports EnvDTE90a ' remove for VS2008 Imports EnvDTE100 ' remove for VS2008 Imports System.Diagnostics Imports System.Collection...