question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
4,468,756 | 4,469,356 | Boost logging - destinations and formatters | I am having a problem with using Boost Logging library, that if I add a formatter or a destination to a logger, using my own Log class, I cannot change that destination or formatter.
Does anybody know how to change the destination or formatter on a boost log object?
The scenario I have is that I want a different dest... | Ok, here's what I would try. It might work for you. It looks as if the logging library is tailored for global loggers, while you are wanting to use thread-local loggers. I'd look up how to create a logger on demand (i.e. directly), for example by analysing BOOST_DECLARE_LOG. Then you can declare a std::map<int, Logger>... |
4,468,770 | 4,468,799 | C++ name mangling decoder for g++? | is there any C++ name-mangling decoder for g++?
| You can use c++filt to demangle c++ symbols. For instance
$ c++filt -n _Z1fv
f()
|
4,468,922 | 4,469,819 | efficient way of making a graph of a dictionary | What is the most efficient way of making a graph of the words in a dictionary with hamming distance=1??
| Hamming distance is only defined for words of equal length, so you'll actually have one disjoint graph for each word length in your dictionary. If you meant levenshtein distance, which permits insertions and deletions, then you will indeed have a single graph.
One option is to construct a BK-tree from your dictionary. ... |
4,469,263 | 4,469,364 | meaning of C++ runtime linking error? | I am getting following runtime error.
anyfile.cpp (60) : E_FATAL : Could not
start process libprocbase_so.so
(/opt/company/processes/sharedbase_so.so:
undefined symbol:
_ZTV16CResourceManager)
I found that meaning of _ZTV16CResourceManager is virtual table of Resource Manager,
Any idea why it is coming? how t... | The problem is that while loading the dynamic libraries (sharedbase_so.so) it has not been able to resolve the symbol. Try to locate in what library (if any) the symbol is defined and ensure that ld can load it (add it to the path). If it is not present in any dynamic library, go back to the object files and try to det... |
4,469,304 | 4,469,662 | Dependency Injection framework for C++ | Is there a DI framework comparable to Google Guice? And what does Google use?
| There is nothing as mature or standard as Guice in the C++ world. However, some people have put together simplistic implementations on their own. Here's a couple.
http://adam.younglogic.com/2008/07/dependency-injection-in-c/ (source for implementation is at the end of the post)
http://sourceforge.net/projects/qtioccon... |
4,469,310 | 4,469,368 | How to avoid conflicts with other programs using shared memory and semaphore | I have program that uses shared memory and protects it with semaphore to communicate with other instances of the same program. I am concerned about security of my shared memory and semaphores.
How can I ensure that semaphore and shm that I use won't be opened by other program that will mess it up? There is one way of... | The semaphores "protect" the shared memory only if all the programs using it are collaborating. I.e. it allows the program which wants to play nicely not to corrupt the shared objects.
This however doesn't guarantee that a malicious program will be able to jump in and corrupt the shared structures if it wants to. I don... |
4,469,550 | 4,469,566 | Why Comment Cannot be Replaced by Spaces in Visual C++ 2008 | In Visual Studio 2008 (without SP1), I can compile and run this code
// vcconsole.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#define NOERROR
#ifdef /*
*/ NOERROR
void pr() {
printf("hello world..\n");
}
#endif
int _tmain(int argc, _TCHAR* argv[])
{
pr();
return 0;
}
... | There's something in the Standard like a comment is replaced by a single space... that effectively removes the newlines. Your tool should do the same.
Note that under [lex.parses] 2.1.1.3 "Each comment is replaced by one space character." before 2.1.1.4 "Preprocessing directives are executed and macro invocations are ... |
4,469,645 | 4,469,745 | Dos and Don'ts of Conditional Compile | When is doing conditional compilation a good idea and when is it a horribly bad idea?
By conditional compile I mean using #ifdefs to only compile certain bits of code in certain conditions. The #defineds themselves may be in either a common header file or introduced via the -D compiler directive.
| The good ideas:
header guards (you can't do much better for portability)
conditional implementation (juggling with platform differences)
debug specific checks (asserts, etc...)
per suggestion: extern "C" { and } so that the same headers may be used by the C++ implementation and by the C clients of the API
The bad ide... |
4,469,806 | 4,472,542 | Using QLocalServer over QtService : how to set security attributes to named pipe created by QLocalServer? | I am trying to use QLocalServer in service application on win7.
QLocalServer's windows implementation uses named pipes, and since winVista try to access it from GUI causes error. There was even QT bug about it, but trolls closed it without any fixing.
So my question is:
Is there a way to change security attributes of a... | if believe to this pipe security attributes cannot be changed under LocalAdmin user...
so I edited QLocalServer, which i did not wanted to do :(
|
4,469,818 | 4,469,954 | Is there a way to limit the number of output files of a process? | An application of our company uses pdfimages (from xpdf) to check whether some pages in a PDF files, on which we know there is no text, consist of one image.
For this we run pdfimages on that page and count whether only one, two or more, or zero output files have been created (could be JPG, PPM, PGM or PPM).
The proble... | One approach is to monitor the directory for file creations: http://msdn.microsoft.com/en-us/library/aa365261(v=vs.85).aspx - the monitoring app could then terminate the PDF image extraction process.
Another would be to use a simple ramdisk which limited the number of files that could be created: you might modify somet... |
4,469,894 | 4,469,911 | How cast C++ class to intrinsic type | Basic C++ class question:
I have simple code currently that looks like something like this:
typedef int sType;
int array[100];
int test(sType s)
{
return array[ (int)s ];
}
What I want, is to convert "sType" to a class, such that the "return array[ (int)s ]" line does not need to be changed. e.g. (pseudocode)
class... | class sType
{
public:
operator int() const { return val; }
private:
int val;
};
|
4,469,948 | 4,469,973 | How new differentiates between PODs and user defined data types? | First:
int *p = new int;
Second:
class A{};
A *pa = new A;
How does new and compiler determines when to call constructor? In first case compiler does not generate code to call constructor of p and in second case it generates code to call constructor of A. Which mechanism is used to make such choice?
| The compiler knows that A is a class, because it has seen the class declaration, so it uses the synthesised default constructor. It knows an int is an int, because the language grammar says it is.
|
4,469,979 | 4,470,178 | How to convert a single-byte const char* to a UTF-8 encoding | I have a function which requires me to pass a UTF-8 string pointed by a char*, and I have the char pointer to a single-byte string. How can I convert the string to UTF-8 encoding in C++? Is there any code I can use to do this?
Thanks!
| To convert a string to a different character encoding, use any of various character encoding libraries. A popular choice is iconv (the standard on most Linux systems).
However, to do this you first need to figure out the encoding of your input. There is unfortunately no general solution to this. If the input does not s... |
4,470,121 | 4,470,798 | How to use lsof(List Opened Files) in a C/C++ application? | Is there any way to get all opened sockets using c++? I know the lsof command and this is what I'm looking for, but how to use it in a c++ application?
The idea is to get the FD of an opened socket by its port number and the pid.
| Just open the files in /proc/net, like /proc/net/tcp, /proc/net/udp, etc. No need to slog through the lsof sources. :)
|
4,470,218 | 4,470,285 | Manual Object Ownership vs Smart Pointers | Right now, object ownership/deletion in my C++ project is manually tracked (via comments mostly). Almost every heap allocated object is created using a factory of sorts
e.g.
auto b = a->createInstanceOfB(); //a owns b
auto c = b->createInstanceOfC(); //b owns c
//auto k = new K(); //not in the code
...
//b is no long... | It's not the creation you should worry about, it's the deletion.
With smart pointers (the reference counting kind), objects can be commonly owned be several other objects, and when the last reference goes out of scope, the object is deleted automatically. This way, you won't have to manually delete anything anymore, yo... |
4,470,553 | 4,470,763 | initialization: parenthesis vs. equals sign | What's the difference between
T a(b);
and
T a = b;
and
T a = T(b);
?
| T a( b );
is direct initialization, unless it parses as a function declaration, in which case it's a function declaration.
T a = b;
is copy initialization, which means that it works as if a temporary object is constructed on the right hand side, and that a is then copy constructed or, in C++11 and later, possibly mov... |
4,470,645 | 4,735,692 | AcceptEx without WSAIoctl | Is there any difference between using AcceptEx direct call or using function pointer obtained by WSAIoctl.
MSDN doesn't fully covers this question regarding performance issue and other problems that can be faced using AcceptEx as direct call.
And other question is:
If I have for example 4 listening sockets in my progra... | WSAIoctl. It's an extension provider that you use for new functions/additions to the winsock functionality, each new windows version usually add a couple of new extensions.
AcceptEx function pointer:
Using the AcceptEx directly binds the application to the Microsoft provider with the need for MSWsock.dll. As for correc... |
4,470,665 | 4,471,532 | How to reference a C++ library project from a .NET one in Visual Studio? | I have 2 projects
A C++ library
A .NET app that uses the above
When I want to run the .NET app I have to build the C++ library manually and copy the binary to the .NET app output folder, so it can Work.
How to automate this?
| First make sure you've got a solution with both projects. Right-click the C++ project, Properties, Configuration Properties, General. Change the Output Directory setting to
$(SolutionDir)bin\$(ConfigurationName)
Repeat for the Release configuration (upper left combo). That ensures the C++ build is using the same ... |
4,470,802 | 4,472,048 | Exporting constants from a DLL | I'm working with VC9 on Windows.
I have a library (lets call it libfoo) which is made of the following files ("include guards" and "#include" directives omited for clarity's sake):
// foo.hpp
class Foo
{
public:
static const std::string SOME_CONST;
};
And:
// foo.cpp
#include "foo.hpp"
const std::string Foo::... | Check if dll actually does dynamic initialization, because it might not, standard has no requirements for dynamic libraries. Wrapping globals in static functions can be the solution.
|
4,470,838 | 4,471,102 | g++ linking issue with GSL | g++ -o program main.cpp classOne.cpp classTwo.cpp -lgsl -lgslblas -lm
that's how i compile when the GSL-packages are installed.
but now I'm working on a server where i don't have rights to install GSL-Library.
What are my options?
thx
| I had to do this regularly, do as following :
On the server, create one directory in your home directory to install the library (let's say mypref) and another one to build the library (let's say tmp). You have two new directories : ~/mypref and ~/tmp.
Download GSL sources in ~/tmp (last version is ftp://ftp.gnu.org/gn... |
4,471,090 | 4,471,120 | Can't link to class with templates using Visual C++ | I wrote a nice little array class in C++ that uses void* to save its entries.
Now, I want make it use templates. This is my new header:
template <typename T>
class SimpleArray
{
public:
SimpleArray();
~SimpleArray();
void SetEntry(int idx, T setEntry);
T GetEntry(int idx);
// and so on
protected:
... | You need to put all the code in the header file. C++ does not effectively support separate compilation of templates.
|
4,471,142 | 4,471,171 | Namespace for a single method c++ | Let's say i have a header file Snake.h:
#include "SnakeBodyPart.h"
#include "GUI.h"
//...
And SnakeBodyPart.h is (among other things) :
#include "GUI.h"
class SnakeBodyPart {
private :
GUI::Orientation orientation;
}
And at last GUI.h :
class GUI {
enum Orientation { NORTH, EAST, SOUTH, WEST };
}
Now... | Please note that in your example, GUI is not a namespace but a class.
That being said, inside turn() you can write using namespace GUI; to access all identifiers in the GUI namespace without explicitely qualifying them. Alternatively, you can import single symbols using e.g. using GUI::EAST;, too:
void Snake::turn(){
... |
4,471,388 | 4,472,308 | shared_ptr coexisting with pointers | I have a function as follows
void a(shared_ptr<X> val) {...}
Sometimes, I want to pass in a heap-allocated object
shared_ptr<X> v(new X());
a(v);
Other times, I want to pass in a stack-allocated object
class C
{
//doesn't work properly b/c when the shared_ptr dies it will try to delete x...
C() { a(shared_pt... | I would just make the function take a template parameter like this:
template<class P>
void func(P ptr) {
// use ptr like a pointer as usual
// for example
*ptr = 10;
}
then you can do like this:
shared_ptr<int> v(new int);
int x;
func(v); // works
func(&x); // also works
You can pass anything that ha... |
4,471,395 | 4,471,406 | C++ Memory management by returning a pointer to a simple type | i want to ask about the following situation
int * foo() {
int fooint = 5;
return &fooint;
}
int myint = *foo();
its based on
http://www.functionx.com/cpp/examples/returnpointer.htm
but i want to ask, if it is safe, because what i think will happen
fooint gets initialized in the scope of foo()
the address of ... | Yes, you shouldn't ever return addresses of temporary variables exactly for the reasons you give. The second variant is okay.
However using dynamic memory allocation for built-in types will be very expensive. In case of built-in types it'll much cheaper to just return by value:
int function()
{
return 5;
}
and it ... |
4,471,714 | 5,696,788 | Pretty print a table in C++ | I am looking for a library similar to prettytable but in C++
http://code.google.com/p/prettytable/
I know how to generate one myself using either printf or iostream. However, I would like to know if there is a library for this.
I am interested only in writing this ASCII table to the console.
Preferably something like:
... | Since I have not found a good C++ solution, I have written one for you all
https://github.com/dattanchu/bprinter/wiki
|
4,471,780 | 4,471,800 | Inherited member from an abstract class can't be initialized by the inherited constructor | class CarPart
{
public:
CarPart(): name(""), price(0) {}
virtual int getPrice() = 0;//{return price;}
protected:
int price;
string name;
};
class Tire: public CarPart
{
public:
virtual int getPrice() {return price;}
Tire(): CarPart(), name("Tire"), price(50)
{}
};
Visual 2010 tells me name... | You cannot initialize members that is not an immediate member of your class. n is not an immediate member of deriv, it's an immediate member of base.
However, n is accessible to deriv, so you can always assign it in your deriv constructor, but you should really initialize it in the base constructor.
Also, you can't ha... |
4,472,047 | 4,472,329 | C++ XML parser QT - not working | Below is my code & xml file. I am trying to read a xml file and store the contents. But its not working. Please help
int ParseConfigFile::populateUserValues ( string &OS, string &dir, string &logPath )
{
QDomDocument doc;
QDomElement element;
QFile file("config_v1.xml");
if ( doc.setContent( file.read... | You should instantiate the QDomDocument like this and then your code will work:
if ( doc.setContent(&file) == false )
return 1;
QDomDocument can work with an IO device (like QFile) making this the optimum way to set the QDomDocument's content from a file.
Anyway, if you're trying to write a configuration file ... |
4,472,111 | 4,472,247 | Static objects and singletons | I'm using boost singletons (from serialization).
For example, there are some classes which inherit boost::serialization::singleton. Each of them has such define near it's definition (in h-file):
#define appManager ApplicationManager::get_const_instance()
class ApplicationManager: public boost::serialization::singleton<... | Instead of using the Singleton anti-pattern, just a global variable and be done with it. It's more honest.
The main benefit of Singleton is when you want lazy initialization, or more fine grained control over initialization order than a global variable would allow you. It doesn't look like either of these things are ... |
4,472,175 | 4,472,335 | Portable lightweight C++ sockets wrapper | I really thought this would be easier to find...
I need a portable c++ sockets wrapper. I'm planning to use it for a windows server application and a client that will be running on a embedded device running ulinux (or something similar). I would use Boost but I need it to be lightweight and easy to add to the embedded... | Just learn to use the socket API directly. You can then easily wrap it yourself. It's not that hard, and you can get started with Beej's excellent guide. As Beej says:
The sockets API, though started by the
Berkeley folk, has been ported to many
many platforms, including Unix, Linux,
and even Windows.
In his gu... |
4,472,208 | 4,472,668 | Implementing a simple server / client concept in C++ | I'm searching for a library / framework / codesnippet that helps me build a really simple server / client. Both should be portable (linux/win/mac).
A picture says more then a thousand words so:
The server should be able to seperate diffrent clients.
What I'm looking for is only a hint on how to do the transfere. I've ... | Have you done Network programming before? Its pretty straight forward in C. And what you want can be implemented in a few hours. I used this manual below to finish my assignments back when i was a student.
http://shoe.bocks.com/net/
Just read this and you are good to go. Its really not very hard.
Good Luck!
|
4,472,257 | 4,472,406 | How do I swap the left hand and right hand sides of a C/C++ assignment statement in gvim? | To be honest, I actually have a solution for this, but Google search finds so many great tips for me from this site, that I had to contribute something back. Here is what I came up with. For a single line:
s/^\(\s\+\)\(.*\) = \(.*\);/\1\3 = \2;/
For multiple lines starting at the current line, add .,.+<line count>. ... | Use 'very magic': add \v to the expression. See :help magic. Basically, it mean that all non-alphanumeric characters have special (i.e. regular expression operator meanings) unless escaped, which means that they do not need to be escaped in your usage above.
|
4,472,438 | 4,473,208 | Why can't the compiler differentiate between typedef and non-typedef? | Sorry for the long title.
I have a typedef in a class List:
template <typename T>
class List {
// Think of a class Iter_ with ListElem *pCurrentPos and List *pList
typedef const Iter_ const_iterator;
const_iterator cbegin() const;
};
and the definition outside of the class, but inside the header file.
t... | The error I get when instantiating cbegin() is that you are passing (const) this to the constructor which takes a non-const pointer to the List.
Basically I doubt this idea works that well.
typedef const Iter_ const_iterator;
|
4,472,481 | 4,472,515 | C++: Char iteration over string (I'm getting crazy) | I have this string:
std::string str = "presents";
And when I iterate over the characters, they come in this order:
spresent
So, the last char comes first.
This is the code:
uint16_t c;
printf("%s: ", str.c_str());
for (unsigned int i = 0; i < str.size(); i += extractUTF8_Char(str, i, &c)) {
printf("%c", c);
}
pri... | your first printf is printing nonsense (the initial value of c). The last c gotten is not printed.
This is because the call to extractUTF8_char is occurring in the last clause of the for statement. You might want to change it to
for (unsigned int i = 0; i < str.size();) {
i += extractUTF8_Char(str, i, &c);
prin... |
4,473,045 | 4,473,097 | C++ initialization of struct containing an array | I have a structure that more or less follows this pattern:
struct sTruct {
int count;
struct {
int A;
int B;
int C;
} array[]; //count is the size of this array
};
I would like to be able to initialize these with something like the following syntax:
sTruct gInit1 = { 2, { {1,2,3},{4,5,6... | You can't do it. If you gave the array a size you could. An alternative might be:
template < int size >
struct sTruct
{
struct { int a, int b, int c } array[size];
};
sTruct<2> gInit1 = {{1,2,3},{4,5,6}};
But, of course, all your sTructs are different types and so it may not be what you want. Your only other alte... |
4,473,064 | 4,473,126 | Force ofstream file flush on Windows | I'm using an ofstream to write data to a file. I regularly call flush on the file but the backing file doesn't always get updated at that time. I assume this is related to an OS-level cache, or something inside the MSVC libraries.
I need a way to have the data properly flush at that point. Preferably written to disc, b... | FlushFileBuffers will flush the Windows write file cache and write it to a file. Be aware it can be very slow if called repeatedly.
I also found this KB article which describes the use of _commit(). This might be more useful to you since you are using ofstream.
CXXFileBuf.flush();
_commit(CXXFileBuf.rdbuf()->fd());
|
4,473,205 | 4,474,151 | Typedefs, (binary) Code duplication and Object File | Suppose I compile a source file file which contains this piece of code,
struct Point
{
int x;
int y;
};
struct Size
{
int x;
int y;
};
Since Point and Size is exactly same (in terms of memory layout of it's members), would the compiler generate duplicate code (one for each struct) in the object file? ... | No single line from your examples will generate any code in the object file. Or, more precisely, it won't generate any data at all. I think "code" means just processor instructions.
The data in an object file is divided into three segments: code, static data and constant data.
The code is generated by actual function d... |
4,473,292 | 4,473,321 | Implementation of Overloaded Functions | In my header file, I have this:
std::string StringExtend(const std::string Source, const unsigned int Length, const bool Reverse);
std::string StringExtend(const std::string Source, const unsigned int Length);
In my cpp file, I have this:
std::string Cranberry::StringExtend(const std::string Source, const unsigned int... | Use a default parameter for your Reverse parameter.
std::string StringExtend(const std::string & Source, unsigned int Length, bool Reverse = false);
Get rid of the second function:
std::string StringExtend(const std::string & Source, unsigned int Length);
|
4,473,452 | 4,474,704 | making mistake in inline assembler in gcc | I have successfully written some inline assembler in gcc to rotate right one bit
following some nice instructions: http://www.cs.dartmouth.edu/~sergey/cs108/2009/gcc-inline-asm.pdf
Here's an example:
static inline int ror(int v) {
asm ("ror %0;" :"=r"(v) /* output */ :"0"(v) /* input */ );
return v;
}
However,... | The following does what you want:
inline unsigned long long rdtsc() {
unsigned int lo, hi;
asm volatile (
"cpuid \n"
"rdtsc"
: "=a"(lo), "=d"(hi) /* outputs */
: "a"(0) /* inputs */
: "%ebx", "%ecx"); /* clobbers*/
return ((unsigned long long)lo) | (((unsigned long long)hi) << ... |
4,473,489 | 4,473,584 | How to make a C++ project to copy its dependencies to the output folder? | I have some libs that are used by my C++ Visual Studio project. But they aren't copied to the output folder. How to add this step to the build process?
| Go to project properties and use Custom Build Step or Build events. Just use command line commands. You can use macros to specify paths.
|
4,473,981 | 4,474,054 | const and non-const in stl containers | The STL vector template defines element accessors as both const and non-const variants, for example:
reference operator[](size_type __n)
{return *(this->_M_impl._M_start + __n);}
const_reference operator[](size_type __n) const
{return *(this->_M_impl._M_start + __n);}
When does the compiler decide to use one... | This takes advantage of a tricky part of the function overload rules. First off, cv-qualifiers after the close parenthesis of a method prototype are just like cv-qualifiers on arguments, but they apply to the implicit this argument. In a hypothetical C++ variant where you had to declare this, the prototypes would be ... |
4,474,043 | 4,474,139 | SDL vs GLUT in opengl 3D programming | I'm beginning a series of tutorials on SDL. Before I dig too far, I'd like to know what type of control SDL gives me over GLUT?
Also, do either support webcam access (for face tracking or motion detection), or is that best managed through OpenCV?
| Neither SDL nor GLUT have any facility for webcams. They are completely webcam-agnostic.
As to your other question: GLUT is unmaintained. It has not seen any updates in well over a decade. It has been partially supplanted by FreeGLUT (which is a binary-compatible replacement), but neither GLUT nor FreeGLUT support Open... |
4,474,076 | 4,474,738 | C++ + OpenCV = Access violation reading location 0x02176000 | This code actually used to work until now. I have no idea what is causing it to throw an error now (I don't actually remember making any changes to the code). Here it is (it reads an image from a file to OpenCV IplImage object and then converts it to jpeg buffer):
IplImage* fIplImageHeader = cvLoadImage( filePath.c_s... | The output buffer is supposed to be resized to the output image, but you have not specified an explicit size with the buf object. At least this is mentioned from your referenced doc page at http://opencv.willowgarage.com/documentation/cpp/reading_and_writing_images_and_video.html
Can you try setting an explicit size o... |
4,474,086 | 4,474,570 | Display QImage with QtGui | I am new to Qt, and I am trying to create a simple GUI Application that displays an image once a button has been clicked on.
I can read the image in a QImage object, but is there any simple way to call a Qt function that takes the QImage as an input, and displays it?
| Thanks All, I found how to do it, which is the same as Dave and Sergey:
I am using QT Creator:
In the main GUI window create using the drag drop GUI and create label (e.g. "myLabel")
In the callback of the button (clicked) do the following using the (*ui) pointer to the user interface window:
void MainWindow::on_pushBu... |
4,474,304 | 4,474,866 | HTTP Json requests in C++? | How to make HTTP Json requests in C++? Any library? Under "HTTP Json request" I mean make POST with Json object as data and receive result as Json.
| Use libCURL to get the actual JSON data. Then parse it with some C++ library like jsoncpp.
|
4,474,431 | 4,474,538 | STL - what is the problem of the following code? | #include "stdafx.h"
#include <string>
#include <map>
using namespace std;
class NiftyEmailProgram {
private:
typedef map<string, string> NicknameMap;
NicknameMap nicknames;
public:
void ShowEmailAddress(const string& nickname) const
{
NicknameMap::const_iterator i = nicknames.find(nickname);
... | Try to post the non-treated warnings.
However, I too remember that I got some level 4 warning from <xtree> in <map> , that could be safely ignored (IIRC it was C4702, which is harmless).
To avoid the warning, I put around the STL #includes some appropriate #pragma warning directives (enclosed in the correct #ifdefs to ... |
4,474,464 | 4,474,935 | Rendering particles as GL_TRIANGLE_FANs with transparency in OpenGL | I want to render particles with hexagons that fade out to the outside. I've used a TRIANGLE_FAN for each particle. However, the transparency doesn't look very nice.
glBegin(GL_TRIANGLE_FAN);
glColor4f(c.x, c.y, c.z, particle.temperature / 100.0);
glVertex3f(0, 0, 0);
glColor4f(0, 0, 0, 0);
glVertex3f(0.... | What you're observing is particles behind others that do not get drawn because a closer Z-value is present in the Z-buffer.
You can draw your particles back to front.
You could also disable depth-testing, but standard alpha blending will not be correct. with the ALPHA/ONE mode, you'll get to accumulate all particles, ... |
4,474,468 | 4,474,546 | Pointer-to-Pointer crashes in case where Pointer doesn't | I'm porting some code to Windows and am stumped. There is some code that runs automatically on launch to copy a pointer to a pointer, and runs again on exit to delete the pointer to a pointer if it is not null.
I have created a sample program to reproduce the behavior
int main()
{
// Pointer to a Pointer, current cra... | So are you familiar with the fact that the type of a pointer hardly has anything to do with the type it points at? In other words, where you under the impression that if T1 inherits from T2 that T1* also inherits from T2*? That would be mistaken. Now, how does that apply to your current situation?
InterfaceClass**... |
4,474,699 | 4,474,911 | Boost Weak_Ptr: Destruction is more expensive than expected | For whatever reason, we're seeing quite a bit of cost from destroying weak pointers. Here's the culprit code:
~weak_count() // nothrow
{
if(pi_ != 0) pi_->weak_release(); // Consumes a huge chunk of our time.
#if defined(BOOST_SP_ENABLE_DEBUG_HOOKS)
id_ = 0;
#endif
}
We aren't in debug mode, and t... | weak_ptr needs something like a shared_ptr to implement itself -- because it needs to be able to determine if the pointer still exists, it needs to have a reference counted structure somewhere that maintains it's own refcounts.
I.e., how does the weak_ptr determine if the object still exists unless the reference count ... |
4,474,933 | 4,475,029 | What exactly is or was the purpose of C++ function-style casts? | I am talking about "type(value)"-style casts. The books I have read pass over them quickly, saying only that they are semantically equivalent to C-style casts, "(type) value", and that they should be avoided. If they mean the same thing an old-style cast does, why were they ever added to the language? Also, because dec... | Function style casts bring consistency to primitive and user defined types. This is very useful when defining templates. For example, take this very silly example:
template<typename T, typename U>
T silly_cast(U const &u) {
return T(u);
}
My silly_cast function will work for primitive types, because it's a functio... |
4,475,113 | 4,475,135 | Conditional operator always replaceable by if/else? | Until now I was thinking the conditional operator int a = b == 2 ? x1 : x2; is always replaceable by an if/else statement.
int a;
if (b == 2)
a = x1;
else
a = x2;
And the choice between one of the two is always a matter of taste. Today I was working with a task where a reference would be useful if I could write:
i... | You are correct. The conditional operator is an expression, whereas if-else is a statement. An expression can be used where a statement can be used, but the opposite is not true.
This is a good counterexample to show when you come across somebody who insists that you should never, never, never, ever use conditional exp... |
4,475,157 | 4,475,877 | Turning GetLastError() into an exception | I have a Visual Studio 2008 C++ project that uses a Win32Exception class in cases where there is an exceptional error. The Win32Exception class looks like this:
/// defines an exception based on Win32 error codes. The what() function will
/// return a formatted string returned from FormatMessage()
class Win32Exception ... |
This has already done by several people, including yours truly
https://github.com/BillyONeal/Instalog/blob/master/LogCommon/Win32Exception.hpp
https://github.com/BillyONeal/Instalog/blob/master/LogCommon/Win32Exception.cpp
Ironically, your code is not exception safe.
if( NULL != error_messageW )
{
// this may ge... |
4,475,187 | 4,476,335 | Can I generate a C/C++ client for a JAX-RS JSON API? | Suppose I have a remote JAX-RS JSON API from a server running Tomcat. I want to access this API from a C/C++ client. Are there any tools available to make life easier for the C/C++ client, e.g. code generators? Or does anybody have a suggestion for an alternative?
| I have never heard of such a tool. More to the point, I suspect that such a tool (a C / C++ generator for JSON) is impractical.
There are a number of reasons why. Some of the most significant ones are:
A key problem is that JSON doesn't have schemas. This means that an API generator would have to resort to looking ... |
4,475,338 | 4,475,493 | generate a boost.uuid from a boost.path string | I'm working in a manager class, that holds string representing paths. From this strings, I'd like to have a boost.uuid using a code like this:
m_log->addMessage("Generating UUID from path",ZEL_APPENDER,LOGLEVEL_DEBUG);
boost::uuids::string_generator str_gen;
boost::uuids::uuid generatedUUID = str_gen(full_path);
asser... | Based on the code in the header the code does not generate hashes but instead parses a UUID-as-string and converts it to a uuid.
It sounds like you are looking for a hash based on the path, which is not the same as a UUID. UUIDs are intended to be unique, implying that e.g. one could have paths of the same value stored... |
4,475,362 | 10,820,690 | How do you compile/build/execute a C++ project in Geany? | I really didn't think it would be this difficult. Geany clearly has the ability to create projects, add files to the projects, compile the individual files, but then even after googling it I could not find a clear description of how to build and execute the project... It's pretty annoying because I really like the simp... | Geany doesn't compile projects. You can use a makefile to serve the same purpose; however, you have to make it manually or use an external command that can figure out dependencies. Geany's "make" command will use the make file called "makefile" by default, so you can simply give your make file that name and all should ... |
4,475,448 | 4,475,567 | Segmentation fault when reading a vector | in a c++ program, when I want to read a vector with the size of 2697806, I always get the Segmentation fault error.
I have had tried all possible ways of reading it:
void AUROC(vector<float> v) {
...
for(std::vector<int>::size_type i = 0; i != v.size(); i++)
if (v[i]>0) ++pos; else ++neg;
for(std::vect... | Since it works for smaller sizes, my best guess is that you're running out of stack space. How to check the stack space and changing it depends on your OS: On Linux run ulimit -s to check and ulimit -s SIZE to set.
Further reading: http://www.learncpp.com/cpp-tutorial/79-the-stack-and-the-heap/
|
4,475,510 | 4,475,522 | Stop C++ Class Instantiation | Is there a way to stop a C++ class if there is an error in the instantiation? Like, return NULL maybe? Basically I have a wrapper class for MySQL, and the constructor does the connecting, but if the connection fails, I want the object to be, um, useless?
PDB::PDB(string _DB_IP, string _DB_USER, string _DB_PASS, string ... | Throwing an exception is really the only way to indicate an error during construction.
http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8
|
4,475,593 | 4,475,606 | How to use map::end from map::find in C++ | I want to use the C++ map function, map::find, to determine if a specific string is within a map. I know that find returns map::end but I am not sure on how to use it. So if the same string exists in both names_ and info_, I want it to print that string to the screen.
In my header:
std::vector<std::string>names_;
std::... | It should be:
for(unsigned int i=0;i<names_.size();i++){
if (info_.find(names_[i]) != info_.end())
std::cout << names_[i] << std::endl;
}
|
4,475,634 | 4,475,691 | Pass a string in C++ | Quick probably obvious question.
If I have:
void print(string input)
{
cout << input << endl;
}
How do I call it like so:
print("Yo!");
It complains that I'm passing in char *, instead of std::string. Is there a way to typecast it, in the call? Instead of:
string send = "Yo!";
print(send);
| You can write your function to take a const std::string&:
void print(const std::string& input)
{
cout << input << endl;
}
or a const char*:
void print(const char* input)
{
cout << input << endl;
}
Both ways allow you to call it like this:
print("Hello World!\n"); // A temporary is made
std::string someString ... |
4,475,786 | 4,475,790 | Why is this valid C? --- ({123;}) evaluates to 123 |
Possible Duplicate:
in what versions of c is a block inside parenthesis used to return a value valid?
The following is a type-safe version of a typical MAX macro (this works on gcc 4.4.5):
#define max(a,b) \
({ __typeof__ (a) _a = (a); \
__typeof__ (b) _b = (b); \
_a > _b ? _a : _b; })
Here, we see that this ex... | It is not a valid C99 or C89 nor C++. It is gcc extension, called "Statement expression". For validating a C code with gcc add options -ansi -pedantic. Also useful options are -W -Wall -Wextra
Docs for statement expressions are here http://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
This gnu extension is widely use... |
4,475,900 | 4,476,060 | 2 dimensional arrays passed to a function in c++ | I'm working on doing calculations in a two dimensional array
but keep getting a nasty error.
i call the function by :
if(checkArray(array))
and try to pass it in like this:
bool checkArray(double array[][10]) //or double *array[][10] to no avail
the error is
error: cannot convert ‘double ()[(((unsigned int)(((i... | Is this really a direct (if edited) copy of your code?
This line:
int n = 10; double array[n][n];
is not valid C++. You can't declare an array with variable dimensions. This would work:
const int n = 10; double array[n][n];
You want to declare checkArray as:
bool checkArray(double array[][10])
and you absolutely do... |
4,476,011 | 4,476,076 | weak_ptr and parent-child cyclic dependencies | I currently have something similar to the following:
class Parent
{
//just a single child... for sake of simplicity
//no other class holds a shared_ptr reference to child
shared_ptr<Child> _child;
System * getSystem() {...}
}
class Child
{
weak_ptr<Parent> _parent;
~Child
{
_pare... | Since by the time the destructor for the the child gets called, the parent's destructor has already run (dtors for member objects get run after the dtor for the containing object), even if the child was holding a plain pointer to the parent, calling the parent's member function would be invalid by the time ~Child() was... |
4,476,182 | 4,476,209 | Which cast to use; static_cast or reinterpret_cast? | int i = 1000;
void *p = &i;
int *x = static_cast<int*>(p);
int *y = reinterpret_cast<int*>(p);
which cast should be used to convert from void* to int* and why?
| static_cast provided that you know (by design of your program) that the thing pointed to really is an int.
static_cast is designed to reverse any implicit conversion. You converted to void* implicitly, therefore you can (and should) convert back with static_cast if you know that you really are just reversing an earlie... |
4,476,217 | 4,476,223 | Is C# a viable language for a major project? | I've been using C# for a while now and I love it for its great integration with Windows. The Win32 API in C++ is a monster, but that's another story. Anyway, I was wondering, is C# a "good enough" language to use for larger projects? Does Microsoft use C# in any of their applications? I've always assumed C++ was the on... | Unless you're after extreme performance (eg gaming), C# is perfectly acceptable for almost any application - I've been developing enterprise-scale apps in it for years and as a general rule, the advantages far outweigh any (negligible) performance losses compared to C++ - especially when you factor in development time ... |
4,476,246 | 4,477,522 | Applying a boost::mpl::list to the template parameter of a type | I have a class that requires a boost::variant containing shared pointers to various types as follows:
template <typename ToySharedPtrVariant, typename ColorSharedPtrVariant>
class ToyPicker {
typedef std::pair<
ToySharedPtrVariant,
ColorSharedPtrVariant
> toyAndColorPair;
typedef std::map<
std... | Using boost::mpl::transform in conjunction with boost::make_variant_over does the trick :
#include <boost/mpl/list.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/variant/variant.hpp>
template<class T>
struct add_shared_pointer
{
typedef boost::shared_ptr<T> type;
};
templa... |
4,476,272 | 4,476,327 | Visual Studio Auto Format Curly Brace on Next Line | I am so used to code like this:
if (...)
{
//somecode
}
that I simply have to change the following to the above:
if (...){
//somecode
}
I get a lot of code from other people that I have to go through and sometimes this is what I get. Is it possible to auto-format that in Visual Studio 2008 for C++?
Now some ma... | VS2008 has a simple formatter (Edit menu, Advanced, Format Selection), but it doesn't move braces.
Check out astyle and its --style=ansi flag.
|
4,476,419 | 4,476,528 | Describing intent with unique_ptr | Is the following a good way of describing ownership intent (without using shared_ptr?)
class Z { };
class A
{
unique_ptr<Z> m_z; //want to say 'I own Z'
};
class B
{
B(A & a)
{
m_z = a._z.get();
}
Z* m_z; //want to say 'I do not own Z, just a ref...'
}
Also, B._z can be dangling. Is th... | unique_ptr is Ok for ownership. If raw pointers to that object are still given out and stored elsewhere (and so it is technically shared) then that may confuse readers of your code.
If you do not want to use shared_ptr and do not want to have dangling pointers then observer pattern might help you out. Using it you can ... |
4,476,446 | 4,476,519 | Can a C/C++ compiler legally cache a variable in a register across a pthread library call? | Suppose that we have the following bit of code:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
void guarantee(bool cond, const char *msg) {
if (!cond) {
fprintf(stderr, "%s", msg);
exit(1);
}
}
bool do_shutdown = false; // Not volatile!
pthread_cond_t shutdown_cond = PTHREAD_CON... | Of course the current C and C++ standards say nothing on the subject.
As far as I know, Posix still avoids formally defining a concurrency model (I may be out of date, though, in which case apply my answer only to earlier Posix versions). Therefore what it does say has to be read with a little sympathy - it does not pr... |
4,476,474 | 4,476,505 | Networking for games? | I want my game to be entirely server side. Meaning, the client only sends their keystrokes. They then are given updates of the changed objects' positions from the server. The client then renders everything each frame.
This is a 2D game
I was thinking of something like this:
calculate the inbetween frame using Box2D, an... | Just a thought, but I think you might be forgetting network latency.
Assuming you're really sending the data 60 times per second in response to something the client sends. Than your maximum latency can be 1 second / 60 = 17ms. That will be a problem for just about any internet connection since your application is bound... |
4,476,488 | 4,476,503 | expecting initial declarator before functions when i put header file in | For some reason when I put my header file in I get this error: expected init-declarator before "int" (or void)
main:
#include "header.h"
int main()
{
char gender;
float gpa;
ifstream inData;
ofstream outData;
inData.open("./Ch7_Ex4Data.txt");
outData.open("./Ch7_Ex4Dataout.txt");
inDat... | Missing semicolon in your declaration of initialize.
void extern initialize(int&, int&, float&, float&); // <---- here
|
4,476,543 | 4,476,551 | OS independent threading in C++? | Is it possible to implement OS independent threading model of User Level Threads (ULT) in C/C++? In other words, can we break down a process logically into ULTs and dynamically make switches in between them?
| Boost.Thread offers a fair amount of abstraction for cross-platform threading.
|
4,476,616 | 4,476,660 | How to use PERL XS to call a C++ function that takes in a STL Vector | I have been using PerlXS to write a perl wrapper around a C++ Object. Usually my fcn takes in a string/int etc and I can just make them with no problem. I just write code like this in the .xs file
MyClass::func_a(std::string a, int b);
This time; I have a need to have a function that takes in a stl vector
MyClass::fun... | You can't directly call the Native function which takes a STL container. You should write a wrapper and convert SV* manually to STL container.
If You don't know how to do this (like I was), try to use SWIG http://www.swig.org/
It can generate wrappers for a native funciton to use it from scripting languages (including ... |
4,476,663 | 4,484,174 | Speed of swig wrappers | If I were to write several classes in c++ then use swig to do the conversion so I could later use them in python, would they run faster or slower than if I completely rewrote them in python? Or is there no noticable speed difference?
| The quality and speed of wrappers generated by SWIG is very good, and they will probably perform just as good as handcrafted wrappers.
From my experience, the wrappers themselves are very thin and add very little overhead to the native functions they wrap, making it a perfectly valid choice to use wrapped libraries in... |
4,476,735 | 4,476,756 | General C++ Linux-to-Windows porting questions | Background: A network-based service (tcp+udp, not http) exists with a soon-to-be public published C++ linux client API. This client API Uses normal tcp sockets, udp sockets, C++ namespaces and parts of the stl like std::map and std::vector, and will be published as a set of header files and .a and .lib files to link ... | As long as the compiler you're using produces genuine .dll or .lib files, you shouldn't have an issue linking them with a standard linker in Windows. However, only either unmanaged development (meaning classic Win32 API development) or C++/CLI will be able to link against these .dlls. If you compile to a .dll (not a .l... |
4,476,804 | 4,477,095 | Can `std::istream::operator>>()` accept integer radix prefixes like stdio's %i format specifier? | When using scanf() and its variants, the format specifier %i will accept data as hex (prefixed "0x"), octal (prefixed "0"), or decimal (no prefix), so for example the strings "0x10", "020", and "16" are all converted to an integer with decimal value 16.
Can this be done with std::istream::operator>> formatted input?
... | The base field in the format flags of basic_istream dictates how to interpret numbers. The field can be set to dec, oct and to hex. By default it's set to dec. If it's set to none of them, basic_istream will behave like scanf's %i flag:
// automatically detect the base, depending on prefix
std::cin.unsetf(std::ios_base... |
4,477,040 | 4,478,247 | Is this way of creating static instance thread safe? | I have the following sample C++ code:
class Factory
{
public:
static Factory& createInstance()
{
static Factory fac;
return fac;
}
private:
Factory()
{
//Does something non-trivial
}
};
Let's assume that createInstance is called by two threads at the same time. So will... | C++11 and above: local static creation is thread-safe.
The standard guarantees that:
The creation is synchronized.
Should the creation throws an exception, the next time the flow of execution passes the variable definition point, creation will be attempted again.
It is generally implemented with double-checking:
fir... |
4,477,139 | 21,426,501 | Warnings or errors for C++ implicit conversion of primitives | I've done some heavy refactoring of some C++ code, and discovered numerous bugs arising from implicit conversions that I'm not aware of.
Example
struct A *a();
bool b() {
return a();
}
void c() {
int64_t const d(b());
}
Issues
In b, the return type of a is silently cast to bool.
In c, the value returned fr... | In the C++ programming language, 3rd edition, appendix C.6, namely "Implicit Type Conversion", Bjarne Stroustrup classifies conversions as promotions and conversions: the first ones "preserve values" (that's your case 2), the second ones doesn't (case 1).
About conversions, he says that "The fundamental types can be co... |
4,477,219 | 4,477,258 | C++, reason of constructors | I have two questions.
1) What does a constructor really do? What happens if we don't use constructors while declaring an instance?
2) Can you tell me the difference between these two?
A a(1,2)
A *a = new A(1,2)
Best regards.
| A constructor initializes the member variables of the class so that it is ready for use. The result of not using a constructor when declaring an instance varies on context.
If you are allocating a variable on the heap, like so:
A *a;
a will point to a random address in memory until it is assigned to NULL or 0, or an e... |
4,477,276 | 4,477,906 | Providing login and password through c++ like expect script in Unix/Linux | Problem ::
I want to remote login to a server by SSH and execute some commands and retrieve output of the excuted commands.
Solution ::
I have achieved the same using my "expect script" in my perl script and then do processing on it. But , it is too slow , takes around 10 seconds to get PID of a remote process and then... | It is possible, but it takes a lot of work and a complete program to do this is too long to post here. Especially I/O buffering should be taken into account when reading and writing are interleaved. A single write phase followed by a single read phase would be pretty easy, though.
In any case, I'd recommend using a soc... |
4,477,318 | 4,477,331 | The purpose of wrapping headers with #ifdef _cplusplus | #ifdef _cplusplus
#include headerfile.h
#endif
I understand the concept behind this, though I don't exactly understand why it's needed.
If the purpose is to prevent "mangling" of headers when the code isn't compiled in C++:
-how is the code compiled if not in C++?
-how would the code continue to function without th... |
how is the code compiled if not in C++?
With C.
how would the code continue to function without that header?
That's why the header is included. If it would compile and work without the header with a C++ compiler, the #ifdef would be pretty pointless.
what circumstances would require this?
They may just bring in ... |
4,477,668 | 4,478,049 | A problem with forwarding an exported function in a DLL | Hi
I am forwarding an exported function of a DLL to another function in my DLL. I use ExpX64 for editing the export table of the DLL.
(for example I forward the ?MyFunc@MyClass@@SAJJAEAUMyStruct@@@Z to myDLL.?MyFunc@MyClass@@SAJJAEAUMyStruct@@@Z)
My problem is that my target function is a member of a class and in runti... | I doubt that the error you get has to do anything with the forwarding. The error is STG_E_REVERTED, and that is related to structured storage (which your method appears to be completely unrelated to). The error is apparently particularly frequent in SharePoint applications.
Edit: Structured Storage is a Microsoft API f... |
4,477,787 | 4,477,806 | why are there not a lot of c++ libraries like in java and javascript | I am just revisiting C++ and I'm already missing all the java libraries like hibernate and JAXB.
So why are there not a lot of open source libraries as there are in java?
| Well, there are, but maybe not the same. That's maybe because C++ programmers have different needs from Java programmers. And sometimes similar libraries exist, but are named differently. There are plenty of XML parsers for C++ too, but of course they are not called Java Architecture for XML Binding.
|
4,477,948 | 4,477,965 | C++: overloading list.end() and list.begin() methods for constant iterators | I'm still trying to implement my own version of LinkedList class and now I have problems with overloading methods for constant iterators. For example, when I try to print out list using this code:
cout << "citer:" << endl;
for (UberList<int>::CIter it = ulist.begin(); it != ulist.end(); ++it)
{
cout << *it << " ";
}
c... | You should provide a conversion from Iter to CIter. Standard containers do (Table 65, in 23.1 "Container requirements", says that X::iterator is convertible to X::const_iterator)
The caller can ensure that the const overload is called by using a const reference, but you shouldn't force them to do that, because they wil... |
4,478,107 | 4,479,387 | Make callback accept temporary on VS 2010 | I have a callback implementation using rvalue references to store arguments that works fine with gcc, but fails to compile in VS 2010 on some code. A short version:
#include <iostream>
#include <string>
class B {
public:
virtual void execute() = 0;
};
template<typename FuncType, typename ArgType>
class F : public... | It's not exactly clear what you hope to achieve with respect to the rvalue reference member. It just doesn't look right. You should avoid storing a reference. You can still use things like std::ref and std::cref if you want the function object to store a reference-like object (much like std::bind behaves).
The issue yo... |
4,478,280 | 4,478,408 | The way of the include in c++ using Eclipse | I learned that if I compile main.cpp the compiler simply replaces all includes with the actual content of the file i.e. #include "LongClassName.h" with the text in that file. This is done recursively in LongClassName.h. In the end the compiler sees a huge "virtual" file with the complete code of all .cpp and .h files.
... |
In the end the compiler sees a huge "virtual" file with the complete code of all .cpp and .h files.
This is wrong. In .cpps you should include just the .hs (or .hpps if you like), almost never the .cpps; the .h in general just contain the declarations of the classes and of the methods, and not their actual body1 (i.e... |
4,478,481 | 4,478,496 | What does `class HelloWorld : public Gtk::Window` mean? | I'm following the Gtk "Hello World" tutorial found here, and I've come across a line in a class declaration I've never seen before (I've only been learning to program for a few months now), and I was wondering if someone could please explain it to me. The line is the
class HelloWorld : public Gtk::Window
I know what c... | It means that HelloWorld is derived from Gtk::Window, so it inherits its behaviour.
HelloWorld represents a Gtk window, so it is just natural to have it derive from the Gtk's window class. It's constructor will probably add a button to the window (the actual window is created by the parent class constructor, which is i... |
4,478,636 | 4,478,653 | std::remove_if - lambda, not removing anything from the collection | Ok, I expect I've made a dumb mistake here. I have a list of DisplayDevice3d and each DisplayDevice3d contains a list of DisplayMode3d. I want to remove all items from the list of DisplayDevice3d that don't have any DisplayMode3d's. I'm trying to use a Lambda to do it, ie.:
// If the device doesn't have any mode... | You need to call erase on the iterator returned from remove_if, It should look something like this:
auto new_end = std::remove_if(MyDisplayDevices.begin(), MyDisplayDevices.end(),
[](const DisplayDevice3d& device)
{ return device.Modes.size() == 0; });
MyDisp... |
4,478,708 | 4,478,737 | setter function for a vector<someClass> in c++ | I have the following classes:
class Vertex {
public: float X;
float Y;
float Z;
Vertex (float first, float second, float third){
X=first;
Y=second;
Z=third;
}
};
class Obj {
vector<Vertex>vertexCoordinates;
vector<vector<int>> faces;
vector <vector<float>... | Since your Vertex has only primitive non-pointer members, you don't necessarily need to define a copy constructor for it: the compiler will generate one for you that copies the elements by their copy constructors (in the case of a float, that's usually a bitwise copy). The copy constructor and assignment operator for s... |
4,478,808 | 4,480,114 | Lag compensation with networked 2D games | I want to make a 2D game that is basically a physics driven sandbox / activity game. There is something I really do not understand though. From research, it seems like updates from the server should only be about every 100ms. I can see how this works for a player since they can just concurrently simulate physics and do... | Typically, what will happen is that the player will view the game 100ms behind how it actually is. That, and you have to accept that some game designs just require faster server updates. Typically, games that need faster server updates use client/server model where the server computes all the physics, not the client. Y... |
4,478,829 | 4,478,994 | How can I ensure that UnhookWindowsHookEx is called even upon abnormal termination? | Unfortunately, MSDN is not clear enough with it. I'm writing a program which uses a global hook, and I'm worrying about what would happen if the program terminates abnormally (crashes, killed by user, etc).
Does Windows automatically unhook global hooks installed by a process when the process terminates?
If not, is it... |
Yes, when a process terminates the system cleans up after it -- all handles are closed implicitly.
No, it's not, and you don't need to anyway.
(It's Yes and no not no and no)
I don't see why there's a DLL loaded in another process involved here. (EDIT: I was originally thinking of a systemwide hook such as CBTProc -- ... |
4,479,005 | 4,479,178 | GTK Scrolled Window - scroll to the bottom | I'm writing an app using GTK+, and I have a problem. I'm using GTK Scrolled Window and I must scroll the vertical scrollbar to the bottom, but I don't know, how. I was looking in Google, but I found nothing.
| You must get the adjustment object (hadjustment, vadjustment), and then call methods on them.
Assuming gtkmm, since you tagged this with c++, something like this:
Glib::RefPtr<Adjustment> adj = win->get_vadjustment();
adj->set_value(adj->get_upper());
|
4,479,017 | 4,479,095 | Storing std map in map | I have to store std::map as value in std::map
std::map< std::string, std::map<std::string, std::string> > someStorage;
How to insert into second(inner) map? I tried with:
someStorage.insert( std::make_pair("key", std::make_pair("key2", "value2")) );
But this throws a lot of errors. What's wrong?
| Try:
std::map< std::string, std::map<std::string, std::string> > someStorage;
someStorage["Hi"]["This Is Layer Two"] = "Value";
|
4,479,381 | 4,479,436 | Delete any container using templates | I have a lot of code where I am deleting vector containers that have pointers in them, that is, I have to delete all the pointers first and then clear the container. Every time I would iterate through and delete the pointers manually (I am aware of stl::algorithms for_each). To circumvent all that code, I created a tem... | You already have a valid answer, but just to provide an alternative, I believe you should consider using Boost Pointer Container and let it handle memory management :
This library therefore provides
standard-like containers that are for
storing heap-allocated or cloned
objects (or in case of a map, the
mapped ... |
4,479,408 | 4,479,501 | Regex for numbers on scientific notation? | I'm loading a .obj file that has lines like
vn 8.67548e-017 1 -1.55211e-016
for the vertex normals. How can I detect them and bring them to double notation?
| The standard library function strtod handles the exponential component just fine (so does atof, but strtod allows you to differentiate between a failed parse and parsing the value zero).
|
4,479,459 | 4,479,627 | What can C++ developer use on Nokia N900 for capturing live audio from microphone? | So I have G++ installed, I can esely capture from main camera with OpenCV (at least 4 fps). But I also want to capture Live sound from mic. What are my options?
| Take a look at QT for Maemo. It should handle the capturing part. Not sure about openCV though.
|
4,479,504 | 4,479,553 | first fstream program | I am trying to write a program that gets data from this text file:
Then, based on this data, the program is supposed to calculate the average gpa of each gender (f=female, m=male) and output the results in a new file.
It must also contain these five functions:
openFiles: this function opens the input and output files ... | You're making good progress.
You don't need the static_casts in averageGrade.
printResults is missing most of its function signature.
In sumGrades, gpa and gender should be local variables, not parameters. You also want to compare to the character literals 'm' and 'f', not variables named m and f with random contents.... |
4,479,522 | 4,479,603 | Alternatives for empty macros | In my C++ header file, I have the following:
#ifdef _DLL
#define DLL_API __declspec(dllexport) // Being compiled as a DLL.
#else
#define DLL_API // Not being compiled as a DLL.
#endif
Later on, I have things like:
DLL_API int GetNumber();
I'm oversimplifying, but the basic question here is whether there's a way to ge... | No.
When DLL_API is defined as preprocessor macro that contains nothing then preprocessor replaces DLL_API with nothing and compiler will see nothing there. If it is undefined for preprocessor then preprocessor does nothing with it. Then compiler will see it unchanged and you get compiler error about unknown identifier... |
4,479,597 | 4,479,652 | Does making a struct volatile make all its members volatile? | If I have:
struct whatever {
int data;
};
volatile whatever test;
will test.data be volatile too?
| Another question can be asked (or simply another way to look at the original question):
Does making a struct const make all its members const?
If I have:
struct whatever { int data; };
const whatever test;
Will test.data be const too?
My answer is : Yes. If you declare an object of type whatever with const then all i... |
4,479,705 | 4,479,732 | Any command in C++ called script (); | I am new to C++ and I am trying to understand a part of code and i am stuck here
try {
Result = Script(ArgStr);
}
Is this come command in C++ .. if i go tolook where is this defined... it says
virtual bool Script(CString ArgStr) = 0;
I am confused about this part....
I would appreciate for your help in this r... | This is not part of normal C++. It looks like it's a member function call called "Script" from the same class you are working in. It's argument type is a single CString and returns a boolean value. The variable Result is just that, a variable and is instantiated elsewhere but assigned within the try-catch block you'... |
4,479,722 | 4,479,831 | C++, OpenGL clipping | I'm making a cube based game (everything is a cube) and currently trying to optimize it by not drawing the stuff outside the field of view.
The following applies only to the x and y planes, I'll worry about the z later... so only side clipping for now.
I know my own position and rotation in the world and the position o... | It would be much, much faster (and less error-prone) to implement an octree. You will then be able to cull all non-visible cubes by discarding the parts of the octree that do not intersect with your viewing frustum. You won't have to perform this test for every single cube, and you'll be able to reduce the test to comp... |
4,479,871 | 4,479,937 | Use of derived class' typedefs in base | I want the derived class to be a descendant of a template class. That class depends on descendant's members.
In short I want this code to compile:
struct IBootParams
{
virtual bool GetImmediate() = 0;
};
template <class T>
struct TBootBootParams
{
typename T::TransType transferType;
typename T::UseAbort_ ... | You can't do it this way. When the compiler instantiates TBootBootParams<BootBootParams> it has not yet completely read the whole definition of BootBootParams so you can't access its members from inside the definition of TBootBootParams (member functions of TBootBootParams are an exception because they are instantiated... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.