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,673,783 | 4,676,380 | Is tellp safe to use with file locking | The general strategy for boost file locking (sharable and scoped file_locks), and file locking in general I think, is this:
open
lock
operate on file contents
unlock
close the file
However, I will be opening the file for append and want to call tellp to see where I am. Is this safe to do in the above scenario? Won't... | This may be environment-specific, but on the majority of platforms:
When a file is opened for append the file pointer is adjusted immediately before every write. So, if you use tellp before locking the file, it might not tell you where your newly appended bytes are going to go, but you shouldn't have two processes usi... |
4,673,883 | 4,673,977 | Metaprogramming template recursion doesn't recurse (edited important) |
I try to invoke function void set (...) recursively using metaprogramming.
The problem is that it seems to invokes only once.
template <int N>
struct GEN
{
enum {value = GEN<N-1>::value};
template <typename T>
static inline void set(T& tup, int l_item)
{
cout<<"item value: "<<l_item<<", N-1:... | There is no recursion. Recursion means calling yourself. The set function in your code does not do this.
Your value declaration does recurse (i.e. GEN<N>::value is defined in terms of GEN<N -1>::value) – but in a pretty uninteresting way, it just propagates the base case value, 0 – and furthermore you don’t seem to be ... |
4,673,932 | 4,684,955 | boost::optional<> in a union? | I have an optional POD struct that will be contained inside a union.
boost::optional<> holds its type by value, so I thought this could work:
union helper
{
int foo;
struct
{
char basic_info;
struct details {
//...
};
boost::optional<details> extended_info;
... | As others have mentioned, the ideal thing to do is to change from a union to a boost::variant<>.
However, if this isn't possible, you can implement a POD approximation of boost::optional<> as follows:
Implementation
template <typename T>
class Optional
{
T value;
bool valid;
public:
// for the if(var) tes... |
4,673,947 | 4,674,866 | Cross compile x86_64 on i686 system on Ubuntu with distcc | I am attempting to setup a small build cluster at home using distcc. There are two x64 systems and 1 i686 systems. All systems are running Ubuntu 10.10 and are up to date. The system that is initiating the build is x64. Distcc works fine between the two x64 systems but all build tasks sent to the i686 system fail.
So f... | Attempting this one again after more research:
GCC has a page describing the i386 and x86-64 options. The -m64 flag says to generate 64-bit code, but you'll also want to specify the type of CPU with -march=i686 or -march=k8 or similar, to use the correct instruction set.
Since distcc sends the GCC command line flags ou... |
4,673,955 | 4,674,102 | High performance XML parsing in C++ | Well a lot of questions have been made about parsing XML in C++ and so on...
But, instead of a generic problem, mine is very specific.
I am asking for a very efficient XML parser for C++. In particular I have a VERY VERY BIG XML file to parse.
My application must open this file and retrieve data. It must also insert n... | You want a streaming XML parser rather than what is called a DOM parser.
There are two types of streaming parsers: pull and push. A pull parser is good for quickly writing XML parsers that load data into program memory. A push parser is good for writing a program to translate one document to another (which is what you ... |
4,674,015 | 4,674,043 | C++ std::vector segfault when using erase(), ok when using pop_back() with g++ | Please consider the following code:
vector<int> myVector;
myVector.push_back(10);
myVector.erase(myVector.end());
This code compiles and runs fine on Windows (VisualStudio), but results in a segfault on Linux when compiled with g++. Replacing erase with pop_back solves the problem on Linux.
Does anyone know why the b... | end() typically returns an invalid position in the array (one beyond the end).
pop_back() removes the last item in the vector.
If you want to erase, you have to do erase(end() - 1); here end() - 1 returns an iterator to the last item.
erase(end()) should invoke UB - which I think is correct...
EDIT: as Martin pointed o... |
4,674,195 | 4,674,251 | Wanting to write a raytracer, stuck on what algebra library to use (C++) | I've been wanting to write my own multithreaded realtime raytracer in C++, but I don't want to implement all the vector and matrix logic that comes with it. I figured I'd do some research to find a good library for this, but I haven't had much success...
It's important that the implementation is fast, and preferably th... | I'd recommend writing your own routines. When I wrote my raytracer, I found that most of the algebra used the same small collection of methods. Basically all you need is a vector class that supports addition, subtraction, etc. And from there all you really need is Dot and Cross.
And to be honest using GLSL isn't going... |
4,674,332 | 4,674,358 | declaring a const instance of a class | Let's say I have a class defined as follows:
class foo{};
now, this is perfectly acceptable;
foo f;
how come this is a compiler error? (uninitialized const ‘f’)
const foo f;
Why do we have to do this?
const foo f = foo();
I know why we can't do this..
const foo f(); // though it compiles..
Interestingly, the follo... | Your class is a POD (essentially because it doesn’t provide a default constructor). POD variables are not initialized upon declaration. That is, this:
foo x;
does not initialize x to a meaningful value. This has to be done separately. Now, when you declare it as const, this may never happen because you cannot assign t... |
4,674,480 | 4,674,580 | do while(false) pattern |
Possible Duplicate:
Why are there sometimes meaningless do/while and if/else statements in C/C++ macros?
Why is the do while(false) necessary in the macros below?
#define LOG(message, ...) \
do { \
Lock<MutualExclusion> lock (logMutex); \
.... a lot of code ...
} while (false)
I dont think it serves any function... | It turns a block into a single statement. If you just use a block (i.e. code enclosed in {}) strange things can happen, for example
#define STUFF() \
{ do_something(); do_something_else(); }
if (cond)
STUFF();
else
//...
the extra semi-colon breaks the syntax. The do {} while(false) instead is a single stat... |
4,674,906 | 4,675,422 | Overload new operator to store objects in mmap'd file | I have a Linux C++ program with fairly large memory requirements. Most of the memory is consumed by just a few classes, and is accessed reasonably infrequent. I want to move these classes from main memory to disk-based storage, while changing as little existing code as possible.
The idea was to override the new operato... | Looking at each question in turn
Is this a very bad idea? Do you know something better to achieve the same?
Its not really clear what you hope to achieve by this. Linux already backs memory used by swap space (so if your data exceeds physical memory, some will be swapped to disk). Are you having problems with runni... |
4,675,141 | 4,675,234 | Timing the runtime of a program via the Terminal | I've written a C++ program of which i would like to time the length of time it takes to complete - is there some terminal command i could use?
| You can use the "time" command available in most (maybe all) the linux distributions. It will print the time spent as system, as user, and the total time.
For example
bash-4.1$ time (sleep 1; sleep 1)
will output something like
real 0m2.020s
user 0m0.014s
sys 0m0.005s
As you can see with the parenthesis you c... |
4,675,329 | 4,675,548 | How to insert a new node in a xml_document using RapidXml for C++ using strings? | std::string src = "<xml><node1>aaa</node1><node2>bbb</node2><node1>ccc</node1></xml>";
std::string src2 = "<nodex>xxx</nodex>";
I want to append the node in src2 inside the tree in src using RapidXml
I do this:
xml_document<> xmldoc;
xml_document<> xmlseg;
std::vector<char> s(src.begin(), src.end());
std::vector<char>... | #include <iostream>
#include <string>
#include <vector>
#include <rapidxml.hpp>
#include <rapidxml_print.hpp>
int main(){
std::string src = "<xml><node1>aaa</node1><node2>bbb</node2><node1>ccc</node1></xml>";
std::string src2 = "<nodex><nodey>xxx</nodey></nodex>";
//std::string src2 = "<nodex>xxx</nodex>";
rapidxml::... |
4,675,457 | 4,678,313 | How to generate the audio spectrum using fft in C++? | I want to generate an audio spectrum (as seen in this video) of a mp3 audio file. Basically this problem requires calculating the fft of the audio signal. How do I program this in C/C++?
I've looked at a couple of open source libraries such as FFTW and I really don't know how to use these for my problem. Any help woul... | There are quite a few similar/related questions on SO already which are well worth reading as the answers contain a lot of useful information and advice, but in essence you need to do this:
Convert the audio data to the format required by FFT (e.g. int -> float, with separate L/R channels);
Apply suitable window funct... |
4,675,590 | 4,675,611 | C++'s pure virtual function implementation and header files | I'm having some trouble implementing pure virtual functions inherited from some abstract class, when the classes in question are divided into *.h and *.cpp files. The compiler (g++) tells me that the derived class cannot be instantiated because of the existence of pure functions.
/** interface.h**/
namespace ns
{
c... | You forgot to declare Derived::method().
You tried to define it at least, but wrote Derived::Interface::method() rather than Derived::method(), but you did not even attempt to declare it. Therefore it doesn't exist.
Therefore, Derived has no method(), therefore the pure virtual function method() from Interface was not ... |
4,675,601 | 4,675,631 | How do arbitrary floating point values compare to infinity? | Basically i want to search for the smallest (positive) value from a bunch of values and need a default value to compare to the first one. The naïve assumption would be, they always compare "less than" (except NaNs, but let's not consider those) but I'm not quite sure.
I'm using the float type and I think it can safely ... | For IEEE 754 floats, except NaN and infinity, everything is less than infinity. Chances are you'll have those on your platform. If you're paranoid, check with numeric_limits<float>::is_iec559. If your platform happens to be not conforming, use numeric_limits<float>::max(); if your sequence is nonempty, it will not give... |
4,675,696 | 4,675,716 | How do I implement a unary operator overload for a forward declared type in C++? | The following code does not compile in Visual Studio 2008. How do I get it to allow a unary operator in the Foo1 class that converts it to a Bar, when Foo1 is defined before Bar?
class Foo1
{
public:
int val;
operator struct Bar() const;
};
struct Bar
{
int val;
};
// This does not compile
Foo1::operator... | I figured out the answer. There are two solutions:
struct Bar;
class Foo1
{
public:
int val;
operator struct Bar() const;
};
Or:
class Foo1
{
typedef struct Bar MyBar;
public:
int val;
operator MyBar() const;
};
(The operator::Bar() implementation remains unchanged)
|
4,675,704 | 4,675,994 | Windows Task Scheduler: IAction.QueryInterface() returns an error I cannot find a definition for | I am attempting to schedule a task (to open an .exe at a specific time) using C++ win32. But at one specific point I am getting an error, I have searched & searched to try & find the definition of this error but I cannot find it?
Do you know what this error means: Hexadecimal: 80004003 Decimal: 2147500035
I wont post ... | 0x80004003 is an "invalid pointer" error, a.k.a. E_POINTER.
I assume the declaration of execAction is something like:
IExecAction* execAction = NULL;
But, QueryInterface expects a pointer to an interface pointer. In other words, you pass a storage location in which to place an IUnknown*... or, in this specific case, ... |
4,675,783 | 4,675,819 | When declaring variables in {} scope, will they still use memory after? | in this example, even though i will never use the variables WNDCLASSEX, x, y, cx, cy, they will still use memory when i'm in the message loop:
int WINAPI WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpArgs, int iCmdShow)
{
WNDCLASSEX wc;
...
RegisterClassEx(&wc);
const int cx = 640;
co... | The compiler has a lot of leeway for handling simple locals, like you have in your examples. They may live on the stack, they may only exist as immediate values in the machine code, or they may just live in registers. Stack space is usually allocated on entry to a function. The compiler will subtract some value from... |
4,675,908 | 4,675,935 | Does cout need to be terminated with a semicolon? | I am reading Bjarne Stroustrup's Programming : Principles and Practice Using C++
In the drill section for Chapter 2 it talks about various ways to look at typing errors when compiling the hello_world program
#include "std_lib_facilities.h"
int main() //C++ programs start by executing the function main
{
cout << "... | The comma operator in C++ can be used as follows:
a, b;
It means "do a, disregard the result, then do b." You can chain it together like this:
a, b, c, (etc.), n;
In general, this isn't considered good style. The comma operator is rarely used in practice because it's confusing. The few times it's legitimately usef... |
4,675,930 | 4,676,091 | Boost tuple + transform | Is it possible to do the following.
Say my boost tuple has <std::string, T>
I would like to use std::transform + mem_fun to insert only the std::string element in a corresponding vector. Is it possible or are we required to use a loop and push_back(get<0>)...
Ie the following doesn't like to compile... (unknown types..... | The type of the get<0> overload that you want is:
const std::string& (*)(const boost::tuples::cons<std::string, boost::tuples::cons<int, boost::tuples::null_type> >&)
If you typedef that to get0_fn_t, then you can declare a pointer to this get<0> overload with:
get0_fn_t getter_fn = &boost::tuples::get<0, std::string,... |
4,676,118 | 4,676,159 | Making Visual C++ DLL from C++ class | I have the following C++ code to make dll (Visual Studio 2010).
class Shape {
public:
Shape() {
nshapes++;
}
virtual ~Shape() {
nshapes--;
};
double x, y;
void move(double dx, double dy);
virtual double area(void) = 0;
virtual double perimeter(void) = 0;
static int nshapes;
};
class _... | In DLL, i suggest to add a macro, and add XYZLIBRARY_EXPORT in pre-processor:
#if defined(XYZLIBRARY_EXPORT) // inside DLL
# define XYZAPI __declspec(dllexport)
#else // outside DLL
# define XYZAPI __declspec(dllimport)
#endif // XYZLIBRARY_EXPORT
class XYZAPI Circle
It will export the Circle class.
In EXE... |
4,676,171 | 4,676,393 | JSON schema validation | Is there a stable library that can validate JSON against a schema?
json-schema.org provides a list of implementations. Notably C and C++ are missing.
Is there a reason I can't easily find a C++ JSON schema validator?
Doesn't anyone else want a quick way to validate incoming JSON files?
|
Is there a stable library that can validate JSON against a schema?
I found a couple hits on google:
From the Chromium project: http://aaronboodman-com-v1.blogspot.com/2010/11/c-version-of-json-schema.html
http://avro.apache.org/docs/1.4.1/api/cpp/html/index.html
You could also plug a Python or Javascript interprete... |
4,676,327 | 4,676,692 | How to open a file with wchar_t* containing non-Ascii string in Linux? | Environment: Gcc/G++ Linux
I have a non-ascii file in file system and I'm going to open it.
Now I have a wchar_t*, but I don't know how to open it. (my trusted fopen only opens char* file)
Please help. Thanks a lot.
| There are two possible answers:
If you want to make sure all Unicode filenames are representable, you can hard-code the assumption that the filesystem uses UTF-8 filenames. This is the "modern" Linux desktop-app approach. Just convert your strings from wchar_t (UTF-32) to UTF-8 with library functions (iconv would work ... |
4,676,547 | 4,676,567 | Making this function non recursive? | I have a function here that is recursive, but I would instead like to make it non recursive. I'm just not sure how.
void AguiWidgetManager::recursiveRender(const AguiWidget *root)
{
//recursively calls itself to render widgets from back to front
AguiWidget* nonConstRoot = (AguiWidget*)root;
if(!nonConstRo... | The easy way is just to maintain your own stack. Psuedoish example code:
stack s;
while(!s.empty())
{
root = s.pop();
//your code here
//replace each recursive call with s.push(it)
}
Also, casting away constness is a bad, bad idea. It shouldn't be a const argument in the first place if you want to modify ... |
4,676,930 | 4,676,940 | Copying a vector reference to another | I've a structure, say SubscriptionData. Two variables of the type are declared in function 1.
SubscriptionData aSubscriptionData;
SubscriptionData aResultSubscriptionData;
The structure in itself has another structure, which in turn has a vector of another structure. The vector is given below
aSubscriptionData.apn_con... | std::copy doesn't allocate elements; you have to make sure there is sufficient space in the destination range to hold all of the elements in the source range.
A common way to do this is to use std::back_inserter, which calls push_back to insert each element into a container:
std::copy(source.begin(), source.end(), st... |
4,677,001 | 4,677,062 | cmath internal decoration | I am just wondering where and how functions like sine, cosine and sqrt are implemented inside cmath. I know cmath includes math.h and math.h has a bunch of stuff but where is the actual "math" behind some of these functions?
EDIT: I am more interested in whether there is tangible source code associated with math functi... | The math for those operations is almost certainly not done in C code, at least for x86 architectures. It is done on chip. Ever since the integration of the 8087 math co-processor into the 486, the x86 family has had instructions on the chip to do sine, cosine, and square root, among others. This page has a nice roundup... |
4,677,136 | 4,677,489 | How to properly assign a value to the member of a struct that has a class data type? | Please kindly see below for the codes. Its compiling successfully but the expected result is not working. Im very confused because my initialization of the array is valid,
//cbar.h
class CBar
{
public:
class CFoo
{
public:
CFoo( int v ) : m_val = v {}
int GetVal() { return m_val; }
private... | The problem is coming from these two lines:
const CBar::CFoo foo1 = CBar::CFoo(2);
const CBar::CFoo foo2 = CBar::CFoo(3);
which is not doing as you intended them to be doing. That is, these statements do not initialize foo1 and foo2 static members from the class CBar, rather they define global variables with name foo1... |
4,677,165 | 4,677,192 | Call function from object instantiated in one class in another | I have two classes, both of which need to be able to call the same instance of entitymanager
class Engine
{
EntityManager::Entitymanager EManager;
}
And I need to add an object to a vector contained by this particular instance of Engine. What I want to do is be able to add a bullet spawned by the player to the vecto... | You are trying to access EManager without a class instance associated with it.
There are 2 solutions for this.
You have to have an instance of Engine around in order to access EManager:
class Engine {
EntityManager::Entitymanager EManager;
};
Then you can access EManager this way:
m_engine.EManager.Add(BULLET)
Yo... |
4,677,508 | 4,677,581 | Accessing and modifying thread data problem in c++ | I have problems to access and modify my multiple thread data. Is there are any proper way to do this?
Here is my full code:
#include <stdio.h>
#include <windows.h>
// Create thread data structure
struct data
{
int a;
float b;
char *c;
};
DWORD WINAPI threadfn(LPVOID lpParam)
{
printf("Address of th... | What on earth are you doing?! All the casting of lpData is very, very wrong. If you have to do that much casting to accomplish something, you are probably not doing it the right way.
Anyway, your code should look like this:
DWORD WINAPI threadfn(LPVOID lpParam)
{
printf("Address of thread data:\n");
data ... |
4,677,592 | 4,678,000 | Specializing function template for reference types | Why is the output of this code :
#include <iostream>
template<typename T> void f(T param)
{
std::cout << "General" << std::endl ;
}
template<> void f(int& param)
{
std::cout << "int&" << std::endl ;
}
int main()
{
float x ; f (x) ;
int y ; f (y) ;
int& z = y ; f (z) ;
}
is
Genera... | The type of both the expression y and the expression z is int. A reference appearing in an expression won't keep reference type. Instead, the type of the expression will be the referenced type, with the expression being an lvalue.
So in both cases, T is deduced to int, and thus the explicit specialization is not used ... |
4,677,669 | 4,677,723 | Binary serialization/de-serialization in C++ and C# | I am working on a distributed application which has two components. One is written in standard C++ (not managed C++ and running on a Linux platform) and the other one is written in C#. Both are communicating via a message bus.
I have a situation in which I need to pass objects from C++ to C# application and for this I ... | gzip won't directly help with serialization - it will just (attempt to) shrink a stream. This may help, or not, depending on the amount of duplicated data in the stream. For dense data with little text, I've seen gzip increase the size of the payload.
Personally I would look at protocol buffers here (but I'm biased, as... |
4,677,691 | 4,678,057 | Boost C++: how to return file from folder via tcp? | so I have a folder "Assets" which is in the same folder with my server executable. I want to return file from it (ofcource if file exists) to any user that connects to my server via tcp and sends a filename (generally I wish to see a asinc, nonblocking tcp server made using boost which would simply return any file form... | This sounds like a job for a web server. This is what web servers do. They are good at it.
Consider using one of the zillion web server apps out there or integrate a little web server into your program:
- https://github.com/cloudmeter/pion
There are more linked from this question:
- https://stackoverflow.com/question... |
4,677,728 | 4,677,774 | Potential g++ template bug? | I've encountered some code which I think should compile, but doesn't. So I'm hoping some of the local standards experts here at SO can help :-).
I basically have some code which resembles this:
#include <iostream>
template <class T = int>
class A {
public:
class U {
};
public:
U f() const { return U(); }
... | The problem with const typename A<T>::U &x is that U is a dependent type and the compiler cannot deduce T from the argument (this is one of the nondeduced context).
You could, for example, have two specializations of A:
class X { };
class Y { };
class Z { };
template <> class A<X> {
public:
typedef Z U;
};
templ... |
4,678,447 | 4,678,485 | MD5 and SHA1 C++ hashing library | I'm trying to find a good (and well documented) hashing library to use with my C++ program, I only need to generate two hashes from a string.
I've tried with crypto++ and mhash and I didn't manage to make them work, also with http://www.zedwood.com/article/121/cpp-md5-function
I would be glad if this library is cross-p... | Try this open source library http://hashlib2plus.sourceforge.net/
|
4,678,507 | 4,678,796 | Carefully deleting N items from a "circular" vector (or perhaps just an NSMutableArray) | Imagine a std:vector, say, with 100 things on it (0 to 99) currently. You are treating it as a loop. So the 105th item is index 4; forward 7 from index 98 is 5.
You want to delete N items after index position P.
So, delete 5 items after index 50; easy.
Or 5 items after index 99: as you delete 0 five times, or 4 through... | Another method:
N times do {remove entry at index P mod max(ArraySize, P)}
Example:
N=5, P=97, ArraySize=100
1: max(100, 97)=100 so remove at 97%100 = 97
2: max(99, 97)=99 so remove at 97%99 = 97 // array size is now 99
3: max(98, 97)=98 so remove at 97%98 = 97
4: max(97, 97)=97 so remove at 97%97 = 0
5: max(96, 97)=... |
4,678,588 | 4,678,631 | Cannot convert from 'T[N][2]' to 'T[][2]' | I have an API taking some options:
void init_api(const char* options[][2]);
I am allowed to pass a NULL pointer for no options, alternatively, an options array such as this can be passed:
const char* some_options[][2] = { {"opt1", "val1"},
{"opt2", "val2"},
... | To declare an empty array of array of pointers to const char, you should use:
const char* my_options[][2] = {};
You need to declare a pointer to an array of pointers to const char instead. I recommend using a typedef to simplify the syntax.
typedef const char* array_of_two_cstring[2];
array_of_two_cstring* my_options... |
4,678,803 | 4,678,963 | AudioQueue screws up output after modification | I am currently working on an audio DSP App development. The project requires direct access and modification of audio data. Right now I can successfully access and modify the raw audio data using AudioQueue but encounters error during playback. The output audio after any modification turns out be noise.
In short, the co... | are you SURE the sample format is SInt16? And how many channels are there? You seem to treat the audio as a single channel short stream, but suppose the format is actually dual channel Float32 or so, and you do the modifications there, than the effect would be exactly as you describe, including the noise on other chann... |
4,678,804 | 4,678,816 | Is there any platform-independent Lib to work with filesystem? | Is there any open source Lib using which I can implement cross-platform working "Directory Listing" program (i.e the lib which works with file-system) and should work on (win, linux, solaris, mac 32 and 64 bit distributions)?
I have looked in boost, but couldn't find such thing. Maybe I wasn't enough attentive...
| boost has boost::filesystem
|
4,678,831 | 4,678,861 | Recommendations for choosing a programming language | Days ago I created a program in Python to download stuff from the Internet, doing HTTP POST and GET and parsing JSON objects. I noticed some slow performance and I was thinking about writing it from scratch using another language, so I started to write it in C++ to make it faster. Finally I give up, C++ wasn't made for... | If you need it to be cross-platform: (i.e. you just write it once and it can run anywhere) Then Java or Python are your only options. This is because any C variant will need compiling specifically for the platform you intend to use it on.
My suggestion: Out of the two I would suggest Python. I have be educated in Java ... |
4,678,903 | 4,678,911 | Async Resolve with Boost.Asio | I'm trying to asynchronously resolve a ftp host using Boost.Asio.
Here's what I've tried so far:
#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
using boost::asio::ip::tcp;
class FtpSession {
public:
void Connect(std::string& host) {
boost::asio::io_service io_s... | You need to call io_service.run() to actually do the work methinks. Think of the async_resolve as a request in a request queue - you need something (the io_service) to process the requests in the queue, and to do that, you actually need to run() it! In this case, it will see one request, execute it, call the handler an... |
4,679,050 | 4,679,070 | Is it possible to define a class in 2 or more file in C++? | I know it's possible to do class implementation in more than one file(yes, I know that this is bad idea), but I want to know if it's possible to write class definition in separate files without getting a redefinition error (maybe some tricks, or else...)
| No, not the same class, but why would you?
You could define two classes with the same name in the same namespace (the same signature! That will actually be the same class at all, just defined in two ways) in two different header files and compile your program, if your source files don't include both headers. Your appli... |
4,679,439 | 4,679,992 | Find largest allocation of memory possible | In 32bit mode application has access to 2GB of virtual address space. How would you find out the maximum size of memory you can allocate to this virtual address space, without malloc or new failing?
For example, lets say you want to take up the whole 2GB of virtual address space, but you just allocated 2MB of data in t... | Source:
http://www.voyce.com/index.php/2009/08/21/largest-free-block-of-address-space/
DWORD FindLargestSizeOfMemory()
{
MEMORY_BASIC_INFORMATION mbi;
DWORD start = 0;
bool recording = false;
DWORD freestart = 0, largestFreestart = 0;
__int64 free = 0, largestFree = 0;
while (true)
{
... |
4,679,855 | 4,680,405 | DOM elements memory allocation management on Xerces-C | It has been two days for me to struggle on xml parsing problems and it still hasn't finished yet :)
Well, After many trils I finally decided to use Xerces-C to parse xml in my c++ application.
Well... I tried TinyXml, RapidXml and others.... Xerces too behave in the same way when managing nodes on the point of view of ... | You need to keep the parser around. Either pass it as an argument (by reference), make it a member of MyTree (again, as a reference), or put it in a singleton class.
(_xmldoc should be a pointer, btw.)
|
4,679,876 | 4,681,945 | how do I translate of lon/lat coordinate by some N-E meters distance on earth surface? | how do I get a new coordinate in geodetic (Lat/Lon) from a reference point (which is in geodetic) after some translation (in meters) on earth surface, and also I need to do the calculation using true earth ellipsoid model such as WGS84.
for example:
suppose I have reference point of 10.32E, -4.31N
then I do translatio... | found the answer :
http://www.movable-type.co.uk/scripts/latlong-vincenty-direct.html
from:
Vincenty direct formula - T Vincenty, "Direct and Inverse Solutions of Geodesics on the
Ellipsoid with application of nested equations", Survey Review, vol XXII no 176, 1975
http://www.ngs.noaa.gov/PUBS_LIB/inverse.pdf
|
4,680,125 | 4,680,173 | Template class constructor issues - designing a container for multidim arrays | I'm trying to create my own container for an array of any dimension for numerical computing. I would like to do this using templates so that I could overload the subscript operator [] so that it works like normal arrays and vectors e.g. access entries like a[10][10][10] etc.
I am having trouble getting the constructor... | Your constructor uses the expression new T[size] and this requires T to be default constructible (if T is a class type).
You need to do something like: allocate raw memory (e.g. using operator new) and construct T instances "in place" using a placement new expression. Alternatively, you could just give container a defa... |
4,680,191 | 4,680,270 | When calling XMLPlatformUtils::Initialize() on Xerces? | I'm using Xerces and references are not very clear about when using Initialize and Terminate.
Well, many web sites typically tells you: "Always put your Xerces code between these two lines".
But do I always have to do that? Or just when parsing?
Thank you
| You have to call this Initialize once per process, before you use any Xerces-C++ functionality. You have to call Terminate once per process, when you're finished using Xerces.
The obvious place to put these is either main, in a singleton object, or in some RAII object that is in scope while Xerces is used.
|
4,680,389 | 4,680,428 | C++ ambiguous call in function overloading | Just a curiosity (academic question :P), consider the following code:
struct Y {};
class PassConstY {
public:
PassConstY(const Y& y) {}
};
class PassY {
public:
PassY(Y& y) {}
};
void z(PassConstY y) {}
void z(PassY y) {}
void h(const Y& y) {}
void h(Y& y) {}
Y y;
const Y cy;
h(cy); //OK
h(y); //OK
z(cy); ... | The reason of this is:
A SCS 1 is better than a SCS 2 if, among other things, SCS 1 binds a reference to const, and SCS 2 binds a reference to non-const.
A UCS 1 is better than a UCS 2 if and only if, among other things, both use the same conversion function or constructor.
For h, which uses a SCS, the first bullet ... |
4,680,431 | 4,680,466 | Memory Allocation char* and char[] | What is the difference between these two in terms of memory allocation.
char *p1 = "hello";
char p2[] = "hello";
| The first one creates a pointer variable (four or eight bytes of storage depending on the platform) and stores a location of a string literal there, The second one creates an array of six characters (including zero string terminator byte) and copies the literal there.
You should get a compiler warning on the first line... |
4,680,470 | 4,680,514 | Problems saving float array to binary file and reading back (C++) | I am trying to simply write an array of float values to a file and then read it back.
I have tried writing it directly from an array, but when reading it back I keep hitting a problem for arrays with length greater than 153. The code example writes each float value one by one for clarity.
For values with index greater ... | FILE* file = fopen (fileName, "wb");
FILE* file = fopen (fileName, "rb");
|
4,680,486 | 4,696,564 | Statically including dll files | I have a problem with statically linking dll files into project. I'm using Builder C++ 6.
I've unchecked:
Project \ Options \ Packages -> Build with runtime packages
Project \ Options \ Linker -> Use dynamic RTL
Project \ Options \ CodeGuard -> CodeGuard Validation
I've also added dll files using Project Manager:
myPr... | When you statically link to a DLL, what is really happening is that the compiler detects which DLL functions your code is calling and sets up stub pointers that the linker then inserts into your application's IMPORTS table. At runtime, when your application is run, the OS loader will first patch the IMPORTS table (amo... |
4,680,795 | 4,681,014 | C# p/invoke, Reading data from an Owner Drawn List Box | I have an Owner Drawn List Box in an external application (America Online) that I need to get data out of for building a component to assist people with its usability. (the utility will be making access of certain things more simple, etc).
Notice
My knowledge of C++ is very poor. I am a C# programmer.
I have the hWnd... | I have two blog posts on the topic
http://taylorza.blogspot.com/2009/08/archive-hacking-my-way-across-process.html
http://taylorza.blogspot.com/2010/06/crossing-process-boundary-with-net.html
These however are for a ListView control, but you might want to take a look at the code. The second post is using P/Invoke to ac... |
4,680,944 | 4,681,046 | Should standards be specified in source code or in CPPFLAGS? | Is it better to #define _BSD_SOURCE or to set CPPFLAGS=-D_BSD_SOURCE?
It seems to me that if a piece of source code relies on a particular standard, it is best to spell it out explicitly in the code itself with a #define. However, a lot of commentary suggests that specifying the standard on the compile line is more ap... | If you specify defines in your source there is a risk that the same header file can be included in several source files (translation units) but with different preprocessor definitions, which can lead to One Definition Rule violation which is often a pain to debug.
By specifying defines for the whole project rather than... |
4,681,011 | 4,681,399 | Thread Exit Events - C++ | When using an event (created with ::CreateEvent(...)) to signal a thread to exit, is it necessary to reset that event (::ResetEvent(...)) prior to exiting the thread or closing the event handle (::CloseHandle(...))? Or, is it good practice, if there is a possibility that the thread will be re-started? This is for a W... | It depends on the semantics of the event you use.
If you are using the event to trigger more than one thread to die, then you should not reset the event in each thread. If you use it to trigger only one thread to die, then it again depends on further semantics. If the event is used to signal other things to other thr... |
4,681,125 | 4,681,182 | Problem in Include file | I want to write two program(.h and .cpp) with below code and use .h file in .cpp but when i run it in TC occur below error
.h File
#ifndef ADD_H
#define ADD_H
int add(int x, int y)
{
return x + y;
}
#endif
.cpp file
#include <iostream.h>
#include <conio.h>
#include "Add.h"
void main()
{
clrscr();
cout ... | There's a few things you should look into:
the location (search path) of header files is implementation dependent, both for the <> and "" variants - make sure your header file is in that path somewhere.
you may find that you need to use add.h (all lowercase).
you shouldn't generally include code in header files (you s... |
4,681,411 | 4,681,942 | find any of the substrings in a string: if found mark that string ok | I have string say "Dog is a kind of animal";
Now if I have to find a string which contains any of these words instead of Dog like Cat, Horse, Tiger, Lion then I have to give status of string OK.
I am fully aware of string.find function which matches a single sub string to a string. But in my case I have to check the st... | Here is a very straight-up way to do it (I'll add alternatives in a monent):
#include <string>
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
string victim = "horse is a kind of animal" ;
vector<string> targets;
targets.push_back("cat");
targets.push_back("... |
4,681,443 | 4,681,487 | "APIENTRY _tWinMain" and "WINAPI WinMain" difference | What are the difference from these 2 function?:
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
int WINAPI WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
... | _tWinMain is just a #define shortcut in tchar.h to the appropriate version of WinMain.
If _UNICODE is defined, then _tWinMain expands to wWinMain. Otherwise, _tWinMain is the same as WinMain.
The relevant macro looks something like this (there's actually a lot of other code interspersed):
#ifdef _UNICODE
#define _tWin... |
4,681,480 | 4,681,533 | variable argument function in C | I have a variable list function
/* vsprintf example */
#include <stdio.h>
#include <stdarg.h>
void PrintFError (char * format, ...)
{
char buffer[50];
va_list args;
va_start (args, format);
vsprintf (buffer,format, args);
perror (buffer);
va_end (args);
}
int main ()
{
FILE * pFile... | You should use the safer vsnprintf, and limit it to 50 characters maximum.
int vsnprintf(char *str, size_t size, const char *format, va_list args);
|
4,681,541 | 4,681,674 | OpenGL Multi Bit Alpha Textures | I'm having some troubles rendering a texture that has a 8 bit alpha channel - namely, its being flattened to 1 bit and glBlendFunc() doesn't seem to be doing anything.
Here is the immediate mode call:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_QUADS);
{
glTexCoord2f(0, 0);
... |
Transparency is best implemented using blend function (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) with primitives sorted from farthest to nearest.
I would check to make sure your polygons are sorted back to front, otherwise blending will have incorrect effects.
I would also make sure your call to glTexImage2D is using GL... |
4,681,738 | 4,681,861 | How do I determine if a window is off-screen? | In Windows XP and above, given a window handle (HWND), how can I tell if the window position and size leaves the window irretrievably off screen? For example, if the title bar is available to the cursor, then the window can be dragged back on screen. I need to discover if the window is in fact visible or at least ava... | Windows makes it relatively simple to determine the size of a user's working area on the primary monitor (i.e., the area of the screen not obscured by the taskbar). Call the SystemParametersInfo function and specify the SPI_GETWORKAREA flag for the first parameter (uiAction). The pvParam parameter should point to a REC... |
4,681,998 | 4,682,105 | Bus error using mpic++ but not using g++ | I have some code written in C++ that compiles and runs fine (with reasonable output) when using g++, but when I try to use mpic++, I get a runtime bus error. I've managed to figure out where the bus error is occuring, but not why. Here is my code:
one = (double *) malloc(sizeof(&one) * nx * nx * nt);
two = (double **) ... | One thing that jumps out is that you are using sizeof(&foo) (size of a pointer to foo) when you probably mean sizeof(*foo) (size of the thing that foo points to).
I bet what is happening is that mpic++ is compiling to a 32-bit target, where the size of doubles is 64 bits and the size of addresses is 32 bits. That gives... |
4,682,350 | 4,682,556 | Conversion to unix timestamp incorrect | I have a function that I wrote (if there is a good standard substitute, please let me know...)
time_t get_unix_time(string time_str) {
time_t loctime;
time(&loctime);
struct tm *given_time;
time_str = time_str.substr(0, time_str.find_first_of('.'));
replace(time_str.begin(), time_str.end(), ':', '... | If you are using glibc you have the timegm function at your disposal, which is a version of mktime that always interprets the time as if it were in the GMT timezone. Unfortunately, the documentation for that function basically states that it cannot otherwise be implemented using standard library calls. So you're sort... |
4,682,355 | 4,682,398 | Use boost C++ libraries? |
Possible Duplicate:
Boost Library
Often when I was trying (and failing) a C++ project I run into Boost when browsing the web. I tried reading the Boost website, but there was no good short description why to use Boost and what it exactly is.
One of the things that I like a lot about Python is that everything is buil... |
What exactly is Boost?
Boost is a collection of useful and extremely high-quality libraries for C++ that complement the rather small standard library.
What are the most import reasons to use Boost?
Boost offers high-quality tools that are missing from C++. Their use is extremely varied though so whether Boost is fo... |
4,682,449 | 4,682,500 | need help understanding MFC projects | can anyone please explain to me what are the files that created when i creating MFC project? what is the main file which running the dialog.
sorry if there is some mistakes i new in MFC.
thanks
| If you opened it as a dialog application (probably because you are not writing a document editor so did not want a "doc-vieW" and there is no option for a menu-driven application otherwise, my pet peeve with MFC):
The "App" is your application. It creates your dialog then calls DoModal() on it.
It will also create by d... |
4,682,482 | 4,682,722 | Strange problem with vectors | I have a really strange problem with stl vectors in which the wrong destructor is called for the right object when I call the erase method if that makes any sense.
My code looks something like this:
for(vector<Category>::iterator iter = this->children.begin(); iter != this->children.end(); iter++)
{
if((*i... | When you erase your element from the vector, each element after it is copied (using the assignment operator) to the previous spot in the vector. Once this is complete, the last element in the vector is destructed. This could be why you're seeing your last element get destructed. Rule number one when using the STL is... |
4,682,603 | 4,682,688 | Would this optimization in the implementation of std::string be allowed? | I was just thinking about the implementation of std::string::substr. It returns a new std::string object, which seems a bit wasteful to me. Why not return an object that refers to the contents of the original string and can be implicitly assigned to a std::string? A kind of lazy evaluation of the actual copying. Such a... | This idea is copy-on-write, but instead of COW'ing the entire buffer, you keep track of which subset of the buffer is the "real" string. (COW, in its normal form, was (is?) used in some library implementations.)
So you don't need a proxy object or change of interface at all because these details can be made completely ... |
4,682,886 | 4,683,725 | CreateDibSection on Disk instead of physical memory | I am having a memory issue with an algorithm I am using to "Flatten" a page in a PDF document.
HBITMAP hbmp = CreateDibSection(...);
ThirdPartyBmpManipulation(hbmp, "C:\\file.pdf", 0); //renders page 0 in file.pdf
void * hdib = ConvertBitmap(hbmp); //copy a Dib Section to a Dib
DeleteObject(hbmp); //frees the HBitmap w... | What is the failure mode? You say "physical memory": windows uses virtual memory, it will page to disk, you don't need to worry about running out of physical memory beyond the performance hit. If you're running out of address space, using the disk may not be able to help you.
However, CreateDIBSection can take a HANDL... |
4,682,889 | 4,682,941 | Is floating-point == ever OK? | Just today I came across third-party software we're using and in their sample code there was something along these lines:
// Defined in somewhere.h
static const double BAR = 3.14;
// Code elsewhere.cpp
void foo(double d)
{
if (d == BAR)
...
}
I'm aware of the problem with floating-points and their represe... | There are two ways to answer this question:
Are there cases where float == float gives the correct result?
Are there cases where float == float is acceptable coding?
The answer to (1) is: Yes, sometimes. But it's going to be fragile, which leads to the answer to (2): No. Don't do that. You're begging for bizarre bugs... |
4,682,919 | 4,682,954 | What are differences between std, tr1 and boost (as namespaces and/or libraries)? | I initially thought they're all the same, but it turned out to be wrong. So can anyone briefly explain the differences between these three? For example:
std::bind ( newest one, next generation of C++ )
std::tr1::bind ( old, extension of C++ std )
boost::bind ( completely separate library )
or std::shared_ptr, std::tr... | 1 - std::bind is the the standard name for it. This will be the name you use for C++11 compliant libraries. List of all libraries in standardized C++.
2 - std::tr1::bind is C++ Technical Report 1 namespace. Between C++03 and C++11 there was the C++ Technical Report 1, which proposed additional libraries and enhancement... |
4,683,049 | 4,683,236 | passing multidimensional arrays to function | I have a method in my class which uses a 3dimensional tfpairexp as input parameter. and I need to use the values in tfpairexp later.
void calctfpairexp (int tf1, int tf2, double tfpairexp[][2][3])
{
int ctr,c;
for (int j = 0; j < cchips && (c = chips[j].crepls); j += c)
{
int ctrl_no=0;
fo... | I would expect a syntax error from that function declaration, as the array param declaration is invalid. You need:
void calctfpairexp (int tf1, int tf2, double tfpairexp[][2][3])
the array index stuff comes AFTER the param declarator
|
4,683,545 | 4,683,609 | Obtaining currently connected network name (SSID) in C++ | I would like to obtain the name (SSID) of the wireless network that the computer is currently connected to. I've looked into the IP Helper API but it seems to have everything but that (DNS servers, IP addresses..). Any help would be appreciated.
| It's OS dependant, the easiest way may be to just shell out and exec the system's netsh or equivalent and then grep the result
eg. on windows 'netsh wlan show int' gives
There is 1 interface on the system:
Name : Wireless Network Connection
Description : Broadcom 802.11g Network Ad... |
4,683,571 | 4,684,181 | Status & Contents of TR2 W.R.T. C++ Specification | Reference Link: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2009/n2849.pdf
I am trying to gather information about TR2 and how it relates to the upcoming C++ Standard, if it does at all.
Here are my questions so far. If I've missed any important questions, please answer those as well. :)
Preliminaries:
The cu... | FYI, the linked document isn't TR2. "TR2" refers to a set of library extensions, in the same style as TR1, while the draft for "decimal floating point arithmetic extensions" is just that. There is no TR2 draft yet and it was originally planned to come out after 0x. So from here on, I'll assume that you aren't asking ab... |
4,683,585 | 4,683,712 | Better design for using function pointers with varying arguments | I have an optimisation algorithm which finds the best partition of a graph.
There are many measures for the quality of a partition (the variable being optimised), so I thought it would be a good idea to use function pointers to these quality functions, and pass that into my optimisation algorithm function.
This works f... | Use function objects. One of those function objects can have a markov_time member that is passed in to the constructor:
struct find_linearised_stability {
std::vector<float> & markov_times_;
find_linearised_stability(std::vector<float> & markov_times)
:markov_times_(markov_times)
{}
float ope... |
4,683,840 | 4,683,864 | Detecting const-ness of nested type | Normally, if I need to detect whether a type is const I just use boost::is_const. However, I ran into trouble when trying to detect the const-ness of a nested type. Consider the following traits template, which is specialized for const types:
template <class T>
struct traits
{
typedef T& reference;
};
template <... | Because the reference is not const, it's the type it's referencing that is const. Right, there are no const references. So imagine that the reference is a pointer, then the difference is easier to understand: int const* not const, int *const is const.
Use remove_reference to get the actual const type:
cout << boost::is... |
4,684,212 | 4,684,275 | 'array bound is not an integer constant' when defining size of array in class, using an element of a const array | #ifndef QWERT_H
#define QWERT_H
const int x [] = {1, 2,};
const int z = 3;
#endif
#include <iostream>
#include "qwert.h"
class Class
{
int y [x[0]]; //error:array bound is not an integer constant
int g [z]; //no problem
};
int main ()
{
int y [x[0]]; //no problem
Class a_class... | The main version works because your compiler has an extension to allow for variable length arrays. Array accesses cannot be constant expressions in C++03, even if the array and the index are both constant expressions, which is the source of the error.
|
4,684,251 | 4,684,311 | Dynamically storing an internal configuration | I've been thinking of The Right Way (R) to store my program's internal configuration.
Here's the details:
The configuration is runtime only, so generated each run.
It can be adapted (and should) through directives in a "project" file (the reading of that file is not in the scope of this question)
It needs to be extens... | You could do worse than some kind of a property map (StringMap is just a typedef'd std::map)
class PropertyMap
{
private:
StringMap m_Map;
public:
PropertyMap() { };
~PropertyMap() { };
// properties
template<class T>
T get(const String& _key, const T& _default = T()) const
{
... |
4,684,440 | 4,684,495 | Light weight C++ SAX XML parser | I know of at least three light weight C++ XML parsers: RapidXML, TinyXML and PugiXML. However, all three use a DOM based interface (ie, they build their own in-memory representation of the XML document and then provide an interface to traverse and manipulate it). For most situations that I have to deal with, I much pre... | I've used expat when I needed to parse XML. It's very light-weight (well, it used to be; it's a while since I've done XML stuff) and does the job.
|
4,684,459 | 4,684,552 | Definition of operator->() in c++ | Please tell me how the operator->() in being defined for the iterator of std::list in order to refer members of the element that is being pointed by an iterator.
EDIT:
The problem is that if you implement like this (Fred Nurk):
template<class T>
struct list {
private:
struct Node { // internal class that actually ma... | With many details elided, here is the gist of how it works:
template<class T>
struct list {
private:
struct Node { // internal class that actually makes up the list structure
Node *prev, *next;
T data;
};
public:
struct iterator { // iterator interface to the above internal node type
T* operator->(... |
4,684,488 | 4,684,521 | Iterating through a boost::dynamic_bitset | I have a boost dynamic_bitset that I am trying to extract the set bits from:
boost::dynamic_bitset<unsigned long> myBitset(1000);
My first thought was to do a simple 'dump' loop through each index and ask if it was set:
for(size_t index = 0 ; index < 1000 ; ++index)
{
if(myBitset.test(index))
{
/* do somet... | find_first and find_next are the fastest way. The reason is that these can skip over an entire block (of dynamic_bitset::bits_per_block bits, probably 32 or 64) if none of them are set.
Note that dynamic_bitset does not have iterators, so it will behave a bit un-C++'ish no matter what.
|
4,684,497 | 4,684,714 | Connect C/C++ with .NET | I'm considering porting an application C / C + + in C + + / CLI.
Mainly I would like to exploit the potential of reflection, XML serialization and in general all the features in. NET framework offered by Microsoft (maybe even in mono).
The project in question does not use the STL heavily, and application objects are ... | Unmanaged classes can have managed members. The trick is to use the gcroot template. Look here
http://weblogs.asp.net/kennykerr/archive/2005/07/12/Mixing-Native-and-Managed-Types-in-C_2B002B00_.aspx
to learn more about it.
EDIT: as a response to some of your other questions: when you have a working C++ code base which ... |
4,684,542 | 4,684,559 | Are the integer comparison operators short circuited in C++? | Like the title states, are the integer (or any numerical datatypes like float etc.) comparison operators (==, !=, >, >=, <, <=) short circuited in C++?
| They can't short circuit. To know if x == y, x != y, etc are true or false you need to evaluate both, x and y. Short circuiting refers to logical boolean operators && and ||. Logical AND is known to be false if the first argument is false and Logical OR is known to be true if the first argument is true. In these cases ... |
4,684,576 | 4,684,851 | C++ How to create a function which takes as argument a reference to a function pointer? | i'm using function pointers typedef'd:
typedef int(*ptr2Func)();
And a function which when given a number will select a function pointer for a function that is already declared.
ptr2Func getPtr2Func(int function);
So if u use getPtr2Func(1); u get a function pointer to the first function.
However i want now to do the e... | To understand how this kind of stuff works, it's best to look at how a callback manager is built. Usually when you write a callback function like this you pass the instance and the static address of the method. You'll want to create a callback manager that looks something like this:
...
class MyCallbackClass
{
p... |
4,684,646 | 4,684,836 | Why assign a return value to a reference? | I'm looking over some code, and all the calls to a function returning a string are assigned to a reference. The function prototype something like:
std::string GetPath(const std::string& top);
and it's used as
std::string& f = GetPath(cw);
or
const std::string& f = GetPath(cw);
Why would one use a reference here ... | If the function returned a reference (which it doesn't) then you might want to assign the return value to a reference in order to keep "up to date" with any changes to that object. The reference returned would have to be to an object with a lifetime that extended beyond the end of the function.
Or (if the returned refe... |
4,684,719 | 4,684,860 | Unusual use of new in historical code. What does it mean? | I am just porting some old code:
#define NewArrayOnHeap(TYPE, COUNT, HEAP, NEWPTR, ERROR) \
((*(NEWPTR) = new ( #TYPE "[" #COUNT "]", __alignof(TYPE), (HEAP), &hr, (ERROR)) TYPE[COUNT] ), hr)
It looks like the original was supposed to define their own magical new operator. I am curious about this usage.
Example usage
... | The section you want to look at is §5.3.4/11-12, paraphrased here:
The new-placement syntax is used to supply additional arguments to an allocation function. If used, overload resolution is performed on a function call created by assembling an argument list consisting of the amount of space requested (the first argume... |
4,684,752 | 4,684,974 | How to link to .lib produced by project in same VC++ 2010 solution | I have a VC++ 2010 solution with multiple project, one of which is a .lib produced by my desire to put some common code in a single place.
I'm now trying to get another of the projects, which is a normal console application, to link to this library. However, VS is complaining that it can't find the .lib even though I ... | In the properties_>Common Properties->Framework & dependecies of your executable you can add projects on which your executable is dependant of. After that you only need to adjust additional include paths of C++->General to let it find your include-file.
EDIT: I have an exe-project named AppTest and a lib-project Dummy.... |
4,685,150 | 4,685,205 | How is the memory of a class handled in C++? |
Possible Duplicate:
How are objects stored in memory in C++?
For example a C++ class:
class A{
int value;
void addOne(){
value++;
}
}
Will an instance of class A be loaded like this [pseudo code]:
[identifier of A]
[this is int value]
[this is void addOne(void)][value++]
Or like this:
[members identifier of A]... | You are asking if the member functions are stored in the instances of the class? No. Each instance uses the same functions, with it's[the instance's] address passed as the hidden parameter this.
|
4,685,220 | 4,685,258 | C++ cyclic inclusion issue | I have this file logger.hpp:
#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_
#include "event.hpp"
// Class definitions
class Logger {
public:
/*!
* Constructor
*/
Logger();
/*!
* Destructor
*/
~Logger();
/*!
* My operator
*/
Logger& operator<<(const Event& e);
private:
... | Get rid of the #include "event.hpp" in logger.hpp - the forward declaration of class Event should be enough if all you need is a reference to an Event object in the function prototype:
#ifndef _LOGGER_HPP_
#define _LOGGER_HPP_
// #include "event.hpp" // <<-- get rid of this line
class Event; // Forward decl
// Clas... |
4,685,610 | 4,685,710 | C++: Counting total frames in a game | Not a very good title, but I didn't know what to name it.
Anyway, I am counting the total frames (so I can calculate an average FPS) in my game with a long int. Just in case the game went on reallly long, what should I do to make sure my long int doesn't get incremented past its limit? And what would happen if it did g... | Average FPS throughout the length of an entire game doesn't seem to be a very useful statistic. Typically you will wish to measure peaks and valleys, such as highest fps / lowest fps and amount of frames spent below and above threshold values.
In reality though, I would not worry. Even if you were to just use a 32 bi... |
4,685,653 | 4,709,578 | Is there an easy way to setup a link seam with Visual Studio 2010's build system? | I used to have a static library which was imported by both my main program and my tests. However, I needed global variables inside of my static library to be constructed, and there's no way to force Visual Studio to do that.
What I'd like to do then is to have a project which compiles all the common C++ files, a projec... | I have done similar setup in VS2008, which I think still applicable for you in VS2010.
To start, I setup my project hierarchy as Build, ProductionCodeBase and TestCodeBase.
Common interface/headers are extracted into folder accessible by all projects.
Then in my "Build" project, I manually add object file(s) from Produ... |
4,685,812 | 4,685,985 | Printing an XML Document in Xerces-C | My problem is simple. I have a XercesDOMParser, so I can access through getDocument() to the DOMDocument stored in it.
I want to get the xml string representing the tree.
What is the correct call? I assume a valid operator/function is provided by the library.
| It's some time since I used Xerces-C but I would look at
http://xerces.apache.org/xerces-c/apiDocs-2/classDOMWriter.html
This takes care of the encoding and other problems (which are easy to overlook).
I'd look first at
virtual XMLCh * writeToString (const DOMNode &nodeToWrite)=0
Serialize the specified node a... |
4,685,862 | 4,686,030 | Equivalent of a python generator in C++ for buffered reads | Guido Van Rossum demonstrates the simplicity of Python in this article and makes use of this function for buffered reads of a file of unknown length:
def intsfromfile(f):
while True:
a = array.array('i')
a.fromstring(f.read(4000))
if not a:
break
for x in a:
y... | In order to disguise an ifstream (or really, any input stream) in a form that acts like an iterator, you want to use the istream_iterator or the istreambuf_iterator template class. The former is useful for files where the formatting is of concern. For example, a file full of whitespace-delimited integers can be read in... |
4,685,960 | 4,686,199 | Dependent Assembly Microsoft.VC90.CRT could not be found Error | I have a .NET application that references some C++ assemblies. My application requires the Visual C++ 9 runtimes to be installed on the machine to run. If I download and install the runtime setup vcredist_x86.exe everything works fine.
However I would like to know if it possible to just include the dlls that I need al... | The reason MS wants you to use the redist is that so many people messed up installing the dll's on their own in the past (Not checking version of already installed dll's, failing to update shared refcount etc)
Only windows 2000 supports stuffing the dll's in system32, XP and later requires the manifest (But it is still... |
4,686,058 | 4,687,326 | Opening the same file twice with different flags? | Can I open the same file twice (with CreateFileA), using different flags (in this case, one with FILE_FLAG_NO_BUFFERING, and one without)?
In detail, this is the case: During startup, I create a temporary file (with FILE_FLAG_DELETE_ON_CLOSE). I fill it up sequentially, and I don't want to worry about doing unbuffered ... | Just remember to include FILE_SHARE_DELETE in share mode. I think FILE_FLAG_DELETE_ON_CLOSE is the only flag that affects more than just "your" handle.
|
4,686,127 | 4,686,523 | Async wait on file descriptor using Boost Asio | I'm trying to integrate D-Bus with my boost::asio application.
D-Bus has an API that enumerates a set of Unix file descriptors (mainly sockets but could also be FIFOs) to be watched.
When those descriptors have something to be read I should inform the D-Bus API so it can read them and do it's thing.
Currently I'm doing... | This is precisely the problem null_buffers was designed for.
Sometimes a program must be integrated
with a third-party library that wants
to perform the I/O operations itself.
To facilitate this, Boost.Asio
includes a null_buffers type that can
be used with both read and write
operations. A null_buffers op... |
4,686,193 | 4,686,240 | Converting a size_t into an integer (c++) | I've been trying to make a for loop that will iterate based off of the length of a network packet. In the API there exists a variable (size_t) by event.packet->dataLength. I want to iterate from 0 to event.packet->dataLength - 7 increasing i by 10 each time it iterates but I am having a world of trouble.
I looked for s... | Why don't you change the type of i?
for (size_t i = 0; i < event.packet->dataLength - 7; i+=10) { }
Try to keep the types of all variables used together the same type; casts should be avoided.
There is no format specifier for size_t in C++03, you have to cast to the largest unsigned integer type you can and print that... |
4,686,383 | 4,686,420 | error C2143. Why VC++ don't find my class? | I'm working in a project with several classes. All header files are into "include" folder, and all src files in another folder. But at this point, a class that has been working without problems is missing.
The code that produce the error is:
namespace render{
class CSprite2D
{
CTexture * m_texture... | just declare it, you use only pointer:
namespace render{
class CTexture; //forward declaration
class CSprite2D
{
CTexture * m_texture;
Of course, as comments suggets:
don't forget to include all necessary headers in your *.cpp files
use forward declarations to break-up circular dependencies (... |
4,686,445 | 4,686,490 | total class specialization for a template | lets say i have a templated class
template <typename T>
struct Widget
{
//generalized implementation
}
but i wanted to totally specialize..
for a template that accepted a parameter?
template <>
struct Widget< TemplateThatAcceptsParameter<N> >
{
//implementation for Widget for TemplateThatAcceptsParameterN
... | This is called a partial specialization and can be coded like this:
template <typename T>
struct Widget
{
//generalized implementation
};
template <typename N>
struct Widget< TemplateThatAcceptsParameter<N> >
{
//implementation for Widget for TemplateThatAcceptsParameterN
//which takes parameter N
};
It wor... |
4,686,507 | 4,686,536 | Lambda Expression vs Functor in C++ | I wonder where should we use lambda expression over functor in C++. To me, these two techniques are basically the same, even functor is more elegant and cleaner than lambda. For example, if I want to reuse my predicate, I have to copy the lambda part over and over. So when does lambda really come in to place?
| 1) It's trivial and trying to share it is more work than benefit.
2) Defining a functor simply adds complexity (due to having to make a bunch of member variables and crap).
If neither of those things is true then maybe you should think about defining a functor.
Edit: it seems to be that you need an example of when it w... |
4,686,538 | 4,686,563 | Free memory after remove_if | In the following example I remove from list some elements in the range for which the application of pr2 to it return true.
m_list.remove_if(pr2(*tmp_list));
It seems to me it is necessary to delete this objects, which was removed above, becase when I create it I use "new" (new CRectangle()). How I can do this? I don't... | Well you could:
HACKISH: delete the object in the predicate.
ANNOYING: Stay away from remove_if and implement everything it does on your own except add the delete.
BETTER: use RAII objects rather than raw pointers. Some sort of smart ptr in other words.
|
4,686,975 | 11,018,151 | std::map with efficient nth element access | I've got a set of data that I need to store in an ordered map (i.e. with efficient insertion, deletion, and locating items by key), but I also need to be able to find the nth element without walking through the entire map (there may sometimes be tens of thousands of items in it).
I know of one way to do it: use a red/b... | This is my answer of other question considering similar issue.
associative / random access container
I guess this might also apply to your question.
I have been looking for such a data structure for a long time.
Recently, I found quite promising library which has all the functionality that you are looking for.
See the... |
4,687,041 | 4,688,226 | Initialize unnamed struct pointer/array | struct A
{
int member1;
int member2;
struct B
{
int member3;
int member4;
} *b;
};
How can I initialize A and at the same time create an array of B's to fill the b field? I want a static variable, so preferably function calling.
I tried this but it does not work (I didn't think it w... | You have tagged this with both C and C++; the following answer is for C.
In C89, you can do:
static struct B a_b_init[] = { {3, 4}, {5, 6} };
static struct A a = {
1,
2,
a_b_init
};
In C99, you can use a compound literal, which has very similar syntax to your attempt:
static struct A a = {
1,
2,
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.