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 |
|---|---|---|---|---|
679,145 | 679,529 | How to set up a Winsock UDP socket? | I want to create a Winsock UDP socket that only sends data to a client. I want the kernel to choose an available port for me. On the other hand, I want to indicate which local IP to use, since I'm running a few nics.
I've tried combing through the maze of socket options, as well as binding with the port in the socket ... | Please excuse the lack of error checking:
char pkt[...];
size_t pkt_length = ...;
sockaddr_in dest;
sockaddr_in local;
WSAData data;
WSAStartup( MAKEWORD( 2, 2 ), &data );
local.sin_family = AF_INET;
local.sin_addr.s_addr = inet_addr( <source IP address> );
local.sin_port = 0; // choose any
dest.sin_family = AF_INET;... |
679,210 | 679,339 | How can I use a dynamically sized texture array with glTexImage2D? | Currently, I'm able to load in a static sized texture which I have created. In this case it's 512 x 512.
This code is from the header:
#define TEXTURE_WIDTH 512
#define TEXTURE_HEIGHT 512
GLubyte textureArray[TEXTURE_HEIGHT][TEXTURE_WIDTH][4];
Here's the usage of glTexImage2D:
glTexImage2D(
GL_TEXTURE_2D, 0, GL_R... | You can use
int width = 1024;
int height = 1024;
GLubyte * texture = new GLubyte[4*width*height];
...
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
width, height,
0, GL_RGBA, GL_UNSIGNED_BYTE, textureArray);
delete [] texture; //remove the un-needed local copy of the texture;
However you still need to s... |
679,370 | 679,393 | DXGetErrorString newbie question | I'm new to C++ and Direct X, and I was wondering what is the proper use of DXGetErrorString and DXGetErrorDescription?
According to http://msdn.microsoft.com/en-us/library/bb173057(VS.85).aspx and http://msdn.microsoft.com/en-us/library/bb173056(VS.85).aspx, these functions return a pointer to a string. However, in all... | Most likely, the functions return a static string, so it doesn't need to be free'd.
It'd be similar to writing code like this, where you would not worry about freeing the return value:
PCWSTR GetErrorCode(int error)
{
switch (error)
{
case 1:
return L"File not found";
...
defau... |
679,520 | 679,526 | Advice on a better way to extend C++ STL container with user-defined methods | I inherited from C++ STL container and add my own methods to it. The rationale was such that to the clients, it will look act a regular list, yet has application-specific methods they can readily be called.
This works fine, but I have read numerous posts about not inheriting from STL. Can someone provide a concrete ad... | why you need extend vector in this way?
use standard <algorithm> with your functors.
e.g.
std::min_element, std::max_element
int max_a = std::max_element
(
v.begin(),
v.end(),
boost::bind(
std::less< int >(),
bind( &Item::a, _1 ),
... |
679,571 | 679,580 | When to use "new" and when not to, in C++? |
Possible Duplicate:
When should I use the new keyword in C++?
When should I use the "new" operator in C++? I'm coming from C#/Java background and instantiating objects is confusing for me.
If I've created a simple class called "Point", when I create a point should I:
Point p1 = Point(0,0);
or
Point* p1 = new Point... | You should use new when you wish an object to remain in existence until you delete it. If you do not use new then the object will be destroyed when it goes out of scope. Some examples of this are:
void foo()
{
Point p = Point(0,0);
} // p is now destroyed.
for (...)
{
Point p = Point(0,0);
} // p is destroyed afte... |
679,660 | 679,666 | How do I define a generic std::list of a custom type? | I'm getting the following error trying to define a list of "Lines":
line-clip.cpp:44: error: expected
initializer before '<' token
#include <list>
using namespace std;
class Line {
public:
Point p1;
Point p2;
Line(Point P1, Point P2)
{
p1 = P1;
p2 = P2;
}
}
// Line List
lis... | You need a semicolon after your class declaration :-).
class Line {
...
}; // put a semicolon here.
|
679,759 | 679,769 | Should C++ template be used in this case? | I have a class that my client uses to Get() a packet. The packet contains a std::vector whose type is not known until the packet is generated internally in my Interface class (in this example, it depends on the Packet::type variable).
I was wondering if template could be used for this since the Packet class is just a g... | You would want to create a base class, and keep the template Packet class that you have. Call this base class PacketBase. Your Packet class would derive from the new PacketBase class. That is to say each Packet<> type that is generated at compile time, will derive from PacketBase.
class PacketBase
{
};
// T can ei... |
679,862 | 679,900 | Defining Function Pointers | I am trying to call the internal Windows NT API function NtOpenProcess. I know calling internal APIs can be a bad idea, but for this particular tool I need the low-level access this API provides.
My problem is that to use such an internal API, I need to use Runtime Dynamic Linking, as specified in this article
To do th... | Did you include "ntdef.h" and "ntstatus.h" ?
The compiler probably cant understand NTSTATUS.
|
679,888 | 679,899 | How can I easily work with a char**? | I have a char** that I frequently need to insert into or perform a lookup. It is very tedious to realloc(), malloc() the array and insert strings.
Is there any standard way that I can add strings to or do lookups in a char**? I guess I'm looking for something like string, but using char**'s instead.
| If you're frequently inserting into this structure, you shouldn't be using a char** at all; an array isn't a suitable data structure for these kinds of operations. Consider a std::vector<string> or something similar if possible.
|
680,011 | 692,039 | Finding Strings Neighbors By Up To 2 Differing Positions | Given a seed string, I want to find its neighbors with at most differ in 2 positions. All the digits involve in generating string are only four (i.e. 0,1,2,3). This is the example for what I mean:
# In this example, 'first' column
# are neighbors with only 1 position differ.
# The rest of the columns are 2 positions di... | Would this do it? It enumerates the tree of possible strings, pruning all with >2 differences from the original.
void walk(char* s, int i, int ndiff){
char c = s[i];
if (ndiff > 2) return;
if (c == '\0'){
if (ndiff > 0) print(s);
}
else {
s[i] = '0'; walk(s, i+1, (s[i]==c ? ndiff : ndiff+1);
s[i] ... |
680,066 | 680,115 | Calling C++ dll function from C#: Of structs, strings and wchar_t arrays | Here's a simple problem I need to solve, but it makes me feel my hair turning gray as all my attempts are returning me the same error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
I have a sample app written in C++ which makes a call to the dll. Here is the re... | I believe it should work if you
Change the declaration on
convertHKID_Name to CharSet.Ansi
Remove the "ref" from the string
parameter
Pass the string num
directly to convertHKID_Name instead
of calling WideCharToMultiByte
|
680,097 | 680,114 | I've heard i++ isn't thread safe, is ++i thread-safe? | I've heard that i++ isn't a thread-safe statement since in assembly it reduces down to storing the original value as a temp somewhere, incrementing it, and then replacing it, which could be interrupted by a context switch.
However, I'm wondering about ++i. As far as I can tell, this would reduce to a single assembly in... | You've heard wrong. It may well be that "i++" is thread-safe for a specific compiler and specific processor architecture but it's not mandated in the standards at all. In fact, since multi-threading isn't part of the ISO C or C++ standards (a), you can't consider anything to be thread-safe based on what you think it wi... |
680,125 | 680,132 | Can I use a grayscale image with the OpenGL glTexImage2D function? | I have a texture which has only 1 channel as it's a grayscale image. When I pass the pixels in to glTexImage2D, it comes out red (obviously because channel 1 is red; RGB).
glTexImage2D(
GL_TEXTURE_2D, 0, GL_RGBA,
dicomImage->GetColumns(), dicomImage->GetRows(),
0, GL_RGBA, GL_UNSIGNED_BYTE, pixelArrayPtr);
... | Change it to GL_LUMINANCE. See https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glTexImage2D.xhtml
|
680,300 | 680,361 | Operator overloading with memory allocation? | The sentence below is from, The Positive Legacy of C++ and Java by Bruce Eckel, about operator overloading in C++:
C++ has both stack allocation and heap
allocation and you must overload your
operators to handle all situations and
not cause memory leaks. Difficult
indeed.
I do not understand how operator over... | I can imagine a couple possible interpretations:
First, in C++ new and delete are both actually operators; if you choose to provide custom allocation behavior for an object by overloading these operators, you must be very careful in doing so to ensure you don't introduce leaks.
Second, some types of objects require tha... |
680,489 | 680,500 | Why do we use 'this->' and not 'this.' to access members? | I was looking at a library a person has made for FaceBook in C++. The header file is this:
#ifndef __FACEBOOK_H__
#define __FACEBOOK_H__
/**
* Facebook Class
* Joel Seligstein
* Last mod: Aug 22, 2006
*
* This is the beginnings of a facebook class set and REST client. Its not documented
* yet nor nearly compl... | this is a pointer to the current object i.e., inside methods (or constructor) of class A, this is of type A *.
(Note that, if the method is tagged as const, this is of type A const *.)
Hence the use of -> (designed only for pointers) and not . (designed only for class objects A or references to class objects A&).
|
680,561 | 693,724 | Beginner questions regarding to "building a library", in Xcode on iPhone specifically | I have never been clearly understand all these linking/building/dependency business. Now, I am trying to build the FreeType library (which is in C++), into the *.a library file for the iPhone (because another library I am trying to use, openFrameworks, would depend on FreeType).
I know that to compile C++ with iPhone I... | Renaming .cpp files to .mm would mean they'll be treated as Objective-C++ code rather than C++ code. I don't think that'd be a good idea, even if it should still work. Besides, FreeType is written in C, not C++.
Google for "compiler linker" and you'll find quite a few documents on how they work. That should help for do... |
680,672 | 680,693 | How to delay the initialisation of a member in a C++ base class until the ctor of derived class is executed? | Here's the scenario:
I want define a base class that allocate some buffer once for all derived classes, while the size of the buffer varies among different derived classes. I could achieve it in this way:
class base
{
public:
base():size(), p_array(0){}
private:
size_t size;
boost::shared_array<unsigned ... | sorry but why do you have 2 arrays (and 2 sizes)? Now if you create a derived class you have a 2 times a p_array. I think the compiler should give an error on this.
Don't you want this?
class base
{
public:
base():size(), p_array(0){}
base(size_t array_size):size(array_size)
{
p_array.reset(new... |
680,715 | 680,741 | Silverlight with C++.Net | Can you use C++.Net for writting a Silverlight application? Not use C# or VB.Net as the backend language but C++.Net
| Check this. A google search would have answered your query.
Update: I was wrong. Apologies for that. Mark has answered it correctly.
Mark : You can use any language so long as it compiles to pure managed code. For example there are Silverlight applications using IronPython, IronRuby. The only restriction is you can't ... |
680,721 | 681,508 | msvcp80d.dll not found while using TBB | I am using Intel TBB C++ for multithreading an application on visual studio 2008. When I run the executable I get a dialog saying "MSVCP80D.dll" was not found. There is so much on the net about this that it confuses me.
Please help.
EDIT: Based on answers, finally I was able to fix the "dll missing" problem. I had gi... | You can find them online at various places. Just scan it for a virus and put it in your program's path and everything should work fine. You may need more than one of the debug dlls, you can use depends32.exe to see what you are missing.
|
680,738 | 680,798 | Law of demeter or return the whole vector | Which one is better:
public:
const vector<int> & GetPointsVector();
private:
vector<int> PointsVector;
Or:
public:
int GetCurrentPoint();
void MoveToFirstPoint();
void MoveToNextPoint();
bool IsAtLastPoint();
size_t GetNumberOfPoints();
private:
vector<int> PointsVector;
| There is no right answer. The answer will vary with context, of which, at present we have very little.
It depends on the clients of your class. In most situations you would not want a casual inspector to change the object's state, so it is better to a certain degree to return a reference to a const object. However, in ... |
681,142 | 681,150 | cpp iterator problem | template<class T>
class mStack
{
private:
vector<T> a;
vector<T>::iterator top;
public:
void push(T);
T pop();
mStack();
void printStack();
};
The code with above class is not getting compiled... why? What is the problem? The compiler says "expected ; above to... | You need a typename:
typename vector<T>::iterator top;
This reassures the compiler thar vector<T> really is a type. For a discussion of this and other template gotchas, see the C++ FAQ.
|
681,148 | 683,318 | How to print a Qt dialog or window? | How do I get Qt to print a complete dialog or window?
I could dump the window contents with an external program like xwd and print that, but I would prefer to do it all with Qt.
| While you can use grabWidget to get the pixmap representation of the dialog, essentially you will be printing the pixels of the pixmap, i.e. the dialog is rasterized a the screen resolution and then scaled to the printer resolution. This may or may not result in some artifacts.
Another way to do it is by using QWidget:... |
681,192 | 681,202 | How to get Vector of Complex numbers from two vectors (real & imag) | I have two vectors of floats and i want them to become one vector of Complex numbers. I'm stuck. I don't mind using iterators, but i am sure it'd be rediscovering the wheel i'm not informed about. Is my code leading me in the right direction?
typedef std::vector<float> CVFloat;
CVFloat vA, vB;
//fil vectors
typedef std... | Here you are creating a "complex" object whose real and imaginary parts are vectors of floats.
Maybe what you actually want to do is creating a vector of complex objects whose real and imaginary parts are floats?
EDIT: myComplexVector is not a vector, is a complex. That's why a const_iterator for it is not defined.
|
681,200 | 681,220 | How to use 2 C libs that export the same function names | Duplicate of the following question: C function conflict
Hi,
in my current project I have to use some kind of interface lib. The function names are given by this interface, what this functions do is developers choice. As far as I can tell a project shall use this functions and when it comes to compiling you choose the... | Namespaces in C solved using library names prefixes like:
libfoo --> foo_function1
libbar --> bar_function1
These prefixes are actual namespaces. so if you write libbar
int bar_function1(int a) {
function1(a);
}
This is the way to solve problems.
C has namespaces --- they just called prefixes ;)
Another option is... |
681,221 | 682,694 | Writing files to USB stick causes file corruption/lockup on surprise removal | I'm writing a background application to copy files in a loop to a USB stick with the "Optimize for quick removal" policy set. However, if the stick is removed part way through this process (specifically in the WriteFile() call below, which returns ERROR FILE NOT FOUND) the application hangs, the drive is then permanent... |
Its almost as if CloseHandle() is blocking indefinitely in the driver somewhere because
the stick is no longer there?
Sounds reasonable. CloseHandle() will ultimately emit a file system IRP and you're not using non-blocking I/O, so that IRP will be synchronous, but it looks like where the actual file system has a... |
681,243 | 681,259 | In C++, how can I avoid #including a header file when I need to use an enumeration? | In my C++ header files I try to use forward declarations (class MyClass;) instead of #including the class header, as recommended in many C++ coding standards (the Google C++ Style Guide is one).
Unfortunately, when I introduce enumerations, I can't do the forward declaration any more. Like this:
//// myclass1.hpp ////
... | You cannot forward declare enum values - and your workaround is a step down the path to complete madness.
Are you experiencing any major compilation slowdowns caused by #including headers? If not, just #include them. Use of forward declarations is not "best practice" it is a hack.
|
681,518 | 681,536 | C++ enum not properly recognized by compiler | Can anyone explain why the following code does not compile (on g++ (GCC) 3.2.3 20030502 (Red Hat Linux 3.2.3-49))?
struct X {
public:
enum State { A, B, C };
X(State s) {}
};
int main()
{
X(X::A);
}
The message I get is:
jjj.cpp: In function 'int main()':
jjj.cpp:10: 'X X::A' is not a static member of 'stru... | X(X::A);
is being seen a s a function declaration. If you really want this code, use:
(X)(X::A);
|
681,725 | 681,736 | What do I get from front() of empty std container? | If front() returns a reference and the container is empty what do I get, an undefined reference? Does it mean I need to check empty() before each front()?
| You get undefined behaviour - you need to check that the container contains something using empty() (which checks if the container is empty) before calling front().
|
681,746 | 681,778 | 2D matrix and overloading operator() / ugly syntax | I'm using a 2D matrix in one of my projects. It's something like it is suggested at C++ FAQ Lite.
The neat thing is that you can use it like this:
int main()
{
Matrix m(10,10);
m(5,8) = 106.15;
std::cout << m(5,8);
...
}
Now, I have a graph composed of vertices and each vertex has a public (just for simplicity... |
Consider using references instead of pointers (provided, it can't be null and you can initialize in the constructor).
Consider making a getter or an instance of a matrix wrapper class for a vertex that returns a reference to 2D matrix (provided, it can't be null).
sampleVertex.some2DTable()(0,0) = 0;
sampleVertex.some... |
681,772 | 681,799 | Equivalent of IllegalArgumentException of Java in C++ | In Java if an input argument to a method is invalid, we can throw an IllegalArgumentException (which is of type RuntimeException). In C++, there is no notion of checked and unchecked exceptions. Is there a similar exception in standard C++ which can be used to indicate a runtime exception? Or is there a common style no... | Unlike Java, C++ does not have a "standard framework" but only a small (and optional) standard library. Moreover, there are different opinions under C++ programmers whether to use exceptions at all.
Therefore you will find different recommendations by different people: Some like to use exception types from the standard... |
681,943 | 681,997 | how can I get a std::set of keys to a std::map | I was writing an algorithm this morning and I ran into a curious situation. I have two std::maps. I want to perform a set intersection on the sets of the keys of each (to find which keys are common to both maps). At some point in the future, I think it's likely I'll also want to perform set subtraction here as well.... | You can use the versatile boost::transform_iterator to return an iterator that returns only the keys (and not the values). See How to retrieve all keys (or values) from a std::map and put them into a vector?
|
682,304 | 699,149 | What am I missing from my environment variables for my linker to fail with LNK1181? | I have a Qt project which I have had a debug console displayed whilst I am developing, I am about to ship the product to I removed the qmake console command:
CONFIG += console
However when I do that I get the following error:
link /LIBPATH:"c:\Qt\4.5.0\lib" /NOLOGO /INCREMENTAL:NO /LTCG /MANIFEST /MANIFESTFILE:"./_obj/... | It seems that the command line is just underquoted:
"/MANIFESTDEPENDENCY:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' publicKeyToken='6595b64144ccf1df' language='*' processorArchitecture='*'"
On the second line, the quotes are gone and the linker treats each word as an object to link. You sh... |
682,432 | 682,489 | VC++ Resource Files and Lengthy String Resources | In our app we have resource strings that are apparently too long for the compiler. The build breaks stating the "line length is too long." I have found little information about the topic of lengthy string resources and even had a difficult time finding what the limit on such a resource string is. Eventually I found th... | I would have a look at RCDATA resources. I used it to store large text files in my application.
Edit: Here is my MFC code, it should be able to give you some pointers.
CString CWSApplication::LoadTextResource(UINT nID)
{
HRSRC hResInfo;
HGLOBAL hResData;
hResInfo = ::FindResource(AfxGetResourceHandle(),
... |
682,434 | 682,521 | What's the difference between these two classes? | Below, I'm not declaring my_ints as a pointer. I don't know where the memory will be allocated. Please educate me here!
#include <iostream>
#include <vector>
class FieldStorage
{
private:
std::vector<int> my_ints;
public:
FieldStorage()
{
my_ints.push_back(1);
my_ints.push_back(2);
}
... | In terms of memory management, these two classes are virtually identical. Several other responders have suggested that there is a difference between the two in that one is allocating storage on the stack and other on the heap, but that's not necessarily true, and even in the cases where it is true, it's terribly misle... |
682,444 | 682,473 | How can you find out the maximum size of the memory stack for a C++ program on linux? (gnu compiler) | I am curious about how to find out what the maximum stack size is for a particular compiler/os combo. I am using Ubuntu/GNU compiler. A few questions I have in addition are:
Who controls the default maximum stack size; OS or compiler?
Is the default maximum scaled according to total memory? (ie a machine with 2gb memo... |
Who controls the default maximum stack size; OS or compiler?
The compiler typically. The OS/hardware does limit it to a certain extent. Default is 8MB on linux IIRC. Think of ulimit -s on Linux (to change stack sizes).
Is the default maximum scaled according to total memory? (ie a machine with 2gb memory would have ... |
682,658 | 682,753 | Negative Speedup on Multithreading my Program | On my laptop with Intel Pentium dual-core processor T2370 (Acer Extensa) I ran a simple multithreading speedup test. I am using Linux. The code is pasted below. While I was expecting a speedup of 2-3 times, I was surprised to see a slowdown by a factor of 2. I tried the same with gcc optimization levels -O0 ... -O3, bu... | The times you are reporting are measured using the clock function:
The clock() function returns an approximation of processor time used by the program.
$ time bin/amit_kumar_threads.cpp
6.62seconds
serial: 2.7seconds
real 0m5.247s
user 0m9.025s
sys 0m0.304s
The real time will be less for multiprocessor tasks... |
682,859 | 682,946 | Restrict functionality to a certain computer | I have a program that is using a configuration file.
I would like to tie the configuration file to the PC, so copying the file on another PC with the same configuration won't work.
I know that Windows Activation Mecanism is monitoring hardware to detect changes and that it can tolerates some minor changes to the hardwa... | Microsoft Software Licensing and Protection Services has functionality to bind a license to hardware. It might be worth looking into. Here's a blog posting that might be of interest to you as well.
|
683,059 | 683,085 | How to validate LPVOID to <Bad Ptr> | I'm working with C++ unmanaged, the problem that I have happens when I call a method that returns an LPVOID.
LPVOID MyMethod(...);
The problem is that this method sometimes returns a Bad Ptr and I want to know if there is a way of detecting this, if the value returned is a Bad Ptr.
I have tried asking if it is NULL wi... | No, there is no easy way to determine if a pointer is bad.
Windows does have IsBadReadPtr, IsBadWritePtr. These functions are inherently flawed - they only determine if a function is readable or writable in your address space at the moment of the call. They can also be the cause of security issues and should never be... |
683,180 | 683,199 | Is this extern harmless? | main.h
extern int array[100];
main.c
#include "main.h"
int array[100] = {0};
int main(void)
{
/* do_stuff_with_array */
}
In the main.c module, the array is defined, and declared. Does the act of also having the extern statement included in the module, cause any problems?
I have always visualized the exter... | The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, ... |
683,544 | 684,913 | AMF0 parser in ObjectiveC | I am writing an application which connects to an FLV stream and parse data to extract SCRIPTDATAOBJECT.
I successfuly get content of a DATASCRIPTOBJECT and am trying to parse AMF0 data to get some metadata, do you know sample code of AMF0 parsing ?
Thanks a lot.
Thierry
| Licensed under MIT style: Objective-C implementation of the Flash Remoting format (AMF0/AMF3) for servers and clients
|
684,112 | 684,130 | The precision of the long double output is not correct. What might be wrong? | I have a long double constant that I am setting either as const or not-const. It is longer (40 digits) than the precision of a long double on my test workstation (19 digits).
When I print it out, it no longer is displayed at 19 digits of precision, but at 16.
Here is the code I am testing:
#include <iostream>
#include... | I get this output:
19
const via cout: 0.6931471805599453094
non-const via cout: 0.6931471805599453094
const via printf: 0.6931471805599453094
non-const via printf: 0.6931471805599453094
But i'm using long double literals instead of double literals:
const long double constLog2 = 0.69314718055994530941723212145817656807... |
684,133 | 684,181 | Passing C# data type parameters to dll written in C++? | Still working on a problem that started from here
Calling C++ dll function from C#: Of structs, strings and wchar_t arrays., but with a different approach.
Following the example Calling Managed Code from Unmanaged Code and vice-versa I wrote a managed wrapper in C++ to access the unmanages class in the unmanaged C++ dl... | One way to convert most C data types is to use the PInvoke Interop Assitant. It will create proper C# / VB.Net types for most C structures. Here is the output for RECO_DATA
[System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential, CharSet=System.Runtime.InteropService... |
684,191 | 684,199 | Howto Construct Char Arrays | I have the following code that tries to enumerate
strings.
#include <string>
#include <iostream>
using namespace std;
string base = "000";
char values[] = {'0', '1', '2', '3' }; // Error Here
for (int i = 0; i < base.length(); ++i)
{
for (int j = 0; j < countof(values); ++j)
{
if (base[i] != values[j])
... | The error is actually in the following line, at the for loop: your code needs to be contained in a function of some sort, most likely int main(void)
|
684,449 | 684,483 | Best practices for a C++ portable opensource application | I am starting an open source cross platform project in C++. My development environment is Linux. There may be other developers who develop from different platforms as well. So I need some help in getting started with the configuration and development environment setup, so that all developers from multiple platforms can... | The most important thing for your project to catch up is portability. It should be easy to build & run for everybody.
GCC (g++) is indeed the compiler of choice. It comes from the opensource world and is therefore most widely adopted by it.
However, a simple Makefile won't cut it. Generating it using CodeBlocks or any ... |
684,475 | 684,527 | C++ how to copy a map to a vector | What's the best way in C++ to copy a pair from a map to vector? I'm doing this so I can subsequently sort the vector.
| This should do what you want:
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
bool cmp(const pair<int, int> &p1, const pair<int, int> &p2)
{
return p1.second < p2.second;
}
int main()
{
map<int, int> m;
for(int i = 0; i < 10; ++i)
... |
684,623 | 684,636 | Howto Pass Filehandle to a Function for Output Streaming | I have the following template function which prints to cout:
template <typename T> void prn_vec(const std::vector < T >&arg, string sep="")
{
for (unsigned n = 0; n < arg.size(); n++) {
cout << arg[n] << sep;
}
return;
}
// Usage:
//prn_vec<int>(myVec,"\t");... | template <typename T>
ostream& prn_vec(ostream& o, const std::vector < T >&arg, string sep="")
{
for (unsigned n = 0; n < arg.size(); n++) {
o << arg[n] << sep;
}
return o;
}
int main () {
vector <int> MyVec;
// ...
ofstream myfile;
// ...
prn_vec(myfile, MyVec, "\t");
myfile... |
684,625 | 684,859 | "Already listening" when invoking an RPC call | I use Microsoft RPC for interprocess communications. I have an interface with a set of methods accepting a byte pipe as an "in" parameter (IDL description):
[
uuid(ActualGuidHere),
version(1.0),
pointer_default(unique)
]
interface IMyInterface
{
//other irrelevant methods here
error_status_t rpcD... | The documentation seems quite minimal - I don't think there is a huge user community for direct use of the RPC APIs - but my guess is that in order to set up the pipe parameter, it is necessary for RPC to internally call RpcServerListen. Only one call to that API is able to block at a time.
The fact that you see the pr... |
684,669 | 684,680 | Why does operator< need to be overloaded when implementing class-based priority queues in c++? | note, I am not asking for answers. I simply am curious regarding why things work
I need to implement a priority queue for a printer simulator for a class assignment. After looking at examples on the internet, I noticed that operator< was being overloaded in order to arrange the priority queue correctly.
code in quest... | STL containers use operator< by default to order the contents, for those containers that order the contents.
You can override this by passing in a comparison functor to the constructor of the container, which allows you to decouple the sorting/ordering from the container object.
Operator> could have been chosen, but on... |
684,684 | 684,720 | Normalize file path with WinAPI |
Possible Duplicate:
Best way to determine if two path reference to same file in C/C++
Given two file path strings with potentially different casing and slashes ('\' vs '/'), is there a quick way (that does not involve writing my own function) to normalize both paths to the same form, or at least to test them for equ... | Depending on whether the paths could be relative, or contain "..", or junction points, or UNC paths this may be more difficult than you think. The best way might be to use the GetFileInformationByHandle() function as in this answer.
Edit: I agree with the comment by RBerteig that this may become hard to impossible to d... |
684,715 | 684,736 | What does it mean when you get a compile error "looks like a function definition" for a class declaration? | I recently encountered this problem. I found many instances of people asking the question—here, for example—but no concrete answers.
Here's the sample code hoisted from that link:
class AFX_BASE_APPLICATION_APP_CLASS CFileExtension
{
public:
CFileExtension ();
virtual ~CFileExtension ();
};
The error... | You've almost certainly missed the header which defines AFX_BASE_APPLICATION_APP_CLASS. In that case, it would be passed through unaltered and VC++ would assume that CFileExtension was a function that returned class AFX_BASE_APPLICATION_APP_CLASS.
And, since it thinks it's a function, it also thinks it needs parenthese... |
684,763 | 684,778 | How to Write Strings Into Binary File | With this code I tried to print the string "foo" 10 times
in binary format. But why doesn't the function to do it work?
#include <iostream>
#include <fstream>
using namespace std;
template <typename T> void WriteStr2BinFh (string St, ostream &fn) {
for (unsigned i = 0; i < St.size(); i++) {
char CStr = S... | There is so much wrong here, I'm just going to list everything I see:
Your for loop condition should be i < 10.
Why are you using a template but not the templatized parameter T?
You're calling the method front() on CStr, but CStr is a char, not a string, so I don't even know how that compiles.
Assuming CStr was a strin... |
684,931 | 684,969 | Content of Binary Output File Created With Output Stream | This code compiles and does execute. It simply print the content
into a binary format. However the output differs from what I expected, namely:
Output file size should be much smaller that those created with std::cout.
The content of output file should be compressed, hence when we open it in editor,
we should not be ... | You must write data in binary format (not text):
void WriteStr2BinFh(const string& St, ostream &fn)
{
char *p = 0;
long l = strtol(St.c_str(), &p);
fn << l;
}
You must be aware that types like long have some maximum values, so you will probably have to split your string into n pieces and save as n longs.
|
685,439 | 685,727 | "Multiple definition of" C++ compiler error | I can't seem to get rid of these seemingly random compiles errors in one of my classes.
I get about 4 errors such as:
multiple definition of `draw_line(float, float, float, float)'
and
multiple definition of `near_far_clip(float, float, float*, float*, float*, float*, float*, float*)'
that are flagged in the middle o... | Why do you #include lines.cpp in ThreeD.cpp? This is very unusual.
Your makefile wants lines.o, so you're going to compile lines.cpp. Anything defined in lines.cpp will be in lines.o and also in ThreeD.o.
There is an intriguing comment in lines.cpp:
Don't forget to put declarations in your .h files.
I think the ins... |
685,601 | 685,616 | About C/C++ stack allocation | While studying C++ (and C) I had some particular doubts regarding the working of stack allocation, that I can't find a solution to:
Does stack allocation call malloc/free functions implicitly? If not; how does it assure there is no conflict between stack allocation and heap allocation?
If yes; does stack allocation in... | Stack allocation doesn't use anything like malloc/free. It uses a piece of memory called program stack which is just a contiguous segment of memory.
There's a special register that stores the top of the stack. When a new object is created on stack the top is raised thus increasing the stack, when an object is deallocat... |
685,907 | 686,271 | How do I do floating point rounding with a bias (always round up or down)? | I want to round floats with a bias, either always down or always up. There is a specific point in the code where I need this, the rest of the program should round to the nearest value as usual.
For example, I want to round to the nearest multiple of 1/10. The closest floating point number to 7/10 is approximately 0.6... | I think the best way to achieve this is to rely on the fact that according to the IEEE 754 floating point standard, the integer representation of floating point bits are lexicographically ordered as a 2-complement integer.
I.e. you could simply add one ulp (units in the last place) to get the next floating point repre... |
685,934 | 685,947 | Does C# clean up C++ allocated memory? | I have a hypothetical COM object with the following signature
void MemAlloc(ref double[] test, int membercount)
where the memory is allocated in C++ using new/malloc. Once this is in C#, using the RCW, how do I ensure that the memory is freed correctly? I would think it would be difficult for .NET to free, considering... | I believe you should use CoTaskMemAlloc() for memory that you want to explicitly free from the managed side. The CLR will take care of freeing the memory once it's no longer reachable. If you want to free it explicitly you can use the managed Marshal.CoTaskFree() routine.
In general the interop marshaler and CLR abid... |
685,951 | 685,981 | How can I check if a client disconnected through Winsock in C++? | How can I check if a client disconnected through Winsock in C++?
| Beej's Network Programming Guide
if you call recv in blocking mode and it returns with 0 bytes read, the socket has disconnected, else it wait for bytes to be received.
Look in this FAQ 2.12
example from select on this page.
int nRet;
if(( nRet = select( 0, &fdread, NULL, NULL, NULL )) == SOCKET_ERROR )
{
// Erro... |
686,131 | 686,144 | Does C++ have a sequential search function? | I have a small unsorted array and I'd like to find the index of a particular value. Does C++ have a built-in sequential search function for this, or do you just write the loop yourself each time it comes up?
I'm specifically using a C-style array like:
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
... | std::find() should work:
#include <stdio.h>
#include <algorithm>
#include <string>
using std::string;
std::string arr[5] = { "EVEN", "ODD", "NONE", "MARK", "SPACE" };
int main() {
string* pArrEnd = arr + sizeof( arr)/sizeof(arr[0]);
string* pFound = std::find( arr, pArrEnd, "MARK");
if (pFound == pAr... |
686,353 | 686,373 | Random float number generation | How do I generate random floats in C++?
I thought I could take the integer rand and divide it by something, would that be adequate enough?
| rand() can be used to generate pseudo-random numbers in C++. In combination with RAND_MAX and a little math, you can generate random numbers in any arbitrary interval you choose. This is sufficient for learning purposes and toy programs. If you need truly random numbers with normal distribution, you'll need to emplo... |
686,378 | 691,009 | C++ Native Way to Pack and Unpack String | Following my earlier question. Is there a way to write a string in a compressed/bit version using C++ native idiom. I am thinking something like Perl's native pack and unpack.
| Based on reading your previous question, I think you mean to say that you want a binary encoded output, rather than a "compressed" output. Generally, "compressed" is used to refer specifically to data that has been reduced in size through the application of an algorithm such as LZW encoding. In your case, you may fin... |
686,452 | 687,904 | Create WCF service for unmanaged C++ clients | I need to get unmanaged Windows C++ clients to talk to a WCF service. C++ clients could be running on Win2000 and later. I have a control over both WCF service and which C++ API is being used. Since it's for a proprietary application, it is preferable to use Microsoft stuff where possible, definitely not GNU licensed A... | For those who are interested, I found one semi-working ATL Server solution. Following is the host code, notice it is using BasicHttpBinding, it's the only one which works with ATL Server:
var svc = new Service1();
Uri uri = new Uri("http://localhost:8200/Service1");
ServiceHost host = new Servi... |
686,470 | 686,489 | Why is my return type meaningless? | I am trying to use a return type of const MyClass * const. However, I get a warning:
Warning: #815-D: type qualifier on return type is meaningless.
Is this not a valid type? I want a pointer than cannot be changed, and I want the thing it points to to not be changed either.
| The pointer itself has value type, so it doesn't make sense to make it const. What the caller function does with the returned value can't be restricted by the called function. This is akin to trying to define something like:
const int getInt();
getInt(), in this case, just returns an int value (not a reference). It go... |
687,049 | 687,074 | Is it possible to provide exceptions in C++ virtual(pure) class member? | If so how?
I know how to provide exception specifications for members such as
class SOMEClass
{
public:
void method(void) throw (SOMEException);
virtual void pure_method(void) = 0;
};
So that the method throws only SOMEException. If I want to ensure that sub-classes of SOMEClass throw SOMEException for pure... | Yes, a pure virtual member can have an exception specification.
I recommend you to read this: http://www.gotw.ca/publications/mill22.htm before getting too much involved in exception specifications, though.
|
687,135 | 687,144 | What is the origin of the throw/catch exception naming? | Was the creator of this construct a baseball fan?
| See Stroustrup's book "The Design & Evolution of C++" - basically, "raise" was already taken.
|
687,448 | 687,455 | C++ Undefined Reference (Even with Include) | I cannot get this simple piece of code to compile without including the TestClass.cpp file explicitly in my main.cpp file. What am I doing wrong? Thanks in advance!
Here is the code:
TestClass.h
#ifndef TESTCLASS_H_
#define TESTCLASS_H_
class TestClass
{
public:
static int foo();
};
#endif
TestClass.cp... | Include TestClass.cpp into the commandline, so the linker can find the function definition:
g++ main.cpp TestClass.cpp -o main.app
Alternatively, compile each to their own object file, then tell the compiler to link them together (it will forward them to the linker)
g++ -c main.cpp -o main.o
g++ -c TestClass.cpp -o Te... |
687,718 | 690,061 | How Do You Call an MSSQL System Function From ADO/C++? | ...specifically, the fn_listextendedproperty system function in MSSQL 2005.
I have added an Extended Property to my database object, named 'schemaVersion'. In my MSVC application, using ADO, I need to determine if that Extended Property exists and, if it does, return the string value out of it.
Here is the T-SQL code ... | I still have not figured out how to do this directly. To get on with my life, I wrote a stored procedure which called the function:
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[mh_getSchemaVersion]
@schemaVer VARCHAR(256) OUTPUT
AS
select @schemaVer = CAST( (select value from fn_listexten... |
687,789 | 687,805 | C++ const std::map reference fails to compile | Is there a reason why passing a reference to a std::map as const causes the [] operator to break? I get this compiler error (gcc 4.2) when I use const:
error: no match for ‘operator[]’ in
‘map[name]’
Here's the function prototype:
void func(const char ch, std::string &str, const std::map<std::string, std::string> &... | Yes you can't use operator[]. Use find, but note it returns const_iterator instead of iterator:
std::map<std::string, std::string>::const_iterator it;
it = map.find(name);
if(it != map.end()) {
std::string const& data = it->second;
// ...
}
It's like with pointers. You can't assign int const* to int*. Likewise... |
687,813 | 687,831 | Are C++ int operations atomic on the mips architecture | I wonder if I could read or write shared int value without locking on mips cpu (especially Amazon or Danube). What I mean is if such a read or write are atomic (other thread can't interrupt them). To be clear - I don't want to prevent the race between threads, but I care if int value itself is not corrupted.
Assuming t... | Use gcc's builtin atomic operations and you'll get warnings if they're not supported:
http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Atomic-Builtins.html
It looks like combinations of addition/subtraction and testing (at least) are possible on the hardware:
http://rswiki.csie.org/lxr/http/source/include/asm-mips/atomic.h
|
688,039 | 688,068 | How can I build a std::vector<std::string> and then sort them? | I have a bunch of strings that I need to sort. I think a std::vector would be the easiest way to do this. However, I've never used vectors before and so would like some help.
I just need to sort them alphanumerically, nothing special. Indeed, the string::compare function would work.
After that, how can I iterate throug... | You can just do
std::sort(data.begin(), data.end());
And it will sort your strings. Then go through them checking whether they are in order
if(names.empty())
return true; // empty vector sorted correctly
for(std::vector<std::string>::iterator i=names.begin(), j=i+1;
j != names.end();
++i, ++j)
... |
688,053 | 688,091 | What to put in precompiled header? (MSVC) | What are the best candidates for a precompiled header file? Can I put STL and Boost headers there, even though they have templates? And will that reduce compile times?
Also, what are the best IDE settings to reduce compile times?
| The quick answer: the STL and Boost headers do indeed belong in the precompiled header file, even though these header files define template classes.
When generating a precompiled header file, a compiler parses the header text (a significant task!), and converts it into a binary format that is optimised for the compiler... |
688,386 | 688,428 | IS C++ converted into MSIL? | I have been a long time C# and .Net developer, and have been playing with the idea of learning c++.
One of the primary reasons I have been thinking about this, is how much faster C++ can be over apps using the .Net framework. But am I right in assuming that if I write a C++ app in Visual Studio, and/or reference .Net ... | Well it's a bit more complicated than that.
There are actually two totally different versions of .NET-supporting C++.
The old one, Managed Extensions for C++, was the only option available in Visual C++ 2002/2003. It's available in newer compilers under the option /clr:oldSyntax. It's kinda clumsy as it tries hard to ... |
688,447 | 688,477 | Best practices for defining your own exception classes? | I have some special exception cases that I want to throw and catch, so I want to define my own exception classes.
What are the best practices for that? Should I inherit from std::exception or std::runtime_error?
| Yes, it's good practice to inherit from std::runtime_error or the other standard exception classes like std::logic_error, std::invalid_argument and so on, depending on which kind of exception it is.
If all the exceptions inherit some way from std::exception it's easy to catch all common errors by a catch(const std::exc... |
688,550 | 690,710 | Windows Named-Pipe ACL under IIS | I am trying to connect a CGI process to my windows service with a named pipe.
My code runs fine using another server on my development machine, but on IIS there are security issues when I call CreateFile() in the CGI process.
The Windows service is the Named Pipe Server and so the CGI process is trying to connect to th... | Since the pipe is created by the server, only the server needs to specify the ACL, the client uses NULL for the ACL.
Inheritance only applies if the named pipe is created in one process and that processes creates a new process in which you want that spawned process to have direct access to the handle (it doesn't reope... |
688,760 | 696,026 | How to create a UTF-8 string literal in Visual C++ 2008 | In VC++ 2003, I could just save the source file as UTF-8 and all strings were used as is. In other words, the following code would print the strings as is to the console. If the source file was saved as UTF-8 then the output would be UTF-8.
printf("Chinese (Traditional)");
printf("中国語 (繁体)");
printf("중국어 (번체)");
printf... | Update:
I've decided that there is no guaranteed way to do this. The solution that I present below works for English version VC2003, but fails when compiling with Japanese version VC2003 (or perhaps it is Japanese OS). In any case, it cannot be depended on to work. Note that even declaring everything as L"" strings did... |
688,802 | 688,862 | Can C++ method names be qualified by the class name, in the header? | Simple question, is this valid C++:
class Foo
{
void Foo::doSomething();
};
The point of the question: is that repeated use of the class name and double colon before the method name valid inside the class declaration?
I'm having issues compiling code that does this using g++ 4.2.3. I would love to see a reference ... | I took a look at the standard, section 9.2 would be the relevant portion. I'm not that great with BNF but I didn't see anything in the BNF for class members that would indicate this was allowed. The identifier is even named "unqualified-id" in the BNF.
G++ changed the behavior in version 4.1, and apparently a lot of ... |
688,945 | 688,948 | How do I make g++ ignore -mregparm for certain code? | Some background:
As a personal project, I've been developing a kernel in c++. Things are going well, in fact I have very good support for much of c++ available in kernel land (I've implemented nearly the entire libc and libstdc++).
One of the more difficult and compiler specific things is RTTI and exception support. Fo... | You are probably best going with options 1 or 2 (1 is clearly easier). To my knowledge g++ has no specific switch for option 3.
|
689,677 | 689,716 | Why cast unused return values to void? | int fn();
void whatever()
{
(void) fn();
}
Is there any reason for casting an unused return value to void, or am I right in thinking it's a complete waste of time?
| David's answer pretty much covers the motivation for this, to explicitly show other "developers" that you know this function returns but you're explicitly ignoring it.
This is a way to ensure that where necessary error codes are always handled.
I think for C++ this is probably the only place that I prefer to use C-styl... |
689,959 | 690,482 | simple cross-platform c++ GUI console -- how to? | I'm writing a game and I'm wound up in needing a console for simple text input; filenames and simple values.
Using SDL, my console looks the following at it's simplest:
class Console
{
public:
typedef std::list<String> InputList;
enum Result
{
NOTHING = 0,
ENTERED,
ESCAPED
};
static const St... | One suggestion I would offer is to use if statements instead of a switch in this case:
if(lastKey == SDLK_RETURN)
lastResult = ENTERED;
else if(lastKey == SDLK_ESCAPE)
lastResult = ESCAPED;
else if(lastKey >= SDLK_SPACE && lastKey <= SDLK_z)
{
input += static_cast<char> (lastKey);
lastResult = NOTHING;
... |
690,176 | 690,252 | C/C++: Optimization of pointers to string constants | Have a look at this code:
#include <iostream>
using namespace std;
int main()
{
const char* str0 = "Watchmen";
const char* str1 = "Watchmen";
char* str2 = "Watchmen";
char* str3 = "Watchmen";
cerr << static_cast<void*>( const_cast<char*>( str0 ) ) << endl;
cerr << static_cast<void*>( const_cas... | It's an extremely easy optimization, probably so much so that most compiler writers don't even consider it much of an optimization at all. Setting the optimization flag to the lowest level doesn't mean "Be completely naive," after all.
Compilers will vary in how aggressive they are at merging duplicate string literals.... |
690,356 | 690,368 | Re-assinging an "auto_ptr" and Managing Memory | I've a situation like this:
class MyClass
{
private:
std::auto_ptr<MyOtherClass> obj;
public:
MyClass()
{
obj = auto_ptr<MyOtherClass>(new MyOtherClass());
}
void reassignMyOtherClass()
{
// ... do funny stuff
MyOtherClass new_other_class = new MyOtherClass();
// Here, I want to:
// 1... | Yes it will.
You can use
obj.reset( new MyOtherClass() );
And I'd better use such constructor
MyClass():
obj( new MyOtherClass() )
{
}
|
690,382 | 690,526 | How can I put an array inside a struct in C#? | C++ code:
struct tPacket
{
WORD word1;
WORD word2;
BYTE byte1;
BYTE byte2;
BYTE array123[8];
}
static char data[8192] = {0};
...
some code to fill up the array
...
tPacket * packet = (tPacket *)data;
We can't do that as easy in C#.
Please note there is an array in the C++ structure.
Alternatively,... | I think what you are looking for (if you are using a similar structure definition like JaredPar posted) is something like this:
tPacket t = new tPacket();
byte[] buffer = new byte[Marshal.SizeOf(typeof(tPacket))];
socket.Receive(buffer, 0, buffer.length, 0);
GCHandle pin = GCHandle.Alloc(buffer, GCHandleType.Pinned);
... |
690,579 | 690,597 | What is the scope of variables declared in a class constructor? | I was curious, what is the scope of variables declared inside a class constructor which are not data members of that class?
For example, if a constructor needs an iterating int i, will this variable be destroyed after the constructor finishes, or is it then global for the program?
| In this sense a constructor is like any other function - any variable declared inside has usual scope limitations and they all surely go out of scope and get destroyed once constructor is finished.
|
691,014 | 691,034 | How to allocate array in base constructor with size based on derived class? | I have a hierarchy of classes. The base class uses some tuning parameters that are loadable from file (and reloadable during runtime). Each derived class may add some additional parameters. I am looking for a way to allocate a correctly sized parameters array in the base constructor, so that I don't have to dealloc... | Why not pass the required array size as a parameter in the constructor of the base class?
(The reason the virtual function doesn't call the derived class is because that is how C++ virtual functions work; conceptually, until the derived class constructor completes, the object's type is still the base class.)
|
691,079 | 691,100 | Is there a standard #include convention for C++? | This is a rather basic question, but it's one that's bugged me for awhile.
My project has a bunch of .cpp (Implementation) and .hpp (Definition) files.
I find that as I add additional classes and more class inter-dependencies, I have to #include other header files. After a week or two, I end up with #include directive... | I always use the principle of least coupling. I only include a file if the current file actually needs it; if I can get away with a forward declaration instead of a full definition, I'll use that instead. My .cpp files always have a pile of #includes at the top.
Bar.h:
class Foo;
class Bar
{
Foo * m_foo;
};
Bar.c... |
691,194 | 691,202 | Why is my implementation of C++ map not storing values? | I have a class called ImageMatrix, which implements the C++ map in a recursive fashion; the end result is that I have a 3 dimensional array.
typedef uint32_t VUInt32;
typedef int32_t VInt32;
class ImageMatrix
{
public:
ImageMatrixRow operator[](VInt32 rowIndex)
private:
ImageMatrixRowMap rows;
};
typedef std:... | The following operators return by value, no writes modify the actual data.
ImageMatrixRow ImageMatrix::operator[](VInt32 rowIndex);
ImageMatrixColumn ImageMatrixRow::operator[](VUInt32 columnIndex);
Use:
ImageMatrixRow& ImageMatrix::operator[](VInt32 rowIndex)
ImageMatrixColumn& ImageMatrixRow::operator[](VUInt32 c... |
691,223 | 691,296 | handling a special character in a string while storing to a record on sqlite | in the following piece of code, I see that when my 'description' is something like:
" ' ' ", I have a problem updating the description to the sqlite record.
How do i handle the ' character. thanks!
sql = wxString::Format(
"UPDATE event SET event_description='%s' WHERE id=%d",
description.c_str(),
event_id);
... | Doubling up all the single quotes in the description string is one way to do it. This way you can avoid malicious descriptions (see Bobby Tables).
' '
becomes:
'' ''
And more importantly, the potentially dangerous description:
' WHERE 1=1 DELETE FROM Event --
becomes the harmless:
'' WHERE 1=1 DELETE FROM Event... |
691,347 | 691,366 | optimize time(NULL) call in c++ | I have a system that spend 66% of its time in a time(NULL) call.
It there a way to cache or optimize this call?
Context: I'm playing with Protothread for c++. Trying to simulate threads with state machines. So Therefore I cant use native threads.
Here's the header:
#ifndef __TIMER_H__
#define __TIMER_H__
#include <t... | I presume you are calling it within some loop which is otherwise stonkingly efficient.
What you could do is keep a count of how many iterations your loop goes through before the return value of time changes.
Then don't call it again until you've gone through that many iterations again.
You can dynamically adjust this ... |
691,686 | 692,512 | How to build C++ app which runs on plain old XP SP2 with Visual Studio 2008 and no Side-by-Side DLLs? | I'd like to compile a C++ project with just a single call to WinExec in order to launch another executable with some command line parameters. I've no idea what settings to specify in my project in order to get produce an executable that works without requiring Microsoft side-by-side DLLs, which I don't want to have to ... | The solution has been answered (partially) by both jachymko and Josh. Here is the full solution:
Set Project Properties / Configuration / Linker / Input / Ignore All Default Libraries to Yes and add kernel32.lib to Additional Dependencies. This alone won't link, as the code automatically refers to __security_check_coo... |
691,719 | 691,742 | C++ display stack trace on exception | I want to have a way to report the stack trace to the user if an exception is thrown. What is the best way to do this? Does it take huge amounts of extra code?
To answer questions:
I'd like it to be portable if possible. I want information to pop up, so the user can copy the stack trace and email it to me if an error c... | It depends which platform.
On GCC it's pretty trivial, see this post for more details.
On MSVC then you can use the StackWalker library that handles all of the underlying API calls needed for Windows.
You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need ... |
691,773 | 691,786 | Visual Studio unmanaged C++ smart file explorer | I use Visual Studio to develop unmanaged C++ apps for a living.
Is there an add-on tool (price isnt the issue) that is smart enough to detect folders that I create within my solution folder and add them to the include path (/I)? It would automatically do this for win32, or x64 platform settings, or debug, and release, ... | You can manipulate files/folders from the IDE! Just click the "show all files" button in the solution explorer (2nd from left, at the top). I just recently found that out.
|
691,954 | 691,957 | Should I comment the declaration or the definition in C++? | Which is more practical to comment, the declaration (in the header file) or the definition (in the source file)? Maybe I should comment both, or comment neither and put it all in a separate file...
| You should completely document the header file with highest priority.
Comments in the definition should be concentrated on implementation details, while header comments should be concentrated on the interface.
A third source of documentation, as you suggested, is useful as well. It should describe the overall concept.
... |
692,225 | 692,278 | What are the differences between C, C# and C++ in terms of real-world applications? | As I posted earlier here I've decided to try my hand at one of these, but given my interests as a web developer, I'd like to know the difference between them in their real-world applications.
Edit Note:
While I'm a web developer, please don't let that limit your answer. I'm 30...I've got years of career changing ahead ... | Both C and C++ give you a lower level of abstraction that, with increased complexity, provides a breadth of access to underlying machine functionality that are not necessarily exposed with other languages. Compared to C, C++ adds the convenience of a fully object oriented language(reduced development time) which can, p... |
692,438 | 692,449 | Is boost shared_ptr <XXX> thread safe? | I have a question about boost::shared_ptr<T>.
There are lots of thread.
using namespace boost;
class CResource
{
// xxxxxx
}
class CResourceBase
{
public:
void SetResource(shared_ptr<CResource> res)
{
m_Res = res;
}
shared_ptr<CResource> GetResource()
{
return m_Res;
}
private:
shar... | From the boost documentation:
shared_ptr objects offer the same
level of thread safety as built-in
types. A shared_ptr instance can be
"read" (accessed using only const
operations) simultaneously by multiple
threads. Different shared_ptr
instances can be "written to"
(accessed using mutable operations
... |
692,541 | 692,547 | C++ template static pointer-to-member initialization | I have a template class which has a static pointer-to-member, like this:
template<class T, T* T::*nextptr>
class Queue
{
T* head;
T* tail;
static T* T::*pnext;
};
My question is how to write the initializer of the static pointer-to-member. I tried the obvious case:
template<class T, T* T::*nextptr> T* Queu... | Queue<T, nextptr>::pnext is declared as type T* T::*, so it should look like this:
template<class T, T* T::*nextptr>
T* T::* Queue<T, nextptr>::pnext(nextptr);
|
692,752 | 692,759 | Naming conventions for template types? | Traditionally, the names of template types are just a single upper-case letter:
template<class A, class B, class C>
class Foo {};
But I hesitate to do this because it's non-descriptive and hard therefore to read. So, wouldn't something like this be better:
template<class AtomT, class BioT, class ChemT>
class Foo {}; ... | For C++ templates I have a couple of patterns
If there is just a single template parameter, I name it T (or U,V for nested templates).
When there are multiple parameters and the use is not immediately obvious then I use descriptive names prefixed with T. For example, TKey, TValue, TIdentifiier, etc ... This makes t... |
692,880 | 692,897 | TCP: How are the seq / ack numbers generated? | I am currently working on a program which sniffs TCP packets being sent and received to and from a particular address. What I am trying to accomplish is replying with custom tailored packets to certain received packets. I've already got the parsing done. I can already generated valid Ethernet, IP, and--for the most par... | When a TCP connection is established, each side generates a random number as its initial sequence number. It is a strongly random number: there are security problems if anybody on the internet can guess the sequence number, as they can easily forge packets to inject into the TCP stream.
Thereafter, for every byte trans... |
692,885 | 692,894 | Cross-platform C++ IDEs? | I'm looking for a good IDE for C++ that has most or all of the following properties (well, the first 4 or 5 ones are mandatory):
cross-platform (at least Mac, Linux)
of course, syntax highlighting and other basic coding editor functionality
reasonably responsive GUI, not too sluggish on mid-size (say, 100 files) proj... | Code::Blocks does the first 5 and it's also got class method browsing (though not a heirarchy display). It's a much more lightweight solition thaen Eclipse or NetBeans, but if you like the minimalist approach it's pretty good.
To summarise CB versus your requirements:
Yes
Yes
Yes
Yes
Yes
No - but you can add it easily... |
692,893 | 693,314 | How can I code my own custom splash screen for Linux? |
This is NOT a question on plain old boring customization; I actually want to create an program, you know, with source code, etc...
I'm thinking about programming my own media centre interface, and I figured it'd look better if I coded my own splash screen for when the OS is loading.
Note: The media centre interface w... | For the graphical output you can use the Linux framebuffer, for application development you can use gtk which support rendering directly to the framebuffer GtkFB.
For the video and such you can use mplayer which also support rendering to the framebuffer.
For the initialization you have to look around the system used, d... |
693,206 | 694,481 | Seeking suggestions for Unit Testing C++ app spread over several dlls | New to unit testing and have an app that is spread out over several dlls. What are some suggestions for unit testing the app? If I put the unit tests in their own project, i can only test the published interface for each dll. Is that what most people do? Or should I put the unit tests in with the code in the dlls a... | Unit testing in C++ means rather class testing. DLL testing would be rather integration testing. Both are necessary, but it's better to test things at as low level as possible. Take a look on v-model: http://en.wikipedia.org/wiki/V-Model_(software_development).
|
693,361 | 706,960 | Visual Studio code metrics plugin for C++ | Is there a VS2008 plugin for code metrics for C++? I have Team System but it doesn't work for non- .NET code. I tried studioTools but it just freezes. So, does anyone know one that actually works?
| Well, I found out that CodeRush does this.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.