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,599,514 | 7,599,989 | libc++ vs VC++: Can non-UTF conversions be done with wstring_convert? | The C++11's std::wstring_convert works great* for the standard UTF-8 <-> UTF-16/UCS2/UCS4 conversions. However, when I attempted to instantiate a wstring_convert or wbuffer_convert with a facet not from <codecvt>, it didn't work as expected:
// works as expected
std::wstring_convert<std::codecvt_utf8<wchar_t>> ucs4conv... | I am admittedly biased in this answer. But I will attempt to back up my claims with references to N3290 (which is unfortunately no longer publicly available). And I will also offer a solution.
Analysis:
The synopsis of wstring_convert in [conversions.string]/p2 includes:
private:
byte_string byte_err_string; // ex... |
7,599,600 | 7,599,658 | difference between using extern and using a getter? | I have a camera class that sets up two variables - a projection and a view matrix. I could either make these extern and include the header in anything I wanted to have access to the variables, or I could make a getter for them / pass references for these variables to anything that needed them. Is this simply a case of ... | A getter has the advantage of not letting external code write in your variable (eg a pointer array can't be incremented).
Otherwise, it's functionally the same, especially if it's for your own use.
|
7,599,801 | 7,599,991 | Number of parallel instances of my process (app) | Is there some portable way to check the number of parallel instances of my app?
I have a c++ app (win32) where I need to know how often it was started. The problem is
that several user can start it parallel (terminal server), so i cannot search the "running process" list because I'm not able to access the the list of o... | Edited to add:
Suppose you have a license that lets you run 20 full-functionality copies of your program. Then you could have 20 mutexes, named MyProgMutex1 through MyProgMutex20. At startup, your program can loop through the mutexes. If it finds a spare mutex that it can take, it stops looping and enters full-funct... |
7,600,057 | 7,600,215 | C++: What are R-Value references on a technical level (ASM)? |
Possible Duplicate:
What is the difference between r-value references and l-value references? (CodeGen)
I was wondering, can anyone explain what R-Value references are on a technical level? By that I mean: What happens on assembler level when R-Value references are created.
For a small test to see what happens insid... |
What happens on assembler level when R-Value references are created.
Whatever is needed to preserve high-level semantics. What compiler does exactly depends on what compiler vendor thought would be a good idea. Assembly has no concept of lvalues, rvalues, or references, so stop looking for them. Turn on the optimisat... |
7,600,303 | 7,600,576 | Valgrind memory leak reported in QT list append | I am using a serializer in QT C++. It looks ok but valgrind (memcheck tool) is reporting a memory leak on this function.
Valgrind cmd: valgrind --tool=memcheck --leak-check=full
QDataStream &operator>>( QDataStream &in, QList<AppNodeRecord *> *objAppNodeListRecord)
{
quint32 len;
in >> len;
objAppNodeListR... | The QList isn't responsible for deallocating the AppNodeRecord pointers you append to it, you have to do it manually (qDeleteAll might help in that case).
But as usual, for lack of a good reason, use QList<AppNodeRecord> to avoid this hassle in the first place.
|
7,600,346 | 7,600,380 | What is a nonstatic member function? | I am being told that I can't use the 'this' keyword in a class function. I'm coming from c# and i'm used to this working, but the compiler tells me that it can only be used within nonstatic member functions.
D3DXVECTOR3 position;
void Position(D3DXVECTOR3 position)
{
this.position = position;
}
| this is a pointer containing the address of the object.
D3DXVECTOR3 position;
void YourClassNameHere::Position(D3DXVECTOR3 position)
{
this->position = position;
}
Should work.
D3DXVECTOR3 position;
void YourClassNameHere::Position(D3DXVECTOR3 position)
{
(*this).position = position;
}
Should also work.
|
7,600,373 | 7,600,495 | Getting List of Volumes always Says C:\ | Why The Following Code always reports C:\ although It reports different Device Name
handle = FindFirstVolumeW(volName, sizeof(volName));
do{
wchar_t wVolName[MAX_PATH];
QString::fromWCharArray(volName).toWCharArray(wVolName);//make a copy of volName on wVolName
wVolName[wcslen(volName)-1] = L'\0';
w... | From the GetVolumePathName documentation:
If you specify a relative directory or file name without a volume
qualifier, GetVolumePathName returns the drive letter of the current
volume.
|
7,600,557 | 7,600,859 | AES cryption quellcode | I need a small, like a two pieced, version of an AES encryption. I googled and found AES - Advanced Encryption Standard (source code), but the code seems to be written for Windows and I need a multi-platform one.
Is there any other small version of an AES encrpytion known or a fix for the used functions which seem to ... | The reference implementation for AES can be found here: http://www.efgh.com/software/rijndael.htm. The main source file only includes <stdio.h>, but it doesn't even depend on that; you should have absolutely no problem using it on any platform.
|
7,600,590 | 7,600,896 | How to use windows DLL (late bound) methods in C++? | I've basically been trying to get this working for the last couple of days, but all of my attempts and all the examples/suggestions found online have failed. I'm trying to use Microsoft's "setupapi.dll" methods in implementing my own .dll to access a peripheral device I have created.
Right now I'm simply trying to use... | Your code fails because you are passing the wrong function name to GetProcAddress(). Like most API functions that have string parameters, SetupDiGetClassDevs() has separate Ansi and Unicode flavors available (SetupDiGetClassDevsA() and SetupDiGetClassDevsW(), respectively), and the API header files transparently hide ... |
7,600,602 | 7,600,921 | how to draw textures using stb_image.c | I want to load this picture into a 2d texture and then draw it onto the screen. The main problem is loading the picture into a texture variable. The follow code output the correct width and height and rgba but how do I put the data into a 3d texture.
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
/* more includes... */... | First you need
a drawable (window, PBuffer, framebuffer)
a OpenGL context associated with the drawable
You can use GLFW, SDL or GLUT for getting those (personally I recommend GLFW, if you need only one single window).
Create a texture name with
GLuint texture_name;
void somefunction(…)
{
glGenTextures(1, &texture_na... |
7,600,621 | 7,601,243 | How to make universal class method? | Is there any way to make a class template function?
So for example
//Warning: this is conceptual pseudo-code
template<typename TemplateClass, TemplateItem>
TemplateClass &TemplateClass::operator=(TemplateItem &B)
{
Item = B.Item;
return *this;
}
//or...
template<typename TemplateClass, TemplateItem>
TemplateCl... | I'm sure I'll get bashed by the "preprocessor is evil" group, but I think you are looking for something like this:
#define DEFINE_ASSIGNMENT(mainClass,memberClass,member) \
mainClass & mainClass::operator = (const memberClass & rhs) \
{ \
member... |
7,600,654 | 7,600,803 | Can someone write this code with better logic? | I am stuck with this problem for 2 days. Can someone help me with the logic ?
I am working on C++ programs for good algorithms. I am now working on the Danielson-Lanczos Algorithm to compute the FFT of a sequence.
Looking at
mmax=2;
while (n>mmax) {
istep = mmax<<1;
theta = -(2*M_PI/mmax);
wtemp = sin(0.5... | Better indentation would go a long way. I fixed that for you. Also, this seems to beg for better locality of the variables. The variable names are not clear to me, but that might be because I don't know the domain this algorithm belongs to.
Generally, if you want to make complex code easier to understand, identify sub... |
7,600,962 | 7,601,009 | How can I make a function only possible to be called by certain subclasses in c++? | I have a class base with a private array (I cannot make it protected).
I have getters and setters set for objects in the array.
base has a subclass sub1 and sub1 has a subclass sub2.
Is there a way to make sub1 only able to access some of base's getter's and setter's and make sub2 able to access other getters and sette... | No. Not in any good fashion
If you want this, you should break your base class into better granularity by creating several polymorphic interfaces and instead pass those interfaces around via pointer or reference so that each class only sees the functions it needs to see.
|
7,601,204 | 7,604,294 | How to suppress "There are still active COM objects in this application" error when closing application? | I've written a few ATL COM objects that are used for drag-and-drop within my C++ Builder application.
Due to reasons beyond my control, my application still has active COM objects when the user attempts to close it. This is because other COM clients that use my objects seem to cache my COM objects and don't release th... | The popup message is displayed by the the TATLModule::AutomationTerminateProc() callback function in atlmod.h. It is registered by the TATLModule::InitATLServer() callback, which calls the VCL's AddTerminateProc() function. When the TForm::Close() method is called, it calls CallTerminationProcs() to see if the app ca... |
7,601,256 | 7,601,317 | Can subclass inline a pure virtual method that is not inline in the base? | As I understand it, the compiler can inline a virtual function call when it knows at compile time what the type of the object will be at runtime (C++ faq).
What happens, however, when one is implementing a pure virtual method from a base class? Do the same rules apply? Will the following function call be inlined?
class... | The answer is of course "it depends", but in principle there's no obstruction to optimization. In fact, you're not even doing anything polymorphic here, so this is really straight-forward.
The question would be more interesting if you had code like this:
child c;
base & b = c;
b.print();
The point is that the compiler... |
7,601,375 | 7,601,470 | delete multidimensional arrays | In C++ FAQ, the [16.16] gives the following example,
void manipulateArray(unsigned nrows, unsigned ncols[])
{
typedef Fred* FredPtr;
FredPtr* matrix = new FredPtr[nrows];
// Set each element to NULL in case there is an exception later.
// (See comments at the top of the try block for rationale.)
for (un... |
The try/catch block is necessary to ensure proper clean-up even if an exception is thrown anywhere in the code before the normal clean-up happens. This includes an exception in one of the new expressions. The delete[] is safe because all the relevant pointers were initially set to zero, so that the deletion is valid e... |
7,601,433 | 7,601,848 | An automated algorithm tool for running time | I am wondering if there is an open source project that can run the algorithm and tell us what the running time is (just need to know the Big-Oh running time).
I know I can do this with hands, but a lot of algorithms are too long or too complex to actually trace the running time.
Thanks.
PS: Mainly for C++ (but it work... | There's just no way to do this. You'll never know generally what set of n you have to test for any given algorithm. For example sin and linear will look almost identical at small values of t (the input). Exponential can look polynomial in various ranges of input. For other functions, the constant time may make a linear... |
7,601,524 | 7,601,589 | Choosing between reference (T&) and const pointer (T* const) | Is there any reasonable use case, where one should use const pointer over reference?
T obj;
T &r = obj; // style-1
T* const p = &obj; // style-2
Both the style can be used for the same purpose. I always prefer the 1st style in the code and consider the later style as deprecated. However I still wonder if missed any u... | A const pointer (T* const) can be NULL, and that can be useful when passing arguments to a function or when returning values from a function. For example, if you have a search function, you might want it to return NULL if it didn't find anything. You can't do that if it returns a reference type.
|
7,601,533 | 7,616,355 | Print types of arbitrary C++ expressions | I'm interested in writing a tool for teaching purposes that evaluates C++ expressions and prints their types. Essentially, my thinking is that my students could type in any expression, and the program would echo back the type of the expression. Is there an existing tool that already does this? If not, is there a pretty... | I came up with an answer inspired by Ben Voigt's comments. Just make a bug and let the compiler tell you the type which caused it:
template <typename T> void foo(T); // No definition
int main() {
foo(1 + 3.0);
}
Result:
In function `main':
prog.cpp:(.text+0x13): undefined reference to `void foo<double>(double)'
Al... |
7,601,556 | 7,601,976 | Double-Ended Queue: is this a sound "add to front" implementation? | I'm working on an implementation of the Double-Ended Queue as a Doubly-Linked List (for personal enrichment), and I was wondering if anyone minded taking a look at my PushFront function to see if I'm on the right track. It should be self-explanatory enough on it's own (I hope).
void DeQueue::PushFront(void* item) {
... | Answer to second edit: You can't. You'll have to retain a reference to it.
void* DeQueue::PopFront() {
if (Empty())
throw logic_error("stack is empty");
QueueItem* deleteme = head->next; //get node
void* temp = deleteme->data;
deleteme->next->last = head;
head->next = deleteme->next;
... |
7,601,731 | 7,602,036 | How does one safely static_cast between unsigned int and int? | I have an 8-character string representing a hexadecimal number and I need to convert it to an int. This conversion has to preserve the bit pattern for strings "80000000" and higher, i.e., those numbers should come out negative. Unfortunately, the naive solution:
int hex_str_to_int(const string hexStr)
{
strin... | While there are ways to do this using casts and conversions, most rely on undefined behavior that happen to have well-defined behaviors on some machines / with some compilers. Instead of relying on undefined behavior, copy the data:
int signed_val;
std::memcpy (&signed_val, &val, sizeof(int));
return signed_val;
|
7,601,981 | 7,602,063 | Higher-order functions in C++, using std::wcout fails with error C2248 | I'm playing around with implementing functional-style stuff in C++. At the moment, I'm looking at a continuation-passing style for enumerating files.
I've got some code that looks like this:
namespace directory
{
void find_files(
std::wstring &path,
std::function<void (std::wstring)> process)
{
... | In display_file_details, you need to take your wostream by reference. iostream copy constructors are private.
|
7,602,201 | 7,602,248 | Expected constructor, destructor, or type conversion before '*' token Templated linked list | My problem is really similar to this. However, my implementation differs in that I'm using a templated linked-list
Here's where I'm getting errors (second line). The purpose of this function is to return a pointer to a node at the k-th location in the list
template <class T>
List<T>::ListNode* List<T>::find(int k)
{
... | You need to use the typename keyword:
template <class T>
typename List<T>::ListNode* List<T>::find(int k)
{
...
}
This lets the compiler know that ListNode is a type. It is needed whenever you have a dependent name (i.e. one which depends on a template parameter) which is a type.
|
7,602,298 | 7,602,424 | C++ Passing variables into a class to a function | I have a class "Month" that has void member functions and void parameter passing. I need to overload the constructor (I think) but the compiler doesn't like my attempts.
class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter); //?
Month::Month(int m) : month(m) {} //Want above ^ t... | Do it like so:
class Month
{
public:
Month(char firstLetter, char secondLetter, char thirdLetter) :
first(firstLetter),second(secondLetter),third(thirdLetter)
{
const char * monthNames[] = {
"Jan","Feb","Mar","Apr","May","Jun",
"Jul","Aug","Sep","Oct","Nov","Dec"
};
... |
7,602,341 | 7,602,971 | VC++ Project, want to compile within another IDE but something is missing | I am fairly new to C++.
I want to write plugins for an application called Cinema 4D.
Maxon, the maker of C4D, provides an API for doing this. The header-files are located in a special folder.
The "cinema4dskd" is a Visual Studio project containing sample plugins. Within this project there is another subproject called _... | 'cORG'
is a so-called multi character literal. Its value does not fit into a char variable, you will need an 'int' to hold it, and according to this post
C++ multicharacter literal
it is compiler-specific how this thing is interpreted. Seems the other compiler you have tested does not support those kind of literals.
|
7,602,656 | 7,602,686 | When I initialize a C++ container (such as a std::list) is the copy constructor called? | When I initialize a STL container such as a list< vector<char> > using e.g. my_list.push_back(vector<char>(5000, 'T')) is this copied after construction? Or does the compiler invoke the constructor inside list< vector<char> > itself?
| In C++03 push_back is defined as void push_back(const T& x);. That means that you are constructing a vector and a const reference to such temporal is being passed to the list. Then the list internally invokes the copy constructor in order to store a copy of such element.
In C++11 there is an extra definition for void p... |
7,602,664 | 7,602,822 | Graph Representation in C++ | I am going through a book The Design and Analysis of Computer Algorithms Reading through the Graph chapter, I am trying to implement DFS. By Reading definition of this algorithm it says, Graph G=(V,E) partiions the edges in E into two sets T and B. An Edge (v,w) is place in set T if vertes w has not been previously vis... | In VTK, edges are stored in a vector, and it always stores a pair (v,w). Near this vector there are 2 other vector of vectors to store in and out edges of graph nodes. When a new edge is added, it added to edge vector, its nodes (v,w) are added to in and out edges vector of vectors, too.
|
7,602,682 | 7,602,703 | Strings between quotation marks in C++ |
Possible Duplicate:
What do single quotes do in C++ when used on multiple characters?
The following code compiles in C++:
unsigned int x;
x = 'abc';
What does it mean? Is putting string between quotation marks legal? What does it do?
| Is not a string, but a multi character literal. See What do single quotes do in C++ when used on multiple characters?. (Vote to close as duplicated)
|
7,602,721 | 7,602,992 | C++ Bytes To Bits Conversion And Then Print | Code Taken From: Bytes to Binary in C Credit: BSchlinker
The following code I modified to take more than 1 Byte at a time. I modified it, and got it half working and then got really confused on my loops. :( Ive spent the last day and a half trying to figure it out... but my C++ skills are not really that good (still... | Man, there is a lot going on in this code, so it's hard to know where to start. Suffice to say, you're trying a bit too hard. It sounds like you are trying to 1) pass in a byte array; 2) turn those bytes into a string representation of the binary; and 3) turn that string representation back into a value?
It just so hap... |
7,602,758 | 7,603,153 | Having issues with execvp() | So here is the bit of my code that's giving me problems:
void childProcessHandler(string command){
int argCounter = 0;
for(int i=0; i!=command.size(); i++)
argCounter+=( command.at(i) == ' ');
char * temp, *token;
char *childArgs[argCounter];
argCounter = 1;
temp = new char [command.size()+1];
strcpy (temp, co... | Your childargs vector of pointers point into the bytes allocated in the block of memory "temp". When you free temp, you are removing the memory pointed to by the childargs pointers, possibly corrupting some of the values within your vector.
Remove the call to delete[] to stop freeing the memory pointed to by the childa... |
7,602,763 | 7,602,913 | Error for the header file of goblin library in c++ | I am trying to use Goblin library which is used for special network algorithms. This library provides some header files and objects in C/C++. So, you can easily add a header file to your program and use some special classes and functions.
Unfortunately, when I add the header file, I get error. In the following you can ... | try:
g++ -lgoblin -L/pathToLibgoblin/ -o test.o test.cpp
|
7,602,793 | 7,602,925 | How would I make a program to monitor another system's vitals with a remote connection? | I'm looking to write a custom program in VB.NET / C++ / C# that would allow me to monitor a system's vitals over a Remote Desktop Connection.
I'm only looking for tips on how to implement a connection like this in code (eg. is it just a simple object or call to a WScript function? or is it much more sophisticated?). As... | I don't think the RDP protocol is the right solution for this. Other mechanisms were invented for this, such as WMI.
WMI is a scriptable interface that allows you to query the local or remote computer's information. You can use your tool of choice - C#, VBScript, or my personal preference - Powershell. Here is an examp... |
7,602,797 | 7,602,817 | C++ std::string and string | I don't suppose anyone tell me whats the difference between using the std::string and just the string data type in C++??
In what situation should the std::string should be used over the standard string??
Thanks.
| They're both the same type. std::string specifies the namespace, while string only makes sense if a using namespace std; or using std::string statement is used. So it doesn't make any difference what you use (as long as you're consistent).
If you're talking about the string literals (such as "hello"), then they're of t... |
7,602,863 | 7,603,067 | Can an array or function lvalue be converted to an rvalue? | According to C++ Standard 2003:
An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue.
What does it mean that array and function cannot be converted to rvalue?
| Both function and array types are covered by later clauses (4.2, 4.3).
An lvalue or rvalue of type “array of N T” or “array of unknown bound of T” can be converted to an rvalue
of type “pointer to T.” The result is a pointer to the first element of the array.
(...)
An lvalue of function type T can be converted to a... |
7,602,867 | 7,603,727 | building c++ config file parser using lex and yacc | I am trying to build config file parser (c++ application)from scratch using tools like lex and yacc. The parser will be able to parse files like
# Sub group example
petName = Tommy
Owner = {
pet = "%petName%"
}
Is there any step by step guide/link to articles on how to achieve this using tools like lex and yacc? Th... | Boost Property Tree
It was designed for configuration files. It does reading, writing in the following formats:
INI
INFO
XML
JSON
Here is the five minute tutorial page which should give you a good idea:
http://www.boost.org/doc/libs/1_47_0/doc/html/boost_propertytree/tutorial.html
|
7,602,962 | 7,603,018 | Return a pointer to an array | Suppose you have a class with a private pointer to an array. How can you use a getter to access (or effectively copy the data) so you can access it in a different variable.
class MyClass
{
private:
double *x;
public:
myClass();
virtual ~MyClass();
double* getX() const;
void setX(doub... | Just a guess, the program is crashing or showing the wrong output. This is because the constructor is setting a pointer to a local array, which leaves scope and gets destroyed at the end of the constructor.
|
7,603,000 | 7,603,026 | STL algorithm to delete all the objects in a container? | Is there a STL utility/algorithm to do delete *the_object_iterator; on all the objects? So that I can clear() safely? The STL container is a set and the objects are pointers to C++ classes created with new.
Boost seems to be the best solution. My goal was to avoid copy-construction on noncopyable classes.
| As far as I know, there is no standard algorithm to delete all objects. However, you can build up one easily:
template< typename T > invoke_delete( T* ptr ){ delete ptr; }
std::for_each( set.begin(), set.end(), &invoke_delete< set_value_type > );
|
7,603,205 | 7,604,077 | Trouble tracking down a Bus Error/Seg Fault in C++ and Linux | I have a program that processes neural spike data that is broadcast in UDP packets on a local network.
My current program has two threads a UI thread and a worker thread. The worker thread simply listens for data packets, parses them and makes them available to the UI thread for display and processing. My current impl... | This may be wrong but....
You seemed to move the wait loop logic out of the method and into the static wrapper. With nothing holding the worker thread open, perhaps that thread terminates after the first time you wait for a UDP packet, so second time around, sp in the static method now points to an instance that has l... |
7,603,413 | 7,603,960 | QT Widget Slot Call Not Activated by Separate Thread Signal | I have 5 classes that interact (maintaining professionally, not author). My problem is that the code that is emitting the signal (there is just one, code below) is never activating the slot (MyWidget::HandleMeasurementChanged). This system has a large degree of complexity. I have tried to reduce that, but think the ... | This was referenced in the link that Jeremy added in a comment to my question, but just for clarity:
The solution was to add:
qRegisterMetaType<shared_ptr<Measurement> >("shared_ptr<Measurement>");
immediately before the call to connect.
|
7,603,420 | 7,603,469 | Why does std::fopen and std::filebuf::open trim trailing space characters on Windows? | I stumbled on a strange problem when trying to port a piece of C++ code from MSWindows to linux (Mint10). I discovered that there was a little typo in a hard-coded filename : a trailing space char (\x20).
The code worked like a charm under Windows (Windows Vista/7), but it had trouble to deal with the erroneous filena... | Windows itself will strip the trailing blanks from a filename, it has nothing to do with the C++ function you use to open the file.
Here's one reference to this behavior in the Windows API function CreateFile: INFO: Filenames Ending with Space or Period Not Supported
|
7,603,484 | 7,603,757 | My C++ OpenGL SDL program is not working as I expected | I have just started learning OpenGL and I am attempting to make a game of pong.
I'm having trouble getting the paddle to appear on the screen and I can't fathom out why: I thought with this code it should appear in the top left corner and move when down and up keys are pressed.
main.cpp -
#include <SDL/SDL.h>
#include... | Give this a shot:
#include <SDL.h>
#include <SDL_opengl.h>
class PlayerPaddle
{
private:
int xloc;
int yloc;
int paddle_height;
int paddle_width;
public:
PlayerPaddle()
{
xloc = 0;
yloc = 0;
paddle_height = 50;
paddle_width = 15;
}
void show()
{
... |
7,603,581 | 7,603,766 | qt hiding a control on showEvent() | I call show() on a window and it has several controls and all controls are displayed.
One of the controls is a custom control that inherits from QFrame.
I want to hide this control if a particular flag is set. So, I have
void MyCustomControl::showEvent ( QShowEvent * /* evt */ )
{
if (!m_visibleAllowed)
hid... | If the problem is with calling hide() during your show event (I can't confirm that it's explicitly disallowed, but it doesn't sound like a good idea in general) and calling hide from your show event is where you really need to have this code then you could use a single shot timer:
QTimer::singleShot( 0, this, SLOT(hide... |
7,603,718 | 7,603,739 | Define the prototype of a function with a std::vector as input parameter in an header | I'm getting crazy since i'm not able to define the prototype of a function i'm actually using.
What i'm doing is create an header file called func1.hwhere i define this prototype (that's because i need to invoke this function from some other function implemented elsewhere):
void FileVector(std::vector<Files> &,const c... | Make sure to include <vector> in your header file. You also mention that the definition of Files is within the cpp file, you should move it to the header as well.
Also place proper header guards to avoid multiple definition errors:
#ifndef MY_HEADER_FILE_GUARD
#define MY_HEADER_FILE_GUARD
... your content here ...
#e... |
7,603,732 | 7,603,867 | Questions about Memory Management, Stack, and Heap |
Possible Duplicate:
Does this type of memory get allocated on the heap or the stack?
I have a few memory-related questions, I was hoping you guys would be able to answer. Consider this code, with Foo representing a large class with lots of methods and lots of primitive data members:
class Foo {
public:
Foo() ... | Everything allocated with new is on the heap, including all its members. The line foo = new Foo(); creates a Foo (including all its members) on the heap.
Only named objects are on the stack. In your case bar (a Bar), and barptr (a pointer to a Bar).
Foos destructor doesn't need to do anything, which is actually quite... |
7,603,833 | 7,603,857 | What happens in C++ when I pass an object by reference and it goes out of scope? | I think this question is best asked with a small code snippet I just wrote:
#include <iostream>
using namespace std;
class BasicClass
{
public:
BasicClass()
{
}
void print()
{
cout << "I'm printing" << endl;
}
};
class FriendlyClass
{
public:
FriendlyClass(BasicClass& myFriend) :
... | It works exactly as for pointers: using something (pointer/reference) that refers to an object that no longer exists is undefined behavior. It may appear to work but it can break at any time.
Warning: what follows is a quick explanation of why such method calls can seem to work in several occasions, just for informativ... |
7,603,868 | 7,603,891 | loop error when numbers entered | why this loop executes 3 times when a number is entered? I only want 's' or 'm' to be accepted.. how could I fix this?
cout << "Are you married or single (m/s): ";
cin >> status;
status = tolower(status); //converting to lower case
//validating imput for marital status
while((status != 'm') && (status ... | Your variable status is probably declared as:
char status;
So, cin >> status reads a single character from the input. However, you probably typed more than one because the input is buffered and you needed to press Enter.
Instead, use this declaration:
string status;
which will get the whole line of input, and then yo... |
7,603,981 | 7,603,999 | C++ initialization lists for multiple variables | I'm trying to learn how to initialize lists.
I have a simple class below and trying to initialize the list of variables. The first Month(int m): month(m) works. I'm trying to do something similar below that line with more than one variable. Is this possible in that format? would I have to break away from the one liner?... | Try this:
Month(char first, char second, char third)
: first(first), second(second), third(third) {}
[You can do this as a single line. I've split it merely for presentation.]
The empty braces {} are the single body of the constructor, which in this case is empty.
|
7,604,154 | 7,604,175 | Overloading I/O operator C++ | I'm trying to overload the << operator. I'm expecting the output to be InitializingHello WorldOut but it is just outputting Hello World. I can't figure out what is wrong with my code. Thanks for your help.
#include <iostream>
using namespace std;
ostream &operator << (ostream &out, const char* &s)
{
out <... | There already is an overload for << with the exact same prototype. The compiler cannot decide which to use...
|
7,604,465 | 7,606,122 | How do I setup Fmod to very basic functionality in a Win32 console application? | I'm new to Visual Studio and would like to set up the very basic functionality of Fmod in a Win32 console application.
What I think the main problem is, is that I don't understand quite good how headers, additional libraries and dll files work.
Currently I have added "fmodex64_vc.lib" to additional dependencies. The fo... | fmodex64_vc.lib is an import library for FMODEx (version 4.xx.xx), FSOUND_Init is a function from FMOD (version 3.xx.xx) the two are not compatible. I'm guessing you have downloaded the latest FMODEx release, but are using example code from somewhere else (designed for FMOD3). I would recommend looking inside the FMODE... |
7,604,628 | 7,604,702 | Is swscanf substring formatting ([a-z]) implemented for osx standard lib? | The following code works on windows, but not on osx.
The docs on swscanf say that:
"...some implementations of wscanf() use "A-Z" to represent the range of characters between 'A' and 'Z'. "
By some implementations, does it mean that osx doesn't implement it?
int main(int argc, const char* argv[])
{
{
wc... | The man page for swscanf(3) states the following under the Bugs section:
In addition to the bugs documented in scanf(3), wscanf() does not support the “A-Z” notation for specifying character ranges with the character class conversion (‘%[’).
Feel free to file a bug report with Apple.
|
7,604,739 | 7,604,791 | C++ correct use of stringstream::str()? | Consider the following C++ program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main (void)
{
string l1, l2;
int n1, n2;
stringstream ss;
getline(cin, l1);
getline(cin, l2);
cerr << l1 << " " << l2 << endl;
ss.str(l1);
ss >> n1;
ss.str(l2);
s... | It is necessary, because the first input from the stringstring hits end of file. Calling str() does not clear any error flags that are already set on the stringstream.
ss.str(l1);
ss >> n1; // Reads the entire buffer, hits the end of buffer and sets eof flag
ss.str(l2); // Sets the string, but does not clear error ... |
7,605,028 | 7,605,402 | Using Google's regex library RE2 for C++: linking errors | I'm trying to use Google's regex library, RE2, in my C++ code but cannot get it to compile. Here is a simple test program that I wrote:
#include <iostream>
#include <re2/re2.h>
using namespace std;
using namespace re2;
int main (int argc, char **argv)
{
cout << "hello world" << endl;
int matchResult;
ma... | The -l option means to add a library to link to. So, when you say -libre2, it means "link to the library ibre2", which is probably not what you meant. Use -lre2.
|
7,605,056 | 7,605,078 | translating C++ snippet | I am working on porting a framework from C++ to Java, and it is turning out to be harder than I expected, as I don't know a whole lot about C++. I came across this one snippet that I don't really understand. If someone could tell me what the lines marked do that would be awesome.
/** Heap data, stored as a vector */
... |
The insert member function returns a pair whose bool component returns true if an insertion was made and false if the map already contained an element whose key had an equivalent value in the ordering, and whose iterator component returns the address where a new element was inserted or where the element was already lo... |
7,605,153 | 7,605,275 | Does a vector have to store the size twice? | This is a rather academic question, I realise it matters little regarding optimization, but it is just out of interest.
From what I understand, when you call new[size], additional space is allocated to store the size of the allocated array. This is so when delete [] is called, it is known how much space can be freed.
W... | std::vector does not allocate memory; std::allocator, or whatever allocator you give the vector, is what allocates the memory. The allocator interface is given the number of items to allocate/deallocate, so it is not required to actually store that.
|
7,605,286 | 7,605,385 | How to have the C preprocessor execute code during compilation? | I'm currently working on a code project that requires me to replace certain strings with hashes of those strings. Seeing as these strings will not change at runtime, it would be advantageous, efficiency wise, to have the c preprocessor run my hash function on each string that I declare to be hashed at compile time.
Is ... | One way to accomplish this is to put all your strings into a header file, and name them:
// StringHeader.h
#define helloWorld "Hello World"
#define error_invalid_input "Error: Invalid Input"
#define this_could_get_tedious "this could get tedious"
Then you can use those strings:
#include "String... |
7,605,399 | 7,607,684 | Debugging native/managed C++ in VS 2010 with NUnit | Is there a way to set breakpoints and step through them using NUnit with a mixed project of native C++ and managed C++?
I have my SUT (Software Under Test) configured as a static library (native C++)
I have my unit test suite as a separate project configured as a dll that depends on my previously stated library. I also... | The most convenient way to do this is to set up a custom tool entry specifying the path to NUnit as the command. For a VS2003 C# project, you can use $(TargetPath) for the arguments and $(TargetDir) for the initial directory.
With Visual Studio VS2005 this becomes a bit harder, because that release changed the meaning ... |
7,605,536 | 7,605,625 | Build Error:Undefined symbols for architecture x86_64: | I am completely new in programming with c++ using the Xcode IDE. What I do is I created a Hashtable myself, and clicked the build button, and I got compilation errors as such. Does anyone have ideas about what is going wrong?
This is the error:
Undefined symbols for architecture x86_64:
"MyHashtable<std::string, ... | Template definition inside of cpp file? Try putting it inside of the header file. The compiler will create a new instance of the class when you declare the instance (MyHashTable<int,int> myVar;), and so during include the entire class definition needs to be present. Hence, the h file instead of the cpp file.
I'm not... |
7,605,623 | 7,605,708 | inputing hex and reading hex with C++ | I'm trying to read and write hex but I'm having trouble inputting hex and reading hex back as hex not ascii. Whats getting me is printing the addresses, and values correctly I'm not quite sure I'm doing it right. any hints as to what I'm doing wrong? ok its working so far now just to fix read to print the actual addres... | You seem to be intending to read and write one character at a time - cin and cout are both capable of working with integral values and this would be ideal here. Keep in mind that hexadecimal strings do represent numbers! Streams are capable of interpreting them as such. Simply changing the variables v and print to type... |
7,605,693 | 7,605,706 | How to clone an instance of oneself , like Chromium does? | When i launch chromium again when it's already started , i can see the following:
%> chromium-browser
Created new window in existing browser session.
Is there any general way in C++ to do a similar thing ? Or is it like just "new" function in C++ , simply clone another object ? I'm confused.
| It is nothing at all like "new" in C++: it's at a vastly higher level. When the new process is started, it looks for an existing process, and if it finds one, it sends it a command to create a new window, then exits. The syntax and nature of that command is specific to the application (or application framework), as is ... |
7,605,783 | 7,605,812 | C++ std::list of pointer to a struct | I believe it's a very easy question but I'm quite confused.
What I am doing wrong ?:
std::list<curvesdata *> curvelist;
curvesdata * curve = new curvesdata;
curvelist.pop_back(curve);
---> no matching function for call to 'std::list<curvesdata*>::pop_back(curvesdata*&)
Seems my pointer is converted to... | void pop_back ( );
Does not take any arguments. It removes the last element in the list container, effectively reducing the list size by one. See the reference here.
Since the function does not take any arguments, the compiler tries to tell you the same by giving the error of non matching function.
To know Why the co... |
7,605,934 | 7,605,959 | Using static const char* const instead of #define | I get the error error: ‘Name’ was not declared in this scope
What am I missing here.
Source File:
#include<iostream>
#include "scr.h"
using namespace std;
const char* const Test::Name;
void Test::Print()
{
cout<<Name;
}
int main()
{
Test *t = new Test();
t->Print();
delete t;
}
Header F... | You can't initialize members in class definition.
Take a look at Parashift post - Can I add = initializer; to the declaration of a class-scope static const data member?
SUMMARY: The caveats are that you may do this only with integral or
enumeration types, and that the initializer expression must be an
expressio... |
7,606,005 | 7,606,061 | How should I cleanly break out of a recv loop? | I'm using the recv function in a loop to receive network data, but let's say I want to stop receiving data mid-loop. I could just break the loop, but this doesn't seem like a very clean way to stop receiving data.
So is there any way to cleanly stop receiving data, or is just breaking the loop ok? It's HTTP GET/POST re... | Breaking out of the recv loop won't close the connection. All that happens is that you stop calling recv and therefore stop reading data from the socket. Data from the peer will still be arriving on your socket. If you want to cleanly shutdown then call close on the socket file descriptor.
|
7,606,277 | 7,606,541 | call function in class | i want to change the "value" when run my app.
but when i call RS232::PackageRecived in "RS232.cpp" i revived This Error :
Error 1 error C2352: 'RS232::PackageRecived' : illegal call of non-static member
//////////////////////////////////////////// RS232.cpp FILE
#include "RS232.h"
void RS232::PackageRecived()... | Your function, "TryCallPackageRecived()" is not a member of the RS232 class. It's trying to call a member function of RS232 that is not static. This is not allowed. When you want to call a non-static member function you need to call it on a particular object.
In this case, you could do:
RS.PackageRecived();
If you wan... |
7,606,408 | 7,606,747 | Interpreting gprof output with <spontaneous> | I am trying to find a performance issue in my program and thus instrumented the code with profiling. gprof creates a flat profile like this:
Flat profile:
Each sample counts as 0.01 seconds.
% cumulative self self total
time seconds seconds calls ms/call ms/call name
2... | Apparently, spontaneous is what gprof uses when it can't work out the calling function. I would try recompiling all code with -pg (is it possible you missed some files?). Also, make sure you have optimisation turned on. Inlining will typically make these little functions disappear into the calling function which is gen... |
7,606,420 | 7,606,636 | mem_func and for_each usage | How to call class member function using std::for_each
Here is what my class is.
template <typename _TyG>
class Graph {
private:
public:
typedef typename Vertex<_TyG> VertexType;
typedef typename std::set<VertexType> GraphStorage;
typedef typename GraphStor... | I do not think you can do what you want to do with std::for_each. As std::for_each calls the given function on each value in the sequence and not each iterator position in the sequence. std::for_each might look like:
template <class iter_t, class fn_t>
fn_t for_each(iter_t first iter_t const last, fn_t fn)
{
for (;... |
7,606,530 | 7,606,651 | c++ Function appearing to not return anything when it should | I currently have a function that is meant to return T (templated function). So I always assumed it MUST return a value, but I recently stumbled across something.
#define PRINTERROR(msg) \
std::cout << msg << "\n\tFILE: " << __FILE__ << "\n\tLINE: " << __LINE__ << "\n\tTIME: " << __TIME__ << std::endl << std::endl;
and... | Omitting to return a value from a function unfortunately is not a compile error.
A compiler may emit a diagnostic message (for example g++ does if compiling with -Wall option) but it's not mandatory.
Omitting to return a value is something that compiler writers are free to assume a programmer will never do, and if a pr... |
7,606,604 | 7,607,063 | Build system for an embedded C/C++ project | I am looking for a high-level build system/tool that can help organise my embedded C project into "modules" and "components". Note that these two terms are highly subjective so my definitions are given below.
A module is a cohesive collection of c and h files but with only one public h file that is visible to other mo... | The conventional way of achieving that would be to place the source code for each module into a separate directory. Each directory can contain all the source and header files for the module.
The public header for each module can be placed into a separate, common directory of headers. I'd probably use a symlink from t... |
7,606,624 | 7,606,702 | How to define thread-local local static variables? | How to define local static variables (that keeps its value between function calls) that are not shared among different threads?
I am looking for an answer both in C and C++
| on Windows using Windows API: TlsAlloc()/TlsSetValue()/TlsGetValue()
on Windows using compiler intrinsic: use _declspec(thread)
on Linux (other POSIX???) : get_thread_area() and related
|
7,606,705 | 7,606,888 | Template class destructors | I'm trying to create a simple template class in c++. I've been trying to compile the following but I only get a compile error. This is the code:
#include <stdlib.h>
#include <stdio.h>
template<int size>
class array {
public:
int len;
int data[size];
array(void) : len(size) {}
virtual ~array(void) {}
};... | Try this:
template<int size>
class array {
public:
int len;
int *data;
array();
virtual ~array(void);
};
// 1 dimension specialized array
template <>
array<1>::array() : len(1)
{
data = new int;
}
template <>
array<1>::~array()
{
delete data;
}
template <int size>
array<size>::array() : len(... |
7,606,760 | 7,606,824 | C++ accesing objects far from current class hierarchy | I think this is a really newb question, but I never found out the answer. I don't know how exactly to phrase this question, but I often find that I have to access objects that are "far away" from the current object in terms of the current hierarchy. I just want to make sure that this is the right (only) way to do thi... | The answer to this sort of question is always the same: Don't worry about it unless and until it becomes a problem, and then, take measurements to decide which option is best. Yes, there's an overhead with calls to subobjects but with the example you've given (and with many real-life examples) this overhead is unavoida... |
7,607,009 | 7,607,049 | error: comp. bet. signed/unsigned integer expressions CODEBLOCKS | the assignment is: have a number saved in a string, then convert from a string to an integer--> convert that number to a decimal number from N-base the user inputs.
#include <iostream>
using namespace std;
int main()
{
string snum;
int n=0, base, res;
cout << "enter n: ";
cin >> snum;
cout << "en... | with
cin << base; //THIS IS LINE 13
you mean
cin >> base;
EDIT:
you should convert the number differently, instead of grabbing each character take the whole string and convert it to a number. You can use a stream for that or just atoi( sum.c_str() ) to get the integer number.
thereafter convert the value to whatever ... |
7,607,083 | 7,608,749 | CORBA : How to pass a QT object as a parameter | I'm new to CORBA and is trying to create a Corba interface for my QT Application. I checked the data types that you could use with CORBA, but I'm not sure if I could use a QT object as a parameter in a CORBA function. What I would want to pass is QWSPointerCalibrationData. Let's say I have a CORBA server code :
//pass... | As you have the code, this is not possible. You have to specify IDL types equivalent to those that you're using in your application, and also provide (sigh, yes) conversion functions between those types defined in CORBA IDL and the ones defined in your application. As an advantage, you blind your application to future ... |
7,607,178 | 7,607,239 | Building LLVM on Linux | Well not that anyones probably going to see this but I A) figured out that LLVM wasn't what I needed it was LLVM-gcc which you can get from sauriks repo. B) realized that the toolchain I torrented already worked minus a la libstdc++ not in /usr/local/lib/gcc/arm-apple-darwin/4.0.1/ so to get libstdc++ I believe I got i... | it look alot like the usual subjects cstdio, cstdlib, cstring are not included.
I would start by trying including them :-)
|
7,607,254 | 7,607,373 | Why is a class' size affected when it contains only a virtual function? | class classWithNoVirtualFunction
{
public:
int a;
void x ()
{
char c;
c = 'a';
}
};
class classWithOneVirtualFunction
{
public:
int a;
virtual void x () {}
};
class classWithTwoVirtualFunctions
{
public:
int a;
virtual void x... | Whenever a class contains at least one virtual function, the compiler needs to add RunTime Type Information to each of the objects. The implementation will usually add a single pointer to each object that refers to a structure, defined by the compiler and hidden from users, with a pointer to the type_info object and th... |
7,607,276 | 7,607,317 | 'out' keyword in C++ | Is there an equivalent to the C# 'out' keyword for out parameters but in C++?
I'd like to have a constructor also set a couple of references to variables where it is called.
| No direct equivalent. In C++ you choose between passing by value, passing a pointer value, or passing a reference parameter. The latter two can be used to get data back from function.
VOID foo(int* pnA, int& nB)
{
*pnA = 1;
nB = 2;
}
int nA, nB;
foo(&nA, nB);
// nA == 1, nB == 2;
|
7,607,287 | 7,618,583 | OpenCV CvSeq recursive element access fails for large images? | My development enviroment is Mingw32 bit CMake on Windows 7.(this same code works fine on Linux)
I use cvFindContours() to detect contours using OpenCV.
I use recursive method to traveser the resultant CvSeq to access the contours by level as follows:
void helperParseCurves(CvSeq* contour, int level) {
//Travel s... | I realized that this happens due to the recursive function.Once I made it an iterative one ,everything worked fine.
Now I know why recursive functions are bad...didnt really "practically" understood that before..
|
7,607,362 | 7,607,778 | Qt: Properly store image resource for custom widget | I'm making a custom widget in Qt, and drawing an image as its background. The background image is to be exactly the same for all instances of widgets. I'd like to know if I'm doing it in an appropriate way.
Here's how I'm doing it now:
// QMyWidget.h
class QMyWidget : public QWidget
{
/* some stuff.. and then: */
prot... | That's one way of doing it, and it's a reasonably good way if you're only dealing with a single image, but if you ever decide to scale and use a couple of custom resources then the Qt Resource System is the better way to do it. It'll save you time in code (don't need to repeatedly do QImage), and has a few other nice f... |
7,607,420 | 7,607,687 | Two Identical Code Segments, Different Results | All I need to do is a simple read from a file in the same directory, but for some reason it refuses to work.
It works perfectly fine in this quick test one I made after I had problems, and outputs the number of entries in the text file.
#include <iostream>
using std::cout;
using std::cin;
#include <cstdio>
int main()... | My best "guess" is that you are trying to re-read the same file. If this is the case then you could try this :
std::ifstream file("7.txt");
std::string line = "";
while(std::getline(file, line))
{
//do something
}
//reset file pointer
file.clear();
file.seekg (0, std::ios::beg);
//re-read file
while(std::getline(fil... |
7,607,428 | 7,607,581 | c++ cross access to classes methods | I'm not very experienced in cpp (used to work in python).
I have the following problem:
1) I have a main class A (a window) and the methods m_A1 and m_A2
2) I have a little class B (a dialog) with a callback m_B1
3) the class B is instantiated and destroyed inside of m_A1
4) from the callback m_B1 I need to call m_A2
I... | Add a Centrino reference in DebugDialog attributes and provide it in DebugDialog contructor. Declare Centrino::io_process_incoming_command() method public and invoke it from DebugDialog::on_button_send_clicked() method:
class Centrino
{
public:
Centrino();
virtual ~Centrino();
Gtk::Window *mp_window;
... |
7,607,492 | 7,612,027 | How do I grab an image retrieved from a camera via web browser? | I have an IP camera that hands me a snapshot of what it is seeing when I enter a specific url which the manual provides. The manual also states that the http response is:
HTTP Code: 200 OK
Content-Type: image/jpeg
Content-Length: <image size>
Body:<JPEG image data>
Looking at the page on Firefox, I can see nothing but... | The easiest solution is probably curl. It's even got an example which lacks just the for (;;) { grab(); sleep(60000); } loop.
|
7,607,502 | 7,607,557 | sizeof(long) in 64-bit C++ | I have downloaded MinGW-64, so I can now compile 64-bit programs for Windows 7, using g++ 4.7.0 (experimental). But the following line:
cout << sizeof(long) << " " << sizeof(void*) << endl ;
prints 4 8, not 8 8. The documentation for g++ 4.6.0 says:
The 64-bit environment sets int to 32 bits and long and pointer to 6... | Because it doesn't have to be. The C++ standard only requires that it is (if memory serves) at least 32 bits wide, and at least as big as int.
MSVC (and the ABI used by Windows) defines long to be 32 bits wide, and MingW follows suit because well, the compiler is a lot more useful when it agrees with the host OS
|
7,607,562 | 7,607,721 | Why isn't this code working? C++ | This code should ask the user for a their name and then split it at the space.
It should put the firstname in the variable first, and the last name in de variable lastname
#include <iostream>
using namespace std;
int main()
{
char string[80];
char first[20];
char lastname[20];
bool f = true;
int c = 0;
cout << "Whats... | Unless you really need to write this using only C functions, it would be much easier to use C++ strings.
Something like (this is untested):
std::string input;
std::string first;
std::string lastname;
// prompt the user
std::cout << "What's your name? ";
// get a line of input
std::getline(std::cin, input);
// find a ... |
7,607,865 | 7,627,459 | Something like Apache Zookeeper with no java? | Is there some library or project out there that works like Zookeeper but has no java dependency? I'm looking at putting this on an embedded linux system, and need minimal footprint... something like a megabyte or less. I have Lua, C and C++ runtimes, and could put something like NewLISP on there if I had to. Most or... | There is accord,
Accord is a high-performance coordination service like Apache
ZooKeeper
It looks like accord is written in c.
|
7,607,891 | 7,611,705 | How to prevent ActiveMQ CPP send method from blocking forever? | I am developing a software that uses ActiveMQ C++ library. The problem that I have is, when I try to send a message and the network is down, the send method (method of cms::MessageProducer class) blocks forever and I need to recover the control in this case.
I am using persistent deliver mode (It is compulsory, I can't... | Do you set the sendTimeout when you create ActiveMQConnectionFactory? It is set to 0 by default, which means "infinite".
auto_ptr<ActiveMQConnectionFactory> connectionFactory(
new ActiveMQConnectionFactory( brokerURI ) );
connectionFactory->setSendTimeout( 1000 ); // number of milliseconds
// ...
// creating Sessi... |
7,607,905 | 7,608,200 | C/C++ Preprocessing Error | I stumble on a compiling error:
Invoking: GCC C Compiler
gcc -O0 -g3 -Wall -c -fmessage-length=0 -MMD -MP -MF"src/3dsloader.d"-MT"src/3dsloader.d" -o "src/3dsloader.o" "../src/3dsloader.c"
In file included from ../src/3dsloader.c:42:
../src/3dsloader.h:8:9: error: macro names must be identifiers
make: *** [src/3dsloade... | C identifiers may not start with a number. Try _H_3DSLOADER instead.
To be exact: They may only start with letters or an underscore.
|
7,608,026 | 7,608,138 | How do I safely hook into the message pump from a DLL? | I'm trying to get messages from the process that loaded my DLL.
I've tried:
SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)WndProc, hInstance, 0);
Which gives me error popups about how "Program X could not be started because Y.dll is missing from your system". This is the reason I put "safely" in the title.
I've also tri... | Messages are related to threads and windows, your DLL might be loaded by processes. So there is no direct correspondence.
Hooks on the other hand are either global or per-thread.
All together this means that you have to choose whether you want messages just from specific threads, or global (all threads in all process... |
7,608,144 | 7,608,199 | Pointer to struct & function pointers -> Seg Fault | I always get a segmentation fault during execution of this test program. I can't figure out why. Maybe someone could explain it to me please, i'm sure i mixed up the pointer stuff.
#include <stdio.h>
struct xy {
int (*read)();
void (*write)(int);
};
struct z {
struct xy *st_xy;
};
stat... | You never allocate the actual xy object. Your test.st_xy is just a garbage pointer that you're not allowed to dereference.
Instead, do something like this:
static struct z test;
static struct xy inner_test;
test.st_xy = &inner_test;
// ...
ret = init(test.st_xy);
|
7,608,229 | 7,608,520 | Preprocessor token pasting in GCC’s _Pragma operator | I’m trying to do something similar to another question, namely, conditionally include OpenMP pragmas in my program. However, I want to go one step further and avoid that the user needs to specify omp every time they use the pragma. In other words, I want the following code to compile:
#include <cstdio>
#include <omp.h>... | After much trial and error, it turns out that the simplest solution works:
#ifdef _OPENMP
# define LIB_PRAGMA_OMP(x) DO_PRAGMA(omp x)
# define DO_PRAGMA(x) _Pragma ( #x )
#else
# define LIB_PRAGMA_OMP(x)
#endif
With -DOPENMP, I get:
# 12 "test_op.cpp"
#pragma omp parallel
# 12 "test_op.cpp"
And without it, not... |
7,608,337 | 7,608,416 | 2-adic number of given integer | i am reading section about A Binary Recursive Gcd Algorithm,where this definition is given
let v_2(a) denotes the 2-adic valuation of a, i.e. the number of consecutive zeroes in the least signicant bits of the binary representation of a ,so i am trying to find v_2(a) here is code for this
#include <iostream>
usi... | You're breaking out of the while too late, since you're running total++ when k==1 has been reached.
Move the if (k==1) block after the k=n%2; line.
Note: The k variable isn't actually necessary. You could simplify the loop to:
while((n%2)==0) {
n>>=1;
total++;
}
|
7,608,342 | 7,608,896 | Custom allocator fails to rebind to Other type | All
I have code for my custom allocator that is written with intent to be a proxy for other allocators to be able for example to gather allocation statistics or whatever else
template<int Id, class T, class BaseAlloc>
class SelfTracingAllocator
: public BaseAlloc
{
typedef AllocationStatistics<Id> StatsType;
pub... | What about using
template<typename Other>
struct rebind
{
typedef SelfTracingAllocator<
Id
, Other
, typename base::template rebind<Other>::other
> other;
};
?
Right now if you have a SelfTracingAllocator<0, int, std::allocator<int> > then rebinding to wchar_t will yield SelfTracingAllo... |
7,608,490 | 7,608,586 | How to create memory DC with 24 bits per pixel? | I need it to work with RGB24 data using GDI functions (specifically StretchBlt() which is pretty fast) and I can't use CreateCompatibleDC() since it can create memory DC only with color depth of other DC. Usually it's used with screen DC (by transmitting NULL pointer to function) and usually screen has color depth of v... | Bits-per-pixel does not really depend on a DC, but on the bitmap selected into it. Create a 24bpp bitmap with CreateDIBSection then select it into a memory DC.
|
7,608,741 | 7,608,920 | C++11 Template function that takes a std::function which depends of template parameters | I am trying to write a template function that accepts a std::function which depends on the template arguments. Unfortunately the compiler is not capable of correctly deucing the arguments to the std::function. Here some simple example code:
#include <iostream>
#include <functional>
using namespace std;
void DoSomethi... | If you are using templates, you can avoid std::function entirely, unless for some reason you want to specifically restrict the function to take std::function:
template < typename Ident, typename Param, typename Func >
void CallFunc( Ident ident, Param param, Func op )
{
op( ident, param );
}
|
7,608,775 | 7,609,553 | template error message c++ | I have the following header file:
#ifndef DATABASE_H
#define DATABASE_H
#include <vector>
#include <iostream>
#include <string>
#include "record.h"
using namespace std;
template <class value>
class Database {
public:
void write (ostream& out, DBScope scope) const;
Database <value>() {};
~Database(... | The first error has to do that the method is const, hence records is const, and reconds.begin() returns a const_iterator.
template <class value>
void Database<value>::write (ostream& out, DBScope scope) const {
vector <Record <value> >::const_iterator itr = records.begin();
The second error means that you probably m... |
7,608,883 | 7,616,401 | Python capture stdout from subprocess line by line | I've read many of the questions related to this and learned a lot but I still haven't been able to solve my problem. I'm building a wxPython app that runs a c++ executable and displays the stdout from that executable in real time. I've run into several strange results trying to make this work. Here's my current setup/p... | I only tested this on Windows, but it works in 2.6.6, 2.7.2, and 3.2.1:
from __future__ import print_function
from subprocess import PIPE, Popen
from threading import Thread
import sys
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # python 3.x
ON_POSIX = 'posix' in s... |
7,608,943 | 7,609,027 | What does the 'hides constructor for' warning mean when compiling C++ with g++? | Using the following code:
#include <stdio.h>
struct my_struct {
int a;
int b;
my_struct();
};
my_struct::my_struct(void)
{
printf("constructor\n");
}
void my_struct(void)
{
printf("standard function\n");
}
int main (int argc, char *argv[])
{
struct my_struct s;
... | The warning points out that the my_struct() function has the same name as the my_struct structure. It means you will be unable to write:
my_struct s; // Error.
Because the compiler will think that you're using a function as a type. However, as you probably realized, you can still instantiate your structure wit... |
7,608,950 | 7,609,023 | Generic keyCompare method | please look through the following program..
#include <stdio.h>
#include <malloc.h>
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
char *key1 = (char*)malloc(sizeof(char)*26);
char *key2 = (char*)malloc(sizeof(char)*26);
int intkey1 = 10;
int intkey2 = 10;
float floatk... |
Is this way of comparing byte streams by memcpy always the safe and foolproof
It doesn't produce the correct result with integers and floats on little-endian architectures. And it can't handle special floating point values like inf and nan.
or should i need to compare based on the types of the fields present in ch... |
7,608,972 | 7,609,021 | error return code from pthread_create is 35 error due to many processes,I have used pthread_exit which should kill the thread isn't it? | I have create a pthread_create inside a pthread_create, I have used socket programming, where I receive a packet and then create a thread which does the writing to the file. When I send a very large file, i get this error...??
The code is as follows...
void *writePack(void *sock)
{
size_t nbyte;
ssize_t writeS... | It could be that the threads you create didn't get a chance to execute, while you've been creating more and more threads reading from the socket.
Instead, create a thread that would do the reading from the socket, another thread that would do the writing, and pass the data in messages between the two threads.
|
7,609,084 | 7,609,110 | 2 byte representation of command line arguments in Visual Studio 2008 | I have a problem when handling command line arguments in a simple C++ application written in Visual Studio 2008. I have written the following code:
#include <iostream>
using namespace std;
int _tmain(int argc, char **argv)
{
char* c = *argv;
for(int i=0; i< argc ; ++i)
{
cout << argv[i] << e... | Your _tmain is receiving UTF-16 characters which, when fed Latin text, have a 0 in every other byte. You are interpreting them as single byte characters. You need to interpret them as wide characters.
I would write it something like this:
#include <iostream>
using namespace std;
int wmain(int argc, wchar_t* argv[])
{... |
7,609,225 | 7,609,315 | C++ to C# event handling | So I've got my C# WinForm Application, from it I call my C++ CLI MFC dll library.
But there are some events on my C++ library, even this events happens in native (non-CLI) part of this library. And I need to call some code from my C# application and get some data maybe right there on this event.
so when this native fun... | So the problem is you need to run C# code in response to MFC event (or C++ callback), right?
Why can't you just register a native handler to the native event/callback, which then just invokes a .NET event, which can be the consumed from C#.
|
7,609,450 | 7,614,611 | Visual studio 2010 project for windows and linux | I'm trying to make a program that works on linux and windows.
I'm writing the program in visual studio in a windows environment.
So I wonder how I could compile my project from visual studio to linux.
| The Microsoft C++ compiler is not capable of producing Linux executables.
You will need to use a more portable compiler for your Linux executables, e.g. gcc. Perhaps you may benefit from a cross-platform IDE like Code Blocks or Eclipse rather than Visual Studio.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.