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,897,445 | 4,897,474 | How to convert epoch time to time String | I have time in Seconds and I want to convert this time in to Readable Time Sting as,
DAY-Date-Hour-Min-Sec-Month-Year.
How to do this in CPP or C.
| time(), localtime() and sprintf() should do the trick.
#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>.
#endif
#include <time.h>
static const char *Weekdays[] = {
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
};
int main() {
time_t cu... |
4,897,844 | 4,897,859 | Is sizeof(bool) defined in the C++ language standard? | I can't find an answer in the standard documentation. Does the C++ language standard require sizeof(bool) to always be 1 (for 1 byte), or is this size implementation-defined?
| sizeof(bool) is implementation defined, and the standard puts notable emphasis on this fact.
§5.3.3/1, abridged:
sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1; the result of sizeof applied to any other fundamental type is implementation-defined. [Note: in particular, sizeof(bool) and sizeof(wchar_t... |
4,897,912 | 4,898,169 | How to properly interrupt a QThread infinite loop | I'm done implementing a Go program where the human can interrupt at any time the software to order it to play. Basically, I've got an algorithm running in another thread that has at every moment a "Best move" available, that it keeps on improving.
My question is : how do I correctly interrupt a thread in an infinite lo... | That sounds a good way to do it. You could also give a look at how it has been made it boost thread. Because it uses exceptions to abort the thread, it permits you to interrupt the thread in several places using interruption_point. Using their thread model you could write your thread function like this:
void myFunction... |
4,897,934 | 4,897,965 | Operator Precedence.. () and ++ | Salute..
I have an unusual problem.
Here in this table in MSDN library we can see that precedence of () is higher than ++ (Pre-increment) .
but when I run this code, it seems that precedence of ++(prefex) is higher:
int main()
{
int a=3,b=2,x;
x=++a + (a-b);
cout<<"x= "<<x;
return 0;
}
and the answer ... | As usual, this is undefined behaviour. There is no sequence point at the +, so it is not defined at what point the ++ updates a. This is not a precedence issue.
|
4,898,021 | 4,898,371 | C++ newbie question: designing a function to return a vector of either string or double--overload or template? | I have written a function that searches a text file for names. It returns vector, where each element of the vector is a different name.
Now I would like to search the same text file for numbers and return the numbers in a vector.
This is probably a dumb question, but I'm wondering what the best approach would be. Ove... | As a function signature does not include its return type, you can't overload a function only on its return type.
Also, as the two functions returns different kind of data (one could return person names, the other could return the persons ages), having the same name for both seems a semantic error.
But anyway...
Move th... |
4,898,126 | 4,898,146 | Thread-safety and atomic reading in Windows OS | I have this piece of code in my application. I suspect that it is not thread-safe, so decide to ask the SOers.
int * volatile int_ptr;
int count;
Thread 1:
void grow(int new_count)
{
if(new_count <= count) return;
int * new_ptr = new int[new_count];
memset(new_ptr, 0 , new_count * sizeof(int));
memcp... | No, this is not safe. get_value can read the value of int_ptr, then get scheduled out. Then another thread can swap out int_ptr and delete the old value. When get_value is swapped back in, it tries to dereference the value it read from int_ptr - which has already been deleted.
A better approach would be based on "Read-... |
4,898,618 | 4,899,199 | how does printf know the address of a CString's character data? | Considering this code fragment:
struct My {
operator const char*()const{ return "my"; }
} my;
CStringA s( "aha" );
printf("%s %s", s, my );
// another variadic function to get rid of comments about printf :)
void foo( int i, ... ) {
va_list vars;
va_start(vars, i);
for( const char* p = va_arg(vars,const char... | The relevant text of C++98 standard §5.2.2/7:
The lvalue-to-rvalue (4.1), array-to-pointer (4.2), and function-to-pointer (4.3) standard conversions are performed on the argument expression. After these conversions, if the argument does not have arithmetic, enumeration, pointer, pointer to member, or class type, the p... |
4,898,854 | 4,898,921 | OpenGL rotating towards a point | Using openGL (just 2d), I'm trying to rotate a texture so it's pointing towards a point on screen. I'll show an image first to help me explain.
http://img692.imageshack.us/img692/3088/probe.png
Say my texture is the blue dot at point 1 and it is moving to its destination at point 2. I want to rotate #1 so that it is "p... | The solution is the super-useful std::atan2 function. Subtract the current position from the target position of a bird, and stuff y and x (note the order!) into atan2 to get the angle.
Edit: Note that atan usually assumes 0° to be at the X+ axis (right). However, you seem to align your 'base direction' to Y+ instead (u... |
4,898,989 | 4,933,601 | What will the effect of trimming my "working set" be on a system with no page file? | A customer is complaining that my program is using too much memory. However, after working with them for a while, I've realised that:
They've turned off their page file (on their terminal services box).
They're worried about the size of the "private working set" figure in task manager for my program.
So, my question... | You've noted that your working set goes up after new/malloc. This is because they ask the OS for memory. You've also noted that it does not go down after delete/free. This is because they don't return memory to the OS. On a normal, sane system, this is not a problem. The unused memory space for your process will end up... |
4,899,001 | 4,899,667 | Async Console Output | I have a problem with my application win32 console.
The console is used to give commands to my application. However, at the same time it is used to output log messages which mostly comes from asynchronous threads. This becomes a problem when the user tries to write some input and simultaneously an async log message is ... | This is possible using the Console API, but it involves quite a bit of work and all the threads that use the console will have to cooperate by calling your output method rather than directly calling the Console API functions or the runtime library output functions.
The basic idea is to have your common output function ... |
4,899,246 | 4,907,147 | How to change, modify, cut and swap pixels from BITMAP | I want to modify a bitmap:
change (swap) pixel position (for later rectification of fish eye)
divide bitmap in sub-bitmaps (e. g. make 4 bitmaps out of 1) (for later texturizing of different GL_QUADS)
For this I need the code how to modify pixels of a bitmap.
The follwing code example works and creates a texture from... | The last argument in the following call is the byte array for the pixels:
glTexImage2D(GL_TEXTURE_2D, 0, 3, bmpOutput.bmWidth, bmpOutput.bmHeight,
0, GL_RGB, GL_UNSIGNED_BYTE, bmpOutput.bmBits);
This means bmpOutput.bmBits points to the first byte in an array containing the following number of bytes:
3 * ... |
4,899,425 | 5,128,193 | What are the real C++ language constructs supported by CUDA device code? | Appendix D of the 3.2 version of the CUDA documentation refers to C++ support in CUDA device code.
It is clearly mentioned that CUDA supports "Classes for devices of compute capability 2.x". However, I'm working with devices of compute capability 1.1 and 1.3 and I can use this feature!
For instance, this code works:
//... | Oficially, CUDA has no support for classes on devices prior to 2.0.
Practically, from my experience, you can use all C++ features on all devices as long as the functionality can be resolved at compile-time. Devices prior to 2.0 do not support function calls (all functions are inlined) and no program jumps to a variabl... |
4,899,476 | 4,901,821 | C++ class/structure data member offset as constant expression | Taking offset of a data member is as easy as this:
#define MEMBER_OFFSET(Type, Member) \
((unsigned long)(((char *)&((Type *)0)->Member) - (char *)0));
I want to make this a constant compile-time expression (or use type traits). For example, to use it to implement SFINAE based solutions using member offsets, use i... | Though I can't get what your compiler is,
the following code can be compiled by VC8, ideone(gcc-4.3.4), and Comeau
online:
struct A { int i; };
template< size_t > struct S;
int main() {
S< offsetof( A, i ) > *p;
}
Gcc has __offsetof__ extension.
VC seems to have a capability to take a non-compile-time constant for ... |
4,899,494 | 4,901,385 | Motherboard beep on Windows CE | I wish to emit a "beep" from the motherboard of a system running Windows CE. Most information / code I have come across use MessageBeep which, from what I can tell, attempts to use the soundcard as opposed to the hardware on the motherboard.
I am using C++ but can you C#.NET if required.
I am running Windows CE 6 on a ... | Have you tried printing a bell character?
cout << '\a';
|
4,899,542 | 4,899,677 | Implementation communication protocols in C/C++ | I am in the process of starting to implement some proprietary communication protocol stack in software but not sure where to start. It is the kind of work I have not done before and I am looking for help in terms of resources for best/recommended approaches.
I will be using c/c++ and I am free to use use libraries (BSD... | Start with interfaces and messages.
Declare the interfaces of session that allow peers to exchange messages. Declare the messages as C++ structs with simple types, like ints, doubles, std::string's and and std::vectors. For example:
// these are your protocol messages
struct HelloRequest {
uint32_t seq_no;
// m... |
4,899,582 | 4,899,651 | I get this error: "glibc detected" | I just wrote a piece of CPP code and I compiled it using G++ in ubuntu.
When I run my code everything is fine, the code runs well and gives output but doesn't exit and it gives this error:
*** glibc detected *** ./a.out: free(): invalid next size (fast): 0x09f931f0 ***
======= Backtrace: =========
/lib/libc.so.6(+0x6... | Even if you're not allocating memory directly, it happens under the hood in vector code and you most likely corrupted some portion of memory by writing where you are not supposed to. The most likely reasons I can think of are:
Writing to an element that is out of bounds
Using a pointer/reference to an element that is ... |
4,899,657 | 4,899,683 | Performance impact of virtual inheritance | I am considering using virtual inheritance in a real-time application. Does using virtual inheritance have a performance impact similar to that of calling a virtual function? The objects in question would only be created at start up but I'm concerned if all functions from the hierarchy would be dispatched via a vtable ... | Common implementations will make access to data members of virtual base classes use an additional indirection.
As James points out in his comments, calling a member function of a base class in a multiple inheritance scenario will need adjustment of the this pointer, and if that base class is virtual, then the offset o... |
4,899,700 | 4,902,424 | OpenMP for loop ignores num_threads clause | I have the following code in VS2008:
int i,j;
bool pr = false;
#pragma omp parallel for private(pr) num_threads(2)
for(i=0;i<PIC_X;i++)
{
int rank = omp_get_thread_num();
int count = omp_get_num_threads();
if ( !pr )
{
printf_s("Hello from thread %d of %d\n", rank, count);
pr = true;
... | You have set pr outside of the parallel region and then made pr private by putting it in a private clause. That means that each thread has a pr, but the private pr variables are not initialized. Use firstprivate rather than private for pr, so that the private variables are initialized.
However, you are incorrect ab... |
4,899,756 | 4,899,830 | Returning *this in member functions | I recently used a library that allows the following type of syntax:
MyClass myObject;
myObject
.setMember1("string value")
.setMember2(4.0f)
.setMember3(-1);
Obviously this is accomplished by having the setters return a MyClass & type; something like return *this. I like the way this code looks, but I don'... | This is sometimes referred to as the Named Parameter Idiom or method chaining. This isn't bad practice, it can aid readability. Consider this example lifted from the C++ FAQ
File f = OpenFile("foo.txt")
.readonly()
.createIfNotExist()
.appendWhenWriting()
.blockSize(1024)... |
4,899,992 | 4,900,126 | Does defining a fluent interface have a performance impact? | I just read this question, which raises for me another question:
Consider this class:
class Foo
{
public:
void setA(int a) { m_a = a; }
void setB(int b) { m_b = b; }
private:
int m_a, m_b;
};
Which could also be written using the "fluent interface" method:
class Foo
{
public:
Foo& setA(int a) { m_a = a; return... | Since the methods are inlined, the compiler should be able to see that the return value is unused and possibly optimize it away.
Use whichever way makes the most sense for your project design. Then, measure the performance and only if it's not good enough would you consider optimizing the code.
|
4,900,068 | 4,900,264 | C++ queue with dependencies | I am looking for a prototype or implementation for a queueing/scheduling system with dependencies between the individual tasks. To be more specific:
task_0, task_1, task_2, ... task 10 arrive at the queue. Tasks are http requests.
I want to send task_2 only if task_0 is completed. task_1 can be sent without expecting ... | The queue can be topologically sorted.
http://en.wikipedia.org/wiki/Topological_sorting
http://www.cs.sunysb.edu/~algorith/files/topological-sorting.shtml
|
4,900,153 | 4,900,824 | Why is my program sending 'Anonymous IP Packets' and how do I stop that? | So, we just got word today that one of our clients firewall is blocking our HTTP requests because "The [software] is sending anonymous packets to our firewall (a Microsoft TMG firewall) so the firewall is dropping the packets as anonymous access is [not] allowed."
For our connection code we are using c++ with curl and ... | What they mean is your app has to authenticate with the firewall. That link provides a wealth of information concerning the TMG product. Your client probably has this configuration:
Require users to authenticate whenever
they request Web access. Every Web
session requires authentication.
When using this method,... |
4,900,309 | 4,900,924 | Caching data from MySQL DB - technique and appropriate STL container? | I am designing a data caching system that could have a very large amount of records held at a time, and I need to know what stl container to use and how to use it. The application is that I have an extremely large DB of records for users - when they log in to my system I want to pull their record and cache some data s... | A1. you're better off with a map, this is a tree that does the lookup for you. Test with a map and (assuming you have the right compiler) or a hash_map (which does the same thing, but the lookup mechanism is different). They have different performance characteristics for different types of data storage workloads.
A2. A... |
4,900,318 | 4,900,359 | Learning Qt - Creating a QApplication | I'm re-learning c++ (I have 10 years Java experience) and I'm also learning Qt in the process...
I'm used to creating objects (in Java) via:
MyObject o = new MyObject();
But when creating a QApplication in c++, the examples simply show:
QApplication app(argc, argv);
app.setOrganizationName("My Company");
app.setApplic... | Not really a Qt question but,
//You have an assignment to app
QApplication app(argc, argv);
// is just the same as
QApplication *app = new QApplication(argc, argv);
In C++ you have the choice of creating objects locally (on the stack) or with new (on the heap). Allocating it locally here makes more sense when the a... |
4,900,346 | 4,900,417 | How to minimize C++ function using boost? | so I have a function like
int f(int i, int j, int c, double d) {
/*...any operations with i, j, c, d affect on some return int we have*/
}
Is there any thing in boost or STD that would take my function and find the input arguments that minimize my function output?
| I understand you to be looking for code to perform mathematical optimization.
Boost does not have anything to do this as far as I know, and neither does the standard library; however, NLopt may be what you're looking for.
|
4,900,425 | 4,900,513 | How to get just the moment a key was pressed with GetKeyState | Using GetKeyState, I can do some task when a key is pressed. However, if I have if (GetKeyState(VK_UP) & 0x80), it returns true the entire time the key is being held.
How do I handle this if I just want this to be true the exact moment the key is pressed (so the contents of the if statement don't run several times)?... | You can use a bool flag = false and use it like this:
if((GetKeyState(VK_UP)&0x80) && ! flag)
{
flag = true;
}
else if((GetKeyState(VK_DOWN)&0x80) && flag)
{
flag = false;
}
if(flag) //key is just pressed
{
//TODO: Your handling here
}
|
4,900,739 | 9,062,862 | Why are designated initializers not implemented in g++ | Is there any specific reason why has support for designated initializers not been added to g++? Is the reason that C99 standards came late and g++ was developed earlier and later people didn't care about this issue, or there is some inherent difficulty in implementing designated initializers in the grammar of C++?
| As I noted in a comment, G++ doesn't support C99 standard designated initialisers, but it does support the GNU extension to C90 which allows designated initialisers. So this doesn't work:
union value_t {
char * v_cp;
float v_f;
};
union value_t my_val = { .v_f = 3.5f };
But this does:
union value_t my_val = {... |
4,900,813 | 4,901,197 | Why does binary saving of array in a file works? [C++] | C++ newbie here.
I'm trying to figure out the following line that writes a buffer into a file:
fOut.write((char *)&_data, sizeof(_data));
_data = array of integers...
I have a couple of questions:
Is &_data the address to the first element of the array?
Whatever address it is, does that mean that we only save the add... | Contrary to your comment, the array must be automatic or static storage duration in order for sizeof to work.
It should be just (char*)_data. The name of an array implicitly converts to a pointer to the first element.
No, write expects a pointer, and stores the content found at that location, not the location's addre... |
4,900,833 | 4,900,884 | array of questions on pointers, double pointers, malloc, realloc and new (to set the record straight) | I'm catching up on pointers. I wrote down a few lines of code to test the different ways I could dynamically allocate a 2d array (posted at the bottom)
My questions are the following:
Should I use malloc in c++, or new? If I use new, can I still use realloc?
When should I use realloc? What are the implications of usin... |
new and new[] are constructor aware, the C memory allocation functions are not.
Similarly, delete and delete [] are destructor aware, whereas free isn't.
realloc does not work with memory allocated with new, there is no standards defined analog to the realloc function with C++ memory management functions.
Do not mix n... |
4,900,929 | 5,067,980 | libvlc - simple C++ streaming | This should be the classic simple error which I can't really find..
I am using libvlc from a VS2010 C++ project. I followed these steps to record from a webcam and streaming it through RTSP:
1)
inst = libvlc_new (1, myargs);
where myargs just contain the plugin path
2)
libvlc_vlm_add_broadcast(inst, "mybroadcast", "... | I found the solution: the URL was malformed.. a "/" at the end of the URL was needed
|
4,900,939 | 4,901,096 | Rules for Argument Dependent name lookup in C++ | There have been some questions on SO recently on ADL that have got me thinking. Basically, I am confused which header files compiler can search when performing ADL ? Is it only the ones included by the user's code or can it include the other header files in which the same namespace which is being used in the user's cod... | Here's how it works... There are 3 basic steps to compiling source into an executable:
preprocessing
compilation
linking
There is zero overlap in these steps in C++. Include directives are preprocessor directives and therefore happen before compilation. Template instantiation is a part of compilation, therefore it ... |
4,901,005 | 4,901,162 | What's the difference between these two local variables? | const std::string s1("foo");
const std::string& s2("foo");
Not sure how they are different but I'm seeing evidence of both usages. Any ideas?
| const std::string s1("foo");
This declares a named std::string object as a local variable.
const std::string& s1("foo");
This declares a const reference to a std::string object. An unnamed, temporary std::string object is created with the contents "foo" and the reference is bound to that temporary object. The tempo... |
4,901,050 | 4,903,586 | Compiler error "collect2: Id returned 1 exit status" using classes with QObject (QT 4.7 with Qt Creator) | I've got the following situation in my current project: "collect2: Id returned 1 exit status" returned by the compiler using the following code:
#ifndef BASE_02_H
#define BASE_02_H
#include <QtCore>
class Base_02
{
public:
Base_02();
virtual void method()=0;
};
#endif // BASE_02_H
#include "base_02.h"
#in... | #include "base_02.h"
#include <QtCore>
has to be:
#include <QtCore>
#include "base_02.h"
Then it compiles!
|
4,901,233 | 4,901,240 | Is there anyway to use a member function as a default parameter? | It tried something like this, which doesn't work. Is there a way to get a similar effect?
class A
{
public:
int foo();
void bar(int b = foo());
};
| Yes. Overload the function and call the member-function in it.
void bar() { bar(foo()); }
|
4,901,311 | 4,901,331 | Testing Release Builds | Here's my problem
I have a C++ project which issues periodic iterations. These are release builds run by hand in MVSC2008.
On my dev machines, these release builds run fine but don't on machines which don't have the build environment installed (in this instance, its not a Side-by-Side error).
My question is how do I si... | This is exactly what Virtual PC was made for.
Microsoft even offers free image downloads for testing:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=21eabb90-958f-4b64-b5f1-73d0a413c8ef&displaylang=en
|
4,901,524 | 4,901,915 | Secure file upload with Qt | I'm in the process of creating a utility to backup user's media files. The media isn't being shared etc its only a backup utility.
I'm trying to think of the best way to protect users from ISPs accusing them of downloading illegal media files by using some sort of secure connection.
The utility is written in C++ using ... | Easiest way would be to just wrap a commandline sftp client with a Qt front end.
On the server any ftp server should do sftp pretty much out of the box.
|
4,901,743 | 4,901,850 | Techniques to keep corresponding native and managed enumerations in sync | I have a manager wrapper for a native library -- the native library is C++ with an exported C interface, and I use P/Invoke on the managed to side to achieve the interop. I am in control of both the managed and native code.
There's an enumeration in the native code that has a corresponding enumeration in managed code, ... | Place them into a separate C# file, #include from C++ side. #define away all the C# fluff (like the initial public). Like this:
#define public
#include "enums.cs"
#undef public
|
4,901,884 | 4,901,982 | C++ GTK make MinGW error simple program | I really need help on getting a simple GTK program in c++ running using MinGW. Here's my program:
# Makefile for Hello World Program (lab0).
all: lab0
lab0: lab0.o
g++ -Wall lab0.o -o lab0 -L C:/Users/Vic/Desktop/MinGW/lib -lgtk
lab0.o: lab0.c
g++ -Wall -I C:/Users/Vic/Desktop/MinGW/include/gtk-2.0/gtk -c la... | Ideally, you would use pkg-config to help you find the header and library paths:
g++ -Wall lab0.o -o lab0 `pkg-config --cflags --libs gtk+-win32-2.0`
Or just the library path:
g++ -Wall lab0.o -o lab0 -LC:/users/vic/desktop/mingw/lib -lgtk `pkg-config --libs gtk+-win32-2.0`
|
4,901,889 | 4,902,619 | GetThreadContext() returns error 18 - There are no more files | GetThreadContext() returns error 18 - There are no more files. I've searched all over the place and cannot find explanation to the error. Could someone clarify this for me?
Big thanks.
| Rob Kennedyand Hans Passant answered my question below. I wanted to just quote Rob and Hans here as an answer:
Hans Passant
First verify that it [GetThreadContext()] returned FALSE, you won't get a valid error code from GetLastError() if it [GetThreadContext()] returned TRUE.
Rob Kennedy
The return value from GetLastEr... |
4,901,999 | 4,902,048 | C++ equivalent of MATLAB's "fileparts" function | In MATLAB there's a nice function called fileparts that takes a full file path and parses it into path, filename (without extension), and extension as in the following example from the documentation:
file = 'H:\user4\matlab\classpath.txt';
[pathstr, name, ext] = fileparts(file)
>> pathstr = H:\user4\matlab
>> name =... | Some possible solutions, depending on your OS:
Visual C++ _splitpath function
Win32 Shell Path Handling Functions such as PathFindExtension, PathFindFileName, PathStripPath, PathRemoveExtension, PathRemoveFileSpec
|
4,902,025 | 4,902,608 | Why does this cin loop never end? | In the following code, if the user inputs something that is not an int, the program goes into an infinite loop. Why does this happen, and what should I do to fix it?
#include <iostream>
#include <string>
using namespace std;
int main()
{
int i;
char str[100];
while (!(cin >> i))
{
gets(str);
... | Clear the error state:
int main()
{
int i;
char str[100];
while (!(cin >> i))
{
cin.clear();
cin.getline(str,100);
cout << "failure read!" << endl;
}
cout << "successful read!" << endl;
return 0;
}
|
4,902,052 | 4,902,175 | How to use C# delegate like functor in C++? | In C++, to sort a vector, a list or any collection, I would use:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main() {
vector<int> vt;
vt.push_back( 3 );
vt.push_back( 1 );
vt.push_back( 2 );
sort( vt.begin(), vt.end(), greater<int>() );
}... | Throughout the .NET framework you will occasionaly find methods (like Sort) which have one or more overloads which accept additional types (either interfaces or delegates) to extend their behavior. Unlike C++, .NET does not have the same approach as the STL to composable algorithms.
In the case of List.Sort there are t... |
4,902,231 | 4,902,274 | How to apply an algorithm for a C# container like functor in C++? | In C++ to apply an algorithm for a collection or container, I overload the operator(). For example generate random number for a container:
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdlib>
using namespace std;
class rnd_gen {
public:
rnd_gen( int lo, int up ) : lo( ... | Yes, in C# the canonical way to do this is using LINQ:
Random r = new Random();
List<int> randomInts = Enumerable.Repeat(0,3) // create 3 dummy placeholder values
.Select( x => r.Next(10,100) )
.ToList();
Breaking the above code down:
Enumerable.Range(0... |
4,902,313 | 4,902,467 | Difference between boost::shared_ptr and std::shared_ptr from the standard <memory> file | I was wondering if there are any differences between the boost::shared_ptr and the std::shared_ptr found in the standard <memory> file.
| std::shared_ptr is the C++0x form of tr1::shared_ptr, and boost's boost::shared_ptr should behave the same.
However, std::shared_ptr, in an implementation that conforms to C++0x standard, should/might have more convenience behavior on the shared_ptr class, as described in the following links:
Differences between diffe... |
4,902,571 | 4,902,636 | Does separating statements with commas instead of semicolons affect my program's speed? | I was wondering if any of these samples works "faster" than the other. I know there can't be a big difference, but I just want to know if there's any difference.
CODE1:
a+b=c;
c=c*c;
d=c*a;
CODE2:
a+b=c,c=c*c,d=c*a;
So does it matter if I use , or ;?
Just asking... :D
| The number of lines of a program is not indicative of its speed. To answer your question: no, there is no difference in speed between the two forms you posted. If you look at the assembly code generated by the compiler for each program, you will see it's exactly the same.
How to read the assembly output of a C program
|
4,902,627 | 4,902,689 | if statement nested in for statement won't work | I've searched all over the internet, but I can't find an answer to my problem anywhere. I'm trying to write a program that will find the inverse of a 3x3 matrix and I'm trying to set up the matrix of minors.
Code(it's not all the code only the part that doesn't work):
for (int d = 0; d < rows; d++) /** d is the row o... | The fourth nested loop
for (int j = 0; j < 0; j++)
never executes. Look at the condition...
|
4,903,326 | 4,903,373 | Watching a C++ array in Visual Studio | I have declared an array as follows:
int *arr;
Is there any way in visual studio to watch all the elements of the array while debugging, rather than having to manually place watch for an element *(arr+1), *(arr+2) and so on.
| If arr is a pointer to an array of ten integers, you can add "arr,10" to the watch window and when you expand it it will show the ten elements [obviously, you can replace the 10 with whatever the length of your array is].
|
4,903,659 | 4,904,604 | Efficiently summing log quantities | Working in C++, I'd like to find the sum of some quantities, and then take the log of the sum:
log(a_1 + a_2 + a_3 + ... + a_n)
However, I do not have the quantities themselves, I only have their log'd values:
l_1 = log(a_1), l_2 = log(a_2), ... , l_n = log(a_n)
Is there any efficient way to get the log the sum of th... | How large is n?
This quantity is known as log-sum-exp and Lieven Vandenberghe talks about it on page 72 of his book. He also has an optimization package which uses this operation, and from a brief look, it seems as if he doesn't do anything special there, just exponentiates and adds. Perhaps exponentiation is not a ser... |
4,903,678 | 4,903,872 | modeless QDialog: closeEvent() not called when application exits? | I have a modeless dialog that overrides closeEvent() in order to save its state. This works fine if I actually close the dialog. However, if I just exit the application by whatever means (which of course results in my dialog closing), closeEvent() never gets called.
Is this by design? Is it a Qt bug? Is there something... | There's a bug in Qt that when an application quits via menu command (instead of closing the last QMainWindow), the event system is not properly shutdown and objects on the heap are just leaked. It basically just calls exit(); right away.
I filed a bug for this on the Mac platform. I don't know what your platform is and... |
4,903,856 | 4,903,882 | What should I read to improve my C++ style | I was developing for quite long time already on C/C++ (mostly C, which makes style poorer). So, I know how to use it. However, quite often I stuck with style decisions like:
- should I return error code here, throw exceptions, return error through a parameter
- should I have all this stuff in constructor or should I cr... | Here is a list of really good books on C++:
The Definitive C++ Book Guide and List
Read few of them as per your level. That would most certainly improve your coding style!
I would personally suggest you to read:
Effective C++ series C++ by Scott Meyers
Exceptional C++ series by Herb Sutter
Exceptional C++ discusses e... |
4,904,142 | 4,904,210 | Which has better performance: executing a Perl script from C++ via system call, or calling a DLL file? | I am new to C++ coding.
I wanted to execute a Perl script (that controls an equipment) inside a C++ Visual Studio Win32 application. I was wondering what would be the most optimized approach in this regards?
Call system function and execute that particular Perl file.
Create some kind of DLL and call that DLL inside... | I believe the "most optimized" approach is to embed Perl in your application.
Your second option is not really feasible, AFAIK. Since Perl is not compiled, your only other option would be to invoke the interpreter (e.g. through a system() or exec()-family call), as per your first option.
Now, there is quite a differenc... |
4,904,179 | 4,904,196 | Why is integer comparison faster then string comparison? | I found comments about avoiding strings for the comparison of values (especially in loops) in a few books because string comparison is a lot slower (using std::string). But why exactly is that?
Is it because integer units in the cpu are working faster?
Strings should be in byte I guess, so wouldn't a byte comparison do... | With an integer, there exist instructions on the machine level which can perform a comparison in one cycle.
A string, however, consists of a lot of characters. In order to compare strings, you, in the worst case, have to look at every character of the strings.
In fact, when you compare strings, you're most likely using... |
4,904,236 | 4,904,372 | projected surface normal vector onto xy plane | i have a plane whose equation is ax+by-z+d=0. hence, its normal vector (a,b-1). Now, i need to project my vector to xy plane in order to compute direction of it from the North axis (i guess it is Y axis in here. please help me to get projected vector. thank you.
| I think what you're looking for is the dot product. Finding the direction the plane is facing is pretty easy that way.
// generic code, actual code depends on your engine.
// BasePlane.GetNormal() would equal to (0,0,1) for the X/Y plane
float dir = YourPlane.GetNormal().Dot(BasePlane.GetNormal());
If it equals to 1, ... |
4,904,308 | 4,904,330 | Axis aligned bounding boxes collision: what sides are colliding | I'm trying to make an arkanoid-like game, and now I'm facing a problem with the collisions. As usual, the bricks are rectangles (in my case, squares) and the ball is a circle, so it's all about axis aligned bounding boxes.
So far, I've got the trivial collision detection algorithm, but I need to know what side of each ... | Don't just set it to one, set it to the penetration depth:
// why is it named mouse?
if(mouse.left < brick.left && brick.left < mouse.right &&
mouse.right < brick.right)
{
left = mouse.right - brick.left;
}
// and so on...
Then when you're done, you can pick whichever is minimum to be your main side.
By the ... |
4,904,327 | 4,904,382 | c++ varargs/variadic function with two types of arguments | I am trying to implement a variadic function. I searched the web and ended up finding out that most examples handle only one type of arguments (for example calculating average of many integers). Im my case the argument type is not fixed. It can either involve char*, int or both at the same time. Here is the code i ende... | since you're doing c++ there's no need to use untyped C-style variadic function.
you can simply define a chainable method like
class Inserter
{
public:
Inserter& operator()( char const* s )
{
cout << s << endl;
return *this;
}
Inserter& operator()( int i )
{
... |
4,904,503 | 4,904,535 | Implementing Reflection in C++ | I have been interesting implementing Reflection in C++, I have a slapped together Reflection, but I am interested in seeing how others have it done. Does anyone know any tutorials, articles or sample code on how to do this?
| http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf
|
4,904,589 | 4,904,616 | How do you run a command line program after compiling with GCC on OSX? | Some of Facebooks programmer puzzles look fun, so I'm trying to get set up to code in C++ on my mac. I decided to try compiling some of my old CS homework with GCC to get started.
My code compiles fine, but when I try to run the executable (called "encrypt") I get this:
-bash: encrypt: command not found
I checked the ... | The current directory isn't in your $PATH, so you have to tell the shell to execute encrypt in the current directory.
./encrypt
or
/path/to/directory/encrypt
|
4,904,636 | 4,904,669 | Problem with operator overloading | I have a scene class with member variables Image **images, int * xcoords, int * ycoords. Now, I'm trying to overload my = operator.
I get the following memory errors (using valgrind)
Conditional jump or move depends on uninitialised value(s)
==6439== at 0x406FCA: Scene::drawscene() const (scene.cpp:160)
==6439== ... | You need this:
if(source.images[i]!=NULL) {
images[i]=new Image;
*images[i]=*source.images[i];
xcoords[i]=source.xcoords[i];
ycoords[i]=source.ycoords[i];
} else {
images[i] = NULL;
}
and that will solve your immediate problem. But rea... |
4,904,762 | 4,904,873 | In C++, why is `new` needed to dynamically create an object rather just allocation? | I've got this trivial class hierarchy:
class Base {
public:
virtual int x( ) const = 0;
};
class Derived : public Base {
int _x;
public:
Derived( int x ) : _x(x) { }
int x( ) const { return _x; }
};
If I use malloc to allocate an instance of Derived, and then try to access the polymorphic function x, ... | Let's go down the line
why is my application crashing, if I don't use new?
Virtual table is corrupted.
The virtual table is stuck right after the allocated memory. when you new a class, the generated code will properly set up the vtable. However, malloc will not properly initialize the vtable
To see the virtual tab... |
4,904,812 | 4,904,985 | execvp() causing EXC_SOFTWARE and bizarre cin.getline loop? | I'm running some code on Mac OSX 10.6.6 and XCode 3.2.4 and I have some pretty standard code: fork(), if pid == 0 then execvp with a command and the args (the args include the command as the first element in the array, and the array is null terminated).
We're going over this in my Operating Systems class and our assign... | One problem is that you do not check the return from cin.getline(), so if you type EOF, the code goes into a tight loop. You're also leaking memory.
Try:
while (cout << prompt && cin.getline(buffer, sizeof(buffer))
{
int count = 0;
char **split = Split(buffer, count);
Run(split, count);
delete[] split;... |
4,904,813 | 4,904,832 | Trouble with accessing a member function | I'm using the EasyBMP library. This library has a method:
int red = image(i, j)->Red;
// Gets the value stored in the red channel at coordinates (i, j) of the BMP named image and stores it into the int named red.
Here's the code that I have:
int red = images[i](x, y)->Red;//images is a dynamic array, I'm using a for... | To answer your question, you have an array of pointers to Images. Subscripting the array gives you a pointer. You have to dereference the pointer first before you can call functions on it.
int red = (*(images[i]))(x, y)->Red;
Note that an extra pair of parentheses are needed because the dereference operator * has a lo... |
4,904,821 | 4,905,806 | How to define a global variable template in C++? | Suppose you have to write a template library that operates on a client-supplied type. Also, suppose that this library really needs to access a global variable parameterized by the client-supplied type. How would you go about implementing this pattern?
| @AnonymousCoward
this is derived from your solution. note the initialization/destruction patterns in this variant (read the output if you don't have it memorized already). you can use this to defer creation until access, and to destruct and free at termination (which may be useful for custom types):
#include <iostream>... |
4,904,922 | 4,905,003 | compute slope of a 3D plane | I have a set of (X,Y,Z) points representing different planar features. I need to calculate the slope of each plane using normal vectors.
i think slope is given by the angle between normal vector (NV) of each plane and NV of imaginary horizontal plane. Assume, the plane equation that I use is; Ax+By+c=z. Then i guess th... | Yes, that's mostly correct, but you've made some small mistakes substituting into the expression for the angle. The angle is cos^{-1} [(a * 0 + b * 0 + (-1) * (-1) / (√{a^2 + b^2 + (-1)^2} * √{0^2+0^2+(-1)^2}] = cos^{-1}(1/√{a^2 + b^2 + 1})
|
4,904,929 | 4,904,937 | How can I make a DEBUG function in C++ such as ConditionalAttribute in C# | In C#, one can make a method such as this:
[Conditional("DEBUG")]
private void MyFunction()
{
}
In release, this method will no longer "exist".
Using C++, I have a class where I want to perform the same assertions at the beginning of every method, so I would like to put the group of assertions in their own method. If ... | The compiler will definitely optimize out the empty functions. I would prefer the function of asserts over different versions of the code for debug and release. Of course, you should name the function appropriately, and document your reasons as well :-)
If, for some reason, you absolutely did have the urge to use #if... |
4,904,980 | 4,905,478 | GNU readline whitespace quoting | i´m working on an application which uses readline to read commands from stdin.
It accepts "cd", and other commands which require a path as an argument. I'm having troubles with paths that include whitespaces. My objective is to somehow make readline quote the whitespaces, and autocomplete the path name after this char... | Try to escape not spaces but the whole path. For example:
cd "/path/to/some where"
|
4,905,030 | 4,905,080 | Where can I learn how to use window formatting and menu items with C++? | I want to make it so it can be used on all unix systems, so I guess this would involve xwindows? Not sure how to communicate with the operating system to make my own top bar, and I guess I would need to have a way to make a scroll bar too. There must be a simple way to do these things.
| Folks are (rightfully) mentioning the Qt toolkit. This is what's used by KDE.
The other popular one is GTK+. The primary language for this is C, not C++. But there are C++ wrappers, such as gtkmm ("GTK minus minus"). This grew out of the GIMP and is the toolkit for GNOME. If you're running Firefox, that's using GT... |
4,905,035 | 4,905,086 | Create C++ Class with "Default/Main" Value (ie 'string') | so i wondering on how you create a class in c++ where the object itself has a main value like how 'string' works
for example:
MySocket m = SOCKET kSocket;
m.Connect(...);
SOCKET aSocket = m;
where m has a default type of SOCKET but has other variables and functions
| It is late.. so I am going to make a big leap here.
I think you are looking for auto type converters. There isn't a default type. What you are looking for is a way to automatically type convert a m into a SOCKET.
look up using something like
class MySocket
{
public:
operator SOCKET()
... |
4,905,053 | 4,905,073 | Variable or Field 'nameOfVariable' declared void no idea why :( | I've googled and searched on various websites and I can not work out why I get the follow errors from one of my functions.
error: variable or field 'ConnectClient' declared void
error: 'Socket' was not declared in this scope
Both of those errors are for the line 38 of my code, which is the...
void ConnectClient(Socket ... | void ConnectClient(Socket _newConnection)
{
int slotIndex = FindFreePlayerSpot();
if (slotIndex == -1)
{
closesocket(_newConnection);
cout << "No player slots available, connection aborted"
}
Two problems here.
1)It should be SOCKET, not Socket.
2) You're missing a semi-colon (;) at end... |
4,905,114 | 4,905,128 | Multithreaded queue destruction in C++ | So I have a shared concurrent queue. It seems to be working nicely, except for destruction.
The way the queue is implemented is that it contains a condition variable and mutex pair.
Several worker threads are started up that wait on this condition variable. When new objects are available to be worked on they are pushe... | You can call join() on each thread to wait until it has finished executing. Something like this:
void DoWork() {};
int main()
{
boost::thread t(&DoWork);
// signal for the thread to exit
t.join(); // wait until it actually does exit
// destroy the queue
}
Or you can use boost::thread_group for mu... |
4,905,414 | 4,905,442 | Introduce boost::exception to me | I am asked to create "customizable exception framework" using boost::exception. Till date I used only simple exceptions defined by me. So std::exception,boost::exception are new to me. The code is below.
#include <iterator>
#include<string>
#include <algorithm>
#include<errno.h>
struct My_exception:public virtual boo... | First of all, your code has error, for example you cannot write this:
e << boost::errinfo_api_function("fopen")
Because errinfo_api_function can be used with int only. So do something like this:
e << boost::errinfo_api_function(100) //say 100 is error code for api error
See the second type parameter to errinfo_api_... |
4,905,582 | 4,906,582 | Problem with bin sort | //element of chain.
struct studentRecord
{
int score;
string* name;
int operator !=(studentRecord x) const
{return (score != x.score);}
};
// binsort, theChain is a single linked list of students and its element is student Record
... | Yes, the bin indeed can be empty. There's a subtle but important difference between the bin being empty and the bin existing. You are correct that the bin is a member of the array, and so there exists a bin in position i for any i that's in bounds in the array. However, that bin doesn't necessarily have to have anyt... |
4,905,675 | 4,905,847 | problems accessing derived class in array | class BaseObj
{
public:
int position;
};
class EnemyObj: public BaseObj
{
public:
int quantity;
};
class PlayerObj: public BaseObj
{
public:
int lives;
};
int main()
{
BaseObj* myObjs[3];
BaseObj* b = new BaseObj();
b->position = 1;
myObjs[0] = b;
EnemyObj* e = new EnemyObj();
e... | C++ is a statically typed language and this means that every variable has a specific type. Your array contains pointers to BaseObj and this means that the compiler will only allow access to the members defined in that class.
You can tell the compiler that indeed one of those pointers is pointing to a more specific (i.e... |
4,905,687 | 4,906,450 | Database problem in Qt | I am creating an application using Qt for Symbian Devices & i want to use database(sqlite)
but it is craeting this error. How to remove this?
Code:
QSqlQuery query;
query.prepare("INSERT INTO glucose(value, date, time, duration, note)""VALUES(:value, :date, :time, :duration, :note)");
query.bindValue(":va... | I think you forgot to add the SQL support in your .pro file
QT += sql
Then you can include QSqlQuery.
|
4,905,728 | 4,905,803 | Making redundant OpenGL calls | I was wondering if it is recommended to eliminate all redundant opengl calls.
For instance, should I be doing something like (wrapped in a function):
if(foobuffer != boundbuffer) {
glBindBuffer(GL_BAR_BUFFER, foobuffer);
boundbuffer = foobuffer;
}
Or is the driver automatically doing such things and this is actual... | You should probably avoid it. Here (specifically 22.040, you'll have to scroll down the page since there's no anchor for it), it is noted that redundant calls are generally bad practice even though some implementations attempt to minimize the impact.
Tools like gDEBugger can be used to help track down where you might ... |
4,905,766 | 4,905,775 | String static member error | I am making a basic program which takes some input and prints it back but I am getting strange error about my static variable.Please help me out.Thanks
Code:
/*
Date:5th January 2011
Programmer:Fahad
*/
#include <iostream>
#include <string>
using namespace std;
class Persons //A class that will store the name,... | instead of
static int count;//initializing the static member
write
int Persons::count;
|
4,906,033 | 4,910,766 | How to compute Aspect angle | I have many 3D planes. The thing that I need to know is the way of computing aspect angle.
I hope, I can compute the aspect angle by using the projected normal vector of each plane (my plane equation is ax+by-z+c=0; so normal vector of this plane is a,b,-1) to the XY plane. Then, from the Y axis I can compute the aspe... | Some quick googling reveals the definition of the aspect angle.
http://www.answers.com/topic/aspect-angle
It's the angle between the geographic north on the northern hemisphere and the geographic south on the southern hemisphere. So basically it's a measure how much a slope faces the closest pole.
If your world is pla... |
4,906,116 | 4,906,145 | Templates with implicit parameters, forward declaration, C++ | There is a declaration of template class with implicit parameters:
List.h
template <typename Item, const bool attribute = true>
class List: public OList <item, attribute>
{
public:
List() : OList<Item, attribute> () {}
....
};
I tried to use the fllowing forward declaration in a different header file:
Anal... | Simple. Remove the default value from the definition, since you already mentioned that in the forward declaration.
template <typename Item, const bool attribute = true> //<--- remove this 'true`
class List: public OList <item, attribute>
{
//..
};
Write:
template <typename Item, const bool attribute> //<--- this is... |
4,906,273 | 4,962,654 | libusb communicate with USB mass storage | I'm currently writing a javax-usb (JSR-80) implementation using libusb 0.1 as a backend. I need to test the bulk transfer functionality and my guess is that the easiest way to do this is to communicate with a USB mass storage device like a USB flash drive. Unfortunately I have no idea how these devices are working. I g... | The USB device class specifications are really not all that difficult to read assuming you know the basics of USB (since you're writing a USB driver, I assume you do). Mass Storage Bulk Only v1.0 is probably the document you want.
|
4,906,301 | 4,906,322 | c++ inheritance question | I have a question about this:
class A
{
int a;
int* pa;
public:
A(int i):a(i) , pa(new int(a))
{
cout<<"A ctor"<<a<<endl;
}
~A()
{
delete pa;
cout<<"dtor\n";
}
int * &get()
{
return pa;
}
};
class B : public A
{
int b;
public:
B (A obj): A(obj) , b(... | Since you have not declared A constructor as explicit compiler is creating an anomymous instance of A using i and using it to initialize B instance. If you don't want the compiler to do these implicit conversions declare your costructor as explicit. Then you will get a compiler error.
|
4,906,341 | 4,906,442 | Why do I get a 'ÿ' char after every include that is extracted by my parser? - C | I have this function:
/*This func runs *.c1 file, and replace every include file with its content
It will save those changes to *.c2 file*/
void includes_extractor(FILE *c1_fp, char *c1_file_name ,int c1_file_str_len )
{
int i=0;
FILE *c2_fp , *header_fp;
char ch, *c2_file_name,header_name[80]; /* we can as... | "ÿ" corresponds to the code point 0xFF. fgetc returns EOF when the end of file is reached, which is (usually) defined as -1. Store -1 in a char and you'll wind up with 0xFF. You must check for EOF between calling fgetc and fpuc.
int ch;
...
/*copy header file content to *.c2 file*/
for (ch=fgetc(header_fp); ch > -1; ch... |
4,906,524 | 4,906,535 | How to access anonymous union/struct member in C++? | This question is my mistake.
The code described below is being built well with no problem.
I have this class.
Vector.h
struct Vector
{
union
{
float elements[4];
struct
{
float x;
float y;
float z;
float w;
}; ... | You need an instance of your struct inside the anonymous union. I don't know exactly what you want to achive, but e.g. something like this would work:
struct Vector
{
union
{
float elements[4];
struct
{
float x, y, z, w;
}aMember;
};
float length() const
{
return aMember.x;
}
};
|
4,906,581 | 4,907,023 | Can an tinyxml someone explain which characters need to be escaped? | I am using tinyxml to save input from a text ctrl. The user can copy whatever they like into the text box and it gets written to an xml file. I'm finding that the new lines don't get saved and neither do & characters. The weird part is that tinyxml just discards them completely without any warning. If I put a & into th... | It is, apparently, a bug in TinyXml.
The simple workaround is to escape anything that it might not like:
&, ", ', < and > got their regular xml entities encoding
strange characters (read non-alphanumerical / regular punctuation) are best translated to their unicode codepoint: &#....;
Remember that TinyXml is before a... |
4,906,736 | 4,906,765 | Working with images in C++ or C | The first thing is that I am a beginner. Okay?
I've read related answers and questions, but please help me with this problem:
How can I open an JPEG image file in C++, convert it to a grayscale image, get its histogram, resize it to a smaller image, crop a particular area of it, or show a particular area of it?
For th... | here is an example using magick library.
program which reads an image, crops it, and writes it to a new file (the exception handling is optional but strongly recommended):
#include <Magick++.h>
#include <iostream>
using namespace std;
using namespace Magick;
int main(int argc,char **argv)
{
// Construct the image obj... |
4,906,738 | 4,906,783 | How to get the amount of used memory when an application is executed | I have looked through GDB documentation, but haven't found anything that works or shows what I need: the maximum amount of memory that is used by my application.
I'm using MinGW-w64 (GCC for Windows) if that's relevant. I'd like something programmatically, not "look in your task manager". Also: my application executes ... | You could wrap malloc/free or new/delete:
How-to-profile-memory-usage-of-a-c-program
Thereby you can check how much memory (heap) you are using at any time.
|
4,906,754 | 4,906,769 | Multiple Dll's calling each others functions though "main" dll | I am building a game engine (in c++) which is split up into multiple projects (compiling to separate dll's and libs on windows and shared objects in linux ) the structure is as follows:
Main.exe
Engine.dll
Graphics Engine.dll Physics Eng... | You can expose an interface using a abstract class (i.e. with pure virtual functions) from the Engine.dll. Then implement this interface in the Engine.dll. Then create an instance of the concrete this class and pass the reference/pointer of this instance (as a abstract class reference/pointer) to the GraphicsEngine.dll... |
4,906,931 | 4,907,039 | NullReferenceException during C++ callback to C# function | developers!
I have very strange problem. My project has DLL writen in C++ and a GUI writen in C#. And I have implemented callback for some interoperability. I planed that C++ dll will call C# code in some circumstances. It works... but not long and I cant understand why. The problem marked in comment in C# part
Here th... | SetDelegate(new WriteToConsoleCallback(PrintSymbol));
Yes, this cannot work properly. The native code is storing a function pointer for the delegate object but the garbage collector cannot see this reference. As far as it is concerned, there are no references to the object. And the next collection destroys i... |
4,906,983 | 4,908,004 | parallelize inner loop using openmp | I have three nested loops but only the innermost is parallelizable. The outer and middle loop stop conditions depend on the calculations done by the innermost loop and therefore I cannot change the order.
I have used a OPENMP pragma directive just before the innermost loop but the performance with two threads is worst... | Unfortunately, current multicore computer systems are no good for such fine-grained inner-loop parallelism. It's not because of a thread creation/forking issue. As Itjax pointed out, virtually all OpenMP implementations exploit thread pools, i.e., they pre-create a number of threads, and threads are parked. So, there i... |
4,907,121 | 4,907,506 | Static library having object files with same name (ar) | A bit context. Let's say I have source files, which need to end up in a static library. Let's say there are two cpp files a.cpp and a.cpp located in two different subdirectories. Something like this:
foo/a.h
foo/a.cpp
bar/a.h
bar/a.cpp
Their content is not clashing and is completely different. The file names are just ... | You must think about ar as very old file archiver. It even doesn't know anything about archiving a directory. (ar archives are flat)
(man ar): ar - create, modify, and extract from archives
man ar, option r:
r Insert the files member... into archive (with replacement). This operation differs from q in that any prev... |
4,907,264 | 4,907,488 | about virtual base class and virtual inheritance in C++ |
Possible Duplicate:
gcc c++ virtual inheritance problem
Hi All,
I am reading Effective C++ by scott myers books. It was mentioned about virtual base class and virtual inheritance as follows.
The rules governing the initialization of virtual base classes are more complicated and less intuitive than are those ... | Let me explain the quotation by an example. Suppose, you've these classes,
struct A { A(int x) {} };
struct B : virtual A { B(int x) : A(x) {} };
struct C : virtual A { C(int x) : A(x) {} };
Note: A is virtual base!
Now you define D deriving from B and C :
struct D : B, C
{
//correct constructor - because A(x) i... |
4,907,401 | 4,907,735 | Qt TcpServer architecture | The question is about the architecture of a server with Qt.
For example, there is a slot ReadyRead() being called when a socket signals readyRead()
If there are several kind of requests we can
void Server::ReadyRead()
{
QString msg = readFirstWordFromAvaiableData();
switch (msg){
case "PING":
case... | If each of your commands have a fixed length of the payload, it may not be necessary to send message length.
QByteArray is a convenient wrapper around unsigned char array, and has some useful utility methods, so it's a good thing to use. You can also use QString if your protocol is text-based, though be aware that by d... |
4,907,413 | 4,907,438 | Cannot convert this pointer | I have a class Foo which looks like this
class Foo
{
public:
void set_bar(int val)
{
_bar = val;
}
protected:
int _bar;
};
which is inherited by class Baz which is declared as follows:
class Baz
: public Foo
{
public:
void set_baz(int val)
{
_baz = val;
}
protected:
... | You need to provide a non-const version of Factory::get_baz that returns a non-const reference to Baz:
class Factory
{
protected:
Baz _baz;
public:
const Baz& get_baz() const
{
return _baz;
}
Baz& get_baz()
{
return _baz;
}
};
When using a const Factory, the const version ... |
4,907,612 | 4,907,636 | Undefined reference error C++ | i accessed a static function(funA()) in class A (all function in this class is static) but getting Undefined reference error. I included header
Please help.
// H file
Class A
{
static void funA();
};
// Cpp file
void A::funA() { }
Accessed in class B
void B::funB()
{
A::funA()
}
| Have you included the right .lib file, if necessary?
|
4,907,727 | 4,928,189 | How do I compile a PHP extension with Microsoft Visual C++ 2008? | I created a PHP Hello World extension DLL with Microsoft Visual C++ 2008. I have the right php.ini (I know because when I enable and disable the gd2 extension, there is an effect), but when I load the extension it does not pop up under the Additional Modules in phpinfo().
When I try to test the function (a simple doub... | Solution from the comments...
-I found the solution forums.zend.com/viewtopic.php?f=55&t=2045
-Possible duplicate: question: stackoverflow.com/questions/3641751/
I get these warnings
c:\wamp\bin\php\php-5.3.5src\zend\zend_build.h(19) : warning C4005: 'PHP_COMPILER_ID': macro redefinition c:\wamp\bin\php\php-5.3.5src\ma... |
4,907,733 | 4,907,813 | Correct way to use enums with pass-by-value and return in functions? | I understand the question title is mightily vague, hence the body text :)
I have several enums I use for identifying file types and other stuff that needs easy differentiating. My former approach was this:
namespace my_namespace
{
namespace fileType
{
enum fileType
{
SOURCE,
... | Personally I use a very simple trick:
struct EnumName
{
enum type {
MemberOne,
MemberTwo,
...
};
};
typedef EnumName::type EnumName_t;
// Usage
EnumName_t foo = EnumName::MemberOne;
In C++0x, you can have scoped enumerators directly:
enum struct EnunName // note: struct and class equivalent here
{
... |
4,907,758 | 4,907,841 | the stack and vtable [re]location | NOTE: To understand my question, you might need to know about my project and the problem. If not, skip right to the "QUESTION" section at the bottom.
PROJECT
I'm working on a writing a C++ class that enables its parent to act like synchronous/blocking threads by having Pause() and Resume().
Here's an example of how ... | I think what you're looking for is cooperative threading. For a fast and simple implementation of it, check out libco. http://byuu.org/files/libco_v16.tar.bz2. The coswitching is implemented in raw assembly and works for x86, x86_64, PPC32 and PPC64. It also has implementation (ab)using setjmp/longjmp and posix ucontex... |
4,907,768 | 4,907,783 | Having numbers generated in for loop how to output them as if their highest value was 1 and lowest 0? | So I have a black and white image in OpenCV, currently I output each of its per pixel color values into file so I get a file of values from 1 to 255. I have lots of really small images so in one image I usually get values that have small difference. like from 25 to 100.. So I need a way to print into file not color val... | Just do a first pass, and find minimum and maximum values. Then do a second pass, and modify each value as (v - min) / (max - min) before writing to file.
|
4,907,805 | 4,907,853 | Using variables in system() function c++ |
string line;
ifstream myfile ("aaa.txt");
getline (myfile,line);
system("curl.exe -b cookie.txt -d test="+line+" http://example.com");
And It doesn't work! I also tried line.c_str(); But it didnt work either. Please help me.
| It doesn't work because you're passing a C++ string to a C function system(). c_str() can help, but you should apply it to the whole string:
system(("curl.exe -b cookie.txt -d test="+line+" http://example.com").c_str());
As noted in the comments below, passing random variables to system() can be quite dangerous, so y... |
4,907,806 | 4,907,833 | Class for calculating arbitrarily large numbers? | I was wondering if there might not be a class that would allow as much accuracy as there is memory. With overloaded operators in order to do arithmetic on it as if it was a normal number.
Ex:
BigNumber num;
num = 8;
for(int i = 0; i < 5000000; ++i)
{
num *= num;
}
Thanks
| There are plenty libraries for that, like GMP (it provides also a C++ interface) or cbignum.
You'll probably find as many libraries of this kind as you wish.
|
4,907,973 | 4,908,781 | Snapshot of a part of a file in Vim: hide comments and blank lines | How to temporary show a snapshot of a file, while hiding comments and blank line?
The purpose would be to get a catch of a C++ function (for example), in a dense page formating.
A manner to do that is to use the global command to filter out lines of comments
:g!/\/\/
but then the syntax highlighting and move controls ... | All comments can be removed from the source with the following command:
:%s/\/\*\_.\{-}\*\/\n\{,1}\|^\s*\/\/.*\n\|\s*\/\/.*//
This can then be undone with the u command, assuming no other actions are there to be undone.
Since vi regexes can be extremely cryptic, below is an explanation of each part. The entire regex i... |
4,908,107 | 4,908,162 | Is the second term in Qt's foreach evaluated only once? | If I have this code:
foreach (QListWidgetItem *ii, selectedItems()) {
urls.push_back(ii->data(Qt::ToolTip).toString());
}
Would selectedItems() be called only once?
| Yup. It will create a copy of the returned container, and use that. (See Qt foreach keyword documentation)
Related:
Since Qt foreach always copies the container, it's best used with either QT-containers (which are copy-on-write) or small STL containers.
Boost's foreach handles this better, and avoids copies unless nec... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.