question_id int64 25 74.7M | answer_id int64 332 74.7M | title stringlengths 20 150 | question stringlengths 23 4.1k | answer stringlengths 20 4.1k |
|---|---|---|---|---|
3,171,838 | 3,171,853 | How to use external cpp projects in a cpp project in Visual Studio 2008 | i m trying to make small test driven example by using cppunit. So i have 2 project which are test and normal library project. Whatever i do, i cannot be successfull. i got alltime LNK Error. Any help will be apreciated.
| Your test program needs to have a dependency on the library, so that it links against it.
In addition to this, you need to add the cppunit libraries as additional libraries, in the "properties -> linker -> input" section of the test program.
|
3,172,024 | 3,172,030 | A quick question on stack impl of C++ standard library | What does the line:
template<typename _Tp1, typename _Seq1>
friend bool
operator==(const stack<_Tp1, _Seq1>&, const stack<_Tp1, _Seq1>&);
in http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.4/a01367.html
do?
Why is _Tp1 repeated twice in arguements list?
Thanks,
| It declares the equality operator between two stacks a friend function of this class, which is necessary for it to access private members.
The const stack<_Tp1, _Seq1> appear twice because there are 2 arguments.
Of course it can be written as
bool operator==(const stack<_Tp1, _Seq1>& y) const { return c == y.c; }
but the C++ standard (§[stack.ops] (23.3.5.3.4)) seems to require this operator to be a free function.
|
3,172,026 | 3,195,635 | Qt setColumnWidth does not work | Have written the following code:
m_selectCategoryTableWidget = new QTableWidget;
m_selectCategoryTableWidget->setRowCount(0);
m_selectCategoryTableWidget->setColumnCount(2);
m_selectCategoryTableWidget->setHorizontalHeaderLabels(QStringList()<<tr("Category")<<tr("Number of items"));
m_selectCategoryTableWidget->verticalHeader()->setVisible(false);
m_selectCategoryTableWidget->horizontalHeader()->setStretchLastSection(true);
//m_selectCategoryTableWidget->setColumnWidth(0,400);
m_selectCategoryTableWidget->resizeColumnsToContents();
m_selectCategoryTableWidget->setColumnWidth(1,100); //this does not take effect
Please help.
| Well, Qt's logic is so, that after column resize, scroll bar area checks how columns fit into it. And if the sum of all columns' widths is less than the widget's visible width, then the last column gets resized to fill up the space leading to no visible result of calling setColumnWidth(). Actually two resizes happen - to shrink and reverse to enlarge.
So, the lesson is - get control's visible width, recalculate sizes as you want, and resize all but the last column. For two column case it's really simple:
int secondColumnWidth = 100;
int firstColumnWidth = m_selectCategoryTableWidget->width() - secondColumnWidth;
if (firstColumnWidth > 0)
{
m_selectCategoryTableWidget->setColumnWidth(0, firstColumnWidth);
}
else
{
m_selectCategoryTableWidget->resizeColumnsToContents();
}
Good luck!
|
3,172,294 | 3,172,387 | What is the proper procedure on compiling templates and/or compiling with templates? | I have some template classes I've written that are dependencies for several other classes I need to compile. I have a few options as to how I can do this in my Makefile:
Each class that requires a template lists its template requirements. This has the drawback of needing to recreate the dependency tree every time I want to add a new class.
Make the templates into target somehow. Either by compiling them, or by making some shadow dependency tree that does not compile anything, but simply forces a recompilation in the event of one of the templates becoming modified.
Any suggestions are welcome.
| As Neil Butterworth mentioned in a comment, make deals with files. Say you have a foo.cpp and a bar.h. The latter contains your template. And the former might do, for example:
#include "bar.h"
class Foo : public Bar<Widget> { [...] };
While your Foo class inherits and thus depends on your Bar template class, you are also already declaring your file dependencies with your #includes.
It's those same file dependencies that you specify in your Makefile:
foo.o: foo.cpp bar.h
g++ -I. -o foo.o foo.cpp
For this rule, make expects that the commands you specify create foo.o, based on the foo.cpp and bar.h files. If you've already built foo.o once, and those dependencies haven't changed, make knows it can skip the rule altogether.
It may seem tedious to specify file dependencies twice, but luckily dependencies in your Makefile can be automatically generated from #includes in your source code by GCC using the -M command-line parameter. You can read about this in the gcc(1) manpage. Simply take GCC's output, save it somewhere, typically foo.d, and include that in your Makefile.
With some wizardry, you can automate the generation of *.d dependency files in the same Makefile that builds your application.
|
3,172,392 | 3,172,404 | Detecting user name from process ID | Ho can i get user account name, that ran the process with specified id. Is there any api function for this?
I am using windows,c++.
| There is not an API function that does this directly, however you can combine a few API calls to do this. Of course your program will need to satisfy any ACLs that are applied to the process that you are interested in examining.
First, given the process ID, you'll need to open a handle to the process. You can use OpenProcess for that, requesting the PROCESS_QUERY_INFORMATION access right.
Once you have that handle, you can call OpenProcessToken, requesting the TOKEN_QUERY access right.
Finally, you can then call GetTokenInformation, requesting the TokenUser information class, which will give you the user account of the token. This information is provided to you in the form of a SID. To convert the SID to the actual name of the account, you can call LookupAccountSid.
Don't forget to call CloseHandle on both the process handle and the token handle once you're finished with them.
|
3,172,399 | 3,172,422 | can memory corruption be caused by invalid *reading* freed memory? | I'm getting
*** glibc detected *** (/my/program/...): malloc(): memory corruption: 0xf28000fa ***
I've run under valgrind, which reports cases of reading memory that has been freed, but no cases of illegal memory writes.
Could reading freed memory cause memory corruption? If not, any suggestions where else to look beyond the valgrind output?
| You can use GDB to watch each write in this memory address, like this:
(gdb) watch *((int*)0xf28000fa)
Then you can debug where the problem is.
Reading doesn't cause memory corruption, but there are a lot of situations that you don't even imagine that could be the cause of this, and Valgrind is not a perfect tool.
See more information about debugging memory issues here.
|
3,172,415 | 3,172,630 | QComboBox and QSpinBox in QTableWidget with appropriate alignment | How to create a QTable widget which has 2 columnes, and in first column there is a QComboBox and in the second column there is a QSpinBox so that the combo box gets all the space of table and only a very small place leaves for QSpinBox (for 2-3 digits).
| First, use setCellWidget() to set the QComboBox and QSpinBox as the widgets to be displayed in the appropriate cell.
Second, use horizontalHeader() to access the QHeaderView for the QTableView, then set the ResizeMode accordingly.
QTableWidget* table = new QTableWidget( this );
table->setColumnCount( 2 );
table->setRowCount( 1 );
table->setCellWidget ( 0, 0, new QComboBox( table ) );
table->setCellWidget ( 0, 1, new QSpinBox( table ) );
table->horizontalHeader()->setResizeMode( 0, QHeaderView::Stretch );
table->horizontalHeader()->setResizeMode( 1, QHeaderView::ResizeToContents );
|
3,172,418 | 3,172,453 | How to create a generic container with unknown member functions? | I noticed that I'm often in the need of a container class. For example when working on a particle system, I create a container class Particles which has a member vector<Particle*>. Then I call: Particles* my_particles like my_particles->draw(), and in the Particles.draw() I iterator over the vector<Particle*> and call draw() on each of the particles again. The same works for member functions like update(), addforce() etc.. Now, I'm working on a project and need a collection of Cube on which I need to call tween(), moveTowards() etc..
I know I can use template, but in the case of a template class the member functions need to be knows before. As I want to check if I can make a generic class, that I can use for example both my Cubes and Particles collections.
Someone who has done this before or can give me some advice on this?
Kind regards,
Pollux
| The short answer is that you can't do this in c++. You can, however, use STL algorithms and containers to wrap this behavior up.
First, you'd put your Cube or Particle instances into a std::vector or other container (like you have now).
Then you'd use STL's std::for_each in combination with std::mem_fun.
It'd result in something like this:
std::vector<Particle*> V;
V.push_back(new Particle);
V.push_back(new Particle);
V.push_back(new Particle);
V.push_back(new Particle);
std::for_each(V.begin(), V.end(), std::mem_fun(&Particle::draw));
|
3,172,451 | 3,172,722 | Error handling for xml parsing | I'm using tinyxml to parse xml files, and I've found that error handling here lends itself to arrow code. Our error handling is simply reporting a message to a file.
Here is an example:
const TiXmlElement *objectType = dataRoot->FirstChildElement( "game_object" );
if ( objectType ) {
do {
const char *path = objectType->Attribute( "path" );
if ( path ) {
const TiXmlElement *instance = objectType->FirstChildElement( "instance" );
if ( instance ) {
do {
int x, y = 0;
instance->QueryIntAttribute( "x", &x );
instance->QueryIntAttribute( "y", &y );
if ( x >= 0 && y >= 0 ) {
AddGameObject( new GameObject( path, x, y ));
} else {
LogErr( "Tile location negative for GameObject in state file." );
return false;
}
} while ( instance = instance->NextSiblingElement( "instance" ));
} else {
LogErr( "No instances specified for GameObject in state file." );
return false;
}
} else {
LogErr( "No path specified for GameObject in state file." );
return false;
}
} while ( objectType = objectType->NextSiblingElement( "game_object" ));
} else {
LogErr( "No game_object specified in <game_objects>. Thus, not necessary." );
return false;
}
return true;
I'm not huffing and puffing over it, but if anyone can think of a cleaner way to accomplish this it would be appreciated.
P.S. Exceptions not an option.
Edit:
Would something like this be preferable?
if ( !path ) {
// Handle error, return false
}
// Continue
This eliminates the arrow code, but the arrow code kind of puts all of the error logging on one place.
| Using return values as error codes just leads to such code, it can't be improved much. A slightly cleaner way would use goto to group all error handling into a single block and to decrease the nesting of blocks.
This does however not solve the actual problem, which is using return values as error codes. In C, there is no alternative, but in C++ exceptions are available and should be used. If they are not an option, you're are stuck with what you have.
|
3,172,549 | 3,172,557 | why macros return what we are not expected |
Possible Duplicate:
Problem with Macros
Hi all
I have defined this macro:
#define SQ(a) (a*a)
and called it in this way:
std::cout << SQ(2+3) << '\n';
the output was 11. Why ?
Thanks
| Macros do only simple text manipulation, i.e. they are very stupid that way in that they don't see 'code', only 'text' which are then sent to to the C/C++ parser for validation.
SQ(2+3) becomes (2+3*2+3)
That's why you should use templates, which are a bit smarter, they would do what you expected: first calculate 2+3, then do 5*5.
|
3,172,571 | 3,172,584 | Force a std::vector to free its memory? |
Possible Duplicates:
reduce the capacity of an stl vector
Is this normal behavior for a std::vector?
I know that std::vectors do not 'free' the memory when you call vector.clear(), but how can I do this? I want it to release all of its resources once I clear it but I don't want to destroy it.
Here is what is happening right now.
I have a class called OGLSHAPE and I push these into a vector of them. I was hoping that once I did shapevec.clear() I'd get all my memory back, but only got 3/4 of it back. I'm not 100% sure if this is a memory leak or not so I want to free all the resources to be sure its not a leak. Thanks
| Use the swap trick:
#include <vector>
template <typename T>
void FreeAll( T & t ) {
T tmp;
t.swap( tmp );
}
int main() {
std::vector <int> v;
v.push_back( 1 );
FreeAll( v );
}
|
3,172,699 | 3,172,736 | Is this normal behavior for a std::vector? | I have a std::vector of a class called OGLSHAPE.
each shape has a vector of SHAPECONTOUR struct which has a vector of float and a vector of vector of double. it also has a vector of an outline struct which has a vector of float in it.
Initially, my program starts up using 8.7 MB of ram. I noticed that when I started filling these these up, ex adding doubles and floats, the memory got fairly high quickly, then leveled off. When I clear the OGLSHAPE vector, still about 19MB is used. Then if I push about 150 more shapes, then clear those, I'm now using around 19.3MB of ram. I would have thought that logically, if the first time it went from 8.7 to 19, that the next time it would go up to around 30. I'm not sure what it is. I thought it was a memory leak but now I'm not sure. All I do is push numbers into std::vectors, nothing else. So I'd expect to get all my memory back. What could cause this?
Thanks
*edit, okay its memory fragmentation
from allocating lots of small things,
how can that be solved?
| Calling std::vector<>::clear() does not necessarily free all allocated memory (it depends on the implementation of the std::vector<>). This is often done for the purpose of optimization to avoid unnessecary memory allocations.
In order to really free the memory held by an instance just do:
template <typename T>
inline void really_free_all_memory(std::vector<T>& to_clear)
{
std::vector<T> v;
v.swap(to_clear);
}
// ...
std::vector<foo> objs;
// ...
// really free instance 'objs'
really_free_all_memory(objs);
which creates a new (empty) instance and swaps it with your vector instance you would like to clear.
|
3,172,717 | 3,172,737 | How to start using xml with C++ | (Not sure if this should be CW or not, you're welcome to comment if you think it should be).
At my workplace, we have many many different file formats for all kinds of purposes. Most, if not all, of these file formats are just written in plain text, with no consistency. I'm only a student working part-time, and I have no experience with using xml in production, but it seems to me that using xml would improve productivity, as we often need to parse, check and compare these outputs.
So my questions are: given that I can only control one small application and its output (only - the inputs are formats that are used in other applications as well), is it worth trying to change the output to be xml-based? If so, what are the best known ways to do that in C++ (i.e., xml parsers/writers, etc.)? Also, should I also provide a plain-text output to make it easy for the users (which are also programmers) to get used to xml? Should I provide a script to translate xml-plaintext? What are your experiences with this subject?
Thanks.
| Don't just use XML because it's XML.
Use XML because:
other applications (that only accept XML) are going to read your output
you have an hierarchical data structure that lends itself perfectly for XML
you want to transform the data to other formats using XSL (e.g. to HTML)
EDIT:
A nice personal experience:
Customer: your application MUST be able to read XML.
Me: Er, OK, I will adapt my application so it can read XML.
Same customer (a few days later): your application MUST be able to read fixed width files, because we just realized our mainframe cannot generate XML.
|
3,172,733 | 3,172,992 | Faster method for rendering anisotropic textures? | Is there any faster methods for improving texture quality on oblique angles than using anisotropic texture filter?
In my previous question i asked if it takes more memory than normal mip mapped textures, but apparently it doesnt, so i am hoping this could be optimized.
So is there any way to optimize the rendering speed ?
| No. The alternatives such as supersampling are significantly slower. Your best bet on OpenGL is using the anisotropic filter.
|
3,172,789 | 3,172,926 | C++/Qt enum - should I use locking to share the value across threads? | I have a C++/Qt QThread worker thread, which stores its current status as an ENUM (e.g. values such as Working, Finished). Only the worker thread sets the ENUM.
I need to be able to read the status of the worker thread from another thread (the GUI thread), to display on the screen whether work is being done.
Is it safe to read/write the ENUM in one thread (worker), and read in other threads? Otherwise, should I use locking like QMutex in places where it is read/written?
| As Neil said: Yes, you need locking. For your use case QReadWriteLock should be better suited than QMutex.
|
3,172,805 | 3,172,974 | C++ Raii and stack unwinding | (I modified the original question to be more meaningful)
With respect to return statement, are Raii object destroyed before/after/between return statement?
for example
size_t advance() {
boost::lock_guard<boost::mutex> lock(mutex_);
return value_++; // is lock destroyed after increment?
}
thank you
| To answer your modified question, given the code:
return X;
X will always be evaluated before the return takes place. Then what happens is equivalent to all the nested scopes of the function being exited, in order from inmost to outmost, with destructors being called appropriately at each exit.
|
3,172,878 | 3,204,966 | How to open file\live stream with FFMPEG edit each frame with openCV and save that as encoded with FFMPEGfile\live stream? | How to open file\live stream with FFMPEG edit each frame with openCV and save that as encoded with FFMPEGfile\live stream?
| Well it is quite simple.
I suggest you begin with the simple ffmpeg decoding example. With that you get a struct which is an FFMPEG image. You have to convert it to an opencv image struct (IplImage). Then you can apply any opencv operation. Then you can look at FFMPEG encoding example and you have your whole processing chain :)
The point is to convert FFMPEG image struct to opencv image struct. It is quite simple after you have read the documentation (the code ?).
Edit your question if you have more precise needs.
my2c
|
3,172,891 | 3,172,972 | How can I find a window with a specific window style? (WS_CHILDWINDOW) | I've got a specific window with the window style WS_CHILDWINDOW. It's the child window of a window of which I've got the handle already. This window is the second-last one. How do I get it?
It's C++ by the way.
| As an alternative to EnumChildWindows posted above, you can use this:
HWND first_child = GetWindow(parent_hwnd, GW_CHILD);
HWND last_child = GetWindow(first_child, GW_HWNDLAST);
HWND prev_to_last_child = GetWindow(last_child, GW_HWNDPREV);
A drawback of this approach is a possibility of a race if a new child window is added at the end of Z-order between steps 2 and 3. Though in practice it shouldn't be a problem. :)
|
3,172,909 | 3,172,912 | How to use local classes with templates? | GCC doesn't seem to approve of instanciating templates with local classes:
template <typename T>
void f(T);
void g()
{
struct s {};
f(s()); // error: no matching function for call to 'f(g()::s)'
}
VC doesn't complain.
How should it be done?
| In C++03 it can't be done, C++0x will lift that restriction though.
C++03, §14.3.1/2:
A local type, a type with no linkage, an unnamed type or a type compounded from any of these types shall not be used as a template-argument for a template type-parameter.
|
3,172,931 | 3,172,948 | C++ - Optional arguments by reference | I have an exam on C++ coming up, and I'm solving a few ones from past years. I have this question in one of them:
A function calculates the volume of a
prysm. Arguments passed are height,
depth and width. Arguments and return value are doubles
Depth is optional and
should default to 10.
Hypothesis 1:
All parameters are passed by value
I answered double volume_prysm(const double width, const double height, const double depth = 10);
Hypothesis 2:
All parameters are passed by reference
How can I define a reference parameter in order for it to default to 10?
Thanks for your time!
PS: Sorry y'all for not translating
| I don't know if that is what the question was aiming at, but temporaries can be bound to const references:
double volume_prisma(const double& largura, ..., const double& depth = 10);
|
3,172,933 | 3,172,961 | How to manually cause a signal of another control to emit? | I wanted to know if its possible to emit some specific signal through coding .. For example, I want to emit another button's clicked event without the user actually clicking that button .. can do I do this ?
| You could call that other button's click function. It will emit the clicked signal.
|
3,173,012 | 3,173,126 | Performing an edge contraction on a graph | I am trying to do edge contraction on a graph.
n is the number of vertices in the graph.
The vector f containing pairs of vertices representing an edge contains the edges which are to be contracted.
The graph does not contain any self loops.
Please point out any logical mistakes if any in the code.
If the method is entirely wrong then please let me know the correct algorithm.
void modify(vector<pair<int, int> > &f)
{
// sorting elements of each pair
for(vector<pair<int, int> >::iterator it = f.begin(); it != f.end(); it++)
{
if(it->first > it->second)
swap(it->first, it->second);
}
// sorting elements of set f
sort(f.begin(), f.end());
reverse(f.begin(), f.end());
for(vector<pair<int, int> >::iterator it = f.begin(); it != f.end(); it++)
{
int x, y;
x = it->first;
y = it->second;
for(int i = 0; i < n; i++)
if(x != i)
{
graph[x][i] = graph[y][i] = graph[x][i] + graph[y][i];
graph[i][x] = graph[i][y] = graph[i][x] + graph[i][y];
}
}
vector<bool> pos(n, false); // array of positions to be deleted
for(vector<pair<int, int> >::iterator it = f.begin(); it != f.end(); it++)
pos[it->second] = true;
// deleting rows
int count = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
graph[i-count][j] = graph[i][j];
if(pos[i])
count++;
}
// deleting columns
count = 0;
for(int j = 0; j < n; j++)
{
for(int i = 0; i < n; i++)
graph[i][j-count] = graph[i][j];
if(pos[j])
count++;
}
// finally dimension of the matrix becomes n - count
n = n - count;
}
Thanks in advance.
| Given the following example graph:
a d
\ /
b---e
/ \
c f
Would "contracting" the edge {b, e} result in the following?:
a d
\ /
g
/ \
c f
"Yes, it is exactly that" - amit. Thx, I wanted to get the specification right, before I answer Your question. Further assumptions are:
Graph is directed
Vertices are represented through integers.
The graph is stored in the two dimensional array graph, graph[x][y] being the weight of the edge (x, y); 0 indicating that there is no edge from x to y
Lets give it a try with some pseudocode:void contractEdge(int v1, int v2) {
for (int i = 0; i < n; i++) {
if (graph[v2][i] > 0) {
graph[v1][i] = graph[v1][i] > 0 ? min(graph[v1][i], graph[v2][i]) :
graph[v2][i];
graph[v2][i] = 0;
}
if (graph[i][v2] > 0) {
graph[i][v1] = graph[i][v1] > 0 ? min(graph[i][v1], graph[i][v2]) :
graph[i][v2];
graph[i][v2] = 0;
}
graph[v1][v2] = graph[v2][v1] = 0;
}
}
The code works like this: Given the edge {v1, v2}, v1 becomes the "contracted" vertex. That means, instead of inserting a new vertex ("g" in my first example), v1 remains in the graph and v2 is deleted from it (by assigning 0 weights on edges to all other vertices, the actual vertex count doesn't change). Further, all edges that contain v2 are bend to contain v1.
Now one can call this method for a set of edges. The runtime will be O(n * #edges_to_contract). I hope this is the behavior You desired.
Important: If You use a different representation for Your edge weights, namely 0 meaning an edge with 0 weight and ∞(infinite) indicating the absence of an edge, then Your problem becomes trivial because all You have to do is:
graph[v1][v2] = graph[v2][v1] = 0
which effectively contracts the edge {v1, v2}, since now it doesn't cost anything to travel between v1 and v2
|
3,173,088 | 3,173,232 | How to set all struct members to same value? | I have a struct:
struct something {
int a, b, c, d;
};
Is there some easy way to set all those a,b,c,d into some value without needing to type them separately:
something var = {-1,-1,-1,-1};
Theres still too much repetition (lets imagine the struct has 30 members...)
I've heard of "constructs" or something, but i want to set those values into something else in different part of the code.
| This is my second answer for this question. The first did as you asked, but as the other commentors pointed out, it's not the proper way to do things and can get you into trouble down the line if you're not careful. Instead, here's how to write some useful constructors for your struct:
struct something {
int a, b, c, d;
// This constructor does no initialization.
something() { }
// This constructor initializes the four variables individually.
something(int a, int b, int c, int d)
: a(a), b(b), c(c), d(d) { }
// This constructor initializes all four variables to the same value
something(int i) : a(i), b(i), c(i), d(i) { }
// // More concise, but more haphazard way of setting all fields to i.
// something(int i) {
// // This assumes that a-d are all of the same type and all in order
// std::fill(&a, &d+1, i);
// }
};
// uninitialized struct
something var1;
// individually set the values
something var2(1, 2, 3, 4);
// set all values to -1
something var3(-1);
|
3,173,441 | 3,173,450 | Requirements for directly returning a class instance from a function? | I'm got a function in C++ that wraps an output stream constructor so it can pass in a pointer to a parent class that it's running in, ala:
pf_istream PF_Plugin::pf_open_in() {
return pf_istream(this);
}
When I do it that way, however, I get something like this:
pf_plugin.cc:103: error: no matching
function for call to
‘pf_istream::pf_istream(pf_istream)’
pf_istream.hh:36: note: candidates
are: pf_istream::pf_istream(const
PF_Plugin*)
pf_istream.hh:29: note: pf_istream::pf_istream(pf_istream&)
I've got a copy constructor and assignment operator defined (as can be seen above), and if I write the function like so:
pf_istream PF_Plugin::pf_open_in() {
pf_istream to_ret(this);
return to_ret;
}
It works just fine. I get similar errors if I try to assign a pf_istream instance directly from a call to the function, eg:
pf_istream inFile = pf_open_in();
What else do I need to add to make this work?
| > pf_istream::pf_istream(pf_istream&)
This is your problem. It's not properly finding your copy constructor, because it's passing a temporary. Your copy constructor should take a const&, like so:
pf_istream::pf_istream(const pf_istream&) { ... }
|
3,173,500 | 3,173,514 | creating a 2D array of vectors | I have been trying to create a 2D array of vector for a game. Here is an example of what I am doing.
struct TILE {
int a;
char b;
bool c;
};
TILE temp_tile;
std::vector<TILE> temp_vec_tile;
std::vector<std::vector<TILE>> tile;
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
temp_tile.a = x;
temp_tile.b = "a";
temp_tile.c = false;;
temp_vec_tile.push_back(temp_tile);
}
tile.push_back(temp_vec_tile);
}
// Why does this not work?
int x = tile[3][5].a;
Note: I don't want to use Boost for this.
Thanks
| You are not clearing the internal vector each time. Probably what you want is to put the internal vector declaration inside of the first for loop.
|
3,173,520 | 3,175,470 | nested class access control in C++ | Can inner class access a private member variable of its enclosing class? There seems to be some contradictions on the internet and compiler. Compile (g++ on cygwin) allows it. But, some technical documents say that it is not allowed.
| This issue has been addressed in Defect Report #10 and Defect Report #45.
The original and the current C++ language standard does not grant the nested class any extra access rights, i.e. it has no privileges when accessing members of the enclosing class. Nested classes are just ordinary completely independent classes, which just happen to be declared inside some other class.
But according to the proposed resolution in the Defect Report #45, the nested class should be given full access rights to the members of the enclosing class. I.e. the nested class should itself be considered a member of the enclosing class and should enjoy all access rights normally granted to members.
Last time I checked, the work on this defect was not finalized yet. Some compilers already implement what they think the new specification will require, i.e. full access rights to nested classes (see the proposed resolution to the DR#45). Some compilers stick to the letter of the current standard. This is why you might still observe some inconsistency between different compilers with regard to access rights granted to nested classes.
|
3,173,603 | 3,173,617 | Implications of a const_cast in a copy constructor? | So I've got an output stream class that owns a pointer to a class that actually does the writing, and I need a copy constructor so that I can return initialized instances from a function so that I can bind certain values transparently to the user. To have reasonable copy semantics I'd really like to clear the writer pointer in the copied object and close it rendering it unusable during copy.
I can do that just fine with a non-const copy constructor, a-la:
class Test {
public:
Test(Test& other);
};
But I want to be able to assign directly from the temporary returned by a function call:
Test test = make_test();
The copy constructor is required to be const. So I'm curious of what the implications of using a const_cast in the copy constructor would be. I'd cast the other reference to a non-const pointer and clear the writer pointer I mentioned. I know const_cast is generally considered evil but could it work in this case? I'm especially curious how it will interact with temporary objects returned from a function call.
Alternatively there's only like four creation functions that I really want to have access to the copy constructor, if there was a reasonable way to scope it so that it was only usable to those functions (including their return values) then I'd prefer that.
| You would be violating the public contract of your object and the expectations of any client code by making your const copy constructor destructive.
Other than that, there's no problem with removing the constness of the parameter.
|
3,173,630 | 3,173,769 | Why does boost::asio appear to do nothing | I'm trying to implement the irc protocol in a very basic manner. My first attempt is to use boost::asio and connect to a server and read the motd. AFAIK the motd is sent to every client when they connect. I have made the following test program and it seems to not do anything. It's not a very good piece of code but this is all I have after several frustrating hours.
#define _WIN32_WINNT 0x0501
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <queue>
class IrcConnection
{
public:
IrcConnection(const std::string& server, int port, boost::function<void (const std::string&)> onMessage, boost::asio::io_service& io_service): s(server), p(port), onM(onMessage), ios(io_service), socket(io_service)
{
}
void connect()
{
somethingHappened = false;
//DNS stuff
boost::asio::ip::tcp::resolver resolver(ios);
boost::asio::ip::tcp::resolver::query query(s , "0");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end;
boost::system::error_code error;
while(iter != end)
{
boost::asio::ip::tcp::endpoint endpoint = iter->endpoint();
endpoint.port(p);
socket.close();
socket.connect(endpoint, error);
iter++;
}
if(error)
{
std::cout << "ERROR" << std::endl;
std::cout << error << std::endl;
}
std::cout << "Connected to: " << socket.remote_endpoint().address().to_string() << std::endl;
//read from the socket until a space is found
boost::asio::async_read_until(socket, currentData, ' ', boost::bind(&IrcConnection::onReceiveFinished, this, boost::asio::placeholders::error));
}
void disconnect()
{
socket.close();
}
void send(int priority, const std::string& message)
{
}
bool somethingHappened;
private:
std::string s;
int p;
boost::function<void (const std::string&)> onM;
boost::asio::io_service& ios;
boost::asio::ip::tcp::socket socket;
std::priority_queue<std::string> outQueue;
boost::asio::streambuf currentData;
void onReceiveFinished(const boost::system::error_code& error)
{
if(error)
{
disconnect();
std::cout << "ERRORRRR" << std::endl;
std::cout << error << std::endl;
}
std::cout << "STUFF IS OCCURING" << std::endl;
somethingHappened = true;
std::istream stream(¤tData);
std::string data;
std::getline(stream, data);
boost::asio::async_read_until(socket, currentData, ' ', boost::bind(&IrcConnection::onReceiveFinished, this, boost::asio::placeholders::error));
ios.dispatch(boost::bind(onM, data));
}
};
void onMe(const std::string& x)
{
std::cout << "MESSAGE" << std::endl;
std::cout << x << std::endl;
}
int main()
{
boost::asio::io_service ios;
std::string server = "irc.efnet.org";
int port = 6667;
IrcConnection x(server, port, onMe, ios);
x.connect();
while(!x.somethingHappened)
{
//
}
return 0;
}
The program attempts to connect to irc.efnet.org and read until a space is sent and then spits that data out to the terminal. However I run this and all that is printed is the ip address of what I connected to and then the program does not terminate.
What do I need to do to get my indented behavior?
| If you're making asychronous calls, you have to post requests to the io_service. In your case after the "x.connect();" you should call "ios.run();"
Just remember if you don't make any further posts after the async callback returns, run will exit/return.
btw in "ios.dispatch(boost::bind(onM, data));" is onM meant to be onMe ?
|
3,173,668 | 3,173,684 | c++ container search by key and value | I'm trying to build a container of string representations of ordinal numbers, searchable both by the string and by the number. For example, I can do it trivially, but inefficiently, with an array:
std::string ordinalStrings = {"zeroth", "first", "second",..}
getting the string with ordinalStrings[number], and the integer with a while(not found) loop, but I figure that one of the STL containers would do a better job, just not sure which one.
It needn't be searchable by both, for example, simply getting the numerical key of a map with a string key would work, but there doesn't seem to be a function for it, and besides, it seems a little messy.
As an aside, is it possible to have a constant STL container? I only need the searching functionality, not the insertion. Also, since I assume I can't, is it possible to fill the container without an initializer function? That is, can a header simply say:
std::map<std::string, int> ordinals;
ordinals["zero"] = 0;
ordinals["one"] = 1;
...
It just seems silly to have an initializer function for what is essentially a constant value;
Thanks,
Wyatt
| You can provide two different lookup mechanisms using boost::multi_index (here's an example of a bidirectional map using multi_index). Another (maybe simpler) option is to maintain two containers: one to lookup by ordinal, one to search by string. You could use two std::map or a std::map and a std::vector (for constant time lookup of ordinality).
As an aside, is it possible to have a constant STL container? I only need the searching functionality, not the insertion.
Yes, but you must initialize a non-const container. You can then copy that into a const container. For example, you can use a helper function: const std::map<string, int> ordinals = create_map();
That is, can a header simply say: ...
No, you should initialize the container within a proper control flow.
|
3,173,708 | 3,173,713 | Help identifying memory leak | I have a class here that is defined like this:
struct USERFPOINT
{
POINTFLOAT UserPoint;
POINTFLOAT LeftHandle;
POINTFLOAT RightHandle;
bool isBezier;
};
struct SHAPEOUTLINE {
GLuint OutlineVBO;
int OutlineSize;
int OutlineWidth;
ARGBCOLORF OutlineColor;
};
struct SHAPECONTOUR{
std::vector<USERFPOINT> UserPoints;
std::vector<std::vector<GLdouble>> DrawingPoints;
SHAPEOUTLINE Outline;
};
struct SHAPEGRADIENT{
GLuint TextureId;
bool IsParent;
bool active;
int type;
std::vector<ARGBCOLORF> colors;
};
struct SHAPEDIMENSIONS {
POINTFLOAT Dimensions;
POINTFLOAT minima;
POINTFLOAT maxima;
};
class OGLSHAPE
{
private:
int WindingRule;
GLuint TextureCoordsVBOInt;
GLuint ObjectVBOInt;
UINT ObjectVBOCount;
UINT TextureCoordsVBOCount;
SHAPEGRADIENT Gradient;
SHAPEDIMENSIONS Dimensions;
void SetCubicBezier(USERFPOINT &a,USERFPOINT &b, int ¤tcontour);
void GenerateLinePoly(const std::vector<std::vector<GLdouble> > &input, int width);
public:
std::string Name;
ARGBCOLORF MainShapeColor;
std::vector<SHAPECONTOUR> Contour;
OGLSHAPE(void);
void UpdateShape();
void SetMainColor(float r, float g, float b, float a);
void SetOutlineColor( float r, float g, float b, float a,int contour );
void SetWindingRule(int rule);
void Render();
void Init();
void DeInit();
~OGLSHAPE(void);
};
Here is what I did as a test. I created a global std::vector<OGLSHAPE> test .
In the function I was using, I created
OGLSHAPE t.
I then pushed 50,000 copies of t into test.
I then instantly cleared test and used the swap trick to really deallocate it.
I noticed that all the memory was properly freed as I would expect.
I then did the same thing but before pushing t into test, I pushed a SHAPECONTOUR (which I had just created without modifying or adding anything into the contour) before pushing t into test.
This time after clearing test, 3 more megabytes had been allocated. I did it again allocating twice as many and now 6MB we remaining. The memory usage of the program peaked at 150MB and it went down to 12MB, but it should be at 8.5MB. Therefore, this must be classified as a memory leak, although I do not see how. There is nothing that I see that could do that. SHAPECONTOUR is merely a structure of vectors with a nested structure of vectors.
Why would this cause a leak, and how could I fix it?
Thanks
| If you've deleted everything, there is no leak, by definition. I don't see any unwrapped pointers, ergo everything gets deleted. Therefore, you have no leaks.
Likely, the OS has simply decided to leave that memory available to your program, for whatever reason. (It hasn't "reclaimed" it.) Or maybe it needs to allocate in groups of4MB, and so going from 12MB to 8MB wouldn't leave enough required memory. Or...
You're cutting out other reasons entirely; you should use a real memory leak tool to find memory leaks.
|
3,173,739 | 5,851,688 | File handle leak on dynamically loaded DLL caused by activation context | I have a dynamically loaded & unloaded DLL which requires COMCTL32.dll >= v6.0 and MSVCR >= v9.0. To ensure that the correct versions are loaded, I enable manifest file generation in Visual Studio project setting, and add this entry to another manifest file:
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
In a test program I call LoadLibrary() followed by FreeLibrary() of that DLL, and ProcessExplorer indicates that the following File handles were leaked:
C:\WINDOWS\WinSxS\x86_Microsoft.VC90.CRT_1fc8b3b9a1e18e3b_9.0.30729.1_x-ww_6f74963e
C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.5512_x-ww_35d4ce83
From disassembly call stack trace I learnt that on LoadLibrary(), an activation context was automatically created and it opens handles to each of these folders. But it appears that the activation context is not deleted on FreeLibrary().
If I remove the manifest files and set project settings to disable manifest generation, these leaks are gone. However, that way I will be unable to ensure that the correct MSVCR and COMCTL are used, since this DLL is loaded by processes I have no control over.
Is there a way to remove this leak without removing the manifest files?
Thanks!
| The ProcessExplorer HANDLE leak reports are a symptom of an activation context leak. Most likely this leak is in your code indirectly in that you've not correctly called MFC.
To help yourself validate that this is your bug and not MFC's, you can create a simple MFC DLL from the AppWizard without any of your code and confirm that when it is LoadLibrary/FreeLibrary several times, there is no accumulative leak.
The missing OS call is either a ReleaseActCtx, or a missing DeactivateActCtx that caused the release to fail. In practice, MFC is calling these functions for you so you'll be looking for a missing MFC call of some kind.
The best debugging technique would probably be to trace or breakpoint the core activation context create/activate/deactivate/release functions (http://msdn.microsoft.com/en-us/library/aa374166(VS.85).aspx) and see what happens. You may see a bunch of calls so some kind of tracing may be necessary. Ideally you might capture the callstack at each call and review them. Your debugger may be able to help you do this. Recent versions of VS can run macros when they hit breakpoints.
As an aside, you are correct that you need the manifest files and should not remove them.
Martyn
|
3,173,772 | 3,173,796 | C++ return value versus exception performance | Somewhere I have read that modern Intel processors have low-level hardware for implementing exceptions and most compilers take advantage of it, to the effect that exceptions become faster than returning results state using variables.
Is it true? are exceptions faster than variables as far as returning state/responding to state? reading stack overflow on the topic seems to contradict that.
Thank you
| I don't know where you read this, but it is surely incorrect. No hardware designer would make exceptional circumstances, which are by definition uncommon, work FASTER than normal ones. Also keep in mind that C, which according to TIOBE is the most popular systems language, does not even support exceptions. It seems EXTREMELY unlikely that processors are optimized for ONE language's exception handling, whose implementation is not even standardized among compilers.
Even if, somehow, exceptions were faster, you still should not use them outside their intended purpose, lest you confuse every other programmer in the world.
|
3,173,902 | 3,174,570 | What is the difference between a .h(header file) and a .cpp file? | I am creating a windows:forms application. I have read some of the answers give to try to understand the concept of .h(header file) & .cpp(implementation files). As I created the GUI for my app. I noticed the code being placed in the .h file. But when I double clicked a button control to add code to the procedure, the code was created in the .h file instead of the .cpp file. Do I cut and place this code into the .cpp file or is this where linking come in? The procedure deffintion stays in the .h file and will be linked to the procedure code in the .cpp file.
| There are two considerations here. First off, header files are not nearly as important in managed code as they are in native C or C++. Managed code compilers read declarations from the assembly metadata, you don't (and shouldn't) write C++/CLI type declarations that need to be visible in other modules in header files. Getting them from the metadata makes your types available to any .NET language.
But the real reason is because of the way the form designer works in the C++ IDE. It is a code generator, driven by the controls you drop on a form or user control and the properties you set in the Properties window. There is a very awkward problem if that code generator needs to generate code in two separate files. Not so much the generating bit, but removing code when you alter the design of the form. Getting the files out of sync produces difficult to diagnose compile errors from auto-generated code. It is a lot more likely to happen than you might think btw, the code generator needs to work with source code files that are in the process of being edited. Very difficult, the code might not parse at all.
The C++ IDE uses the original approach taken by the version 1.1 C# and VB.NET designers, everything goes in one file. Which is unpleasant of course, declarations and code shouldn't be mixed. That was solved in those designers for version 2.0 by adding support to the C# and VB.NET languages for partial classes. That however didn't happen for C++/CLI. Not sure why, the C++/CLI team always looked resource constrained compared to those other teams. It also doesn't have any kind of refactoring support, which is very important to rename methods when the class name changes. Keeping the methods inline avoids the problem.
Anyhoo, you can get your code in the .cpp file but you have to do it yourself. Cut+paste gets it done, but you'll also have to edit the class name back into the method declarations. This is high maintenance, consider if it is worth the effort. Also consider whether you really want to use C++/CLI for the UI, it is an uncommon choice.
|
3,174,676 | 3,174,725 | Are there any predefined functions in Qt which save a QImage object to a JPG/PNG/BMP file? | Pretty simple question .. Are there any predefined functions in Qt which save a QImage object to a JPG/PNG/BMP file ?
| This is exactly what you'll need:
http://doc.qt.io/qt-5/qimage.html#reading-and-writing-image-files
Google is your friend, but more so are the Qt docs.
|
3,174,835 | 3,174,873 | Memory implementation of member functions in C++ | I read an article on virtual table in Wikipedia.
class B1
{
public:
void f0() {}
virtual void f1() {}
int int_in_b1;
};
class B2
{
public:
virtual void f2() {}
int int_in_b2;
};
used to derive the following class:
class D : public B1, public B2
{
public:
void d() {}
void f2() {} // override B2::f2()
int int_in_d;
};
After reading it I couldn't help but wonder how non virtual member functions are implemented in C++. Is there a separate table like the v-table in which all the function addresses are stored? If yes, what is this table called and what happens to it during inheritance?
If no then how does compiler understand these statements?
D * d1 = new D;
d1->f0(); // statement 1
How does compiler interpret that f0() is function of B1 and since D has publicly inherited D it can access f0(). According to the article the compiler changes statement 1 to
(*B1::f0)(d)
| Non-virtual member functions are implemented like global functions that accept a hidden this parameter. The compiler knows at compile time which method to call based on the inheritance tree, so there's no need for a runtime table.
|
3,175,055 | 3,175,229 | Integral promotion when passing and returning argument by reference? | I'm reading something about overload resolution and I found something that bothers me...In the following code:
int const& MaxValue(int const& a, int const& b)
{
return a > b ? a : b;
}
void SomeFunction()
{
short aShort1 = 3;
short aShort2 = 1;
int const & r2 = MaxValue(aShort1, aShort2); // integral promotion
//is it safe to pass r2 around before function SomeFunction completes
// CallSomeOtherFunctionThatCallsSomethingElse(r2);
}
My understanding is that two temporary int's are created and they're allocated on the stack belonging to SomeFunction.
So when MaxValue returns, r2 referencing to one of those temp variables (in this case, the one that holds value 3).
Thus, is should be safe to pass r2 around.
The question is, if my understanding is fine, is this a standard behavior (please verify)? If not, please explain what is happening in above code.
Many Thanks
| Short answer: it is unsafe.
The standard guarantees that a temporary variable can be bound to a constant reference in which case the lifespan of the temporary expands to the lifetime of the bound reference. The problem in your particular case is what reference is actually binding the temporary.
When you call MaxValue( s1, s2 ), two temporary variables of type int are created and bound to the parameter arguments a and b in MaxValue. This means that the lifespan of those temporaries is extended to the completion of the function. Now, in the return statement of your function you are taking a second reference to one of the temporaries and that second reference will not extend the lifetime. r2 will not further extend the lifetime of the object, and you have a dangling reference.
Note that due to the separate compilation, the compiler cannot possibly know from outside of MaxValue whether the returned reference is to one of the arguments or to a completely different object that is not a temporary:
int const & OtherMaxValue( int const & a, int const & b ) {
static int value = 0;
value = (a > b? a : b);
return value;
}
So it cannot possibly guess whether any or which of the temporaries lifetime needs to be extended.
As a side note, for small objects (such as all integer types) passing by reference may be actually worse than passing by value. Also there is already an std::max template that actually implements this functionality.
|
3,175,111 | 3,175,144 | CURL is not following 301 Redirects, what do I need to do? | I am using the CURL c++ api to get quotes from Yahoo's financial API. The curl api and my code seem to be working fine, however I am getting a "301" redirect message when I tell CURL to visit the url I want. How can I get CURL to follow through to the 301 redirect and get the data I want?
Here is the URL I am using:
http://download.finance.yahoo.com/d/quotes.csv?e=.csv&s=WSF,WSH&f=b2b3s
Here is the response I am getting:
<HEAD><TITLE>Redirect</TITLE></HEAD>
<BODY BGCOLOR="white" FGCOLOR="black">
<FONT FACE="Helvetica,Arial"><B>
"<em>http://download.finance.yahoo.com/d/quotes.csv?e=.csv&s=WSF,WSH,WSM,WSO,WST,WTI,WTM,WTR,WTS,WTU,WTW,WU,WWE,WWW,WX,WXS,WY,WYN,X,XAA,XCJ,XCO,XEC,XEL,XEL-A,XEL-E,XFB,XFD,XFH,XFJ,XFP,XFR,XIN,XJT,XKE,XKK,XKN,XKO,XL,XL-Y,XOM,XRM,XRX,XVF,XVG,Y,YGE,YPF,YSI,YUM,YZC,ZB-A,ZB-B,ZB-C,ZEP,ZF,ZLC,ZMH,ZNH,ZQK,ZTR,ZZ,ZZC&f=b2b3ccd1d2ghjkk2k3l2l3mm2m3m4m5m6m7m8opst7vw</em>".<p></B></FONT>
<!-- default "Redirect" response (301) -->
</BODY>
Here are my CURL init options
CURL *eh = curl_easy_init();
curl_easy_setopt(eh, CURLOPT_WRITEFUNCTION, cb);
curl_easy_setopt(eh, CURLOPT_HEADER, 0L);
curl_easy_setopt(eh, CURLOPT_URL, url);
curl_easy_setopt(eh, CURLOPT_PRIVATE, url);
curl_easy_setopt(eh, CURLOPT_VERBOSE, 0L);
curl_multi_add_handle(cm, eh);
I didn't post my code, as it is all working, I just need the general method of following through woth the 301's with CURL.
| In the PHP world, the option is named CURLOPT_FOLLOWLOCATION. I assume the constant names are standardized and come from the same header file, so this should work for you.
curl_easy_setopt(eh, CURLOPT_FOLLOWLOCATION, 1);
(or whatever "boolean true" is in this context.)
Alternatively, when receiving a 30x status code, you can parse the Location header manually for the new address. Obviously though, the "follow location" option is much easier, as it doesn't require a second request.
|
3,175,159 | 3,175,227 | How do i make a some sort of istream for a vector of unsigned chars | how can i create an istream from a buffer unsigned char* or vector.
basically i want :
void Func(vector<unsigned char> data)
{
someSortOfIstream x (data);
x >> something;
}
using boost too....
| I would recommend:
use a std::string (a fancy vector of chars) instead of a std::vector<unsigned char>, because that's what it's for. You can then use the readily available std::stringstream in the <sstream> header.
You can subclass a std::vector<unsigned char> and overload the operator>>() for what you need it.
OR
(harder but theoretically better) You can subclass std::iostream for your case and tell it what to do when you use operator>>() on it
Personnally I'd go with 1, and if you must, with 2a) because frankly, I'd have no idea how to subclass an iostream.
|
3,175,219 | 3,175,232 | Restrict C++ Template Parameter to Subclass | How can I force a template parameter T to be a subclass of a specific class Baseclass?
Something like this:
template <class T : Baseclass> void function(){
T *object = new T();
}
| In this case you can do:
template <class T> void function(){
Baseclass *object = new T();
}
This will not compile if T is not a subclass of Baseclass (or T is Baseclass).
|
3,175,295 | 3,247,258 | Outputting stl from multiple ellipse sources VTK | I currently have a small (I'm a complete beginner) project in VTK where I've used different vtkParametricFunctionSource objects and arranged them spatially. Now what I want to do is find a way to output all that data I'm currently rendering into a .stl file.
I don't know how I'd manage to convert my implicit parametric functions from their formula form that gives me the ellipses to some kind of point-set form that would allow me to output to .stl. I'm probably just not aware of some VTK class that helps me do this, but any and all help would be appreciated.
Best.
EDIT:
Also, in my VTK Scene, I've manipulated the position of some of the objects by changing the positions of the actors that are used to display them on screen. I would like to maintain this position as well in the outputted .stl file. So basically, how would one go about taking exactly what you see in the scene, shape and position wise, and placing all that data in one .stl file?
| a vtkActor only modifies the rendered representation of the data. Because of this you cannot easily write it out using pre-existing vtk writers.
What you want to do is apply a vtkTransformFilter to each vtkParametricFunctionSource with the transformation matrix being equal to the vtkActor for that vtkParametricFunctionSource. You can than group everything together with vtkAppendPolyData and write out that filters output with vtkSTLWriter.
|
3,175,437 | 3,175,875 | Virtual inheritance in C++ | I was reading the Wikipedia article on virtual inheritance. I followed the whole article but I could not really follow the last paragraph
This is implemented by providing
Mammal and WingedAnimal with a vtable
pointer (or "vpointer") since, e.g.,
the memory offset between the
beginning of a Mammal and of its
Animal part is unknown until runtime.
Thus Bat becomes
(vpointer,Mammal,vpointer,WingedAnimal,Bat,Animal).
There are two vtable pointers, one per
inheritance hierarchy that virtually
inherits Animal. In this example, one
for Mammal and one for WingedAnimal.
The object size has therefore
increased by two pointers, but now
there is only one Animal and no
ambiguity. All objects of type Bat
will have the same vpointers, but each
Bat object will contain its own unique
Animal object. If another class
inherits from Mammal, such as
Squirrel, then the vpointer in the
Mammal object in a Squirrel will be
different from the vpointer in the
Mammal object in a Bat, although they
can still be essentially the same in
the special case that the Squirrel
part of the object has the same size
as the Bat part, because then the
distance from the Mammal to the Animal
part is the same. The vtables are not
really the same, but all essential
information in them (the distance) is.
Can someone please shed some more light on this.
| Sometimes, you just really need to see some code / diagrams :) Note that there is no mention of this implementation detail in the Standard.
First of all, let's see how to implement methods in C++:
struct Base
{
void foo();
};
This is similar to:
struct Base {};
void Base_foo(Base& b);
And in fact, when you look at a method call within a debugger, you'll often see the this argument as the first parameter. It is sometimes called an implicit parameter.
Now, on to the virtual table. In C and C++ it is possible to have pointers to function. A vtable is essentially a table of pointers to functions:
struct Base
{
int a;
};
void Base_set(Base& b, int i) { b.a = i; }
int Base_get(Base const& b) { return b.a; }
struct BaseVTable
{
typedef void (*setter_t)(Base&, int);
typedef int (*getter_t)(Base const&);
setter_t mSetter;
getter_t mGetter;
BaseVTable(setter_t s, getter_t g): mSetter(s), mGetter(g) {}
} gBaseVTable(&Base_set, &Base_get);
Now I can do something like:
void func()
{
Base b;
(*gBaseVTable.mSetter)(b, 3);
std::cout << (*gBaseVTable.mGetter)(b) << std::endl; // print 3
}
Now, on to the inheritance. Let's create another structure
struct Derived: Base {}; // yeah, Base does not have a virtual destructor... shh
void Derived_set(Derived& d, int i) { d.a = i+1; }
struct DerivedBaseVTable
{
typedef void (*setter_t)(Derived&,int);
typedef BaseVTable::getter_t getter_t;
setter_t mSetter;
getter_t mGetter;
DerivedBaseVTable(setter_t s, getter_t g): mSetter(s), mGetter(g) {}
} gDerivedBaseVTable(&Derived_set, &Base_get);
And the use:
void func()
{
Derived d;
(*gDerivedBaseVTable.mSetter)(d, 3);
std::cout << (*gDerivedBaseVTable.mGetter)(d) << std::endl; // print 4
}
But how to automate this ?
you only need one instance of a vtable per class having at least one virtual function
each instance of the class will contain a pointer to the vtable as its first attribute (even though you can't really access it by yourself)
Now, what happens in case of multi-inheritance ? Well, inheritance is very much like composition in term of memory layout:
| Derived |
| BaseA | BaseB |
| vpointer | field1 | field2 | padding? | vpointer | field1 | field2 | padding? |
There will thus be 2 virtual tables for MostDerived: one to change the methods from BaseA and one to change the methods from BaseB.
Pure virtual functions are generally represented as a null pointer (simply) in the corresponding field.
And finally, construction and destruction:
Construction
BaseA is constructed: first the vpointer is initialized, then the attributes, then the body of the constructor is executed
BaseB is constructed: vpointer, attributes, body
Derived is constructed: replace the vpointers (both), attributes, body
Destruction
Derived is destructed: body of the destructor, destroy attributes, put the base vpointers back
BaseB is destructed: body, attributes
BaseA is destructed: body, attributes
I think it's pretty comprehensive, I'd be glad if some C++ gurus around there could review this and check I haven't made any stupid mistake. Also, if something is missing, I'd be glad to add it.
|
3,175,449 | 3,175,463 | C++ REG_SZ to char* and Reading HKLM without Elevated Permissions | So I've been trying to get a REG_SZ value out of the registry and store it as a char*. After looking around the internet this is what I came up with. The problem is that the value I get is not what is stored in the registry, I get a bunch of random garbage. How would I correctly get the value?
HKEY hKey;
char value[256];
// Open the key
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE, "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\\", 0, KEY_QUERY_VALUE, &hKey) != ERROR_SUCCESS)
{
return "";
}
// Read the value
DWORD dwType = REG_SZ;
DWORD dwCount = sizeof(value);
if(RegQueryValueEx(hKey, "ProcessorNameString", NULL, &dwType, (LPBYTE)&value, &dwCount) != ERROR_SUCCESS)
{
RegCloseKey(hKey);
return "";
}
// Cleanup and return
RegCloseKey(hKey);
return value;
Also anther quick question. I remember that if my program inst running as admin of Vista/7 then it cant edit the HKLM but can it still read it?
| (Updated, since previous answer was wrong.)
The problem may be that you're returing value, which is a stack-allocated buffer. This will work only if you declared your function as returning a char[256]--if you're trying to return a char*, then the caller is getting the address of the first byte in value, which is now pointing to invalid stack data. You should allocate value as a char* on the heap, which will allow you to return the pointer with impunity.
Whether or not you are allowed to read or edit the registry key depends on what ACLs are applied to the key you're reading. It is possible to set the permissions on the key in such a way that an unelevated user can't even read the key, but it's also possible to set the permissions such that all users can both read and write. The key that you're reading above should be readable by all users, but it won't be modifiable except by admins.
|
3,175,632 | 3,175,671 | c++ pair template struct declaration ambiguity! | In definition of pair class in c++ there are two typedefs. what are they for? there are no use of them in the code!
template <class T1, class T2> struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& x, const T2& y) : first(x), second(y) {}
template <class U, class V>
pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}
| They are just here for you convenience, so you can use them in your code. C++ doesn't have a reflection model , so that's the only way you have "know" what types they are
Suppose you define your own pair
typedef pair MyPair;
Then you can use
MyPair::first_type
MyPair::second_type
for example,
MyPair::first_type my_first(MyPair& pair)
{
return pair.first;
}
Then you won't need to research and replace everywhere in your code , if you change the original definition of MyPair.
|
3,175,832 | 3,175,855 | Which of these is better practice? | Let's say I have a class FOO.
I want to have a std::vector of FOO.
Is it better if I do something like this:
FOO foo;
foo.init();
foo.prop = 1;
std::vector<FOO> myvec;
myvec.push_back(foo);
foo.prop = 2;
myvect.push_back(foo);
or is it better practice to do:
std::vector<FOO> myvec;
FOO foo;
myvec.push_back(foo);
myvec.back().init();
myvec.back().prop = 1;
myvec.push_back(foo);
myvec.back().init();
myvec.back().prop = 2;
I'm basically not sure if its better to make a model and push in the model instead of making an instance, pushing it, then modifying it from the vector. Also, which one is safer and least likely to result in memory leaks?
Thanks
| Neither method has any memory issues as you're dealing with values and aren't dynamically allocating any objects manually.
I would favour giving FOO a constructor which does whatever init does and sets prop to the appropriate value. Then you can just push the values you want:
myvec.push_back(FOO(1));
myvec.push_back(FOO(2));
|
3,175,887 | 3,176,010 | Simple-iphone-image-processing source code question, what does this do | I am going through the source code for the above project and I don't understand the following lines of code can anyone help explain it to me please? I am trying to get the code to work with color images as it currently only works with greyscale images. I have the main methods working however the filters only get applied to the top quarter of the returned images.
//In the heeder file.
inline uint8_t* operator[](const int rowIndex) {
return m_yptrs[rowIndex];
}
//in the .mm file
void Image::initYptrs() {
m_yptrs=(uint8_t **) malloc(sizeof(uint8_t *)*m_height);
for(int i=0; i<m_height; i++) {
m_yptrs[i]=m_imageData+i*m_width;
}
}
From my understanding it looks like it is creating a a reference to the pixels in the images however i don't understand this line of code.
m_yptrs[i]=m_imageData+i*m_width;
Thanks in advance.
| Image::initYptrs() initializes an array of pointers to the beginning of each row of the image.
The line in question should probably read
m_yptrs[i] = m_imageData + i*BPP*m_width;
Where BPP is bytes per pixel (e.g. 3 for RGB, 4 for RGBA images).
|
3,175,972 | 3,223,863 | STL container function return values | When looking over the member functions of the STL containers, an odd thought occurred to me. Why don't functions like std::vector<T>::push_back(T) not have an (optional) return value (iterator or even a reference to the appended object)? I know std::string functions like insert and erase return iterators, but that's for obvious reasons. I'd think it'd often save a second line of code that often follows these function calls.
I'm sure the designers of C++ have a very good reason, please enlighten me :)
UPDATE: I'm including a real-world code example here where it could reduce code length:
if( m_token != "{" )
{
m_targets.push_back( unique_ptr<Target>(new Dough(m_token)) );
return new InnerState( *(m_targets.back()), this );
}
could be reduced to
if( m_token != "{" )
return new InnerState( *(m_targets.push_back( unique_ptr<Target>(new Dough(m_token)) )), this );
If I assume std::list::push_back returns a reference to the added element. The code is a bit heavy, but that's mostly (two sets of parentheses) due to unique_ptr's constructor and dereferencing it. Perhaps for clarity a version without any pointers:
if( m_token != "{" )
{
m_targets.push_back( Dough(m_token) );
return new InnerState( m_targets.back(), this );
}
vs.
if( m_token != "{" )
return new InnerState( m_targets.push_back( Dough(m_token) ), this );
| Returning the added element, or the container in container member functions is not possible in a safe way. STL containers mostly provide the "strong guarantee". Returning the manipulated element or the container would make it impossible to provide the strong guarantee (it would only provide the "basic guarantee").
The reason behind this is, that returning something could possibly invoke an copy-constructor, which may throw an exception. But the function already exited, so it fulfilled its main task successfully, but still threw an exception, which is a violation of the strong guarantee. You maybe think: "Well then lets return by reference!", while this sounds like a good solution, its not perfectly safe either. Consider following example:
MyClass bar = myvector.push_back(functionReturningMyClass()); // imagine push_back returns MyClass&
Still, if the copy-assignment operator throws, we dont know if push_back succeded or not, thus indirectly violating the strong-guarantee. Even though this is not a direct violation. Of course using MyClass& bar = //... instead would fix this issue, but it would be quite inconvenient, that a container might get into an indeterminate state, just because someone forgot a &.
A quite similar reasoning is behind the fact that std::stack::pop() does not return the popped value. Instead top() returns the topmost value in a safe way. after calling top, even when a copy-constructor, or a copy-assignment constructor throws, you still know that the stack is unchanged.
EDIT:
I believe returning an iterator for the newly added element should be perfectly safe, if the copy-constructor of the iterator-type provides the no-throw guarantee (and every i know of does).
|
3,176,004 | 3,176,076 | Object Oriented Design Problem, Liskov Substitution Principle | I'm making the design of a OO framework and I'm facing the following problem.
Let's say that in the framework I have a Shape interface and the users are free to implement and extends (adding new functions) the Shape interface to create their own figures, e.g. Square and Circle. To make these new objects available the users have to register them into a ShapeFactory specifying the name of the shape (string) and the object.
Furthermore, the framework provides an interface called ShapeWorker which defines the following function:
class ShapeWorker
{
public:
void processShape( Shape& shape ) = 0;
};
The users are free to implement the ShapeWorker interface to make specific shape worker, e.g. SquareWorker and CircleWorker. To make these new objects available the users have to register them into a WorkerFactory, specifying the name of shape (string) and the object.
At a certain point, the framework, given a string representing the shape's name, creates a new Shape, by using the ShapeFactory, and afterwards (somewhere else in the code) creates a new ShapeWorker, by using the WorkerFactory with the same shape's name. The processShape is then called providing the Shape instance created before.
[ ... ]
Shape* myShape = shapeFactory.create( shapeName );
[ ... ]
ShapeWorker* myWorker = workerFactory.create( shapeName );
myWorker->processShape( *myShape );
[ ... ]
The point is that, doing so, I force the user implementing, for example, the SquareWorker to make a down-cast from Shape to Square into the processShape function so to access to the full Square's interface:
class SquareWorker
{
public:
void processShape( Shape& shape )
{
Square& square = dynamic_cast< Square& >( shape );
// using Square interface
}
};
This is against the Liskov substitution principle.
Now, is this approach wrong? What would it be the better solution? Note that I don't want to implement the processShape as Shape's member function.
I hope the description has been clear enough.
Thanks in advance for your help.
Simo
| Unless your shapes have a common interface that must be used by the workers, this approach seems fully correct to me. A shape worker is more or less specialized on a specific shape, thus has knowledge about the class it handles. It would be nicer to do that using a common interface for all shapes but you cannot put everything you would need into it, it would end up fully cluttered. Downcasting is a correct mean to solve this.
The use of templates could help you out: you could create a base class for all workers
template <class T>
class BaseShapeWorker : ShapeWorker
{
public:
void processShape( Shape& shape )
{
T& specificShape = dynamic_cast< T& >( shape );
processShape( specificShape )
}
protected:
virtual void processShape( T& shape ) = 0;
};
This would not need the implementers to know about this downcast and ease the implementation by maybe also providing some often reused functionality.
|
3,176,016 | 3,176,027 | Is quick sort followed by binary search faster than linear search? | Is it better to sort then binary search or simply linear search?
Thanks
| It depends how often you want to search after the sort - if only once, then a linear search will probably be faster. Of course, an even better bet is normally (but not always) to maintain things in sorted order using something like set or a map.
|
3,176,035 | 3,176,086 | Link the static versions of the Boost libraries using CMake | I've got both the static and the dynamic versions of the boost libraries in /usr/lib. Now I'd like CMake to prefer the static versions during the linkage of my executable. What can I do?
| In your CMakeLists.txt file:
set(Boost_USE_STATIC_LIBS ON)
find_package(Boost REQUIRED ...)
Where I have ..., you optionally put the names of the libraries you want to use, and then target_link_libraries(targetname ${Boost_LIBRARIES}) later below. If you have a fairly recent distribution of CMake, it should work exactly as advertised. I do it exactly this way in my own projects.
|
3,176,056 | 3,177,662 | Need advice in converting in one of the legacy C++ component into C# | Currently, we are working on a C++ legacy code base, which consists of several software components.
One of the components, are written in a way that is extremely difficult to maintain. (For example, memory allocation is done in X place, but memory de-allocation is done in Y place. This make memory management a painful job). Till now, we able to solve (or workaround) all the memory leakage issues.
However, after several rounds of bug fixing, our feeling is that, due to the high maintenance cost of this software component, we are unable to go too far from current milestone.
I know it might be bad to rewrite the source code : http://www.joelonsoftware.com/articles/fog0000000069.html
However, instead of re-factor the current code, we forsee it will be better to re-write from scratch due to
Till now, no one in the team can fully understand that software component code.
The legacy software component is a small piece of software. 20k lines, I guess
Our teams are pretty clear on the requirement and what we are trying to achieve
Hence, we are planning to go for a managed code, at least make memory management a painless job. We plan to choose C#, as
All our C++ code are compiled using Microsoft VC++
We are using MFC, in other software components. (in DLL form) Every DLL, do have their very own resource.
I am from C++ and Java background, and know nothing much on C#.
How well C# to interface with MFC DLL, with some of the DLL functions will invoke MFC GUI?
Anything I need to pay attention on it?
Will the interfacing with legacy C++ DLLs be easier, if we are using Managed C++?
Thanks.
| I am in a similar situation and I also did some experiments mixing C++ and C#. The problems in my application however were that:
the application is not clearly split up in different modules, making it hard to move specific modules from C++ to C#
the application is quite cpu-intensive and experiments revealed a big overhead in calls from C++ to C# or C# to C++
Additionally, you cannot call C# directly from native/unmanaged C++, which meant that I had to introduce an additional intermediate C++/CLI (or is this called C++.Net?) layer.
Therefore, I chose not to move to C#, but stay with C++.
So, if you want to move from C++ to C#, make sure:
that you have clearly separated modules
that the transition (calls) from C++ to C# or vice versa are in a place that is not used that often (so not during cpu-intensive tasks)
Additionally, remember that if you are not the sole developer of the project, that all (or most) of your developers should also learn C#. You don't want to delegate all C# code to your latest junior developer, because if he leaves, you will be (or could be) in trouble.
|
3,176,110 | 3,189,661 | C++ FSM design and ownership | I would like to implement a FSM/"pushdown automaton" parser for this syntax: parser with scopes and conditionals which has already been "lexed" into Finite State Machine parser
I have the following:
class State
{
public:
virtual State* event( const string &token );
State* deleteDaughter();
private:
A* m_parent;
A* m_daughter;
}
class SomeState : public State
{
public:
State* event( const std::string &token );
}
With B's event() doing (after many if-elseif's) return m_parent->deleteDaughter(). I know this is fishy (and it crashes), but I need way to return the parent State from the daughter State and make sure the daughter State isn't leaked.
My event loop looks like this:
while( somestringstream >> token )
state = state->event();
Before you scold the design and last piece of code, I tried extending a much too simple example from here, which seems pretty ok. I am moving the decision part to the states themselves, for clarity and brevity.
I understand there's loads of books on this subject, but I'm no computer scientist/programmer and I want to learn to do this myself (of course, with the help of all the friendly people at SO). If the concept isn't clear, please ask. Thanks!
| Feel free to still post your take on this, but I have figured out how to handle everything gracefully:
First: my event loop will keep a pointer to the last State* created.
Second: Each State has a pointer to the parent State, initialized in the constructor, defaulting to 0 (memory leak if used for anything but the first State*); this guarantees that no State will go out of scope.
Third: State* endOfState() function which does exactly this (and I'm particularly proud of this.
State* State::endOfState()
{
State* parent = m_parent; // keep member pointer after suicide
delete this;
return parent;
}
When this is called from within a subclass's event(), it will properly delete itself, and return the parent pointer (going one up in the ladder).
If this still contains a leak, please inform me. If the solution is not clear, please ask :)
PS: for all fairness, inspiration was stolen from http://www.codeguru.com/forum/showthread.php?t=179284
|
3,176,114 | 3,177,923 | Under what circumstances will C++ fail to call an inherited class's constructor? | EDIT following resolution, this has been substantially edited to dump irrelevant detail and explain the real issue.
I found a problem recently in some old code. The particular code was only rarely used and had insufficient unit tests (I was adding some more when I spotted the problem). I only relatively recently stopped using Visual C++ 2003, and symptoms didn't show in VC++9, only in MinGW GCC 4.4.0. And only release builds. And the symptoms vanished as soon as I added any trace code. Don't you just hate those?
Anyway, it turned out that the copy constructor and assignment operator overload weren't being called in all cases. As a result, a data structure was becoming inconsistent. Most of the time I was fluking through.
I spotted the issue by stepping through in the VC++9 debugger, even though the VC++9 build didn't show the symptoms. So, at least two compilers are behaving the same, even though the symptoms didn't show for one - a fair hint that the behaviour that caught me unawares is standards compliant, and I've been relying on old non-standard behaviour.
So... under what circumstances will the constructor etc for an inherited base class fail to be called?
FWIW, the problem code is part of the library that led to this question.
RESOLUTION
There were two separate issues - copy construction and overloaded assignment.
The copy construction issue turned out to be the well know return value optimisation issue, in the more recent "named" variant. The involved objects were "cursors" (like iterators) pointing into multiway tree leaf nodes. In order to ensure they are maintained, each leaf node keeps a linked list of cursors that refer into it.
The cursor is a very lightweight class - a leaf node pointer, a subscript within the node, and a next pointer for the maintenance list. The only reason that the explicit construction/destruction/assignment are needed is for the side-effect of maintaining the cursors lists.
Because the class is so lightweight, and because there are rarely more than a few cursors (and especially rarely more than one or two pointing into a particular leaf node), I sometimes used pass-by-value and return-by-value. The latter seems to be the problem.
Changing the copy constructor implementation accidentally bypassed this issue - I get the impression (unconfirmed) that for release builds, both MinGW GCC and VC++ still try to avoid bypassing copy constructors with side-effects, but miss some kinds of side-effects.
Second problem - the assignment overload. This, I think, was an old stupid mistake on my part, and if I hadn't had the copy constructor issue at roughly the same time, I'd have figured it out more quickly.
The assignment overload was inherited through two layers of inheritance, with some template, privacy and dependent-type complications along the way. Neither the middle nor derived class overrode it. This kind of makes sense (in an its-wrong-anyway way) in this special case - the derived class doesn't add any member data, it just supplies the template parameter to the base and adds some methods. But I'd be pretty surprised if the standard has special cases for "but i didn't add any member data".
With older compilers, I think I was fluking through on implicit casting rules allowing the base-class assignment operation to be called. I wouldn't like to try to trace the exact reason for the change in behaviour - the key point is that I'm being punished for writing some messy and bizarrely structured code.
| The most important case is when it skips calling copy constructors entirely. This is a specific optimization that is allowed even in cases where the observable behavior changes.
Another case that catches some inexperienced developers is that unless specified otherwise, Derived::Derived(T) calls Base::Base() - not Base::Base(T)
|
3,176,156 | 3,176,197 | How to use c++ std complex numbers in QtScript | I try to find out how to use complex numbers in QtScripts such that slots defined with complex arguments can be called from a QtScript. Also basic algebra (+,-,exp, ... ) of complex-numbers should be accessible to the user from the script.
Just for illustration want I want to call is:
#include<complex>
typedef complex<double> Complex;
class MyCppClass : public QObject
{
Q_OBJECT
public:
...
public slots:
void mySignal(Complex rCValue); !! <<== should be callable from QtScript
...
}
Any ideas? Thx!
| I think you must implement complex algebra in QtScript (something like http://examples.oreilly.com/9781565923928/text/8-6.txt) and then modify mySignal to accept an object like this.
|
3,176,204 | 3,176,231 | To code background process in Ruby or C++ for rails app? | I've been working on a rails app for a couple of days now that I need an underlying "middle layer" for that connects my rails application to the various services that make up the data.
The basic setup looks like this:
Frontend ("Rails app") -> user requests data to be aggregated -> info goes in database and a JSON request is sent to "middle layer" to retrieve the data from a source of other places, process it, then send it back to the frontend which streams it to the users browser via websockets.
Middle layer -> uses sockets to listen for the frontend making a request. Once request is made, aggregation begins.
Base layer -> load balancing among a scalable network design.
I don't think that this is as efficient as it could be though. I feel like I'll run into concurrency problems or it just being too slow for use. I need to be able to scale it up.
My main question though rests in the area of what language would be more efficient for this to run fast?
| It depends. What are your data sources? Are they on the same machine? Are they databases?
My gut tells me that the language you choose won't play much of a role in how well this kind
of application performs, but it it hard to say without knowing the details.
C++ is probably a bad idea for a scalable web-app though. It is very likely that you will end
up with something which is slower than what you would have written in Ruby, because you end up worrying about irrelevant details. With regards to concurrency concurrency problems, C++ is definitely not the easiest language in which to write concurrent code.
Without knowing more, I would recommend that you stick with Ruby or some other high-level language and profile to see where the bottlenecks are. If you find out that there is some tight loop which needs to run really fast you can write that part in C, but you probably won't need that.
|
3,176,518 | 3,176,531 | C/C++: Pointers within Const Struct | How do I force const-ness of the memory pointed to by obj->val1 in the function fn?
#include <iostream>
struct foo {
int* val1;
int* val2;
int* val3;
};
void fn( const foo* obj )
{
// I don't want to be able to change the integer that val1 points to
//obj->val1 = new int[20]; // I can't change the pointer,
*(obj->val1) = 20; // But I can change the memory it points to...
}
int main(int argc, char* argv[])
{
// I need to be able to set foo and pass its value in as const into a function
foo stoben;
stoben.val1 = new int;
*(stoben.val1) = 0;
std::cout << *(stoben.val1) << std::endl; // Output is "0"
fn( &stoben );
std::cout << *(stoben.val1) << std::endl; // Output is "20"
delete stoben.val1;
return 0;
}
The code here is pretty self explanitory. I need to be able to make a non-const object and fill it with data, but then pass it to a function where this data cannot be modified. How can I go about this?
I know I can just pass in a const int pointer, but theoretically, this class contains several other pointers which I will need in "fn" as well.
Thanks,
Griff
| Since you tagged as C++, you could make the member private and make an accessor that returns a const int *. You could originally set the member via your constructor or a friend function.
|
3,176,612 | 3,176,694 | GlBufferDataARB is giving me memory issues | Basically I do something like this:
GenerateLinePoly(Contour[i].DrawingPoints, Contour[i].Outline.OutlineWidth);
Contour[i].Outline.OutlineSize = OutlineVec.size() / 2;
glBindBufferARB(GL_ARRAY_BUFFER_ARB,Contour[i].Outline.OutlineVBO);
glBufferDataARB(GL_ARRAY_BUFFER_ARB,sizeof(GLfloat) * OutlineVec.size(),
&OutlineVec[0],GL_DYNAMIC_COPY_ARB);
in my class constructor I do GlGenBuffers for all of these and I guarantee that I use GlDeleteBuffersARB in the deconstructor.
The system memory usage goes up as expected. But after destroying the object the memory occupied by thebuffers remains. I don't think this is a memory leak. I call GlDeleteBuffers and it doesn't clear all the memory it uses. Is that normal behavior? What could cause this?
If I only do:
GenerateLinePoly(Contour[i].DrawingPoints, Contour[i].Outline.OutlineWidth);
Contour[i].Outline.OutlineSize = OutlineVec.size() / 2;
Then my memory is managed perfectly as I would expect.
Thanks
| Man page of glDeleteBuffers
It doesn't say anywhere that the memory should be released immediately. If it's not leaking (which is a driver bug), then i would say that what you're expecting is not happening. The GL implementation is free to do the real deallocation anytime it wants, specially if the resources are still used. Remeber that since the CPU and GPU run in parallel, the GPU might be using some resource while the CPU is doing other things.
|
3,176,621 | 3,176,658 | Is the unordered_map really unordered? | I am very confused by the name 'unordered_map'. The name suggests that the keys are not ordered at all. But I always thought they are ordered by their hash value. Or is that wrong (because the name implies that they are not ordered)?
Or to put it different: Is this
typedef map<K, V, HashComp<K> > HashMap;
with
template<typename T>
struct HashComp {
bool operator<(const T& v1, const T& v2) const {
return hash<T>()(v1) < hash<T>()(v2);
}
};
the same as
typedef unordered_map<K, V> HashMap;
? (OK, not exactly, STL will complain here because there may be keys k1,k2 and neither k1 < k2 nor k2 < k1. You would need to use multimap and overwrite the equal-check.)
Or again differently: When I iterate through them, can I assume that the key-list is ordered by their hash value?
| In answer to your edited question, no those two snippets are not equivalent at all. std::map stores nodes in a tree structure, unordered_map stores them in a hashtable*.
Keys are not stored in order of their "hash value" because they're not stored in any order at all. They are instead stored in "buckets" where each bucket corresponds to a range of hash values. Basically, the implementation goes like this:
function add_value(object key, object value) {
int hash = key.getHash();
int bucket_index = hash % NUM_BUCKETS;
if (buckets[bucket_index] == null) {
buckets[bucket_index] = new linked_list();
}
buckets[bucket_index].add(new key_value(key, value));
}
function get_value(object key) {
int hash = key.getHash();
int bucket_index = hash % NUM_BUCKETS;
if (buckets[bucket_index] == null) {
return null;
}
foreach(key_value kv in buckets[bucket_index]) {
if (kv.key == key) {
return kv.value;
}
}
}
Obviously that's a serious simplification and real implementation would be much more advanced (for example, supporting resizing the buckets array, maybe using a tree structure instead of linked list for the buckets, and so on), but that should give an idea of how you can't get back the values in any particular order. See wikipedia for more information.
* Technically, the internal implementation of std::map and unordered_map are implementation-defined, but the standard requires certain Big-O complexity for operations that implies those internal implementations
|
3,176,761 | 3,176,872 | usual hashtable implementation compared to tree | Usually (as in C++), the hash function returns any size_t value -- thus many different hash values are possible (2^32).
That is why I always thought that when people talked about them being implemented as tables, that is not really true in practice because the table would be much too big (2^32 entries). Of course my assumption was wrong that the table must be as big as the full range of hash values.
It seems that the actual implementation is more difficult than I thought. What I always had in mind, what would be the naive implementation, is something like:
typedef list< pair<Key,Value> > Bucket;
typedef map< size_t, Bucket > Hashtable;
Now my question: How does this naive implementation differs from actual implementations in the praxis in terms of complexity (runtime and memory)?
| Note that there are other ways to implement hash tables as Matthieu M points out. The remainder of this answer assumes that you want to use hashing with buckets made of some kind of list.
Assuming you are talking about time complexity.
Hash tables are expected to have O(1) best-case access. Your proposal for implementation in the question uses a map<size_t,Bucket> for access to the buckets which would result in O(log n) time complexity. You need something with O(1) access time complexity, such as a vector<Bucket> to comply with the expected time complexity of a hash table.
More details
Hash tables can vary between having excellent and poor time complexity, depending on how sparsely populated they are.
In the best case, each bucket has at most one entry, and access by key is O(1). This is the commonly quoted complexity for hash tables.
In the worst case, each key has the same hash value, and access by key is effectively searching a list which results in O(n) behaviour.
Real-world use is usually somewhere between these extremes, hopefully closer towards O(1).
The accepted answer to your other question has some simplified code you can use to work through these two extremes to satisfy yourself that this is the case.
|
3,176,766 | 3,178,304 | BST preorder traversal and writing tree content to temporary array | I'm trying to write binary search tree's content to temporary array in order to use in main. However I'm not sure how to do it... I have tried something like this:
void Book::preorder(TreeNode *ptr, Person &temp[], int x)
{
if(ptr!=NULL)
{
temp[x].name=ptr->item.name;
x++;
preorder(ptr->left, temp, x);
preorder(ptr->right, temp, x);
}
}
And, it gives following errors:
declaration of 'temp'a as array of references
no match for 'operator[]' in '((Book*)this->Book::temp[x]'
no matching function for call to 'Book::preorder(TreeNode*&, Person&,
int&)'
| void Book::preorder(TreeNode *ptr, Person temp[])
{
if(ptr!=NULL)
{
temp[globX].name=ptr->item.name;
temp[globX].phoneNumber=ptr->item.phoneNumber;
globX++;
preorder(ptr->left, temp);
preorder(ptr->right, temp);
}
}
is my final code. And i'm pretty sure that it works... Previous code has some kind of logic error. Using global variable (i know it's not recommended) I figured it out.
|
3,176,788 | 3,176,829 | Why does the number of elements in an enumeration change the visibility of a private typedef in C++? | Sorry for the not very descriptive question title. I'm not very sure how to describe this, hopefully I can make it better later if someone can explain this to me.
I was about to come on here and ask why the following example was working. It was exhibiting the behaviour I was hoping for but I wasn't sure why or whether it was standard or whether I just got lucky with the compiler. Anyway, in sorting out a minimal working example to post here I found that it wasn't doing what I thought at all. So here it is ...
struct Foo {
enum BAR { A, B, C, D, E };
private: typedef BAR BAR;
};
int main(int argc, char* argv[]) {
int x = (Foo::BAR)42;
int y = Foo::D;
}
What seems to be happening, and what I was quite pleased about, is that, Foo takes on the enum constants after which BAR is made private. So I get no error on int y = but I get a Foo::BAR is private error at int x=. However this seems to only work with 5 or more constants in the enum, remove that E and it all compiles fine, i.e. BAR remains public.
What's at work here? Thanks.
(PS. Compiler is GCC 4.4.3)
| I can verify your results about four vs. five enum elements... this looks like an obscure GCC bug.
As for "what's at work here", it's due to a technicality between different symbol namespaces in C++ (inherited from C). See this answer for more details.
If you don't want a symbol named BAR to be exposed, simply omit the tag name:
struct Foo {
enum { A, B, C, D, E };
};
If you declare a named public enum, then no matter what you do, even if you hide the name using a typedef, outsiders can access the enum using an elaborated type specifier. Trying to hide a symbol name in this way is fruitless:
struct Foo {
enum BAR { A, B, C, D, E };
private: typedef BAR BAR;
};
int main(int argc, char* argv[]) {
int x = (enum Foo::BAR)42; // works great!
int y = Foo::D;
}
Is there any particular reason you want the constants to be public while the enum name remains private?
|
3,176,845 | 3,176,847 | Is calling base class constructor always necessary in C++? | Suppose I have some class C, and I inherit from it and name this class D. Do I always have to call C's default constructor as in this example:
class C {
public:
C() { ... }
};
class D {
public:
D() : C() { ... }
};
Note that C has only the default constructor. Do I have to call it from D? I couldn't figure out how to find this out.
Thanks, Boda Cydo.
| You don't need to specify the base class constructor in your derived type constructor's initializer list. When it is omitted an attempt will be made to call the base constructor with no parameters. If no such parameterless base constructor exists, then you'll get a compiling error.
|
3,176,867 | 3,176,883 | What do I do if constructor fails to allocate memory in C++? | I just came across a problem where the constructor of a class needs to allocate memory. So I happily wrote char *mem = static_cast<char*>(malloc(100*sizeof(*mem)));. But then I suddenly realized that in case of error I can't return error code (I am not using exceptions in my code). How can I solve this problem?
Should I add an bool initialized member and then after making my class and then check it right after, as in:
myClass mc;
if (!mc.initialized) {
printf("Memory allocation failed in mc's constructor\n");
exit(1);
}
Thanks, Boda Cydo.
| You should use new, not malloc. new throws std::bad_alloc when you are out of memory. An exception should be propagated from the constructor if you fail to allocate (or for any other reason have a problem with initialization), as this is the only way you prevent the destructor from being called. If the constructor successfully completes, the destructor must be called (unless, of course, it was heap allocated and never freed).
|
3,176,899 | 3,176,924 | Do access modifiers work for static class functions? | I just came across code that had protected static class functions, as in:
class C {
...
protected:
static int fun() { ... }
};
I got curious if static class functions could have access modifiers and what would it mean? Since they are class globals and not pre-instance.
Thanks, Boda Cydo.
| Access modifiers in C++ do not work per-instance. They always work per-class. That is how it's always been. Which makes it perfectly logical to have them apply to static members as well.
It is a rather popular misconception that access protection in C++ is somehow supposed to work per-instance, which seems to be what inspired your question as well.
|
3,176,937 | 3,176,946 | What are the most common uses of static class functions in C++? | I am learning today about static class functions in C++ and I can't really understand what are they good for? Does anyone have some good examples where they can be applied successfully?
Thanks, Boda Cydo.
| Static member functions of a class are just ordinary (non-member) functions. You do know what ordinary functions are good for, do you? So, static member functions are good for the same things for the same reasons.
It is just that sometimes an ordinary function has a tight relationship with the class, so it makes sense to declare it as a static member of the class, instead of declaring it as a completely independent standalone function. It helps you to express the fact that the function has that tight relationship with the class. Besides, this gives that function full access rights to the innards of the class - to its private and protected members.
The latter actually makes it possible to implement some useful programming idioms and patterns using static member function. Do a search, for example, for "static constructor" idiom.
|
3,176,989 | 3,177,006 | How does one rename a variable midway through a block? | In C++, how does one rename a variable midway through a block? References and macros feel wrong.
| You can't.
But you can make a reference to it and access it under different "name".
If you really don't like the variable, just go out of current block, return from the function, leave the block.
|
3,177,028 | 3,177,035 | Can I throw C++ exceptions from legacy C callbacks? | I have C++ code that uses some C libraries. The C libraries take C language callbacks. I wrote a callback in my C++ code and now I somehow need to report error from it (but it returns void). I wonder if I can throw an exception from a C callback that is used from C++ code?
This is very difficult for me to understand.
Thanks, Boda Cydo.
| Yes, you should be able to do so. However, keep in mind it's entirely likely that the C library was not written to be exception safe, and as a result you might leave some of that library's structures in some inconsistent state. It depends entirely on the specific library and on the specific callback function. If nothing else, that library would probably have to be written with C++ support in mind from the beginning with respect to that callback.
|
3,177,032 | 3,177,062 | segmentation fault when i access member variables using a callback function | I have a class, in which i declare a static function. I register this function as the callback function for another library. Now, inside this function, i dereference the callback data to the class pointer and invoke a particular non-static member.
The invocation succeeds and the control comes into the non-static member function. But inside this function at the point where i access a member variable of the same class, i get a segmentation fault. This is strange. Can anybody help me with the possible mistake i have made and the solution?
Here is how the code looks like.
class test
{
int count;
int callback(const char * a, const char *b)
{
print(a);
print(b);
count++; //// HERE IS WHERE I GET THE SEGMENTATION FAULT
}
public:
static int callbackwrapper(const char*a, const char *b, void *ptr)
{
test *p = (test *)ptr;
p->callback(a, b);
}
test():count(0) {}
~test() {}
Register()
{
registercallback(callbackwrapper);
}
}
| The ptr passed to callackwrapper is most likely an invalid pointer or not an object of the class test. The invocation still succeeds because as long as you don't access a member variable, a class method is the same as a normal C++ function. Where you access count is when you actually dereference the object, hence the segmentation fault.
|
3,177,141 | 3,299,459 | What is the best free/paid C++ Video Training resource out there? | I'm a .NET Developer, primarily using c#, asp.net mvc, entity framework and programming for the Web. I want to know what you guys recommend to get a quick startup in learning c++. My biggest worries are pointers, memory management and other languages differences between managed and native languages. I want to know if there is some video training resource like Dimecasts and Tekpub for .NET.
Thanks :).
| XoaX.net best video resource I've found so far. I Suggest you guys take a look.
|
3,177,227 | 3,178,090 | Templates, Circular Dependencies, Methods, oh my! | Background: I am working on a framework that generates C++ code based on an existing Java class model. For this reason I cannot change the circular dependency mentioned below.
Given:
A Parent-Child class relationship
Parent contains a list of Children
Users must be able to look up the list element type at run-time
I've modeled this in the following testcase:
Main.cpp
#include "Parent.h"
#include <iostream>
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
Parent parent;
cout << Parent::getType() << endl;
cout << parent.getChildren().getType() << endl;
return 0;
}
Parent.h
#ifndef PARENT_H
#define PARENT_H
#include <string>
#include "Array.h"
class Child;
class Parent
{
public:
Array<Child> getChildren()
{
return Array<Child>();
}
static std::string getType()
{
return "parent";
}
};
#endif
Child.h
#ifndef CHILD_H
#define CHILD_H
#include "Parent.h"
class Child: public Parent
{
};
#endif
Array.h
template <typename ElementType>
class Array
{
public:
static std::string getType()
{
return ElementType::getType();
}
};
When I compile the above code I get:
error C2027: use of undefined type 'Child' at return ElementType::getType();
If I try #include "Child.h" instead of the forward declaration I get:
error C2504: 'Parent' : base class undefined at class Child: public Parent
If I try Array<Child*> instead of Array<Child> I get:
error C2825: 'ElementType': must be a class or namespace when followed by '::' at return ElementType::getType();
The circular dependency comes about because:
Child.h needs to know about class Parent
Parent.h needs to know about class Array
Array.h needs to know about class Child
Any ideas?
| The error is due to the Child class not being present when the template is instantiated.
Add the following either to Main or at the end of Parent.h:
#include "Child.h"
This compiles fine with both g++ 4 and VS 2010.
|
3,177,241 | 3,177,252 | What is the best way to concatenate two vectors? | I'm using multitreading and want to merge the results. For example:
std::vector<int> A;
std::vector<int> B;
std::vector<int> AB;
I want AB to have to contents of A and the contents of B in that order. What's the most efficient way of doing something like this?
| AB.reserve( A.size() + B.size() ); // preallocate memory
AB.insert( AB.end(), A.begin(), A.end() );
AB.insert( AB.end(), B.begin(), B.end() );
|
3,177,268 | 3,353,074 | Generating word documents (.doc/.odt) through C++/Qt | I am using Qt 4.5.3 and Windows XP. I need my application to generate documents that contains the information that is being used and generated. The information that is being used will be just strings (QString to be more specific) and the information that is being generated will be strings and images as well.
I want documents to be a MS word document (.doc) or can be an Open Document Format (.odt) Also I want the documents to be formatted with fonts,images, tables of data, some background colors and all.
I have done the creation PDF files using QTextDocument, QTextCursor and QPrinter. But when I tried to apply the same QTextDocument for odt, I ended up with just format error.
Is there a way to generate such documents using any other libraries that use C++? How you guys use to generate such documents (.odt/.doc) in C++? Any pointers, links, examples regarding this are welcome.
| I have done this through the Qt way. i.e by using ActiveQt module.
The reference documentation for MS Word can be obtained through,
MSDN documentation, which actually pointed to the VBAWD10.chm file that has the ActiveX apis for MS Word.
The Word Application can be initialized by
QAxWidget wordApplication("Word.Application");
The sub-objects of the word application can be obtained through the function,
QAxBase::querySubObject()
For e.g:
QAxObject *activeDocument = wordApplication.querySubObject("ActiveDocument");
To pass the obtained sub-object as an argument,
QVariant QAxBase::asVariant () const
Any function calls involving the word object can be called using the function using,
QAxBase::dynamicCall ()
For e.g:
activeDocument->dynamicCall("Close(void)");
After a quite good amount of struggle and few convinces, it's working fine. :)
Hope it helps for those who are all looking for similar solutions...
|
3,177,302 | 3,177,309 | Is it safe for multiple threads to call the same function? | Is it safe to for example do:
void AddTwo(int &num)
{
num +=2;
}
void ThreadProc(lpvoid arg)
{
AddTwo((int)arg);
}
Would it be safe for this to occur if 4 threads were doing this at the same time? Thanks
| The function itself is safe to call. It becomes dangerous if they're all trying to operate on the same variable.
|
3,177,319 | 3,177,488 | set GLOBAL clipboard text in windows, native c++ | I have an ASCII string (A null terminated char array)
in a console app.
all I want to do is make it so my app will put this string into the "global clipboard"
so that after running it, I can ctrl+v in any standard app (in this case, visual studio) and my string will be pasted!
how do I do this?
I have done:
void SetClipboardText(char* txt)
{
if(!OpenClipboard(NULL))
{
__asm int 3;
}
int l = PIstrlen(txt);
HLOCAL la = GlobalAlloc(LMEM_MOVEABLE,l+1);
void* dest = GlobalLock(la);
PImemcpy(dest,txt,l+1);
GlobalUnlock(la);
if(!SetClipboardData(CF_OEMTEXT,la))
{
__asm int 3;
}
CloseClipboard();
}
I have tried CF_TEXT, CF_OEMTEXT, CF_UNICODE, I have tried NULL and GetDesktopWindow() when opening the clipboard
nothing seems to work.
Edit:
the above code always 'works' it never errors, it just never does what I want!
| How to Set text on clipboard
CString source;
//put your text in source
if(OpenClipboard())
{
HGLOBAL clipbuffer;
char * buffer;
EmptyClipboard();
clipbuffer = GlobalAlloc(GMEM_DDESHARE, source.GetLength()+1);
buffer = (char*)GlobalLock(clipbuffer);
strcpy(buffer, LPCSTR(source));
GlobalUnlock(clipbuffer);
SetClipboardData(CF_TEXT,clipbuffer);
CloseClipboard();
}
How to get text off of the clipboard
char * buffer;
if(OpenClipboard())
{
buffer = (char*)GetClipboardData(CF_TEXT);
//do something with buffer here
//before it goes out of scope
}
CloseClipboard();
|
3,177,552 | 3,359,463 | MS Word/ ODF Automation in Qt | How can I perform automation of MS Word documents (.doc) or ODF documents (.odt) in Qt 4.5? I know using the QAxWidget, QAxObject.
I have data (QString) and few images as well. I have to add them into the document. I googled but I couldn't find any commands for MS- Word/ ODF. But I want the specific commands that should be passed in QAxObject::dynamicCall() function to perform my operations.
For e.g in MS Excel we have to use something like,
excel.querySubObject("ActiveWorkBook");
which will return the object of the Active workbook of the Excel document.
What are all the commands that are available for the generation of MS-Word or ODF (odt) documents? I am using Windows XP. Any links, examples are welcome..
| The ActiveX commands related to the MS Word can be obtained by the VBAWD10.chm that is being installed along with MS - Word.
The details of the ActiveX help documents available can be obtained here.
The toughest part is to conform those in such a way that it can accessed through the ActiveQt Module.
I provided a similar solution to my question here
Hope it helps for those who are all looking similar solutions..
|
3,177,584 | 3,177,626 | C/C++: How to figure out the chain of header files for a given definition? | In Visual C++, one can find the header file where any name (variable or type) is defined by pressing F12 on it or choosing Go to Definition. This feature is very useful, but it only shows the final location (header file) where the name is defined. Is there a way to figure out the chain of header files that lead from my source file to the final header file for a given name?
For example, consider this code:
// main.cpp
#include <stddef.h>
int main()
{
size_t s;
return 0;
}
In Visual C++ 2010, if I look up the definition of size_t in the above main.cpp, it lands me in some file named sourceannotations.h. I know that this header chain begins with stddef.h (which I have included) and ends in sourceannotations.h. How to figure out the links in the middle of this chain?
|
Right click project, "Project Properties"
"Configuration Properties" -> "C/C++" -> "Advanced".
Set "Show Includes" to "Yes".
The complete hierarchy of headers will be printed out in the output window when you compile every file.
|
3,177,686 | 3,177,723 | how to implement is_pointer? | I want to implement is_pointer. I want something like this:
template <typename T >
bool is_pointer( T t )
{
// implementation
} // return true or false
int a;
char *c;
SomeClass sc;
someAnotherClass *sac;
is_pointer( a ); // return false
is_pointer( c ); // return true
is_pointer( sc ); // return false
is_pointer( sac ); // return true
How can I implement it?
Thanks
| template <typename T>
struct is_pointer_type
{
enum { value = false };
};
template <typename T>
struct is_pointer_type<T*>
{
enum { value = true };
};
template <typename T>
bool is_pointer(const T&)
{
return is_pointer_type<T>::value;
}
Johannes noted:
This is actually missing specializations for T *const, T *volatile and T * const volatile i think.
Solution:
template <typename T>
struct remove_const
{
typedef T type;
};
template <typename T>
struct remove_const<const T>
{
typedef T type;
};
template <typename T>
struct remove_volatile
{
typedef T type;
};
template <typename T>
struct remove_volatile<volatile T>
{
typedef T type;
};
template <typename T>
struct remove_cv : remove_const<typename remove_volatile<T>::type> {};
template <typename T>
struct is_unqualified_pointer
{
enum { value = false };
};
template <typename T>
struct is_unqualified_pointer<T*>
{
enum { value = true };
};
template <typename T>
struct is_pointer_type : is_unqualified_pointer<typename remove_cv<T>::type> {};
template <typename T>
bool is_pointer(const T&)
{
return is_pointer_type<T>::value;
}
...but of course this is just reinventing the std::type_traits wheel, more or less :)
|
3,177,842 | 3,177,884 | why append Slot doesn't work? | I have got a problem when I try to make following simple connections
QSpinBox *spinBox = new QSpinBox;
QSlider *slider = new QSlider(Qt::Horizontal);
QTextEdit *text = new QTextEdit("Hello QT!");
QObject::connect(spinBox, SIGNAL(valueChanged(int)),slider, SLOT(setValue(int)));
QObject::connect(slider, SIGNAL(valueChanged(int)),spinBox, SLOT(setValue(int)));
QObject::connect(slider,SIGNAL(valueChanged(int)),text, SLOT(append("slider changed!")));
QObject::connect(spinBox,SIGNAL(valueChanged(int)),text, SLOT(append("spinbox changed!")));
QObject::connect(text,SIGNAL(textChanged()),spinBox,SLOT(clear()));
It can be successfully compiled and excuted.But the two append slots seem not work.I've checked the help manual about QTextEdit and there's a public slot append there.Have I missed something?Help would be appreciated!
| Unfortunately, you cannot pass custom values to your slots via QObject::connect (only type information for the arguments is allowed/interpreted correctly). Instead, create your own slot, something like
void MyWidget::mySliderChangedSlot(int newValue)
{
text->append("slider changed!");
}
and use
QObject::connect(slider, SIGNAL(valueChanged(int)), pMyWidget, SLOT(mySliderChangedSlot(int)));
to achieve your desired behaviour.
I hope that helps.
|
3,177,850 | 3,177,924 | problem splitting a string | Can some one please tell me the problem with this code. I am reading each line using getline function and again using the same function for splitting the string for : delimiter.
string line,item;
ifstream myfile("hello.txt");
if(myfile.is_open()) {
string delim =":";
while(!myfile.eof()) {
vector<string> tokens;
getline(myfile,line);
stringstream iss(line);
while(getline(iss,item,delim)) {
tokens.push_back(item);
}
}
myfile.close();
}
The error message is:
C2780: 'std::basic_istream<_Elem,_Traits> &std::getline(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : expects 2 arguments - 3 provided 1> c:\program files\microsoft visual studio 8\vc\include\string(528) : see declaration of 'std::getline'
| Use char delim = ':'; and I also suggest using istringstream instead of stringstream. Also, the loop is wrong:
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
...
char delim = ':';
while (std::getline(myfile,line))
{
vector<string> tokens;
istringstream iss(line);
while(std::getline(iss,item,delim))
{
tokens.push_back(item);
}
}
myfile.close();
Also, note that tokens will get reset on each line. If you intend to accumulate tokens across lines, declare it before the outer loop.
|
3,177,875 | 3,177,916 | Member function hidden in derived class | Please look at the following code:
#include <iostream>
using namespace std;
class A {
public:
A() {};
virtual void foo(double d) { cout << d << endl; }
virtual void foo(double d, int a) = 0;
};
class B : public A {
public:
B() {};
virtual void foo(double d, int a) { cout << d << endl << a << endl; }
};
int main()
{
B b;
b.foo(3.14);
return 0;
}
The compiler (tried g++ and visual c++ 2008) says that there's no function like B:foo(double). The exact message of g++ is:
main.cpp:21: error: no matching function for call to ‘B::foo(double)’
It looks like the effect of hiding rule, but in my opinion the rule should not be used here, since I'm not overriding foo(double) and both foo methods are defined in base class.
I know that I can fix the problem with
using A::foo;
declaration in the derived class B.
Can you explain why the code does not compile and what rules of C++ apply here?
| The hiding rule is not about overriding, it is about hiding of names. If the derived class declares a member function, this hides other base class member functions with the same name. This also happens in your case.
|
3,178,126 | 3,178,221 | What's the cleanest implementation of this container of typed containers? | I have different types, say A, B, C, that all inherit from some base class Base:
class Base { ... };
class A : public Base { ... };
class B : public Base { ... };
class C : public Base { ... };
I need a container, let's call it Master, that holds pointers to objects of types A, B and C. I want the Master container to provide an iterator over all contained Base objects, as well as specifically-typed iterators over all contained A, B and C objects. As a storage backend, I'll be using std::vector, but it would be nice if this can be switched easily later on.
Conceptually, this is the interface that Master should present to the outside world:
class Master {
public:
add(A *a);
add(B *b);
add(C *c);
remove(Base *base);
iterator<A*> a_begin();
iterator<A*> a_end();
iterator<B*> b_begin();
iterator<B*> b_end();
iterator<C*> c_begin();
iterator<C*> c_end();
iterator<Base*> base_begin();
iterator<Base*> base_end();
// also: reverse iterators, const iterators, reverse const iterators
};
The interface does not have to match this precise syntax. For example, someMaster.begin<A>() is perfectly fine too.
The trouble is, even in this simplified interface, you can already see some code duplication happening. It's much worse in the implementation. This is unacceptable, because I want to be able to extend the Master container easily later on, if I want to add classes D, E and F (also inheriting from Base). Preferably, I would like to extend it with just one or two lines of code.
All this could be implemented with lots of dynamic_casting, but that's ugly. I think some magic with templates and multiple inheritance could help me out here. What would be the cleanest implementation of this class?
| Here's a sketch of what I would do:
// Beware, brain-compiled code ahead
template< typename T >
class typed_container
{
typedef std::vector<T> data_t;
public:
typedef data_t::iterator iterator;
iterator begin() {return data_.begin();}
iterator end () {return data_.end();}
private:
data_t data_;
};
typedef my_type_list<A,B,C> types_t;
class master : public derive_from< typed_container, types_t > {
template< typename T >
struct traits {
typedef typename typed_container<T>::iterator iterator;
iterator begin(typed_container<T>& c) {return c.begin();}
iterator end (typed_container<T>& c) {return c.end ();}
};
public:
template< typename T >
typename traits<T>::iterator begin() {return traits<T>::begin(*this);}
template< typename T >
typename traits<T>::iterator end () {return traits<T>::end (*this);}
typedef my_assembling_iterator<types_t> iterator;
iterator begin() {return my_assembling_iterator<types_t>.begin(*this);}
iterator end () {return my_assembling_iterator<types_t>.end (*this);}
};
That leaves you to implement my_type_list (rather simple), derive_from (not as simple, but not too hard either), and my_assembling_iterator (I hadn't had a need to do something like that yet).
You can find a working C++03 type list implementation here. It only takes up to nine template arguments (but that's easily extended), and you'll have to write
typedef my_type_list<A,B,C>::result_t types_t
but it's simple and free and I know it works (because I'm using this library myself).
The derive_from template would look something like this:
//Beware, brain-compiled code ahead!
template< template<typename> class C, class >
struct derive_from;
template< template<typename> class C >
struct derive_from< C, nil > {};
template< template<typename> class C, typename Head, typename Tail >
struct derive_from< C, my_type_list<Head,Tail> > : public C<Head>
, public derive_from<C,Tail> {};
That leaves the iterator. What are your needs regarding it? Does it have to be a random-access iterator (hard) or would a forward iterator suffice? Do you need any particular order to iterate over the elements?
|
3,178,165 | 3,207,143 | How to use python build script with teamcity CI? | I am currently researching using the TeamCity CI software for our comapanies CI automation needs but have had trouble finding information about using different build scripts with TeamCity. We have C++ projects that need to have build/test automation and we currently have licenses for TeamCity. I have looked into using scons for the build automation but havent been able to find much information about using a python build script with TeamCity. If anyone could provide information about this to a CI beginner would be much appreciated.
Thanks
| We use TeamCity to run our acceptance test suite (which uses Robot Framework - done in python).
Getting it to run was as simple as wrapping the python call with a very simple NAnt script. It does 2 things:
Uses an exec task to run python with the script as an argument.
Gets the xml output from the build and transforms it into something teamcity can understand.
There are probably tasks to run python scripts directly with NAnt but we've not had to use them - it was pretty easy to get up and running. You could do the same sort of thing using Ant or whatever depending on what your platform was.
|
3,178,281 | 3,178,401 | Manage mapped memory (glMapBuffer) with std::vector | it occurred to me that it would be a good idea to manage a range of mapped memory (from glMapBuffer) with a std::vector.
// map data to ptr
T* dataPtr = (T*)glMapBuffer(this->target, access);
[... debug code ...]
// try to construct a std::vector from dataPtr
T* dataPtrLast = dataPtr + size;
mappedVector = new std::vector<T>(dataPtr, dataPtrLast);
the problem is that the memory range won't be used directly but it is copied into the vector.
My question would be: is it possible to make the vector just 'use' the mapped memory range. (and ideally throw exceptions on resize/reserve)
Or is there any other standard container that would accomplish this?
Kind Regards,
Florian
| No, and for good reason. This code would never work. For example, you could alter the MapBuffer and break the size/capacity values inside the vector. You could push into the vector and cause an access violation/segmentation fault. You could cause a resize, destroying the buffer. And, fundamentally, if it's already within a contiguous array, what's the benefit? You could roll a custom container for fixed length arrays, I guess.
Especially! if you already have a pair of pointers to act like iterators.
|
3,178,309 | 3,178,345 | How to create a correct hierarchy of objects in C++ | I'm building an hierarchy of objects that wrap primitive types, e.g integers, booleans, floats etc, as well as container types like vectors, maps and sets. I'm trying to (be able to) build an arbitrary hierarchy of objects, and be able to set/get their values with ease. This hierarchy will be passed to another class (not mentioned here) and an interface will be created from this representation. This is the purpose of this hierarchy, to be able to create a GUI representation from these objects.To be more precise, i have something like this:
class ValObject
{
public:
virtual ~ValObject() {}
};
class Int : public ValObject
{
public:
Int(int v) : val(v) {}
void set_int(int v) { val = v);
int get_int() const { return val; }
private:
int val;
};
// other classes for floats, booleans, strings, etc
// ...
class Map : public ValObject {}
{
public:
void set_val_for_key(const string& key, ValObject* val);
ValObject* val_for_key(const string& key);
private:
map<string, ValObject*> keyvals;
};
// classes for other containers (vector and set) ...
The client, should be able to create and arbitrary hierarchy of objects, set and get their values with ease, and I, as a junior programmer, should learn how to correctly create the classes for something like this.
The main problem I'm facing is how to set/get the values through a pointer to the base class ValObject. At first, i thought i could just create lots of functions in the base class, like set_int, get_int, set_string, get_string, set_value_for_key, get_value_for_key, etc, and make them work only for the correct types. But then, i would have lots of cases where functions do nothing and just pollute my interface. My second thought was to create various proxy objects for setting and getting the various values, e.g
class ValObject
{
public:
virtual ~ValObject() {}
virtual IntProxy* create_int_proxy(); // <-- my proxy
};
class Int : public ValObject
{
public:
Int (int v) : val(v) {}
IntProxy* create_int_proxy() { return new IntProxy(&val); }
private:
int val;
};
class String : public ValObject
{
public:
String(const string& s) : val(s) {}
IntProxy* create_int_proxy() { return 0; }
private:
string val;
};
The client could then use this proxy to set and get the values of an Int through an ValObject:
ValObject *val = ... // some object
IntProxy *ipr = val->create_int_proxy();
assert(ipr); // we know that val is an Int (somehow)
ipr->set_val(17);
But with this design, i still have too many classes to declare and implement in the various subclasses. Is this the correct way to go ? Are there any alternatives ?
Thank you.
| Take a look at boost::any and boost::variant for existing solutions. The closest to what you propose is boost::any, and the code is simple enough to read and understand even if you want to build your own solution for learning purposes --if you need the code, don't reinvent the wheel, use boost::any.
|
3,178,342 | 3,206,195 | Compiling a C++ program with GCC | How can I compile a C++ program with the GCC compiler?
File info.c
#include<iostream>
using std::cout;
using std::endl;
int main()
{
#ifdef __cplusplus
cout << "C++ compiler in use and version is " << __cplusplus << endl;
#endif
cout <<"Version is " << __STDC_VERSION__ << endl;
cout << "Hi" << __FILE__ << __LINE__ << endl;
}
And when I try to compile info.c:
gcc info.C
Undefined first referenced
symbol in file
cout /var/tmp/ccPxLN2a.o
endl(ostream &) /var/tmp/ccPxLN2a.o
ostream::operator<<(ostream &(*)(ostream &))/var/tmp/ccPxLN2a.o
ostream::operator<<(int) /var/tmp/ccPxLN2a.o
ostream::operator<<(long) /var/tmp/ccPxLN2a.o
ostream::operator<<(char const *) /var/tmp/ccPxLN2a.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
Isn't the GCC compiler capable of compiling C++ programs?
On a related note, what is the difference between gcc and g++?
| gcc can actually compile C++ code just fine. The errors you received are linker errors, not compiler errors.
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
which makes it link to the standard C++ library, then it will work just fine.
However, you should just make your life easier and use g++.
Rup says it best in his comment to another answer:
[...] gcc will
select the correct back-end compiler
based on file extension (i.e. will
compile a .c as C and a .cc as C++)
and links binaries against just the
standard C and GCC helper libraries by
default regardless of input languages;
g++ will also select the correct
back-end based on extension except
that I think it compiles all C source
as C++ instead (i.e. it compiles both
.c and .cc as C++) and it includes
libstdc++ in its link step regardless
of input languages.
|
3,178,478 | 3,178,483 | When do I have to declare a function used in a template? | I've got (probably) a simple question.
When do I have to declare a function used in a template?
The following code prints out (using gcc >=4.1):
init my A object
no init
Using gcc 4.0 the following code prints out:
init my A object
init my string object
#include <iostream>
#include <string>
template<typename T>
void init(T& t){
std::cout << "no init" << std::endl;
}
// void init(std::string& t);
template <typename T>
void doSomething(T& t){
init(t);
// do some further stuff
}
void init(std::string& t){
std::cout << "init my string object" << std::endl;
}
class A{
};
void init(A& t){
std::cout << "init my A object" << std::endl;
}
int main(){
A a;
doSomething(a);
std::string s("test");
doSomething(s);
return 0;
}
What is the difference between the usage of std::string and A?
Shouldn't there be the same behaviour?
With the additional forward declaration it works fine,
but when do I need it?
Cheers,
CSpille
| Functions at the instantiation point are looked up only using argument dependent lookup (looking up functions in the namespaces associated with a function argument). Normal lookup is only done at the point of the template definition.
So for std::string, only the generic init function template is visible and called, since there is no specific one for it in namespace std. For A, the more specific function is found in the global namespace of A.
If you forward declare the string specific function to appear prior to doSomething, normal unqualified lookup finds it at the definition and uses it later on.
If you call init as follows, it inhibits argument dependent lookup, and will thus use the generic template for A too.
template <typename T>
void doSomething(T& t){
(init)(t);
// won't do ADL
}
(As a side-node: In that case, not only argument dependent lookup is inhibited at instantiation, but init won't be a dependent name in the first place - only non-parenthesized and unqualified function names are made dependent. Thus only non-ADL lookup at definition is done anyway and no lookup at instantiation is taken place what-so-ever, even if there would be a form different from ADL that would be done there.)
|
3,178,651 | 3,178,661 | Critique this c++ code | Similar to the code written below exists in production. Could you people review it and tell me if such code works well all the time.
class Base
{
public:
virtual void process() = 0;
};
class ProductA : public Base
{
public:
void process()
{
// some implementation.
doSomething();
}
void setSomething(int x)
{
}
virtual void doSomething()
{
// doSomething.
}
};
class ProductANew : public ProductA
{
public:
ProductANew() : ProductA() { }
void doSomething()
{
// do Something.
}
};
int main(int argc, char *argv[])
{
Base* bp = new ProductANew();
dynamic_cast<ProductA*>(bp)->setSomething(10);
bp->process();
}
| With good design you wouldn't need a dynamic_cast. If process() can't be called without calling setSomething() first they should have been exposed in the same base class.
|
3,178,739 | 28,086,658 | Invoking MSVC compiler from VS extension | Is it possible to invoke cl.exe, the MSVC++ compiler, from inside a Visual Studio extension? I'm using VS2010 and not bothered about maintaining compatibility for 2008/2005. I've hunted through MSDN and had a poke through my DTE object, but not found anything of use. The documentation on what you can do with this stuff is kinda sparse.
| You certainly can invoke cl.exe from the normal command line if you simply set up the appropriate environment variables.
|
3,178,877 | 3,181,637 | Multiple application entry points | Recently I was trying to add unit tests to an existing binary by creating a extra (DLLMain) entry point to an application that already has a main entry point (it is a console exe). The application seemed to compile correctly although I was unable to use it as a DLL from my python unit test framework, all attempts to use the exe as a dll failed.
Has anyone any ideas or experience in adding extra application entry point with any input as to why this would or wouldn't work?
| There are some problems which you should solve to implement what you want:
The exe must have relocation table (use linker switch /FIXED:NO)
The exe must exports at least one function - it's clear how to do this.
I recommend use DUMPBIN.EXE with no some switches (/headers, /exports and without switches) to examine the exe headers. You can compare the structure of your application with Winword.exe or outlook.exe which exports some functions.
If all this will not helps, I'll try to write a test EXE application which can be loaded as an exe and post the code here.
UPDATED: Just now verified my suggestion. It works. File Loadable.c looks like following
#include <windows.h>
#include <stdio.h>
EXTERN_C int __declspec(dllexport) WINAPI Sum (int x, int y);
EXTERN_C int __declspec(dllexport) WINAPI Sum (int x, int y)
{
return x + y;
}
int main()
{
printf ("2+3=%d\n", Sum(2,3));
}
The only important linker switch is /FIXED:NO which one can find in advanced part of linker settings. The program can run and produced the output "2+3=5".
Another EXE loaded the EXE as a DLL and calls Sum function:
#include <windows.h>
#include <stdio.h>
typedef int (WINAPI *PFN_SUM) (int x, int y);
int main()
{
HMODULE hModule = LoadLibrary (TEXT("C:\\Oleg\\ExeAsDll\\Loadable.exe"));
PFN_SUM fnSum = (PFN_SUM) GetProcAddress (hModule, "_Sum@8");
int res = fnSum (5,4);
printf ("5+4=%d\n", res);
return 0;
}
The program also can run and produced the output "5+4=9".
|
3,178,928 | 3,178,978 | uvaoj 208 how can i speed up my program | why my program Time Limited Error?
because of the sort?
this is the question
link text
#include <cstdio>
#include <cstring>
using namespace std;
int map[22][44];
int book[22];
int total;
int sum;
int way[22];
int tails[22];
int tail;
void init()
{
memset(map,0,sizeof(map));
memset(book,0,sizeof(book));
sum =0;
memset(way,0,sizeof(way));
way[1]=1;
memset(tails,0,sizeof(tails));
}
void sort()
{
int t;
for (int i=1;i<=22;i++)
{
if (tails[i]==0)
break;
else
{
for (int j=1;j<=tails[i]-1;j++)
for (int k=j+1;k<=tails[i];k++)
{
if (map[i][j] > map[i][k])
{
t = map[i][j];
map[i][j]=map[i][k];
map[i][k]=t;
}
}
}
}
}
void dfs(int x,int y)
{
if ((x < 1)||(x > 22))
return;
if (book[x]==1)
return;
//printf("%d \n",x);
if (x == total)
{
sum++;
for (int i=1;i<=y-1;i++)
{
printf("%d ",way[i]);
}
printf("%d",total);
printf("\n");
return;
}
tail = tails[x];
for (int i=1;i<=43;i++)
{
book[x]=1;
way[y]=x;
dfs(map[x][i],y+1);
book[x]=0;
}
}
int main()
{
int temp1,temp2;
//freopen("ex.in","r",stdin);
//freopen("ex.out","w",stdout);
int c = 0;
while(scanf("%d",&total)!=EOF)
{
c++;
printf("CASE ");
printf("%d",c);
printf(":");
printf("\n");
init();
for (;;)
{
scanf("%d%d",&temp1,&temp2);
if ((temp1 == 0)&&(temp2 == 0))
break;
else
{
tails[temp1]++;
tail = tails[temp1];
map[temp1][tail]=temp2;
tails[temp2]++;
tail = tails[temp2];
map[temp2][tail]=temp1;
}
}
sort();
dfs(1,1);
printf("There are ");printf("%d",sum);printf(" routes from the firestation to streetcorner ");printf("%d",total);printf(".");
printf("\n");
}
return 0;
}
| Because your sorting algoritm is in worst-case O(n*n), you can use InnoSort for better worst-case complexity O(n*log(n)).
You are using C++ then use sort function from <algorithm> header to do this simplest.
Documentation you can find at http://www.sgi.com/tech/stl/sort.html
|
3,178,946 | 3,178,962 | Using #define to include another file in C++/C | I want to define a macro which includes another header file like so:
#define MY_MACRO (text) #include "__FILE__##_inline.inl"
So that when the preprocessor parses file person.h, MY_MACRO(blahblah) expands to
#include "person.h.inline.inl"
any hints on how to do this ?
| It's not possible to use #define to construct other preprocessor directives, unless you run the preprocessor twice.
But in your case even running the preprocessor twice won't help because the #include must be a single string of the form "..." or <...>.
|
3,179,199 | 3,179,234 | Simplest way to write output message to 'output window' in Visual Studio 2010? | I've tried OutputDebugString function and most of the time I get error like :
error C2664: 'OutputDebugStringA' : cannot convert parameter 1 from 'int' to 'LPCSTR'
Examples
Attempt 1:
//ERROR: sprintf is unsafe. Use sprintf_s instead
int x = 4;
char s[256];
sprintf(s, "There is %d numbers", x);
OutputDebugString((LPCWSTR)s);
Attempt 2:
//FAIL: outputs junk (sprintf_s doesn't understand unicode?)
int x = 4;
char s[256];
sprintf_s(s, "There is %d numbers", x);
OutputDebugString((LPCWSTR)s);
Attempt 3:
//ERROR: no instance of overloaded function "sprintf_s" matches the argument list
int x = 4;
TCHAR s[256];
sprintf_s(s, "There is %d numbers", x);
OutputDebugString((LPCWSTR)s);
Attempt 4:
//ERROR: no instance of overloaded function "sprintf_s" matches the argument list
int x = 4;
TCHAR s[256];
sprintf_s(s, L"There is %d numbers", x);
OutputDebugString((LPCWSTR)s);
Attempt 5:
//ERROR: no instance of overloaded function "swprintf" matches the argument list
int x = 4;
TCHAR s[256];
swprintf(s, "There is %d numbers", x);
OutputDebugString(s);
Attempt 6:
//ERROR: 'swprintf': function has been changed to confirm with the ISO C standard, adding an extra character count parameter
int x = 4;
TCHAR s[256];
swprintf(s, L"There is %d numbers", x);
OutputDebugString(s);
| It only accepts a string as a parameter, not an integer. Try something like
sprintf(msgbuf, "My variable is %d\n", integerVariable);
OutputDebugString(msgbuf);
For more info take a look at http://www.unixwiz.net/techtips/outputdebugstring.html
|
3,179,494 | 3,179,812 | Under what circumstances are C++ destructors not going to be called? | I know that my destructors are called on normal unwind of stack and when exceptions are thrown, but not when exit() is called.
Are there any other cases where my destructors are not going to get called? What about signals such as SIGINT or SIGSEGV? I presume that for SIGSEGV, they are not called, but for SIGNINT they are, how do I know which signals will unwind the stack?
Are there any other circumstances where they will not be called?
|
Are there any other circumstances where they[destructors] will not be called?
Long jumps: these interfere with the natural stack unwinding process and often lead to undefined behavior in C++.
Premature exits (you already pointed these out, though it's worth noting that throwing while already stack unwinding as a result of an exception being thrown leads to undefined behavior and this is why we should never throw out of dtors)
Throwing from a constructor does not invoke the dtor for a class. This is why, if you allocate multiple memory blocks managed by several different pointers (and not smart pointers) in a ctor, you need to use function-level try blocks or avoid using the initializer list and have a try/catch block in the ctor body (or better yet, just use a smart pointer like scoped_ptr since any member successfully initialized so far in an initializer list will be destroyed even though the class dtor will not be called).
As pointed out, failing to make a dtor virtual when a class is deleted through a base pointer could fail to invoke the subclass dtors (undefined behavior).
Failing to call matching operator delete/delete[] for an operator new/new[] call (undefined behavior - may fail to invoke dtor).
Failing to manually invoke the dtor when using placement new with a custom memory allocator in the deallocate section.
Using functions like memcpy which only copies one memory block to another without invoking copy ctors. mem* functions are deadly in C++ as they bulldoze over the private data of a class, overwrite vtables, etc. The result is typically undefined behavior.
Instantiation of some of smart pointers (auto_ptr) on an incomplete type, see this discussion
|
3,179,676 | 3,179,963 | C++ Exposed property for COM in idl is showing as lower case "all of a sudden" | I have this old C++ COM component. I took the latest code base, built it and found that one of the properties has become lower case. For example, in the pre-compiled dll i have a property "Type", but when building from source it's called "type". The idl shows that the property is called "Type". So what could possibly be happening here?
| You discovered a quirk in the OS stock implementation of ICreateTypeLib, used by practically all tool chains on Windows that can create a type library. It uses a rather crude way to deal with possible problems caused by languages that are not case-sensitive, VB/A being a prominent example.
At issue is the definition of an identifier with one casing, being referenced elsewhere in the type library with another casing. Not a problem at all in, say, VB, big problem when the client programmer uses a case-sensitive language like C# or C++.
The "fix" it uses is to force the casing to be consistent everywhere in the library. Unfortunately it is not very sophisticated about it. Best example is a method declaration earlier in the type library that takes an argument named type. Any identifier named Type in the rest of the type library will now get case-converted to type.
Repairing this problem is easy enough, just change the name of the identifier so it no longer matches. You'll have to find it, not so easy, best to use Oleview.exe, File > View Typelib command. Copy/paste the decompiled IDL into a text editor and use its Search command.
|
3,179,729 | 3,179,762 | Is there anything that prevents this form of use of XOR test? | Is there anything that prevents this form of use of XOR test?
bool result = false;
bool b1 = false;
bool b2 = false;
...
if ( b1 ^ b2 )
{
result = true;
}
| I would prefer the much clearer:
if ( b1 != b2 )
{
result = true;
}
|
3,179,936 | 3,179,974 | Goto out of a block: do destructors get called? | Consider the following code:
void foo()
{
{
CSomeClass bar;
// Some code here...
goto label;
// and here...
}
label:
// and here...
}
Will the destructor of bar be called ?
| The C++ Standard says:
On exit from a scope (however
accomplished), destructors (12.4) are
called for all constructed objects
with automatic storage duration
(3.7.2) (named objects or temporaries)
that are declared in that scope, in
the reverse order of their
declaration.
So the answer is "yes".
|
3,180,138 | 3,180,168 | On Sandboxing a memory-leaky 3rd-Party DLL | I am looking for a way to cure at least the symptoms of a leaky DLL i have to use. While the library (OpenCascade) claims to provides a memory manager, i have as of yet being unable to make it release any memory it allocated.
I would at least wish to put the calls to this module in a 'sandbox', in order to keep my application from not losing memory while the OCC-Module isn't even running any more.
My question is: While I realise that it would be an UGLY HACK (TM) to do so, is it possible to preallocate a stretch of memory to be used specifically by the libraries, or to build some kind of sandbox around it so i can track what areas of memory they used in order to release them myself when i am finished?
Or would that be to ugly a hack and I should try to resolve the issues otherwise?
| The only reliable way is to separate use of the library into a dedicated process. You will start that process, pass data and parameters to it, run the library code, retrieve results. Once you decide the memory consumption is no longer tolerable you restart the process.
|
3,180,164 | 3,180,235 | Correct way of checking if threads are done? | I'm using multithreading in my application with _beginthread and right now to wait until all threads are done I have global bools that get set to true as each thread completes so I'm in a while loop until then. There must be a cleaner way of doing this?
Thanks
| You can use WaitForMultipleObjects to wait for the threads to finish in primary thread.
|
3,180,268 | 3,180,285 | Why are C++ STL iostreams not "exception friendly"? | I'm used to the Delphi VCL Framework, where TStreams throw exceptions on errors (e.g file not found, disk full). I'm porting some code to use C++ STL instead, and have been caught out by iostreams NOT throwing exceptions by default, but setting badbit/failbit flags instead.
Two questions...
a: Why is this - It seems an odd design decision for a language built with exceptions in it from day one?
b: How best to avoid this? I could produce shim classes that throw as I would expect, but this feels like reinventing the wheel. Maybe there's a BOOST library that does this in a saner fashion?
|
C++ wasn't built with exceptions from day one. "C with classes" started in 1979, and exceptions were added in 1989. Meanwhile, the streams library was written as early as 1984 (later becomes iostreams in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.
Ref:
Bjarne Stroustrup, A History of C++: 1979−1991
C++ Libraries
You can enable exceptions with the .exceptions method.
// ios::exceptions
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::ifstream file;
file.exceptions(ifstream::failbit | ifstream::badbit);
try {
file.open ("test.txt");
std::string buf;
while (std::getline(file, buf))
std::cout << "Read> " << buf << "\n";
}
catch (ifstream::failure& e) {
std::cout << "Exception opening/reading file\n";
}
}
|
3,180,702 | 3,180,801 | Convert datetime from one timezone to another (native C++) | Customers from around the world can send certain 'requests' to my server application. All these customers are located in many different time zones.
For every request, I need to map the request to an internal C++ class instance. Every class instance has some information about its 'location', which is also indicated by a time zone.
Every customer can send requests relating to instances belonging to different time zones. To prevent my customers from converting everything themselves to the time zone of the 'target' instance, I have to convert everything myself from one time zone to another. However, I only find in C++ (unmanaged, native) functions to convert times between local time and GTM, but not from/to a time zone that is not your current time zone.
I could ask my customers to send every date time in UTC or GTM, but that does not solve my problem as I still have to convert this to the time zone of the 'instance', which can be any time zone in the world.
I also don't seem to find a Windows function that does this. What I do find is a managed .Net class that does this, but I want to keep my application strictly unmanaged.
Are there any Windows (XP, Vista, 7, 2003, 2008) functions that I can use (and which I overlooked in the documentation), or are there any other free algorithms that can convert between one time zone and the other?
Notice that it is not the GMT-difference that is posing the problem, but the actual DST-transition moment that seems to depend on the time zone. E.g:
Western Europe goes from non-DST to DST the last Sunday before April 1st.
USA goes from non-DST to DST the 2nd Sunday after March 1st.
China has no DST.
Australia goes from non-DST to DST the 1st Sunday after October 1st.
All this DST-transition information is available somewhere in the Windows registry. Problem is: which Windows function can I use to exploit this information.
| I don't know of a way to extract information about other TimeZones via the API: I've seen it done by querying the registry though (we do this in a WindowsCE-based product).
The TimeZones are defined as registry keys under
HKLM\Software\Microsoft\Windows NT\Current Version\Time Zones
Each key contains several values, and the one which tells you about offsets & Daylight Savings is the TZI key. This is a binary blob, and it represents this structure:
typedef struct
{
LONG m_nBias;
LONG m_nStandardBias;
LONG m_nDaylightBias;
SYSTEMTIME m_stcStandardDate;
SYSTEMTIME m_stcDaylightDate;
} TZI;
Look up MSDN's TIME_ZONE_INFORMATION page (http://msdn.microsoft.com/en-us/library/ms725481(v=VS.85).aspx) for how to interpret the Bias fields, and especially the StandardDate and DaylightDate fields -- they are gently abused to support constructs like "the last Saturday in April".
HTH
|
3,180,887 | 3,180,897 | std::string vs string literal for functions | I was wondering, I normally use std::string for my code, but when you are passing a string in a parameter for a simply comparison, is it better to just use a literal?
Consider this function:
bool Message::hasTag(string tag)
{
for(Uint tagIndex = 0; tagIndex < m_tags.size();tagIndex++)
{
if(m_tags[tagIndex] == tag)
return 0;
}
return 1;
}
Despite the fact that the property it is making a comparison with is a vector, and whatever uses this function will probably pass strings to it, would it still be better to use a const char* to avoid creating a new string that will be used like a string literal anyway?
| If you want to use classes, the best approach here is a const reference:
bool Message::hasTag(const string& tag);
That way, redudant copying can be minimized and it's made clear that the method doesn't intend to modify the argument. I think a clever compiler can emit pretty good code for the case when this is called with a string literal.
Passing a character pointer requires you to use strcmp() to compare, since if you start comparing pointers directly using ==, there will be ... trouble.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.