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 |
|---|---|---|---|---|
7,844,454 | 7,844,507 | Make data member accessible everywhere, but read-only | I'm just starting my own Windows API wrapper and I've run into an unfamiliar topic while rewriting a structure to include C++ features.
I'm turning this:
typedef struct _RECT {
LONG left;
LONG top;
LONG right;
LONG bottom;
} RECT, *PRECT;
into
#define RECT_POS 1
#define RECT_SIZE 2
typedef struct Wrap... | It is quite bad practice to expose your data members. It is also really bad practice to have multiple copies of the exact same information inside your classes. It is both inefficient and bug-prone.
You definitely need to use accessor functions.
That being said, you don't need to have getX(); - just x() would be fine.
I... |
7,844,548 | 7,846,199 | Variable declaration in 'if' expression follow-up | This is a follow-up to C++, variable declaration in 'if' expression
if( int x = 3 && true && 12 > 11 )
x = 1;
The rules (so far as I can tell) are:
can only have 1 variable declared per expression
variable declaration must occur first in the expression
must use copy initialization syntax not direct initializatio... | C++03 standard defines selection statement as:
selection-statement:
if ( condition ) statement
if ( condition ) statement else statement
switch ( condituion ) statement
condition:
expression
type-specifier-seq attribute-specifieropt declarator = initializer-clause
C++11 additionally adds the follow... |
7,844,651 | 7,844,914 | open source marching cubes algorithm in c++? | i am trying to use marching cubes to visualize molecular densities and i was wondering if there was a place on the web that has a open source libraries to do this. i have seen many people post their code online, but i don't want to "steal" code.
i know i can email them and ask for permission, which i might end up doing... | Take a look at VTK open source library. I used to use that before:
vtkMarchingCubes Class Reference
|
7,844,677 | 7,844,714 | Declaring a string array in GNU C++ | To me it seems like it should be so simple, but I just feel like I'm missing something.
I have in my header file a private variable _stoplist When I declared it in the header file the code looks just like this.
private:
std::string _stoplist[];
But when later in my function I decide to access this, it segfaults on... | You're getting an array out of bounds error because _stoplist doesn't have a size. You should either give it a size, and only access elements within that range, such as:
private:
std::string _stoplist[100];
now you should be able to index _stoplist[0] through _stoplist[99]. However a better solution would probably... |
7,844,915 | 7,845,147 | MS Visual Studio 2005 C++ exception handling | I have a C++ application built in MS Visual Studio 2005 that links to a 3rd party library. For a certain input, the application crashes in the 3rd party library (apparently somewhere in realloc.c; so has to be a memory issue of some kind). I ran in release because the input is huge. So I ran until it crashes and then c... | Have you tried catching the crash by calling SetUnhandledExceptionFilter?
|
7,845,012 | 7,845,026 | Why do class members have the same address as their object? | In the following cases, each member has a different name or entity so why are their addresses the same?
struct B { int x; };
struct A { B b; };
int main()
{
A obj;
cout << &obj.b.x << endl;
cout << &obj.b << endl;
cout << &obj << endl;
}
| Because a pointer to a struct always points to it's first member (as the struct is laid out sequentially).
In C, does a pointer to a structure always point to its first member?
(C1x §6.7.2.1.13: "A pointer to a structure object, suitably
converted, points to its initial member ... and vice versa. There may
be unn... |
7,845,149 | 7,845,661 | Designing Managed DLL (C++/CLI) for Static Lib | I am working with C++/CLI for C Library. I explored in the net about it. I got several links about it.
Mixed mode C++/CLI performance considerations - best practices
I am developing a C++/CLI DLL which will wrap a C static library.
There was one suggestion that I really wanted to discuss here is "One should not ... | If you have a regular C++ library (non-CLI), you should avoid turning on the 'CLI' compilation option for that library, for performance reasons.
Instead it is good practice to create a library that just has your wrapper classes in it. This library will of course be C++/CLI, and will create an assembly that can be ref... |
7,845,196 | 7,854,912 | Best Way to send strings to Arduino? | I'm working on a project for my computer science class that basically uses an Arduino board with an LCD as a "message board". The large-scale goal of my project is to have a program on a computer where one can enter a message, which will then be displayed on the Arduino screen. My big sticking point at the moment is ho... | Mitch's links should point you in the right direction.
A common way of sending and receiving strings from the host computer to the Arduino and back is using the Arduino's Serial library. The Serial library reads and writes a byte at a time over the connection to the computer.
The below code forms a String by appending ... |
7,845,386 | 7,962,220 | Are there good tips or tools for removing third party C and C++ libraries from a codebase? (OS X or Linux) | I am in the process of reducing and quarantining my usage of some libraries. Many existing programs I've written use these libraries directly. I would like the compiler (GCC and/or Clang in this case) or some tool to help me identify these uses across my codebase. In short, I would like to poison use of these libraries... | Is code base size really a good reason to not use something like find and grep? These will run significantly faster than compiling the projects.
If you're only worried about libraries that are linked in you can limit yourself to grepping through your build config files. You're talking OS X so maybe its just the xcode c... |
7,845,627 | 7,845,665 | Suggestion for parallelizing an application? | I have to parallelize some c++ application for my college project. But, I could not think of any application that is not very huge and can be parallelizes. I would like suggestions from you guys.
Please suggest me some serial application that I can parallelize. Please point me to some link where I can get code for some... | Do some Fourier-Transformation. There are gazillion good reasons to do one and it can be parallelized. Edith reminded me that if a Fourier is too complicated, do a Discrete Cosine Transform. Much easier to code. Just google "DCT" and you will find examples and explanations.
|
7,845,640 | 7,845,675 | Using a static pointer to a class memory mangement? | I have a class for stars in my game, I want them to use the same texture so I've come up with this code...
sf::Texture* Star::starTexture = NULL;
unsigned int Star::refCount = 0;
Star::Star() : starSpeed(0), starScale(0), locX(0), locY(0)
{
if (starTexture == NULL)
{
starTexture = new sf::Texture();
... | Yes, it'll mess up if you don't explicitly define copy constructor and copy assignment operator for you class.
STL containers like vector have copy-by-value semantics. When Star object is copied into a vector, the raw pointer inside it is copied. So you now have multiple pointers pointing to a single memory, which def... |
7,845,756 | 7,855,569 | open source C++ projects as an addon for Thunderbird | Could you will please tell me if there is open source C++ projects as an addon for Thunderbird? I need to develop one for e-mail processing. Any information on this subject is welcome. Thank you!
| Enigmail comes to mind. It has XPCOM components in C++.
|
7,845,807 | 7,845,877 | What should be my virtual function's prototype? | Let's say I have an abstract base class Base with a virtual function doSomething()
There are two derived classes, one of which takes no parameters in doSomething() while the other takes a structure and an integer as a parameter.
A function in another class (SomeClass) calls doSomething() using a Base* variable.
It als... | One way to do this would be:
class Base {
public:
Base();
virtual ~Base();
virtual void doSomething();
};
class DerivedOne : public Base {
public:
DerivedOne();
void doSomethingElse(int a,struct b);
};
class DerivedTwo : public Base {
public:
DerivedTwo();
virtual void doSomething();
};
Y... |
7,845,886 | 7,845,994 | Linking dll in Visual Studio | How can I add a .dll in Visual Studio 2010? I just cannot find the option there.
| On Windows you do not link with a .dll file directly – you must use the accompanying .lib file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies and add path to your .lib as a next line.
You also must make sure that the .dll file is either in the directory... |
7,845,979 | 7,846,145 | Wrapping C callback in C++/CLI | I have a static C library where I have non static call back function. The Client program that register this callback gets Video data from camera .
Now I am writing Wrapper(DLL) for this in C++/CLI.This Wrapper Dll will be used in C# application.
How to Implement the callback in C++/CLI so that C# code can register it ... | In C++/CLI, you can have static functions (with native C signature, which can work as a callback from a C library), calling managed delegates:
// MyDispatcherClass.h
#pragma once
public delegate void MyDelegateType();
public ref class MyDispatcherClass
{
public:
static MyDelegateType^ MyDelegate;
};
static void ... |
7,846,221 | 7,846,255 | C++ post-increment operator overload in iterators (compiling with -Wall -Werror) | I'm currently creating my own iterator for a b-tree, and I'm stuck on how to implement the post-increment operator without the compiler complaining.
The error message is as follows, and is expected (since I am doing exactly what the error message says)
cc1plus: warnings being treated as errors
error: reference to local... | The error is clear enough -
error: reference to local variable 'temp' returned
In your function, you return reference to temp, which is temporary object.
Maybe you need to return a copy(as you don't want to use new ). So, instead
template <typename T> btree_iterator<T>& btree_iterator<T>::operator++(int) {
you mayb... |
7,846,511 | 7,846,542 | no matching function for call to Foo::Foo | I believe this question has been asked before. I tried looking for it but still can't figure out the problem. I'd greatly appreciate any help I can get here. Thanks
I get the following error. I get an idea that I am not initializing the Vertex once I call the constructor of the Edge. But I can't seem to figure out how.... | Always use constructor initialiser lists to initialise data members — your Vertex has no default constructor, this is one of the cases where you absolutely must use an init list.
Edge::Edge(Vertex U, Vertex V) : U(U), V(V), edge_weight(...) { }
Vertex::Vertex(int x, int y) : x(x), y(y) { }
|
7,846,710 | 7,846,734 | Multiple instances of a class with constant variables use same memory for constants? | If I have a class that defines multiple constant variables like so...
class SomeClass {
public:
SomeClass() : SOME_CONSTANT(20), ANOTHER_CONSTANT(45), ANOTHER_CONSTANT2(25), ANOTHER_CONSTANT2(93) { }
private:
const int SOME_CONSTANT;
const int ANOTHER_CONSTANT;
const int ANOTHER_CONSTANT2;
cons... | If they are not static, then no, they will not be optimized out. Each instance will have space for all the constants. (In fact, I don't think the compiler is even allowed to combine them in any way.)
If you do declare them static, they are in global memory and not in each instance. So yes, it will use less memory.
EDIT... |
7,846,753 | 7,854,314 | how to create iterators for synthetic data? | I am making iterators using boost::iterator_facade<> for synthetic data. The data are only accessible by calling a function on a handle. The handle is wrapped into MyHandle. I have figured out that I need to use MyHandle for both Value and Reference template parameters. So the iterator declaration looks like this:
clas... | boost::function_input_iterator wraps a generator function in an iterator. Dereferencing the iterator calls the function and returns its result:
http://www.boost.org/doc/libs/1_47_0/libs/iterator/doc/function_input_iterator.html
|
7,846,796 | 7,846,909 | Windows Threading-C++ | I'm looking for an API on windows that enables to to create and kill threads at will. Also having ability to bind threads to cores. I was introduced to Win32 Threading API here.
However when I checked MSDN I see _beginthreadex(), and _endthreadex(). So I'm guessing there should be a call to _endthreadex everytime I cre... | Having thread created (such as with _beginthreadex) you need to let the thread exit gracefully as you never know if it is in the middle of something just now (having a lock on a certain resource - for instance). Still you have an option to blow it away with TerminateThread API any time.
SetThreadAffinityMask and friend... |
7,847,030 | 7,847,069 | Why can't a non-static variable reside in a header file? | Take for example:
// myheader.h
static int myStaticVar = 0;
// If we remove 'static' the compiler will throw linker error.
void DoStuff();
// and myheader.cpp, and main.cpp; etc
This is how I would explain it:
Static variables do not have external linkage, and when we compile
without 'static' we are "including" ... |
Why can't a non-static variable reside in a header file?
Because it breaks the One Definition Rule(ODR).
When you include the header file containing a non-static variable, the declaration of the variable gets pasted in each source file where it is included. Thus you end up having more than one definition of a va... |
7,847,336 | 7,847,379 | How to return "not found" when return value is const reference | I have a problem that when I use something like this:
const MyList& my_list = getListForThisRegion(/*region ID, ...*/);
I dont know what to return when no value is found.
My problem is that I would like to have a way to signal (when returning value from getListForThisRegion) "value not found" to the caller. If I was ... | There are two idiomatic ways to handle this:
Change your interface to return a type that has the ability to refer to nothing (e.g. a pointer that can be null, an iterator to end).
Or
Throw an exception if the item isn't found.
Returning a dummy object is a bit hacky, and you don't gain anything over returning a p... |
7,847,341 | 7,847,539 | C++ CRTP with parametized base class? | I am trying to use CRTP with a small variation. I have one derived class template and wish to apply this to multiple base classes. But this is either impossible or I just can't get the syntax right. The following code does not compile but hopefully illustrates what I want to achieve:
template <class Derived> struct ... | Your compile error can be solved by this:
Base<Wrapper<Base> >
You forgot the template arguments.
|
7,847,371 | 7,890,130 | WinINet InternetGetProxyInfo : error 1003 ERROR_CAN_NOT_COMPLETE | I'm trying to make an application compatible with the auto proxy API provided by the WinINet library in order to make local pac files work, and am stuck with the error ERROR_CAN_NOT_COMPLETE when trying to call InternetGetProxyInfo...
I have been following the post of Eric Loewenthal (dev @Microsoft so I hope his sugge... | After making sure it works on a new project, I traced the cause of my problem and the call to get the proxy infos starts failing after a call to OleInitialize. Now, there was a comment about it in here, but I didn't know what this guy was talking about (and God knows I wish I never knew) so it didn't help me back then ... |
7,847,442 | 7,848,707 | Prime number generation algorithm | Please look at the following and see if you could advise.
cout << "2" << endl;
cout << "3" << endl;
ofstream of("Primes.txt");
unsigned long prime = 0;
unsigned long i = 1;
for (i = 1; i < 100000; i++)
{
prime = ((i*2)+(i+1) + (i % 2));
of << prime << endl;
}
of.close();
return 0;
The partially completed for... | Eliminating numbers dividable by prime numbers (2,3,5,7 etc.) is a not soo bad idea when you look for a list of (small) prime numbers but you should use the newly found prime numbers too to be sure that the list contains only primes (not only 2,3,5,7 but also those passing: 11,13,17 etc.)
For bigger primes (you just ca... |
7,847,454 | 14,430,451 | How do I install the boost library to my MinGW compiler? | I'm compiling from the command line using g++ on a Windows MinGW installation. How do I get boost...conceptually or if it is easy...what do I need to download and install?
| I know this is an old question but for future reference for anybody coming to this page try this website,
http://nuwen.net/mingw.html
They have done all the hard work so you don't have to. The most recent distribution on this page has boost 1_52_0 (which is the latest version on the boost website as I'm writing this) i... |
7,847,466 | 7,847,813 | Call C++ DLL in Delphi app | I want to call a function of a C++ DLL in my Delphi app.
The problem is that i get an access violation. But not while calling my C++ DLL but when I leave the Delphi function in which I do that.
Error message (shortened):
Access violation at 0x7445c9f1: Reading from address 0x00000000.
My C++ method is like that:
extern... | Sounds like SetName uses the wrong calling convention, try using cdecl;
Something like this:
var
SetName : procedure(nameArg: PChar); cdecl;
Otherwise your stack will be messed up.
|
7,847,525 | 7,847,545 | Explanation of this new() statement | I am reviewing a section of C++ code an I came accross this statement block:
static void Vector3DefaultConstructor(Vector3 *self)
{
new(self) Vector3();
}
I have not come accross the new operator being used in this way before. Can someone explain why new is being called in this way?
| This is called "placement new". By default, it does not allocate memory but instead constructs the object at the given location (here, self). It can, however, be overloaded for a class.
See the FAQ for more info.
The correct way to destroy an object constructed using placement new is by calling the destructor directly:... |
7,847,789 | 7,850,758 | reverse_iterator adapter | I'm trying to implement a reverse-iterator adaptor for my iterator and const_iterator classes with a little bit of trouble. If anyone could guide me through this, that would be greatly appreciated!
The idea is that I should be able to create a reverse-iterator from my rbegin() and rend() function calls
reverse_iterator... | reference and pointer are dependent names, so you have to use
typename I::reference operator*() const;
typename I::pointer operator->() const;
In addition, the constructor should accept just the I.
However, there is no need to write this class at all. The standard library has reverse_iterator for this. Or if you are n... |
7,847,835 | 7,847,909 | How to configure Crypto++ in Eclipse? | I want to use Crypto++ in Eclipse.
I've installed it correctly but I dunno why it cannot find the path.
using namespace CryptoPP;
Symbol CryptoPP cannot be resolved
and if I use #include "aes.h", for example is an unresolved inclusion.
How can I solve this?
| You have to set the include paths for your project.
Assuming you are using CDT go to "Project->Properties->C/C++ Build->Settings" and now in your configured compiler to "Includes" and add the path to your library. The same has to be done for your linker with "Libraries".
|
7,847,891 | 7,848,007 | Unable to iterate through template map. How to deal with this error? | I have a graph class that employs two dimension vertices using a map with another map nested inside, as such(V is my template):
map< V , map< V , int> > vertices;
Defining an iterator as such seems to be ok:
typename map< V, map< V , int>::iterator i;
However when I try to use that iterator, like this i = vertices.b... | The member function dump(), inside which you write i = vertices.begin(), is a const member function, which effectively makes vertices a const object, for it is a member of the class. So you need const_iterator:
typename map<V, map<V, int> >::const_iterator i;
//^^^^^ note this
It should w... |
7,847,900 | 7,847,993 | How to disable OpenMP directives in a nice way? | I have C++ code with OpenMP pragmas inside. I want to test this code both for multithread mode (with OpenMP) and in single thread mode (no OpenMP).
For now, to switch between modes I need to comment #pragma omp (or at least parallel).
What is the cleanest, or default, way to enable / disable OpenMP?
| Look into the compiler manual for the switch that disables OpenMP. For GCC, OpenMP is disabled by default and enabled with the -fopenmp option.
Another option would be to run the code with the OMP_NUM_THREADS environment variable set to 1, though that is not exactly the same as compiling without OpenMP in the first pla... |
7,847,950 | 7,847,994 | Windows Clipboard function crashing when assigning null terminator | In my function to copy text I do the following:
// Allocate a global memory object for the text.
hglbCopy = GlobalAlloc(GMEM_MOVEABLE,
((text.length() + 1) * sizeof(WCHAR)));
if (hglbCopy == NULL)
{
CloseClipboard();
return;
}
// Lock the handle and copy the tex... | You don't have to assign the null terminator yourself.
If you want to do it yourself do it like this:
((WCHAR*)lptstrCopy)[text.length()]=L'\0';
|
7,847,951 | 7,848,134 | Can an empty virtual table exist? | #include <iostream>
using namespace std;
class Z
{
public:
int a;
virtual void x () {}
};
class Y : public Z
{
public:
int a;
};
int main()
{
cout << "\nZ: " << sizeof (Z);
cout << "\nY: " << sizeof (Y);
}
Because Y inherits Z, so it will also have a virtual table. Fine. But, it doesn't have... | This is entirely compiler-dependent. When I force instantiation of Y and Z, g++ 4.4.5 produces two distinct virtual tables for Y and Z that have the same size.
Both tables point to the same x() but point to different typeinfo structures:
;=== Z's virtual table ===
_ZTV1Z:
.quad 0
.quad _ZTI1Z ; ... |
7,847,971 | 7,847,990 | Difference between unsigned and unsigned int in C++ | What is the difference between unsigned and unsigned int?
This question was already answered for C (there is no difference):
Difference between unsigned and unsigned int in C
I am interested in knowing whether there is any practical difference in C++. Are they the same type?
| They are the same type, as in C. No differences at all.
Of course, unsigned can be used as a qualifier for other integral types. But by default, unsigned is the same as unsigned int.
|
7,848,130 | 7,848,233 | Is it possible to get a (n-1)-argument function out of a n-argument function by setting one argument to a fixed value? | I was wondering if in C++ it was possible to get a function taking (n-1) arguments out of a function taking n arguments by setting the value for the nth argument to some value (to be determined at runtime)?
E.g. I would like to do something like the following:
float foo(float a, float b, float c){
// do some stuff
}
... | You cannot do it with function pointers, however, it can be done with function objects. I recommend you look at Boost.Bind if you're using C++03. If you're using C++11, std::bind is part of the standard and works the same way. C++11 also introduces built-in lambdas which do what you're attempting.
For storing the re... |
7,848,225 | 7,848,492 | Passing integer array to a c++ DLL | C++ dll function declaration is
static void __clrcall BubbleSort(int* arrayToSort,int size);
My C++ dll function is
void Sort::BubbleSort(int* sortarray,int size)
{
int i,j;
int temp=0;
for(i=0; i< (size - 1); ++i)
{
for(j = i + 1; j > 0; --j)
{
... | Arrays in managed C++ need to use the managed syntax.
static void __clrcall BubbleSort(array<int>^ arrayToSort, int size)
This translates in C# to
public static void BubbleSort(int[] array, int size);
Your declaration, instead matches the C# declaration using pointers (unsafe code).
public static void BubbleSort(int*... |
7,848,249 | 7,849,740 | Game main loop logic | I'm writing a game in c++ using allegro 5. Allegro 5 has events which are stacked in an event queue(like mouse clicked or timer ticked after 1/FSP time). So my question is how should be the logic of the main loop of my game, or since it's event based I can implement it without the main loop??
Any ideas how real games d... | I don't have any experiences with Allegro too but logic would be the same.
(so called) Real games also have game loops but the diference is they use threads which are working parallel but within different time intervals. For instance there are different threads for physic calculations, AI, gameplay, sound, rendering...... |
7,848,333 | 7,848,416 | Setting and using path to data directory with GNU AutoTools | I am trying to use GNU AutoTools for my C++ project. I have written configure.ac, makefile.am etc. I have some files that are used by the program during execution e.g. template files, XML schema etc. So, I install/copy these files along the executable, for which I use something like:
abcdir = $(bindir)/../data/abc/
abc... | The AC_DEFINE solution is fine in principle, but requires shell-like variable expansion to take place. That is, _ABC_PATH_ would expand to "${bindir}/../data/abs", not /data/abc.
One way is to define the path via a -D flag, which is expanded by make:
myprogram_CPPFLAGS += -D_ABC_PATH='\"${abcdir}\"'
which works fine i... |
7,848,420 | 7,848,442 | Why C++11 and PHP closures require declaring the closed-over variables? | Function literals in both C++ and PHP require programmer to specify which variables they are using from the current lexical context. What's the reason behind this requirement?
I guess it's not meant for the compiler/interpreter, because one can statically infer this information from function literal's body. Is it only ... | For C++11 at least, [=] () {...} will automatically pull in all and only those local variables which the function body uses. (Or, equally, [&]...)
You can specify individual variables to be captured by reference or by value if you have any specific needs beyond this catch-all.
In PHP, variables are created when their n... |
7,848,546 | 7,848,607 | Finding whether strings are anagrams - Revisited | I am sure this question has been discussed in the distant past several times on Stack Overflow. I am just trying to verify whether my answer is valid or not. I saw this question in this thread. I am sorry that this post is a duplicate of the thread and if it has to be removed, I shall do it.
I thought of doing this in... | I'm sorry but this won't work.
Sure, if it is an anagram, the code (if it works correctly) will say so but you will also have a lot of 'false positives' because several (different) strings can yield the same output.
|
7,848,619 | 7,848,675 | Use of an iterator when comparing two wstring | I am iterating through a list and through a vector. Both are filled with wstring s.
I need to compare the two strings they are pointing at and find out if "wstring1" exists in another "wstring2".
n and k are the two iterators.
When I try:
wcscmp(*n,*k);
it fails because a const wchar t is ecpected, if I understand ... | std::wstring n = L"Hello you little fello";
std::wstring k = L"little";
if ( n.find(k) != wstring::npos )
{
...
}
|
7,848,790 | 7,854,659 | Imitating constructor of static objects in C | I want to have a global names variable, which looks like that
char* names[NAMES_CAP];
int names_len = 0;
And I want every one who links to this library to be able to add an item to this list.
It's easy to do that from main.
int main(int argc,char**argv) {
names[names_len++] = "new name";
names[names_len++] = "... | Update: Refer to https://stackoverflow.com/a/2390626/270788 for updated version of this answer.
Below is a pre-processor abstration to support C static initializer functions with GCC and MSVC. The GCC version will also work with LLVM CC, maybe some other compilers as well.
The MSVC version works by placing a ptr to the... |
7,848,839 | 7,849,551 | Memory exception in program - file handling and strings | I'm getting the following error:
Unhandled exception at 0x7580b9bc in _ObjDraw.exe: Microsoft C++ exception: std::invalid_argument at memory location 0x0024f718..
When I run:
ifstream file(fileName);
if(!file)
{
return;
}
faces = vector<Face>();
string number = "";
Face tFace;
... | Just turn on first chance exception catching (in the menus Debug ==> Exceptions... or CTRL+ALT E in VS 2010) and run it under debugger. It will stop immediately when the exception is thrown and you can go up the stack to your code and (maybe) understand what is wrong.
|
7,848,865 | 7,881,921 | DLL-Exporting static members of template base class | Within a DLL I have an exported non-template class with a template base class. This template base class has a static member variable. I use the static base member in an executable that links to the DLL with the exported non-template class.
In many scenarios I get unresolved external symbols or complaints about incons... | In C++ generally, when a plain class has a static member, it should be declared in the header, but instantiated in a source file. To do otherwise would cause too many instances of the static class member to be created.
Templates are kind of the same way, except the compiler has some magic for templates that it doesn't... |
7,849,009 | 9,458,363 | cmake with Intel compiler set as platform toolset | I have the Intel compiler platform install on my development machine, when using Cmake to generate a visual studio 2010 solution, I want to be able to specify the platform toolset to be using "Intel" instead of "vc100".
I cant seem to find the setting to change this, when I change the compiler to icl the solution still... | I was looking for similar functionality as well, for setting the Windows SDK 7.1 as the default toolset for a large number of projects, without having to go through and change each one by hand.
I believe that the CMAKE people have added that functionality, and you can use something like:
set_target_properties(${YOUR TA... |
7,849,081 | 7,880,984 | Preventing copying of structures - with recursive functions | a very simplistic (and silly) abstraction of what I'm doing is described below:
class A{
private:
template <typename InIt>
A foo(InIt begin, InIt end, A& a) {
// {begin, ind} is a datastructure containing all "terms" to search for.
auto iter(sub.begin());
auto e(sub.end());
// s... | UncleBens indeed gave the correct question I needed to find a "solution".
I completely "forgot" you can obviously use arguments-by-reference as output too. I don't have to return anything as I edit the original "a", not a copy.
|
7,849,307 | 7,849,425 | difference between function pointers in c and c++ |
Possible Duplicate:
How to print function pointers with cout?
What is the difference between function pointers in c and c++? When I'm printing function pointer in c++ it's giving 1, but in c it's giving an address.
#include <iostream>
int fun()
{}
typedef int (*f)();
int main()
{
f test = fun;
std::cout ... | The function pointer can't convert to void*, so in program using C++ i/o it converts to bool. The C program is also a C++ program. You should get no difference when you compile it as C++.
Cheers & hth.,
|
7,849,541 | 7,849,586 | How to write a unit test for a stopwatch? | I have a class which measures the time between calling Start and Stop. I have created a unit test that sleeps using boost::this_thread::sleep between Start and Stop and I test that the result is near the time slept.
However, this test fails on our build agent but not our development machines. The problem is: How do I ... | There is no way to test something like this reliably on a non-realtime system. The way to go would be to wrap the APIs for getting the system-time that your stop-watch uses and mock them in the tests.
|
7,850,125 | 7,850,160 | Convert "this" pointer to string | In a system where registered objects must have unique names, I want to use/include the object's this pointer in the name. I want the simplest way to create ??? where:
std::string name = ???(this);
| You could use string representation of the address:
#include <sstream> //for std::stringstream
#include <string> //for std::string
const void * address = static_cast<const void*>(this);
std::stringstream ss;
ss << address;
std::string name = ss.str();
|
7,850,307 | 7,850,406 | performSelector on c++ class method? | Can I call performSelector on c++ class member function somehow?
I'm thinking of creating a dummy objc class that will receive performSelector call, and this dummy class calling the desired c++ member function.
But is there a better way?
(Reason I don't want to just call the method right away is because of thread... | You cannot call an objective c message on a c++ class instance because of fundamental differences in the internals (look into objc_msgSend(), which requires the objective c run-time). You could look into function pointers, or boost C++ libraries like bind or function. Alternatively, you could, as you say, make a wrappe... |
7,850,374 | 7,850,672 | stuck in infinite loop in deallocating memory | i had asked help on this question here Static member reclaiming memory and recovering from an exception
the program below is to allocate memory using own new operator. I have to throw exception on 5th object allocation and recover by freeing up memory (strange question i know, but it is assignment)
i have written the c... | The infinite loop occurs because the destructor (~object()) is called before object::operator delete(). Your destructor is attempting to delete the most recent object allocated, which calls the destructor on the same object. The operator delete() is never being called.
I'm not sure what the allocatedObjects achieves he... |
7,850,422 | 7,850,523 | Check if surface has been freed before SDL_FreeSurface | When using SDL_Surfaces to handle images, I run into the problem that running SDL_FreeSurface(SDL_Surface *) (doc) twice on the same pointer yields a segmentation fault.
I understand why that happens, but I need to know how I can avoid that. I'd like to check the state of the pointer (find out if its pointing to an ex... | You write a class that encapsulates an SDL_Surface pointer which frees the surface in it's destructor. Also, make sure you properly implement or disable the copy constructor and the assignment operator. (see The rule of 3)Then, you never work directly with SDL_Surface pointers again.
Here's an example of a wrapper ar... |
7,850,837 | 7,852,394 | ProgressBar gets 'stuck' when running without debugger | I'm working on a Visual C++ application, and part of this depackitises a file, sinjce this can take a while I implemented a progress bar to reflect the progress of the depackitisation.
This works fine when running with the debugger, however when I run without the debugger or from the .exe file, the progress bar consis... | You must never, ever, ever block the UI thread.
You're doing extensive calculations in the main thread of your application, which means its not available to answer the message pump and to draw/update drawings of controls on the screen.
You should look into multithreading and message passing as the solution to your que... |
7,850,843 | 7,852,911 | C++, Need Reason for error : cannot convert parameter 1 from 'char *' to 'const char *&' | Whey we cannot Convert pointer to a character ->TO-> a reference to a pointer to a constant character
I am interested in knowing the reason of syntax error when we call foo_ptr. When foo_char is allowed why not foo_ptr.
[Update 1.] I would be happy in knowing the reason that foo_char() is working, why foo_ptr() is not... | Revised with more examples:
Raymond Chen provides the correct answer. By passing a non const pointer (char *) as reference parameter of a const pointer (foo_ptr(const char * ¶m)) you risk returning a const pointer type (const char *) and the compiler won't allow you to do that.
Here's Raymond Chen's example of... |
7,850,937 | 7,851,218 | Which C++ design approach is more maintainable? | The current specifications is:
Given string data in the form of wide or narrow character arrays write the functionality for a class that provides statistics on the data and modifies the data.
The requirement is for it to be maintainable over the long term.
So my first approach is to require the raw char arrays be mars... | The best approach would be to do something like what stl algorithms do.
Have a process algorithm that only takes the string char/wchart_t begin and end iterator. This way you algorithm will seamlessly work for all strings that can contiguous in memory.
|
7,851,021 | 7,851,319 | RVO, move operations and a dilemma | I have been learning about move constructors over the last day or so, trying to stick to a general rule of returning by value as most people seem to suggest, and have come across an interesting (to me) dilemma.
Assume that I have an expensive to construct/copy class 'C' that has correctly defined copy constructor, assi... | The implicit move-on-return is only legal in the same contexts in which RVO is legal. And RVO is legal when the expression is the name of a non-volatile automatic object (other than a function or catch-clause parameter) with the same cv- unqualified type as the function return type ([class.copy]/p31/b1).
If you transf... |
7,851,144 | 7,851,245 | C++ how to accept server-push data? | My situation: I would like to create a hobby project for improving my C++ involving real-time/latency programming.
I have decided I will write a small Java program which will send lots of random stock prices to a client, where the client will be written in C++ and accept all the prices.
I do not want the C++ client to ... | Why not just have the Java server accept connections and then wait for some duration of time. e.g. 10 seconds. Within that time if data becomes available, send it and close the connection.
Then the C++ client can have a thread which opens a connection whenever the previous one has completed.
That should give quite low... |
7,851,197 | 7,851,385 | Is it possible to port a Linux daemon to Windows using Cygwin or MinGW? | I have a Linux C++ application which run as a daemon. When user executes this application, it will be running in the background, listening on a port, and waiting for connection from the clients.
Is it possible to port this kind of application to Windows platform using Cygwin or MinGW?
Thanks.
| Cygwin aims at POSIX/Linux source level compatibility, so your application is supposed to build and work there with no or only minor modifications.
MinGW does not try to provide such a compatibility layer. It's just the GNU toolchain for Windows, so you would need to replace any uses of POSIX/Linux-specific APIs with W... |
7,851,273 | 7,851,326 | Allocating base class object to a derieved class | Consider I am creating objects of two classes:
BaseClass B;
DerievedClass D;
and then i am doing:
B=D;
D=B;
Which is legal and why. This was a question asked by an interviewer of a C++ related Job. I know mostly B=D; will be valid (object slicing); but is it so that D=B; will only be valid if B has a default construc... | B=D;
D=B;
First line will always compile. The second line may or may not compile, as it entirely depends on how you have written each class. The rest of the answer will shed light on it. Read on.
is it so that D=B; will only be valid if B has a default constructor?
No.
D=B will be valid only if D has defined operat... |
7,851,325 | 7,851,412 | Why is my lib forcing the inclusion of mfc40.lib? | So I was beating my head against my desk for days trying to figure out why my MFC project kept failing at link phase because it couldn't find mfc40.lib. I checked for #pragma comment, I checked for lib inputs in project settings, i grepped folder after folder, I could find NOTHING.
Just before I was about to lose my m... | If when you created the project for your library you chose an MFC based library, whichever version of MFC is available gets added as a default library. To remove it, in your project properties go to Linker > Input > Ignore Specific Libraries and enter mfc40.lib.
More info on that property: http://msdn.microsoft.com/en-... |
7,851,427 | 7,851,565 | Can the main (or entry-point) function be implemented as a lambda? | Is this valid under the recently updated standard?
auto main = [](int argc, char* argv[]) -> int
{
return 0;
};
My best guess is that it depends on whether main() MUST be a function, or if it is allowed to be any globally scoped symbol that is callable (with ()).
| No, and here's why:
[n3290: 3.6.1/1]: A program shall contain a global function called
main, which is the designated start of the program. It is
implementation-defined whether a program in a freestanding environment
is required to define a main function. [ Note: In a freestanding
environment, start-up and term... |
7,851,504 | 7,851,667 | Convert .a file to .dll | This question is surely answered here somewhere, but I couldn't find it. I've been writing Java for over a decade now and my C experience was on Unix, so I'm kinda at square one here. In my Unix experience, someone else wrote the makefile and it just worked.
I have downloaded the C source code for libtar-1.2.11 from fe... | The generated libmylib.a is actually an archive of all *.o for libtar-1.2.11.
you can verify this by doing nm libmylib.a, it will print all the *.o files.
Write your code, and link:
gcc -o my_application my_application.o -lmylib
You generated this with cygwin, you can't generate a dll out of that as far as i know.
|
7,851,872 | 7,851,955 | std::bad_alloc error when declaring struct table | I declared simple structure:
struct Heap {
int size;
int *heap_array;
};
When Im trying to create table, where k is int from stdin:
Heap *rooms = new Heap[k];
I got:
terminate called after throwing an instance of 'std::bad_alloc'
what(): std::bad_alloc
Aborted
Using int literally everything is ok:
Heap *rooms... | Chances are your value read from stdin was invalid. If the read failed you might have some default value in it like 2^32.
|
7,851,947 | 7,852,053 | Fast hamming distance between 2 bitset | I'm writing a software that heavily relies on (1) accessing single bit and (2) Hamming distance computations between 2 bitset A and B (ie. the numbers of bits that differ between A and B). The bitsets are quite big, between 10K and 1M bits and i have a bunch of them. Since it is impossible to know the bitset sizes at c... | (1) Probably vector<char> (or even vector<int>), but that wastes at least 7/8 space on typical hardware. You don't need to unpack the bits if you use a byte or more to store them. Which of vector<bool> or dynamic_bitset is faster, I don't know. That might depend on the C++ implementation.
(2) boost::dynamic_bitset has ... |
7,852,101 | 7,852,154 | C++ lambda with captures as a function pointer | I was playing with C++ lambdas and their implicit conversion to function pointers. My starting example was using them as callback for the ftw function. This works as expected.
#include <ftw.h>
#include <iostream>
using namespace std;
int main()
{
auto callback = [](const char *fpath, const struct stat *sb,
... | Since capturing lambdas need to preserve a state, there isn't really a simple "workaround", since they are not just ordinary functions. The point about a function pointer is that it points to a single, global function, and this information has no room for a state.
The closest workaround (that essentially discards the s... |
7,852,167 | 7,852,341 | C++ std::string alternative to strcpy? | I know there is a similarly titled question already on SO but I want to know my options for this specific case.
MSVC compiler gives a warning about strcpy:
1>c:\something\mycontrol.cpp(65): warning C4996: 'strcpy': This function or
variable may be unsafe. Consider using strcpy_s instead. To disable
deprecation, use _... | The reason you're getting the security warning is, your faceName argument could point to a string that is longer than LF_FACESIZE characters, and then strcpy would blindly overwrite whatever comes after lfFaceName in the LOGFONT structure. You do have a bug.
You should not blindly fix the bug by changing strcpy to str... |
7,852,371 | 7,852,391 | Why is (10^(-10)) == -4 | I am trying to calculate something and want to check if the difference between two numbers is smaller than 10^-10. It didn't work, so I used std::cout << (double)(10^-10) and it printed -4. Is this the correct behavior? How could I change it so that it actually results in 0.0000000001?
| ^ is exclusive or in C. For constants you probably want to use scientific notation 1e-10. For varying exponents std::pow is, as the other answers say, the solution.
|
7,852,429 | 7,852,538 | SQLite's sqlite3_exec and callback as class member | I'm trying to do it
class Foo
{
static int ReadSelfFromBase(void *userarg, int argc, char **argv, char **ColName){...}
public:
void Bar(sqlite3* db)
{
...
rc = sqlite3_exec(db, "select * from test", &ReadSelfFromBase, this, &zErrMsg);
...
}
}
int main()
{
Foo test;
...
test.Bar(db);
}
But callback doesn't cal... | Since ReadSelfFromBase is a static function, Foo::ReadSelfFromBase should work the same in the Bar method as it does in main.
|
7,852,500 | 7,852,570 | building the same file for different targets with different options | I have one "helper" file included in two "main" files which are built into two executables with the same makefile. I have debug print statements in the helper file. I want the print statements to actually be printed in one executable, but not the other. Is there a way to do it? Right now I have the following, and I was... | You will need two different object files (main1-helper.o and main2-helper.o) and target-specific compiler flags:
main1: CXXFLAGS=-DDEBUG_PRINT
%.o: %.cpp
gcc $(CXXFLAGS) -g -o $@ -c $<
Note: This leaves you with the problem of generating main1-helper.o from helper.o. There are a few ways to solve this; however... |
7,852,520 | 7,852,839 | How to make inline C++ function calls in R? | All right, so I'm programming in R and I want to make a C++ function. I've imported the Rcpp and inline libraries. For right now, I'm just trying to make a simple function that adds 2 numbers, but no matter what I try, I get errors.
Here's my code:
cppstring = 'double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).... | Is there a reason you are not starting from the (literally!!) dozens of Rcpp examples using inline?
Also, what on earth is RcppSexp? What documentation are your following?
Here is an example I did last night for someone on the rcpp-devel (which you should probably join):
library(Rcpp)
library(inline)
xorig <- c(1, -2,... |
7,852,563 | 7,857,291 | OpenGL VS2008 on C++: Same code bevahes differently even on the same computer | I have two exact same codes OpenGL C++ , compiled using VS2008 in different project , but when i compile them, it behaves differently. One of them can recognize the condition if ( mod == GLUT_ACTIVE_CTRL && button == GLUT_WHEEL_UP ) and one of them is not.
Here is the complete function:
void mouse(int button, int stat... | I found the problem, In the project that can not recognize wheel up/down condition (despite that it should), I included:
freeglut.lib glut32.lib opengl32.lib user32.lib
This can be solved by including only the following libs:
opengl32.lib user32.lib
Thank you @melak47 for suggesting to check the project settings.
|
7,852,731 | 7,853,060 | C++ memory allocation mechanism performance comparison (tcmalloc vs. jemalloc) | I have an application which allocates lots of memory and I am considering using a better memory allocation mechanism than malloc.
My main options are: jemalloc and tcmalloc. Is there any benefits in using any of them over the other?
There is a good comparison between some mechanisms (including the author's proprietary ... | If I remember correctly, the main difference was with multi-threaded projects.
Both libraries try to de-contention memory acquire by having threads pick the memory from different caches, but they have different strategies:
jemalloc (used by Facebook) maintains a cache per thread
tcmalloc (from Google) maintains a pool... |
7,852,783 | 7,852,840 | Passing types containing SSE/AVX values | Let's say I have the following
struct A
{
__m256 a;
}
struct B
{
__m256 a;
float b;
}
Which of the following's generally better (if any and why) in a hard core loop?
void f0(A a) { ... }
void f1(A& a) { ... } //and the pointer variation
void f2(B b) { ...}
void f3(B& b) { ... } //and the pointer variation
... | The answer is that it doesn't matter.
According to this:
http://msdn.microsoft.com/en-us/library/ms235286.aspx
The calling convention states that 16-byte (and probably 32-byte) operands are always passed by reference. So even if you to pass by value, the compiler will pass it by reference underneath.
In other words, XM... |
7,853,017 | 7,853,055 | Cast in constructors for c++ type | I have the following c++ code:
#include <iostream>
#include <string>
int main( int argc, char* argv[] )
{
const std::string s1 = "ddd";
std::string s2( std::string( s1 ) );
std::cout << s2 << std::endl;
}
The result is:
1
Why?
When I use -Wall flag, compiler write warning: the addr... | Most-vexing-parse.
std::string s2( std::string( s1 ) );
is parsed as the declaration of a "function taking a std::string parameter named s1 and returning a std::string". You then try to print that function, which will first convert it to a function pointer (normal decay/conversion rule). Since the operator<< of std::... |
7,853,213 | 7,853,407 | 'Object' has not been declared error | I'm new to c++ coming from Java so I'm not sure what I'm doing wrong here
the following line in person.h is giving me the error Transaction has not been declared.
void pay(Transaction transaction);
I have a Transaction object, do I have to declare / include it in the person.h file somewhere?
here is my person.h source... | In C++, seperating the declarations from the definitions is a big thing. Declarations tell how to use the code, and are in header (.h) files. Definitions are the code itself, and are in source (.cpp) files.
If a file only refers to Transaction by pointer or reference (as is common in a header), then you only need to ... |
7,853,237 | 7,853,268 | Replacing enum with class with int identifiers - doesn't compile | I am working on a project where we had a standard enum like this:
enum Services {
RequestShower = 611,
RequestBath = 617,
RequestShave = 612,
RequestHaircut = 618
};
But my boss was saying that the latest C++ standard doesn't regard an enum to be equivalent to an int so instead proposed using a... |
the latest C++ standard doesn't regard an enum to be equivalent to an int
The specification of enum has not changed: an enumerator is still implicitly convertible to its underlying integral type.
C++11 adds a new concept, enum class, which is a "strongly typed and scoped enum." This new kind of enumeration does no... |
7,853,384 | 7,853,582 | Type mapping in object factory | Suppose that I have two sets of associated types, for example Animals and their Offspring:
/* Animal types */
struct Animal
{
virtual string getType() const = 0;
};
struct Cat : public Animal
{
virtual string getType() const { return "Cat"; }
};
struct Dog : public Animal
{
virtual string getType() const { retu... | This looks like a classic case of double-dispatch. One pattern for solving this problem in C++ is the Visitor pattern.
class Offspring;
class OffspringFactory;
class Animal {
public:
// ... rest of Animal class ...
virtual Offspring* acceptOffspringFactory(OffspringFactory& factory)const = 0;
};
class Offspr... |
7,853,476 | 7,853,586 | Simple 3D smoke algorithm for particle emitter in OpenGL | I need to create a simple particle emitter to achieve somekind of a smoke-like effect.
I need help with the algorithm that should do something like this:
*Create X amount of particles in a frame with lifetime L
*Define the velocity for each individual particle in a frame
Is there some nice mathemtical algorithm availa... | Most I've seen simply has an emission velocity at emitter level, then when you emit the particle you pick a velocity vector which slightly deviates from the emitter both in direction & length. More advanced solutions makes it volumetric by simulating it as fluids instead. Googling volumetric smoke will likely turn up a... |
7,853,675 | 7,880,109 | external properties of boost graph behaving weird? | I am doing my first steps with Boost::Graph and encountered some (to me) unexpected behavior.
What I want is to have a series of edge_weight properties (the number is only known at runtime), and use the minimum of all weights that satisfy certain constraints. First, the typedef declarations:
typedef adjacency_list<vecS... | I was able to fix it. The key observation one has to make:
WeightMap is just an interface type. If it is initialized as in the question's code, the behavior is undefined.
Instead, you need to store the data in a container and make sure it implements the according interface (that is, the get(), put() and operator[] meth... |
7,853,730 | 8,189,067 | How does one configure VS2010 code generation features? | Sorry if this is already covered, or better asked in another of the stackoverflow properties...
What I'm looking for is a way to control how the boiler plate "create a new class" in C++ is handled in VS2010.
Currently, create a new class X with parent Y generates
X.h
#include "Y.h"
class X :
public Y
{
public:
X(... | I hate to answer this myself, but the reality is that VS2010 (and older) don't support being able to customize the code generation for C++ (but do for other languages).
So Zannjaminderson is right if you're looking for anything but C++
|
7,853,735 | 7,853,770 | Which type in c++ can store 2^63? | I need to store 2^63 natural number in my program. Int has 4 bytes: http://www.cplusplus.com/doc/tutorial/variables/ so it is 2^(8*4) = 2^32, which type should I use?
| You can use unsigned long long, but I would check that your compiler supports that type.
#include <iostream>
int main()
{
std::cout<<sizeof(unsigned long long)<< " bytes" << std::endl;
return 0;
}
Prints 8 bytes on my machine which is enough room to store 2^63.
|
7,853,942 | 7,853,999 | Weird behavior with variables in Release vs. Debug builds | I've got a C++ project in Visual Studio 2010.
I'm simply trying to compare two strings to one another but I'm seeing wildly different behavior in my Release build. The Debug build works as expected. I haven't made any changes to optimizations other than the default values that Visual Studio 2010 sets.
Here's my code:
w... | Release builds are optimized, so it's often hard for the debugger to give you values of individual variables, especially local variables which are often stored registers that are used for something else a few instructions later.
That's why you use a debug build for debugging, and the release build for the build that yo... |
7,854,221 | 7,854,563 | Using Templates in C++ | I have a homework that asks me to do the following:
Design a template class named FlexArray which offers flexible array
indexes. The user of the class can set the lower index and upper
index when the object is declared.
Examples of user code:
FlexArray a (1,5); // lower index is 1 and the upper inde... | You're off to a good start. A couple of things to point out.
The assignment asks for a default constructor, BUT also states that resizing the array is not supported. These two requirements logically conflict -- your assumption (to use size=0) seems logical, but then this default constructed object will always be empt... |
7,854,533 | 7,913,928 | How to pass C++ object to NPAPI plugin? | I'm writing an NPAPI plugin in C++ on Windows. When my plugin's instantiated, I want to pass it some private data from my main application (specifically, I want to pass it a pointer to a C++ object). There doesn't seem to be a mechanism to do this. Am I missing something? I can't simply create my object in the plug... | There is no way to do this via NPAPI, since the concept doesn't make sense in NPAPI terms. Even if you hack something up that passes a raw pointer around, that assumes everything is running in one process, so if CEF switches to the multi-process approach Chromium is designed around, the hack would break.
You would be b... |
7,854,598 | 7,854,642 | vs2010 C4353 why isn't this an error | I ran into this today in an if and after looking into it found that all these are all valid statements that generate the C4353 . My only guess is that this is the old way of doing noop in C. Why is this not an error. When would you use this to do anything useful.
int main()
{
nullptr();
0();
(1 == 2)()... | Using constant 0 as a function expression is an extension that is specific to Microsoft. They implemented this specifically because they saw a reason for it, which explains why it's wouldn't make sense to treat it as an error. But since it's non-standard, the compiler emits a warning.
You are correct that it is an alte... |
7,854,627 | 7,879,103 | Effectively merging files with libxml2 SAX API | I'm trying to merge several files with libxml2 SAX. Original files look like this:
<xml>
<section1>
<data />
<data />
</section1>
<section2>
<data />
<data />
</section2>
<section3>
<data />
<data />
</section3>
</xml>
What I want to do is to make data from s... | I don't think this would be possible. You could start a secondary parsing at an arbitrary time in the original file's callback, but I don't think you can stop the secondary parsing (to go back to the original parsing) without fully finishing or aborting the 2nd one.
I'd strongly recommend looking into the xmlReader in... |
7,854,691 | 7,856,743 | How do I make my procedural Knapsack problem brute-forcer into an object-oriented one? | This is my first shot at brute-forcing the NP-complete knapsack problem. In this form you have a list of items which must be thrown off a plane each with a weight and cost. The goal is to throw out some remain_weight while minimizing cost.
Each recursion level(y direction if graphed) is a new remain_weight after item... | int &cost_low, int &cost_high is a tip-off. If a function is called repeatedly, and on each iteration modifies the same objects, then that function and those objects should probably be members of the same class.
If you look further, you see that algo also works on cost_matrix[] and weight_matrix[] (No, it's not a 2D a... |
7,854,951 | 7,857,455 | Determining who is accessing a file on a shared folder in Windows 2008 R2 server / Windows 7 | I need to find a way to determine what files on a shared folder are being accessed, and by whom. Commands like "Net Files" and "Net Session" can give this information, as well as PSFile.exe in SysInternals, but I cannot figure out how to do this programmatically. I have found a way to determine who is accessing a share... | NetFileEnum level 3 seems to be what you're looking for.
|
7,854,954 | 7,854,988 | Is the C++ std library platform independent? | I would like to know if some code I write with 'fstream' in C++ will work on all platforms? Is the C++ standard library platform independent or has the headers been rewritten for each platform?
| Both. You can compile a C++ program using fstream for any platform, but the headers are implementation-dependent. They will differ between compilers and operating systems, but they fulfill the purpose they've been designed and specified for.
|
7,855,044 | 7,855,117 | What's the fastest way to read a file full of strings (separated by newlines) in an array of unsigned char arrays (and vice versa)? | Well, maybe the title is misleading a bit. All I want you to do is to take a quick look at the following two snippets and to give me some tips on how to improve the performance as much as possible without getting too exotic code. The code is needed to function on win32 only. Unfortunately STL containers are not an opti... | Well... what I would do is:
Use memory-mapped files. That's THE fastest way of reading files;
Then memcpy() all the file's contents in a new buffer;
Then run through the buffer once and count the newlines;
Make an array of as many pointers as there are newlines;
Run through the buffer another time, and this time:
Rep... |
7,855,141 | 7,855,683 | can a library contain multiple bindings | if i have written a library in C++, and have bindings for C, Ada, Fortran, D & other compiled languages.
could all these bindings be in the same binary with the C++ compiled code even if they use the same function names?
and could you use the bindings like this?
| Depending how you create your bindings a library may not be even necessary:
Bindings written some interpreter specific APIs:
For example, ruby extensions written using the MRI API, are basically a shared library providing a:
void init_Modulename()
This function then uses the MRI api like rb_define_module, rb_define_... |
7,855,174 | 7,855,273 | Set minimum version of boost in cmake | I want to define a minimum boost version to be available on the system. I tried the following approach. Unfortunately this did not work, as it tries to compile also with only boost 1.40.0 available on the system.
SET(Boost_USE_STATIC_LIBS OFF)
SET(Boost_USE_MULTITHREAD OFF)
SET(BOOST_MIN_VERSION "1.47.0")
FIND_PACKAGE... | Based on this it seems that FIND_PACKAGE ignores SET(BOOST_MIN_VERSION "1.47.0") instead you could use FIND_PACKAGE(Boost 1.47.0 REQUIRED) or slightly nicer FIND_PACKAGE(Boost ${BOOST_MIN_VERSION} REQUIRED)
|
7,855,194 | 7,855,246 | About CreateMappingFile and Memory mapped files | I tried to read a lot of resources about CreateMappingFile but unfortunately I don't have that good english, so I need to ask you about what I concluded if it is true or not:
CreateMappingFile makes a RAM-like structure for a file in the virtual memory NOT in RAM , so this structure (or whatever is called) is located i... | CreateFileMapping just prepares a file for mapping and allocates a handle for the file mapping. MapViewOfFile actually gives that mapping an address in the virtual address space of the calling process.
It's up to the operating system to decide how to dedicate physical RAM to that file mapping. Whenever the process read... |
7,855,222 | 32,759,407 | How to asynchronously read input from command line using boost asio in Windows? | I found this question which asks how to read input asynchronously, but will only work with POSIX stream descriptors, which won't work on Windows. So, I found this tutorial which shows that instead of using a POSIX stream descriptor I can use a boost::asio::windows::stream_handle.
Following both examples I came up with ... | I just spent an hour or two investigating this topic so decided to post to prevent others to waste their time.
Windows doesn't support IOCP for standard input/output handles. When you take the handle by GetStdHandle(STD_INPUT_HANDLE), the handle doesn't have FILE_FLAG_OVERLAPPED set so it doesn't support overlapped (as... |
7,855,226 | 7,855,777 | Use getline() without setting failbit | Is it possible use getline() to read a valid file without setting failbit? I would like to use failbit so that an exception is generated if the input file is not readable.
The following code always outputs basic_ios::clear as the last line - even if a valid input is specified.
test.cc:
#include <iostream>
#include <str... | You can't. The standard says about getline:
If the function extracts no characters, it calls is.setstate(ios_base::failbit) which may throw ios_base::failure (27.5.5.4).
If your file ends with an empty line, i.e. last character is '\n', then the last call to getline reads no characters and fails. Indeed, how did you ... |
7,855,248 | 7,855,301 | Does using inline keyword in methods definition may cause ptoblems? | I used inline in every method in my program (implementation of algorithm), does it can make problems?
| Depends on what your code looks like.
But not understanding what your code means? That is definitely going to cause you problems.
Why don't you try to learn what inline actually does, rather than simply whether or not it's going to cause any problems?
The primary effect of the inline keyword in C++ is to make the compi... |
7,855,398 | 7,855,540 | C++ object hierarchy - how to manage circular dependencies? | I want to make two classes: an object and an object_manager, but I'm confused about how they should see/include each other. I've heard that it's forbidden for two headers to include each other and if my code dependencies has circles then it's a bad code design and usually it should be like a hierarchy structure (town->... | Use forward declaration:
class ObjectManager;
class Object
{
private:
ObjectManager* m_objManager;
....
public:
....
};
In .cpp file you can include the ObjectManager.h
Also instead of ObjectManager make the interface which will give you more abstraction for implementation IObjectManager.
|
7,855,480 | 7,855,524 | Pack Class Object Pointer into char * for message queue | Is it possible to properly and safely pass a class object pointer through a POSIX message queue?
For instance,
Object *obj = new Object();
mq_send(mqdes, static_cast<char*>&obj, sizeof(obj), 1);
and on the receive side, perform a reinterpret_cast back to my Object?
Since message queues use a file descriptor on Linux... | Not really... only if the object contains only basic type fields and other structs with basic type fields. If you send a pointer it cannot be reused from the other side if it resides in another process or in another system.
Also using classes with inheritance and virtual methods, it may be a mess!
It is better to add a... |
7,855,563 | 7,855,601 | Does vector.insert(...) call the constructor or the assignment operator? | I have a vector with elements of type class A. Class A has an explicitly defined copy constructor, but the copy operator has been made private and undefined (it's not meant to be used). If I insert new elements to the vector like below
A walker; //This calls the default constructor.
std::vector< A ... | vector is indeed using the copy constructor for the inserted element. However vector still needs the assignment operator internally, is within the requeriments for the vector type to be assignable. I believe C++11 now only requres move-assignment.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.