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,667,322
7,667,356
What knowledge is required/recommended before approaching compiler development?
There is a question on stackoverflow about Learning to write a compiler. I have looked at it and I think it's an undertaking I want to tackle. I think (like many others) the knowledge will be invaluable to a programmer. However, my skills are primarily in C++ and I would say I am very comfortable with the syntax of the...
I would recommend you start with an interpreter first as you don't need proprietary hardware knowledge to implement it. The key concepts are usually how is the language defined, what makes a statement, building parse trees, etc... The hardware knowledge to me is secondary than actually understanding how to read and eva...
7,667,635
7,667,678
Both threads blocking on call to boost::mutex::lock()
I have a boost::mutex that's being used in two threads. The first thread is constantly locking and unlocking the mutex. The second thread only uses the mutex on a certain condition. When this condition occurs, both threads block on the lock. What could possibly causing this? Some random facts about my program: The mute...
Did you remember to unlock the mutex in the main thread after you signal the condition? Alternately, did you get into a deadlock situation?
7,667,648
7,667,929
Query about C++ template specialization and partial template specialization
I am studying C++ concepts - Template specialization and Partial template specialization. Have a code as below, which I want to understand so I get these concepts correctly. I have few questions regarding that, which are asked inline below: template <typename T, int nSize> class Buffer { private: T m_atBuffer[nS...
C++ doesn't have/support partial specialization of function templates, only of class templates. As such, none of the code you're looking at is related to what you (at least say you) want to study/understand at all. A partially specialized class template would be something like this: template <class T, class U> // the ...
7,667,925
7,667,951
double while, new feature in C++?
I found that this compiles in Microsoft Visual C++ 2010. void main() { int i=9; while (i>4) { i--; } while (i>6); } Probably not.. the second while does not seems to have an effect
There is nothing unusual about it. It's two while statements, except the other one has an empty body. The bigger problem is void main.
7,668,050
7,668,243
Code documentation editor
I've been looking for a code documentation editor app. I don't mean just a generation tool like doxygen, but an application that allows me to edit the documentations and change it directly at the code. Does anyone out there know of a good editor? Thanks!
If you're talking about Visual Studio... I've written an add-in, AtomineerUtils Pro Documentation, which will help a lot with documentation creation & editing. To create comments, the addin uses as much information as possible from the code element you are documenting to fil in a skeleton documentation comment for you...
7,668,161
7,668,189
How can I create a single Visual Studio project that mixes C and C++ using CLR?
I am working on porting code that builds on GCC on Unix to windows using Visual Studio 2008. I would like to create a single executable that does not depend on any dll(s) of my own creation and only built in ones to the Windows operating system. My code includes zlib which itself includes C files which I can build and ...
You could change it to cpp to get it compiled by the C++ compiler (and fix any compile errors that introduces). That may be more difficult than just using a shared library (dll).
7,668,783
7,669,149
Why is this causing a segmentation fault?
I've been coding this in project in C++, normally I wouldn't have too much trouble with a segmentation fault, but I'm new to C++. Basically I'm making a pointer to an IntList and calling prepend() to make a IntList from the pointer. The problem is when prepend is called it is getting stuck somewhere in the header file ...
Any pointer that has not been initialized has an undefined value, e.g. it probably points to random garbage in the unallocated regions of the heap. Any dereference into an area of the heap which is not allocated is a segmentation fault. You need to use the new operator to allocate some heap memory and get the address o...
7,669,118
7,669,136
C++ import loop with two classes?
I'm sure this question has been asked before, but I can't seem to find it. I have two classes, Vector and Point. The files are as such (a bit repetitive): vector.h: #include <math.h> #include <stdlib.h> class Vector { friend class Point; public: ... Vector(Point); // Line 16 vector.cpp: #include <math.h...
You shouldn't be including .cpp files, you should be including the .h files. vector.cpp needs #include "point.h" and (presumably) point.cpp needs #include "vector.h". A forward declaration is only sufficient if you're not doing anything that requires the type's size or interface. Because Vector's constructor is taking...
7,669,213
7,671,528
In Qt how do I reset the background colour of an item in a ListView from the Model?
In Qt I have a QListView that is using a custom Model class that contains the data to display. Based on the data, I want the background (and eventually the foreground/text) colour to be set to match the state of the data. So far I have accomplished this by returning a QBrush with the selected QColor inside of a QVaria...
Try something like this in your data method: if (role == Qt::BackgroundRole) { bool itemStateIsNeutral = ... if (itemStateIsNeutral) return QVariant(); // else: return QVariant(QBrush(item.color())); } You might have to do return QVariant(QBrush()) instead, I'm not sure about this.
7,669,334
7,672,052
Changing the Visual Studio Default Class Setup
I want to change the default code generated by visual studios 'add->class...' for C and C++. Currently it looks like #pragma once class GlWindow { public: GlWindow(void); ~GlWindow(void); }; Whereas I would like to use proper include guards, no premade constructor/destructor, and have the curly brace up next ...
You can find the code behind generating a generic C++ class in INSTALLED_FOLDER\VC\VCWizards\CodeWiz\Generic\Class\Scripts\1033\default.js.Where INSTALLED_FOLDER represents "C:\Program Files (x86)\Microsoft Visual Studio 10.0\" You can write a custom template or wizard to generate code which meets your own standards. ...
7,669,378
7,673,011
How to get event notification in an ATL ActiveX control when a specified registry value changes for use as a windows mobile ActiveX control
I have an activex control that I display in a webbrowser control on a windows mobile device using a C# forms app. The activex control is working. I want to add a feature to the activex control where an event is raised in the activex control when a registry value changes state. I have implemented the same (but reversed)...
To avoid polling, you can use CRegKey::NotifyChangeKeyValue, which is in turn built on top of RegNotifyChangeKeyValue. You can have an event signaled with a change under the key. So your worker thread might be waiting for this event [possibly among others] and once your wait is satisfied you would do whatever you do in...
7,669,386
7,670,395
Streaming sequence of image with Live555
Instead of using: videoSink->startPlaying(*videoSource, afterPlaying, videoSink); I'm looking for a way to feed videoSink image by image, one after another. This way I can get my webcam images and feed them to the Live555 for streaming. Is that possbile?
You can accomplish that using the live555 event trigger of the DeviceSource mechanism. Searching the live555 mailing list for EventTrigger, DeviceSource should provide you with a way to get started. AFAIR there was a section on live sources in the FAQ. I would advise you to encode the data before hand. You can use FFMP...
7,669,409
7,669,872
setenv, unsetenv, putenv
I am working on a custom shell for a systems programming class. We were instructed to implement the built-in setenv() and unsetenv() commands with a hint of check man pages for putenv(). My issue is that setenv(char*, char*, int) and putenv(char*) do not seem to be working at all. My code for executing a command entere...
You appear to be calling fork unconditionally before examining the command line. But some shell built-in commands need to run in the parent process, so that their effect persists. All the built-ins that manipulate the environment fall in this category. As an aside, I wouldn't try to use the C library's environment ma...
7,669,433
7,669,564
C++: How to make a my program open a .exe with optional args
I'm having some trouble with a program. My goal is to have it open several .exe files with optional args passed. For example if I wanted to open up a pdf I could type the string below into a cmd window. // If used in a cmd window it will open up my PDF reader and load MyPDF.pdf file "c:\Test space\SumatraPDF.exe" "c:\T...
Welcome to Stack Overflow! The system method works by passing it's argument to cmd /c. So you will need an extra set of quotes around it. See related question posted by sled. As an alternative to system, take a look at the ShellExecute or ShellExecuteEx Win32 API function. It has more features although it is not as por...
7,669,500
7,669,519
C++ Segfault on clearing a binary search tree
I'm trying to eliminate any memory leaks in in my Binary Search tree that I'm making so I made a simple recursive delete method. This is the method that first causes void BST::copy(const BST& other){ if (other.root != NULL){ Clear(); Which Clear(); will first thing call recursiveDelete(root); void BST::re...
First comment: You should probably clear the object's data in the copy if the other object has data or not. If the other object is empty, then the copy should make this object empty too. Second comment: I cannot tell from your question, but I expect that head->left or head->right was not set to NULL properly during con...
7,669,680
7,669,803
What is this vertex shader doing?
I recently took over a project that was left stagnate a team member quit a few months ago. While trying to get myself up to speed I came across this vertex shader and I'm having a hard time understanding what its doing: uniform int axes; varying vec4 passcolor; void main() { // transform the vertex vec4 point; ...
I can't seem to find documentation that explains this. The GLSL specification is pretty clear about how swizzle selection works. What the shader is basically doing is an obtuse way of picking two axes from a vec4. Notice that the Z and W of the point are overwritten after the selection. By all rights, it could be rew...
7,669,949
7,669,972
What does void Classname::operator()(){ .... } do?
Im working my way through some C++ code and came across the following void Classname::operator()() { //other code here } I assume this has something to do with overloading the constructor, but can someone elaborate on that?
operator() is the function-call operator. It allows you to use a class instance like a function: Classname instance; instance(); //Will call the overload of operator() that takes no parameters. This is useful for functors and various other C++ techniques. You can essentially pass a "function object". This is just an o...
7,669,971
7,670,021
Sort vector based on extra parameters
I have a pointer to a vector of object pointers vector<object*>* vec; Which happens to hold information for objects that can currently be colliding with another object. This is great- but I need to sort this vector by distance from the root object, and I don't know of the best way to do that. As it stands the object ...
Try functor with parameters: struct sorter { object *host; sorter(object *host) : host(host) { } bool operator()(object* first, object* second){ return distanceBetweenObjects (host,first) < distanceBetweenObjects (host,second); } }; sort(tosort.begin(), tosort.end(),sorter(host));
7,670,000
7,670,544
Addresses of identical function template instantiations across compilation units
Why does this work? I see similar SO questions stating that it does, but could someone explain it in more detail? Particularly, is this behavior protected by a standard? i.h #ifndef I_H_ #define I_H_ typedef void (*FuncPtr)(); template<typename T> void FuncTemplate() {} class C {}; #endif a.cc #include "i.h" Fun...
This is covered under the one definition rule: 3.2 One definition rule [basic.def.odr] Paragraph 5: There can be more than one definition of a class type (Clause 9), enumeration type (7.2), inline function with external linkage (7.1.2), class template (Clause 14), non-static function template (14.5.6), static data m...
7,670,024
7,670,031
Returning a Class that Stores on Heap
I'm having a memory-related crash in my project. I managed to reduce it down to the following "toy" project: class Foo { public: Foo() : bar(nullptr) { bar = new int(3); } ~Foo() { if (bar) { delete bar; bar = nullptr; } } private: int* bar; }; Foo...
You violated the rule of three. When you're manually managing memory inside your constructor and destructor, you MUST also provide a copy constructor and assignment operator, otherwise your program will double-delete and use memory after delete. In your particular example, you have the compiler-provided copy constructo...
7,670,059
7,670,103
Understanding C-strings & string literals in C++
I have a few questions I would like to ask about string literals and C-strings. So if I have something like this: char cstr[] = "c-string"; As I understand it, the string literal is created in memory with a terminating null byte, say for example starting at address 0xA0 and ending at 0xA9, and from there the address i...
In the first case you are creating an actual array of characters, whose size is determined by the size of the literal you are initializing it with (8+1 bytes). The cstr variable is allocated memory on the stack, and the contents of the string literal (which in the code is located somewhere else, possibly in a read-only...
7,670,109
7,671,676
Converting OpenCV kinect_maps to DLL
I'm new to making DLL's and I would like to convert the C++ kinect_maps project which i got from the OpenCV2.3 project examples to a DLL so i can use it from my C# project. I've been able to create a DLL but without luck it can't grab images from my kinect. Is it my linking to the libraries that is wrong or any other s...
You should use a COM interface because they are different languages. Find a COM/COM+ tutorial, try it at first with some simple "Hello world" (COM is not the simplest technology in the world), and then put your code in the COM dll. Then you''ll be able to add it as reference to your C# project, #import it, instantiate ...
7,670,110
7,670,254
Strange GCC Behaviour
Given the following C++ code: struct vertex_type { float x, y, z; //vertex_type() {} //vertex_type(float x, float y, float z) : x(x), y(y), z(z) {} }; typedef struct { vertex_type vertex[10000]; } obj_type; obj_type cube = { { {-1, -1, -1}, {1, -1, -1}, {-1, 1, -1}, ...
This is a long-standing missing optimization in GCC. It should be able to generate the same code for both cases, but it can't. Without the constructors, your vertex_type is a POD structure, which GCC can initialize static/global instances of at compile time. With the constructors, the best it can do is generate code ...
7,670,374
8,917,996
Partial template specialization for initialization of static data members of template classes
How would one initialize static data members of a template class differently for particular parameters? I understand that templates are different than other kinds of classes and only what is used in the project ever gets instantiated. Can I list a number of different initializations for different parameters and have th...
Should work. You may need to put these into the .c file instead of the header. int someClass<int>::someData = 5; double someClass<double>::someData = 5.0; Here is also a working partial template specialization with initialization of static data members: // .h template <class T, bool O> struct Foo { T *d_ptr; ...
7,670,589
7,681,413
How can I process C++ definitions in C#?
I have a bunch of *.h files, containing only c-style definitions like #define ALPHA_REACTOR_CODE 99641 #define BETA_REACTOR_CODE 99642 #define GAMMA_REACTOR_CODE 99643 #define DELTA_REACTOR_CODE 99644 How can I use this files in my С# code without changes and work with this constant in my code?
apologies for the late answer when I promised one earlier. The idea I have involves using the runtime code compiler as well as reflection to dynamically generate a class that contains all these constants. So the steps (or pseudocode), as I see it are: For each .h file read all the lines that begin with #define and st...
7,670,887
7,671,918
C++ OpenMP directives for a parallel for loop?
I am trying OpenMP on a particular code snippet. Not sure if the snippet needs a revamp, perhaps it is set up too rigidly for sequential implementation. Anyway here is the (pseudo-)code that I'm trying to parallelize: #pragma omp parallel for private(id, local_info, current_local_cell_id, local_subdomain_size) shared(...
I'm not sure I understand your code. However, I think you really want some kind of parallel accumulation. You could use a pattern like size_t total = 0; #pragma omp parallel for shared(total) reduction (+:total) for (int i=0; i<MAXITEMS; i++) { total += getvalue(i); // TODO replace with your logic } // tot...
7,670,901
7,670,954
Shorter way of resolving type to the class::typedef
I have several classes. For now they are separated by one symbol. Few of them contains type (a typedef) and few of them doesn't have it. struct A { ... public: typedef someclass type; } struct B { ... }; I want to implement a SFINAE class in such a way that, Resolve<A>::type o1; // should resolve to 'A::type' Resolve...
template<typename> struct void_ { typedef void type; }; template<typename T, typename = void> struct Resolve { typedef T type; }; template<typename T> struct Resolve <T, typename void_<typename T::type>::type> { typedef typename T::type type; };
7,670,914
7,670,925
Strange behaviour for loop C++
I am having trouble understanding why in this code snippet the "Hello" statement is not being printed. I thought that the condition statement in the for loop starts getting tested after only at the second iteration. for ( count = 0; count < 0; ++count) { cout<<"Hello!\n"; }
It never enters the loop at all because for loops are tested at the start. You start with count = 0, but the loop condition is count < 0. So it fails right away and skips the entire loop. do-while loops are the ones that are tested at the end of the iteration.
7,670,978
7,671,002
C++ namespace.... anonymous namespace is legal?
namespace { int Foo (int a) ; } Like this. Is this code snippet legal? Is this legal? and, can I reference Foo in anywhere? or only certain domain? Thank you.
It is legal, You can use Foo anywhere in the same Translation Unit. Anonymous namespace is the standard prescribed way of saying static on variables to limit their scope to the same Translation unit. C++03 Standard section 7.3.1.1 Unnamed namespaces para 2: The use of the static keyword is deprecated when declaring ...
7,671,089
7,671,113
How to know library to link in command line?
So, for example, I want to link a boost::thread library, I have to type -lboost_thread in the command line. However, how do I know the name of other libraries, so I don't have to guess the name to put in the command line. For example, to link thread library, I put -lboost_thread as a random guess from another linking e...
Read the manual that comes with the library.
7,671,242
7,671,276
C++. member function cannot be called. error : "foo is private"
#include <stdio.h> class MyClass { void Foo(const int par); }; void MyClass::Foo(const int par) { } main() { MyClass A; A.Foo(1); } Anyone can help me? What is wrong with my code? This is the error I get when compiling with gcc: error: ‘void MyClass::Foo(int)’ is private
Class members and class member functions are by default private, meaning they can only be accesed by methods of the same class and friends. class MyClass { // members declared here will be private public: // members declared here will be public void Foo(const int par); private: // private };
7,671,290
7,672,316
Network connection in C++
In a c++ application (which I didn't write) It uses network connection. in a loop it is always check if the connection is still available. if I'm taking out the LAN cable, my application just fails because a timeout occured. Is I know the socket number and connection info. is there any way to know that It is a network ...
Unplugging the cable is not necessarily a "network error" per se. A TCP connection can easily survive across the disconnection if it's temporary enough not to reach the timeout set on the TCP connection, which is done on the socket in your case. So you can set the timeout lower, or have some other logic that tests th...
7,671,300
7,671,333
Homework: Cout incorrectly handling a return value of 0.0 from a class method
First, this is homework, so I can not dynamically allocate memory for an array of any size, and I can not use a vector. I have a class which includes a double array holding 30 elements, and two other variables to keep track of how many elements have been added and the max number of elements that can be stored. There ar...
average() has divided something by zero and got minus infinity, and that's how cout has displayed it.
7,671,471
7,671,507
generating random numbers - srand c++
I am having trouble using srand. i am trying to generate a random number in the interval 100 to 200. The number will keep being generated and placed in an array. Once the method is called again the same sequence of random numbers needs to be generated again. Because of this I need a seed, no matter what I try I cannot ...
If you just want to repeat an arbitrary sequence, you can set the seed with srand() by giving it the same argument. For example: pax$ cat qq.c #include <iostream> #include <cstdlib> int main (void) { srand (42); for (int i = 0; i < 5; i++) { int x = 100 + (rand() % 101); std::cout << x << std::...
7,671,697
7,674,657
Moving temporary objects into a vector
#include <iostream> #include <utility> #include <vector> int i = 0; struct A { A() : j( ++i ) { std::cout<<"constructor "<<j<<std::endl; } A( const A & c) : j(c.j) { std::cout<<"copy "<<j<<std::endl; } A( const A && c) : j(c.j) { std::cout<<"move "<<j<<std::endl;...
I've slightly recoded your example: #include <iostream> #include <utility> #include <vector> int i = 0; struct A { A() : j( ++i ) { std::cout<<"constructor "<<j<<std::endl; } A( const A & c) : j(c.j) { std::cout<<"copy "<<j<<std::endl; } A( A && c) : j(c.j) { std...
7,671,719
7,671,753
creating multiple objects for classes/structures?
I have a question. Is it possible to create multiple objects during run time for classes or structures? #include<iostream> #include<conio.h> using namespace std; struct node { int no; }; int main() { int i; for(i=0;i<4;i++) { struct node s[i]; } cout<<"Enter the values"; for...
replace for(i=0;i<4;i++) { struct node s[i]; } with struct node s[4]; the way you wrote your program will not work. You defined the node array s inside a block so it will not be visible outside of that block. If you want to dynamically allocate the memory you have to do something like: struct node *s = new ...
7,671,756
7,672,263
What are the pros and cons of specifying an include prefix in the source file versus in the search path parameter of the compiler?
When a C or C++ library comes with several headers, they are usually in a specific folder. For example, OpenCV provides cv.h and highgui.h in a opencv folder. The most common way to include them is to add this opencv folder to the search path of the pre-compiler (e.g. gcc -I/pathto/opencv), and simply include the heade...
They have slightly different purposes, and I think need to be used carefully. Consider the fact that in the -I case it was /pathto/opencv. You're suggesting possibly #include <opencv/cv.h> but you'd never write #include </pathto/opencv/cv.h>. There's a reason for that, which is that you expect cv.h is always in a direc...
7,671,780
7,673,145
Trouble compiling OGRE tutorial example.
I have built and installed Ogre to my Debian with Code::Blocks. Next, I tried to compile a tutorial application but I'm getting these errors: obj/Debug/BaseApplication.o: In function `BaseApplication': /home/ver/projects/testogre/BaseApplication.cpp:34: undefined reference to `Ogre::StringUtil::BLANK' /home/ver/projec...
when you compile you have to link OgreMain library to your executable.
7,671,856
7,671,899
QLibrary resolve returns false
I´m trying to include classfiles dynamically right now and chose to do so by loading the .dll into a QLibrary. The problem I´m having now is, that when I try to call the resolve()-method it returns 0. EDIT: In the meantime the problem has been solved and I decided to edit the code, so others can see how it works: This ...
You need to export your class using __declspec(dllexport) class __declspec(dllexport) DivFixture : public QObject {
7,671,866
7,672,015
How does a compiler decide whether it's worth making my functions inline or not?
I am wondering if anyone knows the logic which C++ compilers generally use to decide whether or not to inline a function at compilation (assuming inline has been requested). Is this type of thing public knowledge?
I gave a more thorough answer in this other question. Basically compilers have heurstics based on cost-analysis, quoting myself (does this mean I am going senile ?) If you think about inlining, and its consequences, you'll realise it: you avoid a function call (with all the register saving/frame adjustment) you expos...
7,672,163
7,672,222
Why is a non-default constructor NOT considered in the Rule of Three?
The rule of three (also known as the Law of The Big Three or The Big Three) is a rule of thumb in C++ that claims that if a class defines one of the following it should probably explicitly define all three: destructor, copy constructor, copy assignment operator. Why is a non-default constructor not considered as one of...
Why is a non-default constructor not considered as one of them? When there is any resource managed in the class, programmer has to define a non-default constructor anyway. That is not necessarily true. The constructor might not aquire any resource. Other function(s) might aquire them as well. In fact, there can be m...
7,672,205
7,672,288
VC++ what does return code do?
I have a code. like this: int functionA (){ Foo(**,**,**); return 0; } Foo() is a huge function(more than 10,000 lines). Which I don't understand all.Foo function includes some multi-thread code. The problem now is, if I have "return" code right after Foo, Foo can be run correctly. If I insert some other code ...
If I insert some other code (even a really simple cout code) between Foo() and "return". The Foo function will act weird(partly not run correctly). Sounds like Foo is corrupting the stack in some way. You'll probably find that declaring redundant variables (and hence changing the contents of the stack) "fixes" the p...
7,672,314
7,672,411
lambda with templates
I am currently doing some exercises with templated functions. I had the task to write a implementation of the transform algorithm. I did it like the following and it works: template <class in, class out, class T> out stransform(in b, in e, out d, T p(const T&)) { while (b != e) *d++ = p(*b++); return...
The predicate is normally a simple template argument: template <class in, class out, class UnaryPredicate> out stransform(in b, in e, out d, UnaryPredicate p); This will accept pointers to function, lambdas and function objects.
7,672,321
7,672,373
Conversion in Point Cloud Library from proprietary format to float; no matching function found
I have what I think is a fairly basic question about a conversion in the point cloud library from a proprietry data type to float. My issue I think comes from a lack of experience with templates, data types and C++ in general. The function that should perform this conversion is copyToFloatArray, defined in the document...
First, you need to allocate memory in your floatArray. Then, you need to derefence the fpfhs ptr using *. finally, there is no need for a double pointer array there. Here is the corrected code : pcl::PointCloud<pcl::FPFHSignature33>::Ptr fpfhs (new pcl::PointCloud<pcl::FPFHSignature33> ()); // populate fpfh... float *m...
7,672,374
7,672,396
Should I explicitly zero initialize auto_ptr?
Some of my colleagues prefer to explicitly initialize std::auto_ptr to 0 in constructor initialization list, but it will be initialized to 0 in it's constructor without any explicit initialization. So is there any reason to do it? #include <memory> class A { A() : SomePtr(0) { } private: std::auto_ptr<SomeTyp...
No, the default constructor of std::auto_ptr does exactly that, so doing it explicitly is not necessary. In any case, it's a matter of style and you should be consistent. For instance, would you explicitly call the default constructor of a member vector in the constructor initialization list? As a side note, std::auto...
7,672,567
7,672,587
Why do I get an "Access violation reading location" error with this code?
Can anyone tell me why I get "Access violation reading location " with this code example? And how can i fix this? #include <vector> using namespace std; struct StructTest; struct Struct1; typedef struct Struct1{ StructTest* test; } Struct1; typedef struct StructTest{ vector<Struct1*> test123; } StructTest; st...
It's crashing on this line: abc->test123.push_back(a1); The reason is because you allocate it two lines above using malloc. Therefore, the contents of test123 are uninitialized. So it crashes when you call push_back on it.
7,672,723
7,672,951
extract common blocks into functions in C++
There's something I recurently struggle with while working on C++ code. Let's say I've got a method doing X, Y and then Z. Now I'd like to introduce another method that should do X, Y', Z. If that was plain old C code, I'd then make functions X() and Z() with the common code, declaring them static so that the compiler ...
If X and Z are doing stuff relevant to the class, then make them member functions of the class (and if not, then there's no problem, since their implementations can easily be put elsewhere, out of public view). If they're not supposed to be part of the public interface of the class, make them private. If it bothers you...
7,672,792
7,672,820
Calling C++ exe functions from C#
I'm trying to monitor a running application written in C++ using a different C# application. In my C++ code I have defined an API: _declspec(dllexport) //is this even possible when compiling an .exe? int getSomething(); Is there a way to call this function from the C# code? Will the classic approach work: [DllImport(...
Yes, any PE executable can export functions this way. Just keep in mind that the compiler will sometimes mangle the export names, resulting in stuff like this: MyAPIFunction@16 You can check that the names are OK by loading the executable file into a tool such as PEInfo. You should be able to call it in exactly the sa...
7,672,918
7,672,946
How to use function from static library if I don't have header file
Is it a way to use function from static lib, if I don't have header file, only *.a file, but I know function signature?
Yes, if you know the function signature Just write the function signature before calling it, as: void f(int); //it is as if you've included a header file //then call it f(100); All you need to do is : link the slib.a to the program. Also, remember that, if the static library is written in C and has been compiled with...
7,673,040
7,677,568
WinAPI: Create resizable window without title bar, but with minimize/maximize/close buttons (as Firefox/Chrome/Opera)
If you look at the windows of the browsers Firefox, Chrome or Opera, you'll notice that their windows have minimize/maximize/close buttons are resizable but have no title bar I'm interested: how can I create such a window? What I have already tried: I looked around on StackOverflow (and googled, too), and found this:...
The programs remove the non-client area (the title bar) and have a bunch of custom handling for reproducing the window buttons, icons, system menu etc. The benefit of this is that they can draw to the new "title bar", which is actually part of the standard client area, adding tabs or other custom controls. The followi...
7,673,532
7,673,764
reducing memory usage
i am developing a project in which i have used many classes. for creating classes i have used the new operator...example, in banana class i have an instance variable of class apples...... THIS IS A SCALED DOWN REPRESENTATION OF WHAT I WANT TO SAY & DOES NOT REPRESENT THE CODE WORD-TO-WORD...SO PLEASE DO NOT POINT AT SY...
First you should find out what kind of relatioship your banana->apple relation is. If it is a composition (A banana is composed of its apple and...) the simplest think is to store an apple instance in a banana. class banana { apple apple_; // a banana HAS A apple }; If this is true, but you have myriads of bananas ...
7,673,597
7,673,625
include string or string.h
To use memset(), what is the difference between #include <string> //did not work and #include <string.h> //worked Thanks!
<string> is a C++ standard library include, and <string.h> is C standard library include. The equivalent of <string.h> in C++ is <cstring>, although both will work. The difference is: <cstring> wraps everything in the std namespace whereas <string.h> puts everything in the global namespace. Also, expect some stricter t...
7,673,709
7,673,738
how does the program print 10 statements?
This program recursively calls the function tester. #include <iostream> void tester(); int i = 1; int k = 1; int main() { tester(); } void tester() { while(i++ < 10) tester(); std::cout << "called " << k++ << " times" << std::endl; } I am surprised by this output : called 1 times called 2 times cal...
The while body is executed only once in each recursive depth. The while is false when i is 10, which will be when tester () is called 10 times recursively. As the i is declared global, the i++ update will be visible to each call of tester (). At the last recursive depth when the while condition is false, the last teste...
7,673,749
7,673,809
A common class type for all bidirectional iterators, c++
I have a bunch of classes which implement geometric objects based on vertices, such as TriangleMesh, PointClouds or Edgesets. They all inherit from VertexBasedGeometry. I now want all of them to return a bidirectional iterator on references of its vertices. This would allow to access the vertices of any VertexBasedGeom...
std::iterator is only a tag class that you derive from, and the type of your iterator must be known at compile-time to the implementing class. If you want to hide the iterator implementation from the iterating code, you must add an indirection level, e.g. Thomas Becker's any_iterator.
7,673,827
7,677,249
Strings/signatures comparison of AntiViruses
Does signature-based AntiVirus software match each currently-scanned file with all strings/signatures that exist in the database? Does it need to pass through all signatures in order to compare them with a file? The comparison is done from the "database to the file" not from the "file to the database", is that true ? T...
Typically how this is done is that the database of known virus signatures is used to build a state machine (often something very similar to the Aho-Corasick string search algorithm). Then, each file that is to be checked is run through the state machine. This turns out to be surprisingly fast, as all matching virus sig...
7,674,195
7,674,300
FindFirstFile Not working with Wild cards
I am trying to use the FindFirstFile function to traverse through all of my .txt files, but I am getting INVALID_VALUE_HANDLE error when I try it, here is my function: int search(LPSTR lpszPath) { WIN32_FIND_DATA WFD; HANDLE hSearch; CHAR szFilePath[MAX_PATH + 1]; PathCombine(szFilePath, lpszPath, "*.t...
I imagine that the problem is that this will only find objects that match *.txt. You are wanting a recursive search that descends into directories. But it will only descend into directories that match *.txt. For a recursive search like this you have to enumerate all the directories without the *.txt wildcard. It may be...
7,674,357
7,674,681
non-static data member initializers questions
I've built MinGW from trunk-version GCC-4.7.0: http://code.google.com/p/mingw-builds/downloads/list In the description of changes of this version it is said that non-static data member initializers are implemented: http://gcc.gnu.org/gcc-4.7/changes.html http://www.open-std.org/JTC1/SC22/WG21/docs/papers/2008/n2756.htm...
The problem seems to be an ambiguity in determining whether you are declaring a function or an object, and the compiler is choosing the function. You should try initializing the string using this syntax instead: std::string s = "string"; If we follow the link from the GCC Release Notes concerning non-static data membe...
7,674,580
7,674,738
How to verify the integrity of a image file in c++ or python?
I want to check whether the images is downloaded completely. Is there any library to use? The images I want to verify including various formats such jpeg, png, bmp etc.
The standard go-to library for that kind of thing in Python is the Python Imaging Library (PIL).
7,674,653
7,674,704
C++: Is there a less verbose way represent custom numeric types?
I need to represent Volts, Ampers, And Watts and their relations (e.g. W = V * I).. This is what I came with, but it seems really verbose. Any idea on how to make it more concise ? #include <stdio.h> #include <iostream> template<class T> class double_val { public: explicit double_val(double val):_val(val)...
There is indeed a less verbose way in library form, Boost.Units which defines the SI units as type safe class template instantiations. In particular, it defines the units volt(s), ampere(s) and watt(s).
7,674,695
7,676,073
obj.template operator() construct does not work with xlC 11.1
The following piece of C++ code: template <typename T> static void execute(T& obj) { obj.template operator()<int>(); } when compiled with IBM's xlC 11.1 results in the error message: 1540-0063 (S) The text "operator" is unexpected. If I use a function instead of an operator, it works fine, but I do not want to rew...
The best way to get the .template operator construct to work would be to submit a bug report to IBM. This code conforms to the C++ standard. It is, in fact, the only legal way to write this code. When you file the report you can use the following as evidence: §14.2/4 states: When the name of a member template special...
7,674,776
7,674,811
IntSet array implementation
i have following code for implement IntegerSet Class,idea is that when i insert element it should sort ,and then print it #include <iostream> using namespace std; class IntSet{ public : int n,*x; public: IntSet(int maxelms,int maxval){ x=new int[1+maxelms]; n=0; x[0]=maxval; } i...
Your insert code never enters the loop (since the first element in the vector is always larger than whatever has been been passed to the function) and returns without doing anything. The code is a bit obscure. Look up insertion sort – this is what you need here. Apart from that, your code leaks memory since the class d...
7,675,007
7,675,050
string.compare for c++
I am asking user to input a word then have my program compare it with an input .txt file but even tho I type in exactly a word in data.txt it still executes false. //------------in my data.txt--------- // Banana Bed Today // Apples Chair Window // Corn Tomorrow Hive string testData; cout<<"enter Data: "; cin>>test...
If you replace: for(i=0; i<s.size()-1; i++){ with: for(i=0; i<s.size(); i++){ // Adjusting to check last entry as well. cout << "[" << s[i]->name << "][" << testData << "]" << endl; you may find it becomes blindingly obvious. There's a good chance that one of your strings is not quite what you expect.
7,675,075
7,692,566
Map API that allows image corner-point coordinates and is suitable for a non-web language
I have been asked to add map support from one of any number of map APIs to a geographical display in our software. The display currently shows geographical coordinates, such as a series of GPS fixes; we'd like to show a map behind them. We use C++ Builder 2010 (and occasionally Delphi) so this is natively compiled so...
Use the OGC WMS GetMap request to get an image This page explains how to get this image. The image is from DEMIS, but there are thousands of providers out there with WMS services I do recommend DEMIS, but here are some lists of free WMS services. The GeoServer list The gis.stackexchange.com list of lists
7,675,298
7,676,438
Unhandled AccessViolationException Error calling a DLL into VB.Net
I'm trying to call a C++-compiled DLL from VB.net and I'm running into some problems. Seems like there's an obvious solution, but I can't figure it out. Here is the function declaration in C++: MyFunction(int trailingaveragesize, double sigmasize, int myflag, int sizeSeries, double *Xdata, double *Ydata, int sizeinput...
Declare Function MyFunction Lib "C:\Dev\asdf.dll" (ByVal trailingaveragesize As Long, _ ByVal sigmasize As Double, ByVal myflag As Long, ByVal sizeSeries As Long, ByRef Xdata As Double, ByRef Ydata As Double, ByVal sizeinputparameter As Long, ByRef averagePairs As Long, ByRef PositionsSize As Double, ByRef PnLS...
7,675,358
7,675,493
Allow C++ class to access some "internal" member of other class, but not private?
When coding classes that are tightly coupled functionally, but where you want a simple interface to the rest of the world, it would be neat if I could do something like this: class log { private: log_context& cont; public: create_log_section(std::string name) { cont.create_log_section(name);// this is fine! I...
You can use an internal class to do so class log_context { class internal { friend log; static void create_log_section( log_context & context, std::string name) { context.create_log_section( name ); } } private: void create_log_section(std::string n...
7,675,369
7,675,672
Class not registered 0x80040154
I get a "Class not registered 0x80040154" error when i run my application. My environment setup is windows 2008 using visual studio 2005. I just migrated from windows xp, where the application used to work with no error. Thanks!
The dll or exe that provides the interface defined by the CLSID that you are passing to CoCreateInstance either does not exist on your new PC or if it does exist it has not been registered.
7,675,622
7,675,704
win forms C++/CLI How to use .cpp class from header
Hello I have sample #include "stdafx.h" using namespace System; ref class RefClass { public: int X; RefClass(int x) { X = x; } }; How can I use this class in Form1.h? Like RefClass^ d = gcnew WinFormsTest::RefClass(); public ref class Form1 : public System::Windows::Forms::Form private: Sys...
Create a RefClass.h file where you'll put the class declaration. Create a RefClass.cpp file where you'll put the class definition. The implementation. For using it in any other class you have to include RefClass.h first and then you can do auto refClass = gcnew RefClass();
7,675,993
7,676,288
Boost::graph Dijkstra : initially populating the queue
I'm using boost::graph and its Dijkstra implementation. I want to compute THE shortest path from a set of vertices to another set of vertices. I do not want to compute all the possible paths between those sets. The idea is the following : I'm in a building with entrances on various streets. So I can start my journey on...
I've not used boost::graph, and I hope somebody with better knowledge of it will give a better answer, but perhaps you could create a graph type that wraps the existing graph, leaving the original unmodified, but exposing to the algorithm a view that includes your virtual nodes and edges? If not, is it infeasible to co...
7,676,291
7,676,417
another copy algorithm
I have two vectors. vector<Object> objects; vector<string> names; These two vectors are populated and have the same size. I need some algorithm which does assignment to the object variable. It could be using boost::lambda. Let's say: some_algoritm(objects.begin(), objects.end(), names.begin(), bind(&Object::Name, _1) ...
I can't think of a std:: algorithm for this. But, you can always write your own: template < class It1, class It2, class Operator > It2 zip_for_each ( It1 first1, It1 last1, It2 result, Operator op ) { while (first1 != last1) op(*first++, *result++); return result; } EDIT: Another al...
7,676,327
7,676,371
Looking for QT function to round a variable (integer) of type qint64 to the nearest ten
I'm looking for a QT function to round a variable (integer) of type qint64 to the nearest ten. For example: 1013 would round to 1010. 1019 would round to 1020 QT Assistant doesn't seem to list any built in functions that would do this, but I could be looking in the wrong spot. Any help would be appreciated. Thanks, Wes...
You may try this old trick for positive numbers, replace + with - for negative: i_rounded = 10 * ((i + 5) / 10);
7,676,402
7,676,932
How can I debug a C++ executable compiled externally (with debug flags set) from inside Eclipse?
I have a large C++ project, different parts of which are compiled in different ways (bjam/make). I was having trouble getting it to build from within Eclipse. Could I build the code externally (with g++ -g), and then just run the debugger from within Eclipse?
I figured it out. Should've looked earlier at this: http://wiki.eclipse.org/CDT/User/FAQ#Debugging_C.2FC.2B.2B_Projects I first added my project to eclipse. Then I followed the instructions above to set up a debug configuration. And somewhat surprisingly eclipse is able to figure out that the binary I want to run refer...
7,676,406
7,686,041
How to disable Autoscroll to top in a QTableView when the underlying model changes?
I have created my own class that derives from QTableView, the associated model is is derived from QAbstractTableModel. The data in the model is performance data(process name, mem usage etc.) which continuously gets updated with a short interval. Updating the model is done by first removing all data (enclosed with a beg...
Working solution The scrollbar movement was due to signalling removing of all data using beginRemoveRows/endRemoveRows. In order to avoid this I instead emitted a dataChanged(...) signal with the start/stop indexes of the updated list of items if it was smaller than the existing model, and with indexes from the existin...
7,676,604
7,676,964
How to enumerate all QObject classes in Qt?
Is there a way to enumerate all QObject classes declared in an application or DLL? I am trying to create an application that loads DLLs and lists all QObject classes inside the DLLs. Update: Actually I am trying to create a Unit Test GUI. It will load DLLs, instantiate the QObject inside, and call QTest::qExec against ...
If the program code is not stripped you can get some instrospection by reading the binary: objdump -demangle=C++ -t SomeQtLibrary.so |grep qt_static_metacall it shows roughly the QObject derived classes. I think they all implement this symbol. Of couse since you are on Windows you would have to use Windows tools such a...
7,676,615
7,678,342
How can I make a dotted line separator in an MFC dialog?
Is there a control for this anywhere? Or a way to use another control to make it look like a separator? Thanks
Override the OnPaint function of your dialog and have it draw the line. Ordinarily the OnPaint for a dialog doesn't do anything, as all the content is in controls which paint themselves.
7,676,622
7,698,746
Is data-driven testing bad?
I've started using googletest to implement tests and stumbled across this quote in the documentation regarding value-parameterized tests You want to test your code over various inputs (a.k.a. data-driven testing). This feature is easy to abuse, so please exercise your good sense when doing it! I think I'm indee...
I think the main problem is testing with "randomly generated data". It is not clear from your question whether this data is re-generated each time your test harness is run. If it is, then your test results are not reproducible. If some test fails, it should fail every time you run it, not once in a blue moon, upon some...
7,676,672
7,685,250
How do I prevent qmake creating an extra "moc" folder in this 'out of source' build scenario?
(Apologies, I can't think of a better way of explaining except through including the following detail) Pre-build structure: F:\ └ Project\ └ Project.pro └ ProjectSettings.pri └ Source\ └ Source.pro └ My_Library\ └ My_Library.pro └ library.cpp └ ... Contents of "Project.pro": TEMPLATE = ...
1. The folders are created before the Debug and Release scopes are run. qmake produces one primary make file (Makefile) and if there is source to build: two child make files (Makefile.Debug and Makefile.Release). The scopes are set for the children, but not for the parent therefore qmake decides it must create the fo...
7,676,793
7,676,972
Create a C++ GUI/API for Mac
I am quite confused about 1) the difference between a GUI and API 2) Where to learn to make my own GUI/API 3) What all the premade GUI/API's there are My goal is to learn how to make actual programs instead of just using console and yes, I would like a solution for doing this on Mac OS X (preferably cross-plat...
GUI stands for Graphical User Interface, while API stands for Application Programming Interface. It is common in programming terminology reusable libraries are called as API. I assume by GUI/API you mean an API that allows you to create GUI based applications. For example Swing is Java API for creating GUI. For C++ t...
7,676,817
7,676,940
Forcing improper enum values?
I came across some unusual (to me at least...) behavior with C++'s enums. I've tried the following in Visual Studio 2008 and g++ version 4.4.3 #include <iostream> using namespace std; enum testEnum { // no zero enum one = 1, two = 2, three = 3 }; int main(int argc, char *argv[]) { testEnum e; //...
An enum is guaranteed to hold any value in the range between its smallest defined value and its largest, and is unspecified on how it handles numbers outside the range. §7.2/3 ...if not explicitly specified, the underlying type of a scoped enumeration type is int." § 7.2/7 ...for an enumeration where emin is...
7,676,864
7,677,130
How to check if a _bstr_t contains (similar to str.find) a string
I am new to _bstr_t's and still trying to get the hang of it. I was trying to check whether a particular string x is contained anywhere within the bstring. Something I would normally do like; String x = "hello"; String example = "You! hello there"; ... if (example.find(x) != string::npos) { ... Just for the record the...
There is no need to use _bstr_t. Use the BSTR type. Next, read Eric's Complete Guide to BSTR Semantics. Lastly, you can use the BSTR in native code the way you would a normal character array in most cases. BSTR bstr = SysAllocString(L"FooBarBazQux"); if (wcsstr(bstr, L"Bar") != NULL) { // Found it! Do something. } e...
7,676,878
7,676,923
Difference between & and * as a parameter
What is the difference between the following two parameter types? The first accepts a pointer, which is in effect a memory address, and the second is also a memory address? foo(float& bar) { // do stuff } foo(float* bar) { // do stuff } Could you not call both with: float pow = 3.0f; foo(&pow); or float* p...
A pointer can be NULL, while a reference can't. This can be useful if you need to pass a NULL object for whatever reason. With the pointer syntax, you pass a pointer when you call the function. With references, you just pass the variable: refer(float& bar) {} point(float* bar) {} float afloat = 1.0f; refer(afloat);...
7,676,915
7,676,979
Why does GCC not optimize this set of branching and conditionals as much as it could?
The following three pieces of code achieves exactly the same effect. Yet, when compiled with -O3 on GCC 4.5.2 the times for a lot of iterations vary quite markedly. 1 - Normal branching, using multiple conditions, best time 1.0: // a, b, c, d are set to random values 0-255 before each iteration. if (a < 16 or b < 32 or...
The OP has changed a bit since my original answer. Let me try to revisit here. In case 1, because of or short-circuiting I would expect the compiler to generate four compare-then-branch code sections. Branches can obviously be pretty expensive especially if they don't go the predicted path. In case 2, the compiler can ...
7,676,971
7,677,191
Pointing to a function that is a class member - GLFW setKeycallback
I'm writing a GLFW app, in which I've wrapped the function calls into a simple class. I'm having trouble setting the key callback. My class is defined as: class GAME { private: bool running; public: GAME(); int execute(); void events(int, int); int loop(); int render(); }; The execute function...
There is a C++ syntax for pointing to class member methods but you cannot pass them to a C style API. C understands function calls and every non-static object method, taking your events as an example, looks like this thinking in C terms: void events(void* this, int, int); meaning that every method apart from the standa...
7,677,002
7,677,169
How static libraries work? (C/C++)
I know how to use and create them, but I can't find a text about how it is implemented, how function call happens and so on, can someone help me with that information? Because I want to understand them, but not just know what is it and how it is working
As you may know, when you compile a source file you get an object file. Depending on your platform its extension may be .o or .obj or anything else. A static library is basically a collection of object files, kind of like a .zip file but probably not compressed. The linker, when trying to generate an executable tries t...
7,677,007
7,677,043
passing vector to function c++
I have a main.cpp test.h and test.cpp> I am trying to pass my vector through so i can use it in test.cpp but i keep getting errors. //file: main.cpp int main(){ vector <Item *> s; //loading my file and assign s[i]->name and s[i]-address tester(s); } //file: test.h #ifndef T...
A std::vector<T> and T* [] are not compatible types. Change your tester() function signature as follows: //file: test.cpp int tester(const std::vector<Item>& s) // take a const-reference to the std::vector // since you don't need to change the values ...
7,677,092
7,737,034
Creating an android.graphics.Bitmap from C++
I have some NDK based C++ code that needs to build an android bitmap object. I'm sure there is a way to do this directly from the C++ code but its not the easiest of things to do ;) So the method I want to call is Bitmap.createBitmap( width, height, Bitmap.Config.ARGB_8888 ); So to do this from native code I need to...
I have this in my code, so I can give you answer that works. 1) Get the static method id of createBitmap(int width, int height, Bitmap.Config config): jclass java_bitmap_class = (jclass)env.FindClass("android/graphics/Bitmap"); jmethodID mid = env.GetStaticMethodID(java_bitmap_class, "createBitmap", "(IILandroid/graphi...
7,677,158
7,677,453
How to detect negative numbers as parsing errors when reading unsigned integers?
I want to read unsigned integers in base-10 (decimal) representation from a C++ iostream with at least rudimentary error detection. In my view, minus signs would clearly be an error in this case, because unsigned integers have no sign. However, the gcc is of a different opinion: #include <iostream> #include <sstream> ...
Consulting C++03, 22.2.2.1.2/11, the formats are inherited from scanf and friends, which in turn all say that the converted character sequence is "optionally signed", even for the ones with unsigned output. strtoul is the same. So, I suppose you could say the standard that mandates the behavior is C89 for C++03, C99 fo...
7,677,285
7,680,432
How to get the length of a file without downloading the file in a cURL binary get request
I want to create a cURL request in some C++ code which will get me the length of a file in a server without downloading the file. For that, I use some cURL options to tell I only want headers in the request response, and then I examine the response to get the file length. I'm setting the following request options: curl...
CURLINFO_CONTENT_LENGTH_UPLOAD is the number of bytes uploaded. You need to use CURLINFO_CONTENT_LENGTH_DOWNLOAD instead. Note that if the server dynamically generates the data, the length may be different when you actualy download the file versus just downloading its headers. Also note that if the server sends data a...
7,677,358
7,677,391
For cycle [C/java like syntax]
So here I am with this simple question Consider these two for cycles and please explain to me if there's any difference between the two ways of writing method 1 : for(i=(max-1) ; i>=0 ; i--){ do-some-stuff } method 2 : for(i=max ; i>0 ; i--) { do-some-stuff } the reason I'm asking this is because today at sch...
Yes, there's a big difference - in the version, the range is [0, max-1]. In the second version, it's [1, max]. If you're trying to access a 0-based array with max elements, for example, the second version will blow up and the first won't. If the order in which the loop ran didn't matter, I'd personally use the more idi...
7,677,364
7,677,494
Is there a way to expand a dynamic memory array in C++?
Is there a way to expand a dynamic memory array? like this: int *a = new int[5]; *a = new int[2]; Is this legal?
You cannot expand this type of a dynamic memory array. You can use malloc and realloc though if you need this facility but I would advice against that and suggest including <vector> and using std::vector instead. It has a resize method. Also, what you described won't compile. The following will: 1: int *a = new int[5];...
7,677,607
7,677,645
Should "const" be used semantically or syntactically?
class A { ... public: shared_ptr<Logger> GimmeLogger () const { return m_logger; } private: shared_ptr<Logger> m_logger; }; In class A, should GimmeLogger be const or non-const? It would make sense to be const because it is a simple getter that doesn't modify *...
If you make that non-const, then you cannot write this: void f(const A & a) { auto v = a.GimmeLogger(); //error } So if you want to write this; that is, if you want to call GimmeLogger on const object, then make GimmeLogger a const member function, because you cannot invoke a non-const member function, on const ob...
7,677,649
7,677,776
reference type variable initialisation and storage
Is this legal? int& foo = 0x00000000; I don't know if 'int' is the right data type. If you wanted to store an address what data type would you use? Or do you have to use a pointer? in addition to this, is this legal? int foo = 5; int bar = &foo; Essentially what I'm asking is, is there a way of storing addresses with...
If you wanted to store an address what data type would you use? Or do you have to use a pointer? For storing addresses, you normally use pointers. If for who-knows-what reasons you to store pointers in an integral type, you can, provided the integral type is big enough to hold the pointer (64bit integer for 64bit poi...
7,677,735
7,677,843
Is it safe to return by value a shared_ptr that is guarded by mutex?
Here is a code sample: class A { boost::mutex a_mutex; boost::shared_ptr<int> a; boost::shared_ptr<int> clone_a(void) { boost::lock_guard<boost::mutex> lock(a_mutex); return a; } }; The suggestion is that the boost::shared_ptr copy constructor call on A::a will precede the boost::lock_guard destructor...
If by "safe" you mean you won't get data races on a, then yes. It is exactly as you say. However, it won't protect further accesses to *a (or *clone_a()), as you probably know. I'm not sure, why is the method called "clone", as it doesn't clone anything.
7,677,770
7,677,804
boost::smart_ptr and COW containers
I'm using boost::scoped_array in a container that I want to make copy-on-write but I fear that scoped_array won't work. Which boost::smart_ptr container is closest to cow-safe scoped array?
You could use boost::shared_array.
7,677,855
7,677,922
getting into the loop when the initial condition is false
I am confused and have no clue for what is going on here : #include <iostream> void recur(); int i = 1; int main() { recur(); } void recur() { std::cout << "\nvalue of i above while loop : " << i << std::endl; while(i++ < 10) { recur(); std::cout << "statement just after the recursive call to tester an...
No, when recur() returns, you are still in the while statement, you have to execute std::cout after recur(). void recur() { std::cout << "\nvalue of i above while loop : " << i << std::endl; while(i++ < 10) { recur(); // <b>each time `recur()` returns, its return to here</b> std::cout <<...
7,677,903
7,677,957
beginner reference type parameter confusion
foo(int &bar) { bar = 5; } The call to this function would be int foobar = 2; foo(foobar); Am I right in thinking that the function parameter essentially 'gets' the memory address of the variable, but does not then have to be dereferenced in foo, and that I would be changing the original value of foobar? Before ...
References are usually implemented with underlying pointers (although that is not mandated by the standard), but they are a totally different beast than pointers. A reference is simply a new name or alias for an existing variable. When you do void foo(int& bar) { bar = 5; } int foobar = 2; foo(foobar); you are in...
7,678,001
7,678,078
When a function behave when "return" out o of the function in C++
I have a code. like this: int functionA (){ Foo(**,**,**); return 0; } Foo() is a huge function(more than 10,000 lines). Which I don't understand all.Foo function includes some multi-thread code. The problem now is, if I have "return" code right after Foo, Foo can be run correctly. If I insert some other code ...
This is known as a race condition, some of your code is likely interfering with the operation of Foo(), without a more detailed description of the problem it is impossible to determine how to fix it. Either sleep() while the threaded operations are in progress, or read the documentation to determine if foo() can be sa...
7,678,093
7,678,557
Using glDrawRangeElements in OpenGL 2.1
Based on the information in Questions about glDrawRangeElements() and given the following items: struct MyVertex { GLfloat x, y, z; //Vertex }; const GLushort pindices[] = { 0, 1, 2, 3, 5, 4 }; struct MyVertex pvertex[6]; //VERTEX 0 pvertex[0].x = 0.0; pvertex[0].y = 0.0; pvertex[0].z = 0.0; //VERTEX 1 pver...
Your problems are not directly related to glDrawRangeElements, but to incorrect use of VBOs. First of all, when using VBOs (or more precise, when binding a VBO to GL_ELEMENT_ARRAY_BUFFER), the index pointer argument to glDraw... is interpreted as a byte offset into the buffer bound to the GL_ELEMENT_ARRAY_BUFFER bindin...
7,678,228
7,678,289
How to use string::replace with a char*
I am trying to replace a substring with char*, the strng::replace refuses to take anything that is not a const string * map<string,char *> renamed_files; map<string,char *>::iterator rename_it; Is there any way of using cPath to replace the substring in the map? rename_it = renamed_files.begin(); char cPat...
No, the key in a map is const. Therefore the problem is that rename_it->first is const but replace is (of course) a non-const member function. If you were to somehow modify it, that would change the correct position of the entry in the map, but the map has no way to detect that you're changing the string, so it can't m...
7,678,303
7,678,464
How to watch the vtable in gdb in a C++ program?
I have an interesting problem in one of my C++ programs. Apperantly the vtable of one of my classes is/becomes messed up during program execution. In a gdb session I found out that if I call a method of the object directly it succeeds, but if I use a pointer or reference I end up in the destructor of a completely unrel...
You can use the -fdump-class-hierarchy option of gcc which will give you the vtable information, however the output can be very verbose and hard to read. For instance, given the following trivial classes: class Base { public: ...
7,678,327
7,678,347
SNMP access via c,c++ or Java
I have printer HP LaserJet P2015 Series configured in the lan and i have enabled the snmp access in the printer. Need a way to get output for snmp-mib's ? via c , c++ or java
For Java, take a look at the snmp4j project. For C, take a look at the Net-SNMP project. Both projects are open source and provide SNMP client APIs.