question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,590,548 | 3,597,386 | Concurrent access to a large collection of items | I'm working on a simulation project using c++ on both windows and linux.
There will be several thousand objects (Perhaps 3000-5000) in the simulation. In plan to have several threads performing actions on the objects so that it makes good use of multi core machines, for example one thread handling movement and location... | Instead of having the threads perform different actions on the objects, why not have each thread work on different objects? It sounds like you're doing particle collisions. I worked on a project similar to this, although mine wasn't threaded. But if you can group your objects into 'spaces', each thread can work on its ... |
3,590,550 | 3,590,681 | Detect memory leaks in dbx with new and delete operators | I'm very interested in using Sun Studio to detect memory leaks in C++ applications with dbx debugger but I think this debugger only shows memory leaks produced by malloc/realloc and free; I'm not sure about this but I've tried with a C++ program and I've obtained no memory leaks. In this case, I'd try Valgrind. If I've... | Well some points which you need to make sure,first,the application you traces do have any memory leak.if not then profiler won't show anything.If there is a leak and profiler is not capturing then need to check how you doing it. So valgrind is another best option you can try.So when you say "something wrong (high possi... |
3,590,727 | 3,590,780 | Design choice when implementing an EXE in a web execution model | I'm designing a component to be run as a backend of a website. The component will take care of some AI logic, and I'm building it under C++. Would it be best if I let each session start a new EXE address space, or the EXE would be up and running and each session will start a new thread?
Or is there is any better sugge... | I would be better to keep a process alive and create a new thread for each 'session': if you are looking for good performances under heavy load, starting a new process (fork, initialization of your app, etc.) will be really slow and can constitute a bottleneck.
Compared to that, creation of a new thread (in user space)... |
3,590,804 | 3,590,856 | Facebook puzzle error: throws it's automated mail regarding build/run error | I solved the problem (Hoppity) as given on Facebook Puzzle Page. I solved it in c++ language (using g++ compiler) and mailed the .cpp file as an attachment to the mentioned e-mail address. I didn't zip the file. After few hours I received a mail regarding run/build error. Can anyone please help me with this. Where m I... | What strikes me is that you do not take the name of your input file from the command line like the Hoppity puzzle demands. Instead, you read input from some "a.in" file.
Furthermore, you're expected to write the results to STDOUT, not some "output.in" file.
|
3,590,880 | 3,590,904 | Can we create a VC++ executable which will work natively on both 32 bit and 64 bit Windows? | Is there any way to build a VC++ project so that the dll/exe created by it will work as a 32 bit application on a 32 bit Windows OS and as a 64 bit application on a 64 bit Windows OS (not in WOW64).
I know that is possible for C# applications using the /ANYCPU option.
| The CLR has special loader support for the /ANYCPU option.
If you really want to do this for native, the best way to do it is to:
Build your binary for both 32- and 64-bit
As part of building the 32-bit binary, include the 64-bit binary as a resource
On 32-bit machines, just run the 32-bit binary
On 64-bit machines, w... |
3,591,024 | 3,591,068 | Typedef (alias) of an generic class | is it possible in C++ to create an alias of template class (without specifying parameters)?
typedef std::map myOwnMap;
doesn't work.
And if not, is there any good reason?
| In C++98 and C++03 typedef may only be used on a complete type:
typedef std::map<int,int> IntToIntMap;
With C++0x there is a new shiny syntax to replace typedef:
using IntToIntMap = std::map<int,int>;
which also supports template aliasing:
template <
typename Key,
typename Value,
typename Comparator = std::less... |
3,591,146 | 3,591,399 | Operator precedence in boost::spirit? | I made some tests using the spirit mini_c sample. Unfortunately it does not keep the operator precedence as expected:
int main()
{
return 3 > 10 || 3 > 1;
}
evaluates to 0.
return (3 > 10) || (3 > 1);
returns 1
I tried to move the definition of "||" and "&&" to the very top in the constructor of
template <typena... | Confirmed, that's a bug in the mini_c example related to operator precedence. I committed a fix to SVN, which will be available in Boost V1.45. Here is what I changed in the header file mini_cb.hpp:
old code:
equality_expr =
relational_expr
>> *( ("==" > relational_expr [op(op_eq)])
| ("!=" > re... |
3,591,226 | 3,591,257 | Generate random keys | I was given task to generate random 80 byte keys and i have decided following strateges
in my computer sizeof(char)=1 so i have created array of english alphabetical letters
char *p=" ";
char a[0..26] and in cycle
for (int i=0;i<=80;i++){
*(p+i)+= a[(rand()+100) % 26];
}
but it does not work it sto... | Try this out:
#include <iostream>
#include <string.h>
#include <cstdlib>
using namespace std;
int main(){
// ensure the target has enough memory for the key and a null terminator
char p[81];
// this string will do as nicely as the character array
char a[] = "abcdefghijklmnopqrstuvwxyz";
// no +=... |
3,591,311 | 3,591,316 | else statement is seemingly ignored | void PacketRecord::determineAppProtocol()
{
if (ipProtocol == IP_PROTO_UDP)
{
std::istringstream ss(udpData);
std::string line;
if (getline(ss, line) && (line.find("SIP/2.0") != std::string::npos))
{
appProtocol = APP_PROTO_SIP;
}
else
{
... | You should replace
appProtocol == APP_PROTO_RTP;
by
appProtocol = APP_PROTO_RTP;
(no double equal sign)
The else statement is executed. But you are not assigning the value to appProtocol in it.
|
3,591,533 | 3,592,231 | Implementing "NOT" in boost::spirit mini_c | I tried to modify the mini_c example of boost::spirit to match to my existing vocabulary.
I therefore added a operator "NOT that should behave equal as "!":
unary_expr =
primary_expr
| ("NOT" > primary_expr [op(op_not)]) // This does not work
| ('!' > primary_expr [op(op_not)])... | With your change the small test:
int main()
{
return NOT 1;
}
parses successfully and returns 0. So it is not obvious to me what doesn't work for you. Could you provide a failing input example as well, please?
|
3,591,556 | 3,591,586 | Switch inside For loop - Getting weird results in Release mode | Is there anything speaking against a structure like to following. In Release mode, Visual Studio seems to ignore i < 10 and execute the loop without end. If I set a break point I see that i runs from 0 to 9 and stays at 9 in all further iterations. If I printf i, I get a error after the 10 iteration, because arr only h... | nothing wrong with your example. Perhaps you have some accidental stack-overwriting or something like that in other parts of your code that introduce weird side effects in that place (and no sense making debugging sessions)?
|
3,591,694 | 3,591,711 | Constraint - Derived Class must have a default Constructor | I want to Constraint that the Derived Class must have a Default Constructor.
I am currently thinking it in a perverted way
template <typename Derived>
class Base{
public:
Base(){
}
virtual ~Base(){
new Derived;
}
};
Another idea comes to mind is to keep a pure virtual create() method with no a... | Yes, there's a way in PHP LOL:
abstract class Base {
public final function __construct() {
$this->constructImpl();
}
abstract protected function constructImpl();
}
class Derived extends Base {
protected function constructImpl() {
/* implementation here */
}
}
Basically, you just ha... |
3,591,735 | 3,591,936 | Boost serialization compiling issue | I am using boost serialization on windows, and I wanted to test my code on linux (ubuntu) and unfortunately it does not compile.
#include <string>
#include <fstream>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/serialization/string.hpp>
#include <boost/serializa... | You've encountered the Most Vexing Parse. In your main method, change
MyClass obj();
to
MyClass obj;
also, on my Linux system, the link line is
g++ test.cpp -lboost_serialization
Note the underscore instead of dash, like in your example
g++ test.cpp -lboost-serialization
|
3,591,772 | 3,591,786 | Global Object not accessible to other source files C++ | I have an ErrorLog class, that is used to write and modify log files. I'd like to write to it before and after major events for debugging purposes and I only want to use one instance of the ErrorLog class for the entire application. I tried declaring an ErrorLog object as a global by placing ErrorLog exe_log; into a he... | You need a declaration in a header file and a definition in a source file.
foo.h:
extern ErrorLog exe_log; // declaration (note the "extern")
foo.cpp:
ErrorLog exe_log; // definition
bar.cpp:
#include "foo.h"
|
3,591,815 | 3,591,846 | Why does the compiler not resolve this call to a template function? | In below program why does the compiler generate an error for the call to the printMax template function and not the call to the printMaxInts function?
#include <iostream>
template<class A>
void printMax(A a,A b)
{
A c = a>b?a:b;
std::cout<<c;
}
void printMaxInts(int a ,int b)
{
int c = a>b?a:b;
std::cou... | In order for the compiler to deduce the template parameter A from the arguments passed to the function template, both arguments, a and b must have the same type.
Your arguments are of type int and double, and so the compiler can't deduce what type it should actually use for A. Should A be int or should it be double?... |
3,591,826 | 3,592,703 | Using Embarcadero Borland | As I'm more and more dissapointed with VS 2010 I'm trying to find some alternative and I was looking at Embarcadero's new edition of C++ env.
Is there any point of learning new (not popular I think) product when VS practically dominates market?
Thanks.
| I've been using both the Embarcadero Borland, now RAD Studio 2010, c++ and VS2008 every day for the last 6 months. My programming philosophy has always been to use the right tool for the project, no matter what that particular tool is. So a couple of my observations/opinions are -
Advantages
The WYSIWYG screen desig... |
3,591,832 | 3,591,909 | Perfect Forwarding in C++03 | If you have this function
template<typename T> f(T&);
And then try to call it with, let's say an rvalue like
f(1);
Why isn't T just be deduced to be const int, making the argument a const int& and thus bindable to an rvalue?
| This is mentioned as a potential solution in the document I linked in the recent C++0x forwarding question.
It would work fairly well, but it breaks existing code. Consider (straight from the document):
template<class A1> void f(A1 & a1)
{
std::cout << 1 << std::endl;
}
void f(long const &)
{
std::cout << 2 <<... |
3,591,842 | 3,593,107 | How to compare 2 volumes and list modified files? | I have 2 hard-disk volumes(one is a backup image of the other), I want to compare the volumes and list all the modified files, so that the user can select the ones he/she wants to roll-back.
Currently I'm recursing through the new volume and comparing each file's time-stamps to the old volume's files (if they are int t... | Part of this depends upon how the two volumes are duplicated; if they are 'true' copies from the file system's point of view (e.g. shadow copies or other block-level copies), you can do a few tricky little things with respect to USN, which is the general technology others are suggesting you look into. You might want t... |
3,592,116 | 3,592,326 | Draw on DeviceContext from COLORREF[] | I have a pointer to a COLORREF buffer, something like: COLORREF* buf = new COLORREF[x*y];
A subroutine fills this buffer with color-information. Each COLORREF represents one pixel.
Now I want to draw this buffer to a device context. My current approach works, but is pretty slow (== ~200ms per drawing, depending on the... | Under the circumstances, I'd probably use a DIB section (which you create with CreateDIBSection). A DIB section is a bitmap that allows you to access the contents directly as an array, but still use it with all the usual GDI functions.
I think that'll give you the best performance of anything based on GDI. If you need ... |
3,592,357 | 3,592,373 | String concatenation | Why it is possible to do
const string exclam = "!";
const string str = exclam + "Hello" + " world";
And not possible to do this:
const string exclam = "!";
const string str = "Hello" + " world" + exclam;
I know (although can't understand why) that it is not allowed to do:
const string str = "Hello" + " world" + "!";... | The + operator is left-associative (evaluated left-to-right), so the leftmost + is evaluated first.
exclam is a std::string object that overloads operator+ so that both of the following perform concatenation:
exclam + "Hello"
"Hello" + exclam
Both of these return a std::string object containing the concatenated string... |
3,592,378 | 3,592,452 | Is naming variables after their type a bad practice? | I'm programming C++ using the underscore naming style (as opposed to camel case) which is also used by the STL and boost. However, since both types and variables/functions are named all lower case, a member variable declaration as follows will lead to compiler errors (or at least trouble):
position position;
A member ... | The local meaning is rarely a good unique global description of the type:
cartesian_point_2d position; // rectangular, not polar coordinates
mouse_over(ui_entity entity); // not a business layer entity
xyz_manager& manager; // what's a manager without something to manage?
audio_system audio;
|
3,592,449 | 3,592,503 | swapping adjacent nodes in a Linked list | I have problems swapping adjacent nodes in a linkedlist.
for ex: input : 1->2->3->4->5->null
output: 2->1->4->3->5->null
bool swapAdjacent(node** head)
{
//1->2->3->4->null
//2->1->4->3->null
if(head==NULL)
return 0;
node* current = *head;
*head = (*head)->next ;
node* prev = NULL;
cout<<"head val "<<(*hea... | Why so complicated?
int swapAdjacent(node** head) {
if (!*head || !(*head)->next)
return 0;
node* const sw = (*head)->next;
(*head)->next = sw->next;
sw->next = *head;
*head = sw;
swapAdjacent(&(sw->next->next));
return 1;
}
Edit: changed return value.
|
3,592,550 | 3,592,566 | C++ Single Header File Structure | I want to speed up the build time of my c++ project, and I am wondering if my current structure may cause unnecessary recompilations.
I have *.cc and corresponding *.h files, but all my *.cc files include a single header file which is main.h.
In main.h, I include everything necessary and extern global variables and dec... | It depends. If main.h is seldom modified, you could use precompiled headers, which will greatly improve compilation time.
On the other hand, if main.h is regularly used, it's probably not a good design.
An additional problem introduced by putting everything in one include file is that it doesn't really promote structu... |
3,592,557 | 30,988,141 | Optimizing away a "while(1);" in C++0x | Updated, see below!
I have heard and read that C++0x allows an compiler to print "Hello" for the following snippet
#include <iostream>
int main() {
while(1)
;
std::cout << "Hello" << std::endl;
}
It apparently has something to do with threads and optimization capabilities. It looks to me that this can surpri... |
Does someone have a good explanation of why this was necessary to allow?
Yes, Hans Boehm provides a rationale for this in N1528: Why undefined behavior for infinite loops?, although this is WG14 document the rationale applies to C++ as well and the document refers to both WG14 and WG21:
As N1509 correctly points out... |
3,592,580 | 3,592,624 | Problem with Inheritance | This is a fragment from "Exceptional C++" Item 24, Solution, first bullet from the bottom of the page:
Never use public inheritance to implement "IS-ALMOST-A." I've seen some programmers, even experienced ones, inherit publicly from a base and implement "most" of the overridden virtual functions in a way that prese... | The point is that the semantics for the Square class are different from those of the Rectangle class. Say you have a general utility function like this:
void doubleArea(Rectangle &rect) {
rect.setWidth(rect.getWidth() * 2);
}
The intention is that a call to that function will double the area (width × height) of the ... |
3,592,648 | 3,592,690 | C++ Weird Diamond inheritance issue | I have this
A
/ \
B C
\ /
D
A has a pure virtual function, prototyped as:
virtual A* clone(void) const = 0;
B and C virtually inherit from A ( class B: public virtual A, class C: public virtual A)
B has the virtual function, prototyped as:
virtual B* clone(void) const {};
C has the virtual func... | avoid diamond inheritance? ;->
anyway, here is sample (really sample - don't cast like that)
// ConsoleCppTest.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "iostream"
class A {
public:
virtual void* clone() = 0;
};
class B: public A {
public:
virtual void* clone()... |
3,592,753 | 3,592,761 | C++ Specify Headers Include Directory in Code | Is there a way to specify include directories in the code, perhaps via a #pragma?
I have my project setup as "src/" and "include/" folders. I am trying to compile in Visual Studio 2010, but I don't want to set it up in the project settings.
Is there another way to allow it to compile instead of having to specify the in... | The Correct(tm) way to specify search directories is with compiler flags. In Visual Studio you do this by playing with the project settings, or its compiler's /I commandline parameter.
|
3,592,903 | 3,592,934 | How to write handles for classes that don't have clone() member? | I'm following an example in Accelerated C++ and writing a simple Handle class that will act as a smart pointer. This uses the virtual ctor idiom using a virtual clone() function. So far so good. But what to do when I want to use my Handle for classes that I don't control that don't provide clone()?
The method suggested... | The solution to this problem is to simply not write Handles for these kinds of classes. No. Really.
auto_ptr (deprecated as of C++11) never needs to clone the underlying object, because auto_ptr never copies the object. An auto_ptr only ever has one copy of the object, and when the auto_ptr is copied, control of the ob... |
3,592,968 | 3,592,981 | Have I managed the memory correctly here? (simple C++ stack) | I'm a complete noob with dynamically allocated memory. Will this have a memory leak or any other memory problem?
#include <iostream.h>
template <class T> class stack
{
struct node
{
T value;
node* next;
};
public:
stack()
... | I don't see any memory management errors -- but I do see several other kinds of errors. For example, what happens when T is something other than int? :)
Also, implementing a stack as a linked list is wasteful and will perform relatively poorly when compared to a deque or vector implementation like that used by std::sta... |
3,593,032 | 3,593,047 | Calling friend function defined in struct requires forward declaration? | While reading Karlsson's Beyond the C++ Standard the author defined the friend function intrusive_ptr_add_ref in the body of class reference_counted (see pg 36). That function is called automatically using Argument Dependent Lookup at the proper time.
Never having seen friend functions defined in the body of a class, ... | Yes, this behaviour is standard. The relevant part of the standard is 7.3.1.2 [namespace.memdef] para 3:
If a friend declaration in a non-local class first declares a class or function the friend class or function is a member of the innermost enclosing namespace. The name of the friend is not found by simple name look... |
3,593,135 | 3,593,164 | Are the C formatted I/O functions (printf, sprintf, etc) more popular than IOStream, and if so, why? | I've been looking through a lot of code made by others lately and happened to notice everyone uses "printf" style C functions a lot, but the C++ functions learned in school (cout, specifically) don't seem so popular.
Is this a valid observation, and is there a reason for this?
Convention?
Thanks,
R
| Personally, I use printf over the iostream stuff (like cout) because I think it's clearer.
When you do formatting with iostream, you have to << all sorts of weirdness like setiosflags and setf. I can never remember which namespace all this stuff lives in, let alone what it all does. Even when I do, I'm disappointed wit... |
3,593,283 | 3,602,257 | Displaying pixmap with glDrawPixels | I've written a small example program using OpenGL and GLUT to display a 2-by-2 grid of four colored squares using the glDrawPixels function. Unfortunately, I've found that:
The colors in the grid are not being displayed properly; and
When the glPixelZoom function is passed negative arguments to rotate the pixmap, no... | After some experimentation, I think that I've found a solution that appears to be suitable for my own purposes. First, given the example code in my question above, it appears that the pixmap needs to be passed to the glDrawPixels function as an array GLubyte color[2][2][4] with an alpha channel. As mentioned by Vaay... |
3,593,332 | 3,593,394 | Is there a good way to allow a function to write to the console, a file, or a memory buffer without using the IOStream library? | Comments on my answer here have made me think about how one might implement the same pattern I've been doing with C++ streams. Specifically, I need to be able to have a function which can write to the console, a file, or a string/memory buffer. I don't need most of the formatting features and such that IOStreams provid... | Totally untested, but you get the idea.
struct stdio_stream {
enum { invalid_t, file_t, str_t } which;
union {
FILE *file_p;
string *str_p;
};
int printf( char *fmt, ... );
int scanf( char *fmt, ... );
stdio_stream() : which( invalid_t ), file_p( NULL ) {};
// etc
};
int... |
3,593,427 | 3,593,562 | Using a for statement to create variables from array | I have a set of numbers that I need to pass from a function to a few other functions before it is actually used. I figured an array is a good way to do this, however I can't remember how to do what I want to do. The code looks like this
int set1; // variables that hold settings
int set2;
int set3;
cout << "Setting 1"... | If the functions you're calling need to change the array content, Change your array decl to this:
int *(settings[3]) = {&set1, &set2, &set3}; //array that holds pointers to variables
Then change your loop to:
for(int i=0; i<3; i++)
{
*(settings[i]) = setting[i]; // should set set1 = setting[0]; etc
}
Not sure if I u... |
3,593,601 | 3,593,613 | covariant return type | $10.3/5
"The return type of an overriding
function shall be either identical to
the return type of the overridden
function or covariant with the classes
of the functions. If a function D::f
overrides a function B::f, the return
types of the functions are covariant
if they satisfy the following
criteria... | The warnings on lines 5 and 9 that the "type qualifier on return type is meaningless" are because non-class type rvalues are never cv-qualified.
Since the result of a function that returns by value is an rvalue and a pointer is a non-class type, the returned pointer is not cv-qualified, even if the return type says t... |
3,593,630 | 3,593,663 | Creating object in the heap | I'm using boost::ptree for parsing fils. The problem is that I can't create the object in the heap. All samples is only for stack.
#include <boost/property_tree/ptree.hpp>
ptree *tree_handle;
read_info("path", tree_handle);
I need this because the code is in a function and I have to return the ptree-object from it.
Er... | From what I can see, ptree does not seems to be recognized, are you sure the #include is alright or that ptree is realy what you meant?
|
3,593,681 | 3,593,686 | Type within namespace in c++ | Suppose I defined A::B::int, how can I refer to the standard C++ int inside A::B?
| You cannot have a typedef named int, even if it is in a namespace. int is a keyword.
Keywords are reserved for their specific uses and you cannot use them for any other purpose in your code.
|
3,593,687 | 3,593,698 | Two different values at the same memory address | Code
#include <iostream>
using namespace std;
int main() {
const int N = 22;
int * pN = const_cast<int*>(&N);
*pN = 33;
cout << N << '\t' << &N << endl;
cout << *pN << '\t' << pN << endl;
}
Output
22 0x22ff74
33 0x22ff74
Why are there two different values at the same address?
|
Why are there two different datas at the same address?
There aren't. The compiler is allowed to optimize any mention of a const to be as though you had written its compile-time value in there.
Note that the compiler is also allowed to generate code that erases your hard disk when you run it if you do nasty tricks lik... |
3,593,764 | 3,593,792 | C++: can an int be assigned a char*? | I am reading chapter 2 of Advanced Linux Programming:
http://www.advancedlinuxprogramming.com/alp-folder/alp-ch02-writing-good-gnu-linux-software.pdf
In the section 2.1.3 Using getopt_long, there is an example program that goes a bit like this:
int main (int argc, char* argv[]) {
int next_option;
// ...
do {
... | Neither C nor C++ have a type that can store "characters" as values with some dedicated character-specific properties. In that sense, there's no "character" type neither in C nor in C++.
In both C++ and C languages char is an integral type. It contains numbers. It is just a smallest (in terms of range) integral type. C... |
3,593,838 | 3,593,935 | Nested quantifiers in boost::regex | Is \d++ a valid regular expression in programming languages that don't support possessive quantifier?Is it equivalent to (\d+)+?
When testing it in Python,an error sre_constants.error: multiple repeat will be raised.In C#,it will throw a runtime exception:System.ArgumentException: parsing "\d++" - Nested quantifier +... | The above code throws an instance of boost::bad_expression with "Invalid preceding regular expression" for me.
Its a redhat linux system compiled with gcc 3.4.6 and boost 1_32.
|
3,593,944 | 3,594,009 | Two dimensional array allocation | i have following code for allocation two dimensional array
#include <iostream>
using namespace std;
int **malloc2d(int r,int c){
int **t=new int*[r];
for (int i=0;i<r;i++)
t[i]=new int[c];
for (int i=0;i<r;i++){
for (int j=0;j<c;j++){
t[i][j]=i+j;
}
}... | With an int ** you have lots of pointers to tiny (4 byte) memory spaces which is inefficient due to malloc overhead (every malloc implementation has an overhead, the minimum normally is sizeof(void*) AFAIK which in your case would mean there's at least a 100% overhead for all "cells").
As an alternative, you could use ... |
3,593,959 | 3,617,134 | Integrating Lua to build my GameEntities in my Game Engine? | I really want to add Lua Scripting to my Game Engine. I am working with Lua and bound it to C++ using luabind, but I need help to design the way I will construct my Game Entities using Lua.
Engine Information:
Component Oriented, basically each GameEntity is a list of components that are updated in a delta T interval. ... | I'd suggest using a composite structure instead for your game entities. Add objects inheriting from a common game entity component to each game entity as you encounter them while parsing the Lua configuration table. This task is a perfect candidate for the factory method. Note that composing your entities in this way s... |
3,594,045 | 3,594,060 | Converting a string with a hexadecimal representation of a number to an actual numeric value | I have a string like this:
"00c4"
And I need to convert it to the numeric value that would be expressed by the literal:
0x00c4
How would I do it?
| The strtol function (or strtoul for unsigned long), from stdlib.h in C or cstdlib in C++, allows you to convert a string to a long in a specific base, so something like this should do:
char *s = "00c4";
char *e;
long int i = strtol (s, &e, 16);
// Check that *e == '\0' assuming your string should ONLY
// contain hex... |
3,594,349 | 3,594,359 | C++ Too many destructors called so few objects | Here is the code (also at http://pastebin.com/yw5z2hnG ):
#include <iostream>
#include <vector>
using namespace std;
class X
{
public:
int i;
X();
~X();
};
X::X()
{
i = 1;
cout << "---constructor" << '\n';
}
X::~X()
{
cout << "***desctructor" << '\n';
}
int main()
{
vector<X> *vx = n... | If you define your own copy constructor you will see the other objects being constructed:
class X
{
public:
int i;
X(const X&);
X();
~X();
};
X::X(const X& x) : i( x.i )
{
cout << "---copy constructor\n";
}
// ... rest as before
The compiler will provide a copy constructor that performs no lo... |
3,594,728 | 3,594,749 | Overzealous method doing work without a call? C++ Glut initialization gone rogue | rookie C++ programmer here still.
I'm using VC++ VS2008 compiler and glut library. All working fine and up to date ( I know there's 2010 just cba because of XNA (C#) support reasons)
Ok this time I have a question that is code related but I can make the code work. What I can not do is figure out what is happening unde... | Why not stick a break point on your init code and then walk up the call stack to see where it's being called?
Step through it slowly and I would imagine you'll find the source..
Edit: keeping initialisation of things like libraries out of the constructor is good practice. Personally, I would just test that glut has bee... |
3,594,964 | 3,595,034 | Modulus operator changes |
$5.6/4 in C++03 states- "If both
operands are nonnegative then the
remainder is nonnegative;if not, the
sign of the remainder is
implementation-defined74).
where Note 74 is
According to work underway toward the
revision of ISO C, the preferred
algorithm for integer division
follows the rules defined ... | Truncation towards zero means converting a real number to an integer by selecting the next integer nearest zero. Equivalently, you write the number down, and ignore everything after the decimal point, whether the number is positive or negative.
Consider 11/4 = 2.75 -- if you truncate this towards zero, you get 2.
consi... |
3,594,973 | 3,594,991 | Output of the Program? | #include<stdio.h>
int fun(int, int);
typedef int (*pf) (int, int);
int proc(pf, int, int);
int main()
{
printf("%d\n", proc(fun, 6, 6));
return 0;
}
int fun(int a, int b)
{
return (a==b);
}
int proc(pf p, int a, int b)
{
return ((*p)(a, b));
}
// direct link of program : http://codepad.org/fBIPiHGT
| The program's output is:
1
Ok, so let's see what's going on there.
#include<stdio.h>
This line just include standard input/output functionality.
int fun(int, int);
This tells the compiler: Ok, we have a function named fun taking two int variables, returning an int.
typedef int (*pf) (int, int);
This installs kinda ... |
3,595,022 | 3,595,453 | window api for smtps | is there any windows api that can send mail using smtp along with attachment.
I have heard its not possible,and i have to use other socket methods,if its true how can I do that??
please suggest c++ or c solution only,no c# or java(like system.net.mail etc)
| This is one of those places that (at least in my experience) you're better off without libraries. Microsoft provides (at least) MAPI, Simple MAPI, and CDO as ways of sending email. Unfortunately, at least in my experience all of them (especially MAPI) are considerably more complex than doing the job on your own.
At lea... |
3,595,033 | 3,595,046 | Ensure camera position is always the center of the screen? | Given 2 functions Translate(x,y) and Scale(x), I want the camera's position to always be the center of the screen. There is also a scalefactor variable and by modifying it it either zooms in or out from the center of the screen. Given that I know the dimensions of the screen in pixels, how could I achieve this? Thanks ... | Something like this:
screen_coords = (world_coords - camera_world_coords) * camera_zoom + 0.5 * screen_dimension
|
3,595,174 | 3,595,220 | smart automatic C code generator with nested if in python | I'm generating automatic C++ code from python, in particular I need to select some events for a list of events. I declare some selections:
selectionA = Selection(name="selectionA", formula="A>10")
selectionB = Selection(name="selectionB", formula="cobject->f()>50")
selectionC = selectionA * selectionB # * means AND
th... | It's unlikely that a compiler could optimize this code. Partly because cobject->f() might have side effects the compiler can't see.
You could help in a minor way by declaring your bools as const.
Otherwise, it looks like you're already overloading operators to compose selections. So it shouldn't be too hard to make a... |
3,595,247 | 3,595,262 | Which data type to use for a very large numbers in C++? | I have to store the number 600851475143 in my program. I tried to store it in long long int variable and long double as well but on compiling it shows the error
integer constant is too large for "long" type.
I have also tried unsigned long long int too. I am using MinGW 5.1.6 for running g++ on windows.
What datat... | long long is fine, but you have to use a suffix on the literal.
long long x = 600851475143ll; // can use LL instead if you prefer.
If you leave the ll off the end of the literal, then the compiler assumes that you want it to be an int, which in most cases is a 32-bit signed number. 32-bits aren't enough to store that ... |
3,595,330 | 3,595,533 | copying sockaddr_storage to another sockaddr_storage changes address | Hey... As in a recent question (nobody did react on the last changes) I have a problem with assigning a sockaddr structure filled by recvfrom.
As I have been advised , I did change my sockaddr to sockaddr_storage and casted it in the last moment to be sure of having enough space for the address...
But the problem of
s... | Your copying appears to be correct (the memcpy, at least). I suspect you are misparsing the result. You can try using memcmp to verify that the copy was successful.
|
3,595,387 | 3,595,482 | Is metaprogramming being used in real-world c++ software projects? |
Possible Duplicate:
What's the use of metaprogramming?
I know that in C++, there are libraries providing metaprogramming facitlities, like Boost MPL.
But are they really useful in real-world C++ projects ( or just used in rare situations ) ? ( I have the feeling that metaprogramming code are weird and can generate ... | Of course it's useful. Have you ever used std::distance or std::advance? They use metaprogramming to do the right thing for bidirectional/random access iterators. (that is, repeated ++ or -- for bidirectional iterators, and += or -= for random access iterators).
TMP is most useful for libraries that need to do one thin... |
3,595,547 | 3,595,560 | Failling Qt application on Ubuntu | I have Ubuntu 10.04 and have the Qt library install. When I run the code
#include <QDir>
#include <QFileInfo>
#include <QtDebug>
int main( int argc, char **argv )
{
foreach( QFileInfo drive, QDir::drives() )
{
qDebug() << "Drive: " << drive.absolutePath();
QDir dir = drive.dir();
dir.... | g++ seems to not find Qt includes files.
You should add an include directory when compiling. and linked with the Qt library.
|
3,595,750 | 3,595,836 | g++ standards support | I am a bit puzzled reading this: Gcc 4.5 online manual --- Standards section.
They explain this
The original ISO C++ standard was published as the ISO standard (ISO/IEC 14882:1998) and amended by a Technical Corrigenda published in 2003 (ISO/IEC 14882:2003). These standards are referred to as C++98 and C++03, respecti... | gcc doesn't support the uncorrected standard, it's aiming at (although doesn't reach 100%) C++03 conformance. Technically, there is only one current standard of C++ and the version including TC1 is it. As it says "supports most of the changes in C++03. To select this standard... use one of the options -ansi or -std=c++... |
3,595,859 | 3,595,874 | "too many template-parameter-lists" error when specializing a member function | I would like to define some template member methods inside a template class like so:
template <typename T>
class CallSometing {
public:
void call (T tObj); // 1st
template <typename A>
void call (T tObj, A aObj); // 2nd
template <typename A>
template <typename B>
void call (T tObj, A aObj, B bO... | Please read a C++ template tutorial on how to give a template multiple parameters. Instead of
template<typename A> template<typename B> void f(A a, B b);
The way it is done is
template<typename A, typename B> void f(A a, B b);
Multiple template clauses represent multiple levels of templates (class template -> member ... |
3,595,937 | 3,595,978 | Combine multiple DLL's into 1 | I'm wondering if it's possible to combine multiple DLL's into 1. I'm currently working on a C++ project that is dependent on many dynamic link libraries,so would it be possible to combine them into 1 DLL file, and if so, how would I do that?
| Realistically, no. In theory, if you wanted to badly enough you could do something like disassembling all of them, then re-assembling all the separate files into object files, then re-linking those object files into one big DLL. Getting this to actually work would usually be non-trivial though -- there are likely to be... |
3,596,147 | 3,596,159 | C++ Modules - why were they removed from C++0x? Will they be back later on? | I just discovered this old C++0x draft about modules in C++0x.
The idea was to get out of the current .h/.cpp system by writing only .cpp files which would then generate module files during compilation, which would then in turn be used by the other .cpp files.
This looks like a really great feature.
But my question is:... | From the State of C++ Evolution (Post San Francisco 2008), the Modules proposal was categorized as "Heading for a separate TR:"
These topics are deemed too important to wait for another standard after C++0x before being published, but too experimental to be finalised in time for the next Standard. Therefore, these fea... |
3,596,258 | 3,596,437 | Newbie problem with QT C++ - Qimage dont work? | I am trying to do console application to read pixels from image:
#include <QtCore/QCoreApplication>
#include <QtGui/QImage>
#include <iostream>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QImage *img = new QImage("adadad.jpg");
//std::cout << "Type filename:" << std::endl;
img-... | It is possible to use QImage in a console application, you must make sure that QtGui is configured though. If you chose a console app, your .pro file might contain something like
CONFIG += console
QT -= gui
If that's the case, remove the QT -= gui line.
|
3,596,316 | 3,596,344 | Confused in using opensource 3rd party libraries | How do you integrate C or C++ open-source third party libraries in your projects? Do you copy all the files it comes with (I.e. README, makefiles etc) to a separate directory somewhere inside the project and build it using its configs? Or do you only get needed source files and headers from a source package? Or do you ... | The generic way is to put in your README and INSTALL that you depend on a library and that the user should download and install the shared library. Then link against that shared library at compile time.
Never put the source into your own application unless theres a good reason (like gnulib).
Your application should hav... |
3,596,349 | 3,596,361 | Getting type of an object | I'm trying to do something along these lines:
int var = 5;
std::numeric_limits<typeid(var)>::max();
but surprise, surprise it doesn't work. How can I fix this?
Thanks.
| You can use the type:
int the_max = std::numeric_limits<int>::max()
You can use a helper function template:
template <typename T>
T type_max(T)
{
return std::numeric_limits<T>::max();
}
// use:
int x = 0;
int the_max = type_max(x);
In C++0x you can use decltype:
int x = 0;
int the_max = std::numeric_limits<declt... |
3,596,523 | 3,597,067 | Is it possible to read an LLVM bitcode file into an llvm::Module? | I'm writing a compiler with LLVM. Each source file is compiled into an LLVM bitcode file. Eventually the linker links and optimizes all the bitcode files into one final binary.
I need a way to read the bitcode files in the compiler in order to access the type information. The LLVM documentation shows a class called Bit... | I looked through the source to the llvm-dis tool and found the function I was looking for:
Module *ParseBitcodeFile(MemoryBuffer *Buffer, LLVMContext& Context,
std::string *ErrMsg = 0);
from llvm/Bitcode/ReaderWriter.h.
|
3,596,622 | 3,596,747 | Negative NaN is not a NaN? | While writing some test cases, and some of the tests check for the result of a NaN.
I tried using std::isnan but the assert failes:
Assertion `std::isnan(x)' failed.
After printing the value of x, it turned out it's negative NaN (-nan) which is totally acceptable in my case.
After trying to use the fact that NaN != Na... | This is embarrassing.
The reason the compiler (GCC in this case) was optimising away the comparison and isnan returned false was because someone in my team had turned on -ffast-math.
From the docs:
-ffast-math
Sets -fno-math-errno, -funsafe-math-optimizations, -fno-trapping-math,
-ffinite-math-only, -fno-round... |
3,596,708 | 5,135,560 | Boost Phoenix: Binding to reference members of structures? | I would like to use Boost Phoenix to generate a lambda function for use in a std::find_if operation on a structure that contains reference-type members. A contrived example is as follows:
struct MyStruct
{
MyStruct() : x(0) {}
int& x;
};
std::vector<MyStruct> AllStructs;
// Search the array for an elemen... | Sorry that this is far too late, but for future reference, you can use a member pointer:
std::vector<MyStruct>::const_iterator it =
find_if(AllStructs.begin(), AllStructs.end(),
(&boost::phoenix::arg_names::arg1)->*&MyStruct::x == 5
);
|
3,596,935 | 3,596,959 | Several C++ classes need to use the same static method with a different implementation | I need several C++ classes to have a static method "register", however the implementation of register varies between those classes.
It should be static because my idea is to "register" all those classes with Lua (only once of course).
Obviously I can't declare an interface with a static pure virtual function. What d... | Based on how you've described the problem, it's unclear to me why you even need the 'virtual static method' on the classes. This should be perfectly legal.
class SomeClass {
static void register(void) {
...
}
}
class SomeOtherClass {
static void register(void) {
...
}
}
int main(int argc, char* argv[... |
3,596,990 | 3,597,053 | What's the graceful way of handling out of memory situations in C/C++? | I'm writing an caching app that consumes large amounts of memory.
Hopefully, I'll manage my memory well enough, but I'm just thinking about what
to do if I do run out of memory.
If a call to allocate even a simple object fails, is it likely that even a syslog call
will also fail?
EDIT: Ok perhaps I should clarify the ... | Well, if you are in a case where there is a failure to allocate memory, you're going to get a std::bad_alloc exception. The exception causes the stack of your program to be unwound. In all likelihood, the inner loops of your application logic are not going to be handling out of memory conditions, only higher levels of ... |
3,597,404 | 3,597,433 | C++ clock() function giving incorrect values | I was trying to program a Timer class (unaware that boost had one), then when that wasn't working, I tried to just output the value of clock(), using this code:
#include <ctime>
#include <iostream>
int main()
{
for(int i = 0; i < 50; ++i)
{
std::cout << std::clock() << " ";
}
return 0;
}
When I run the program,... | The clock() return value is specified in microseconds. But typical granularity of whatever low-level system call the clock() implementation uses is much lower. So it seems that on your system the granularity is 10ms. Also note that clock() does NOT measure real time - it measures CPU time used by the program. So the ti... |
3,597,530 | 3,603,270 | Good free profiler that supports MingW32 please? | I asked in another thread, how to profile my stuff, and people gave me lots of good replies, except that when I tried to use several of free profilers, including AMD Codeanalyst for example, they only support Microsoft PDB format, and MingW is unable to generate those.
So, what profiler can help me profile a multi-thre... | If you don't want to use gprof, I'm not surprised.
It took me a while to figure out how to do this under GDB, but here's what I do. Get the app running and change focus to the app's output window, even if it's only a DOS-box. Then I hit the Control-Break key (while it's being slow). Then GDB halts and I do info threads... |
3,597,584 | 3,597,643 | C - printf and scanf - How do I terminate input? | I am working on a simple application written in C. I am working in a Unix environment.
My application is doing some simple I/O. I use printf to prompt the user for some input and then use scanf to get that input.
The problem is, I don't know how to tell my application that I am ready to proceed after entering in a valu... | Check the return value from scanf(). Once it has gotten EOF (as a result of you typing control-D), it will fail each time until you clear the error.
Be cautious about using scanf(); I find it too hard to use in the real world because it does not give me the control over error handling that I think I need. I recommend... |
3,597,602 | 3,597,608 | What C++ projects should I start? | I'm a high school student, and I have a decent amount of programming experience (HTML, Javascript, PHP, Actionscript 3.0). I know C++, but unlike the other languages I know, I have never actually made any decent sized projects with it. I am puzzled at what kind of project I should start, as there are so many things you... | Find some open source projects and offer your help. You get to see other's code and have a goal on what to develop.
Find something that interests you. That will keep your attention the longest.
|
3,597,660 | 3,597,677 | Cannot Convert struct** to const POINT* for argument? | hi everyone im using winapi and i want to do a square in 3d im defining the points to unite them with a function and ive been trying 3 functions but i cant make them work i get the same error in the 3 of em >.<
The Error says
In member function `void Cube::Show(void)':|
cannot convert `const Cube::Show()::POINT3D*... | You're passing in your version of POINT the POINT3D not the POINT from the global namespace. Of the structures are the same just cast. In addition you're passing in an array of arrays not a single array.
So I suggest you revist the API to see what it needs - something like
Polygon(_hdc,((POINT *) (Faces[0])),6) perhap... |
3,597,693 | 3,597,707 | How does the pimpl idiom reduce dependencies? | Consider the following:
PImpl.hpp
class Impl;
class PImpl
{
Impl* pimpl;
PImpl() : pimpl(new Impl) { }
~PImpl() { delete pimpl; }
void DoSomething();
};
PImpl.cpp
#include "PImpl.hpp"
#include "Impl.hpp"
void PImpl::DoSomething() { pimpl->DoSomething(); }
Impl.hpp
class Impl
{
int data;
public:
... | The main advantage is that the clients of the interface aren't forced to include the headers for all your class's internal dependencies. So any changes to those headers don't cascade into a recompile of most of your project. Plus general idealism about implementation-hiding.
Also, you wouldn't necessarily put your im... |
3,597,754 | 3,598,084 | How to convert a float to a non standard encoding | I am writing a program that creates ICC color formats. These formats specify a data type called s15Fixed16Number which has a sign bit, 15 integer bits and 16 fractional bits. IEEE 754 32-bit floats have a sign bit, 8 exponent bits and 23 fractional bits.
I need to get input from a text box, and convert them into a s15F... | Assuming your C environment does 2's complement integers, then this is much simpler than it seems.
typedef long s1516; // 32bit 2's complement signed integer
s1516 floattos1516(double f) {
return (s1516)(f * 65536. + 0.5);
}
The representation is a fixed point value, with 16 bits of fraction. That is the same as ... |
3,598,067 | 3,598,180 | MultiCasting using UDP in C++ | I want to develop one client server App using Multicasting using UDP in c++
Any code snippet or ideas...
Thanks in Advance.
| Other possibility in my mind: Windsock.
|
3,598,556 | 3,598,562 | g++ warning: comparison of unsigned expression < 0 is always false | To compile my C++ code I use the -W flag, which causes the warning:
warning: comparison of unsigned expression < 0 is always false
I believe this was considered as a bug and was fixed on version GCC 4.3, but I'm using GCC 4.1
Code that is obviously offending here:
void FieldGroup::generateCreateMessage (const ApiEven... | You are testing if a positive value is below 0.
A size_t is unsigned, so at least 0.
This can never happen and the compiler optimize things out by just removing the test. The warning is here to tell you because if someone does that, it might be a mistake.
In your case, you might just remove the test, it should be fine.... |
3,598,775 | 3,598,894 | How to detect whether there is anything left inside a boost archive | Is there a way to detect whether there is anything left inside a boost archive after I read from it? I tried this piece of code:
const string s1("some text");
std::stringstream stream;
boost::archive::polymorphic_text_oarchive oAr(stream);
oAr << s1;
boost::archive::polymorphic_text_iarchive iAr(stream);
string s2;
iA... | stream.eof() may be set when you tried to read something after end of file, not when you have read last byte from it.
Enabling exceptions in stream and trying to read until exception thrown may work.
|
3,598,811 | 3,599,046 | Removing duplicates in an array while preserving the order in C++ |
Possible Duplicate:
How to make elements of vector unique? (remove non adjacent duplicates)
Is there any standard algorithm which is provided as part of STL algorithms which can remove duplicates from an array while preserving the order. For example, if I have an array like int a[] = {2,1,3,1,4,2}; after the removal... | There is no standard algorithm for this, but it's fairly easy to implement. The principle is to keep a std::set of the items you've seen so far, and skip duplicates while copying to a new vector or array. This operates in O(n lg n) time and O(n) memory. If you're using C++0x, you can get it down to O(n) time by using s... |
3,598,833 | 3,598,916 | How does it work, Test *pObj = new Test(); as constructor does not return anything | I am trying to get better at c++.
I have a Test class and below code in main().
Test *pObj = new Test();
If we debug by steping one by one instruction, First it goes to new function to allocate memory, then it calls constructor. Then it comes back to main() function. As we all know, constructor does not return anythin... | When you use a new expression the compiler generates code to allocate memory and then call the constructor on the allocated memory to create a new object. If successful, it returns a pointer to the new object.
Constructors have no return values, the compiler just adds a call to the constructor on a piece of memory wher... |
3,599,018 | 3,599,101 | Operator Overloading with Chaining | I would like to overload << operator for chaining like below
function1(param1, param2)<< obj2 << obj3 << string4
function1 would return an object.
What I want to do is after string4, I need to call a function using param1, param2.
My questions will be
How do I know string4 is the last parameters in the expression an... | You can return a helper object from function1 by value which calls function2 in it's destructor.
Consider this example:
#include <iostream>
using namespace std;
void function2( int i, int j ) {
cout << "function2 called with " << i << " and " << j << endl;
}
struct Function2Caller {
Function2Caller( int param1... |
3,599,197 | 3,599,447 | event driven simulation with objects | i am writing an event driven simulation program. i have 3 subclasses that inherit 1 base class. i need to generate those three randomly and each subclass will go through different event path (sorry its a bit hard to describe what i meant), ill give an example:
let say we have a car park simulation at a mall, we have th... | This might lead u there
VehicleControl::VehicleControl() {
mapOfFreq["Car"] = 6; // based on 10 per 60 sec
mapOfFreq["Bike"] = 200;
.....
}
vehicle* VehicleControl::getVehicle() {
time_t t = time();
if (t - mapOfCreatedTime["Car"] > mapOfFreq["Car"]) {
mapOfCreatedTime["Car"] = t;
return new Car();
}
... |
3,599,588 | 3,599,594 | Stumped at a simple segmentation fault. C++ | Could somebody be kind to explain why in the world this gives me a segmentation fault error?
#include <vector>
#include <iostream>
using namespace std;
vector <double>freqnote;
int main(){
freqnote[0] = 16.35;
cout << freqnote[0];
return 0;
}
I had other vectors in the code and this is the only vector that seems... | You're accessing vector out of bounds. First you need to initialize vector specifying it's size.
int main() {
vector<int> v(10);
v[0] = 10;
}
|
3,599,638 | 3,600,460 | How can I wrap std::wstring in boost::asio::buffer? | I am writing a client server application using boost::asio. I want to transfer a structure from a client to the server. The struct has a few std::wstrings in it. How do I encode the structure in boost::asio::buffer?
| Typically I use boost::asio::streambuf for serializing structures.
Message.h
#ifndef MESSAGE_H
#define MESSAGE_H
#include <boost/serialization/string.hpp>
#include <string>
struct Message
{
std::string _a;
std::string _b;
template <class Archive>
void serialize(
Archive& ar,
... |
3,599,645 | 3,599,672 | Pointer addition vs subtraction | $5.7 -
"[..]For addition, either both operands shall have arithmetic or enumeration type, or one operand shall be a pointer to a completely defined object type and the other shall have integral or enumeration type.
2 For subtraction, one of the following shall hold:
— both operands have arithmetic or enumeration type; ... | The difference between two pointers means the number of elements of the type that would fit between the targets of the two pointers. The sum of two pointers means...er...nothing, which is why it isn't supported.
|
3,599,695 | 3,599,717 | Why isn't this method call virtual like I was expecting? | I want to ask what happen, when I use virtual functions without pointers ? for example:
#include <iostream>
using namespace std;
class Parent
{
public:
Parent(int i) { }
virtual void f() { cout<<"Parent"<<endl; }
};
class Child : public Parent
{
public:
Child(int i) : Parent(i) { }
virtual void f() { Par... | This effect is called "slicing."
Parent b = Child(2); // initializes a new Parent object using part of Child obj
In C++, the dynamic type may only differ from the static type for references or pointers. You have a direct object. So, your suspicion was essentially correct.
|
3,599,725 | 3,600,191 | Designing a string class in C++ | I need to design (and code) a "customized" string class in C++. I am seeking any documentation and pointers on design issues or potential pitfalls I should be aware of.
Links are very welcome, as are the identification of problems (if any) with current string libs (Qstring, std::string, and the others).
| Despite the critics, I think this is a valid question.
The std::string is not a panacea. It looks like someone took the class from a pure-OO and dumped it in C++, which is probably the case.
Advice 1: Prefer non-member non-friend methods
Now that this is said, in this hour of internationalization, I would certainly adv... |
3,599,806 | 3,599,833 | check for memory leak in c++ | I have a code of about 10,000 lines. I have to maintain a track for new and delete statements to check and avoid memory leaks. i can use new libraries or functions but i can't change the code. How can i do it? Please donot suggest for any memory cheking tool.
Any help would be appreciated.
|
i can use new libraries or functions but i can't change the code.
Link to a heap implementation, which implements the global new and delete operators, and which keeps track of how many times each one is called.
HI ChrisW, Thanks for your reply. I implemented your suggessted way. it is working but i also want to know... |
3,599,956 | 3,600,020 | Is it necessary to overload placement new operator, when we overload new operator? | I have below piece of code
class Test
{
public:
Test(){}
Test(int i) {}
void* operator new (size_t size)
{
void *p = malloc(size);
return p;
}
//void* operator new (size_t size, Test *p)
//{
// return p;
//}
};
int main() {
Test *p = new Test;
int i = 10;
new(p) Test(i)... | Usually no, since it's not often used. But it might be necessary, since when you overload operator new in a class, it hides all overloads of the global ::operator new.
So, if you want to use placement new on objects of that class, do; otherwise don't. Same goes for nothrow new.
If you've just changed the allocation sch... |
3,600,222 | 3,600,494 | Code for identifying programming language in a text file | i'm supposed to write code which when given a text file (source code) as input will output which programming language is it. This is the most basic definition of the problem. More constraints follow:
I must write this in C++.
A wide variety of languages should be recognized - html, php, perl, ruby, C, C++, Java, C#...... | You have a problem of document classification. I suggest you read about naive bayes classifiers and support vector machines. In the articles there are links to libraries which implement these algorithms and many of them have C++ interfaces.
|
3,600,244 | 3,600,286 | use sfinae to test namespace members existence | I was trying to figure out if it is possible to use sfinae to test namespace member existence.
Google is rather silent about it. I've tried the following code, but it fails.
namespace xyz{
struct abc{};
}
struct abc{};
struct test_xyz{
typedef char yes;
typedef struct{ char a[2]; } no;
template <class C> static... | No, that won't work. There is also no way to use SFINAE in such a way (this was last discussed on usenet for a compatibility test against some C++0x component). The C inside xyz::C is not related to the template parameter at all.
Remember that templates are not just macros. The parameter C denotes not just a piece of ... |
3,600,245 | 3,600,616 | FIFO Queue linked list implementation | Here is code in which I am trying to implement a queue using linked list:
#include <iostream>
#include <cstdlib>
using namespace std;
template <class Item>
class Queue{
public:
struct node{
Item item;node *next;
node (Item x){
item=x; next=0;
}
};
typedef node* link;
link he... | ON: The -> operator can be overloaded so the development environment cannot be sure what to do with it. You can do the following (temporarily or permanently) if you really want to have auto-completion.
// IMPORTANT. Make sure "head" is not null before you do it!
Node &headNode(*head); // Create a reference
headNode.ne... |
3,600,471 | 3,600,605 | Best NoSQL-way to store machinedata? | I'm looking for a NoSQL-way to store machinedata like information about tools, work pieces, products, operations and so on... Currently I'm concentrating on BerkeleyDB and need input from you guys, whether I should consider using another nosql-database which might fit better on my requierements. Data stored in this db ... | Berkeley db seems to be a good fit for your requirement
|
3,600,712 | 3,600,761 | About scope and lifetime | Quoting "The C++ programming language" (special edition, section 4.9.6, "Objects and Lvalues"), and as is well known:
[...] an object declared in a function is created when its definition is encountered and destroyed when its name goes out of scope
OK ! And in section 4.9.4:
A name can be used only in specific part ... | The code in your sample is indeed undefined behavior, and it will appear to work in simple examples like this. But the compiler may choose to reuse the slot used to store variable b. Or it may be destroyed as the result of data being pushed on the stack because of a function call.
|
3,600,862 | 3,601,173 | How to re-engineering design from source code using rational rose | I would like to create class diagram from existing source code using rational rose.
I have VC++ 6 MFC project and I installed Rational Rose Enterprise Edition Version 2003.06.16. Now I would like to re-engineering the project to create design(class diagram) from the source code. Pls help me step-by-step process to do t... | It's pretty simple. You create a new project, add a component (represents your app), specify the source files in the properties, click Reverse Engineer and Presto: A tangled mess. Then you start dragging things around, moving related groups to different views, etc.
I will caution you that you may be disappointed with t... |
3,601,154 | 3,601,237 | name lookup of 'iter' changed for new ISO 'for' scoping | I'm trying to compile the two files below, but get an error message from the compiler: gcc 4.3.3 (Linux)
The error is in the line signed with: LINE WITH ERROR
What I'm I doing wrong, how should I change it?
Luis
...............................
$ g++ -c b.h b.cpp
b.cpp: In function 'void calcularDesempPop(std::vector<I... |
$6.5.3/3 - "If the for-init-statement
is a declaration, the scope of the
name(s) declared extends to the end of
the for statement."
Therefore iter cannot be accessed outside the for loop scope. Check the semicolon immediately after the for loop. Most probably you did not intend it that way.
|
3,601,161 | 3,601,201 | Problem with leading zero's in a vector array of doubles | I'm tring to calculate the standard deviation of a vector of doubles (called A).
Now I have a function called StDev that will do this. However, the first
few elements of vector A are zero and I need to remove these. To do this I
create a sub-array and then pass this to my StDev function as follows:
std::vector<dou... | If you can modify your StDev function to take an iterator range instead of a whole container, you can do this quite easily:
template <typename ForwardIt>
std::iterator_traits<ForwardIt>::value_type
StDev(ForwardIt first, ForwardIt last) { /* ... */ }
// called as:
double stdev = StDev(Data.begin(), Data.end());
// o... |
3,601,295 | 3,601,316 | Why string string is allowed and int int is not allowed by Compiler? | I am just trying to check whether compiler allows type name as variable name.
When i tried
int int;
It reported an error saying
error C2632: 'int' followed by 'int' is illegal
But when i tried
#include <string>
using namespace std;
int main()
{
string string;
}
It didn't give any error.
Both string and ... | string is not a C++ reserved word, but int is, and a reserved word cannot be used as an identifier.
And its syntactically fine to have class name and object name to be same.
class test {};
int main() {
test test; // test is an object of type test.
}
|
3,601,431 | 3,603,609 | base class 'class std::vector<...>' has a non-virtual destructor | One of my C++ classes derives from std::vector so that it can act as a container that also perform custom actions on its content. Unfortunately, the compiler complains about the destructor not to be virtual, which I cannot change, since its in the standard library.
Am I doing the whole thing wrong (thou shall not deriv... | It can be safe to have a public base class with a non-virtual destructor but behaviour is undefined if someone allocates an instance of your class with new, refers to it with a vector<...>*, and then deletes it using that pointer without casting it back to a pointer to your class. So users of your class must know not t... |
3,601,487 | 3,602,313 | constraints when dynamically loading a shared object from another shared object? | I'm dynamically loading (whith dlopen()) a shared object (named libprofile1.so) from main.
In libprofile1.so I have defined factory function CreateProfile and class Profile. CreateProfile function creates an instance of Profile class and returns a pointer to it. Class Profile has a method pMethod.
In main, after l... | If you dynamically load a DLL you must make sure that it has no unresolved symbols.
The easiest way to do this is to link it against the other DLLs that it needs so that they load automatically rather than you having to load and resolve all dependencies manually.
So if libprofile1 always uses libdatasources make sure t... |
3,601,493 | 3,601,514 | C++ string reassigned, is the old string correctly freed? | I have a c++ class with a member that is a string, something like:
class Phone {
string name;
void foo()
{
name = string("new_name");
}
}
Now, within the function "foo", I reassign the string to "new_name". My question is:
What happens to the old, empty string? Is it correctly "freed"? Does it still occupy m... | Yes, std::string manages memory for you. (That's one of the reasons for its existence!) How it does that is an implementation detail (for example, it may use copy-on-write, reference counting, or deep copy semantics) but for the most part, std::string will always correctly free the memory if it is not needed anymore.
O... |
3,601,792 | 3,602,044 | Declare Before use in C++? | Following code does compile whereas name "aNumber" is not declared before use.
class A
{
A()
:aNumber(100)
{
}
void foo()
{
aNumber = 0;
}
int aNumber;
};
If above code compiles then why not following :-
A.
class Dummy
{
void foo(INT);
typedef int INT;
};
B.Defaul... | You're comparing apples and oranges. The following code is OK:
class A {
A() :aNumber(100) { INT bNumber = aNumber; }
void foo() { aNumber = INT(42); }
void bar(int bNumber = INT(1)) { aNumber = bNumber; }
int aNumber;
typedef int INT;
};
The problem is not what you declare, but where the declarat... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.